32909090f6672d0a39c8aa307d0351ac504e225b
[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                 </managerEventInstance>
106         </managerEvent>
107         <managerEvent language="en_US" name="RTCPReceived">
108                 <managerEventInstance class="EVENT_FLAG_REPORTING">
109                         <synopsis>Raised when an RTCP packet is received.</synopsis>
110                         <syntax>
111                                 <channel_snapshot/>
112                                 <parameter name="SSRC">
113                                         <para>The SSRC identifier for the remote system</para>
114                                 </parameter>
115                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='RTCPSent']/managerEventInstance/syntax/parameter[@name='PT'])" />
116                                 <parameter name="From">
117                                         <para>The address the report was received from.</para>
118                                 </parameter>
119                                 <parameter name="RTT">
120                                         <para>Calculated Round-Trip Time in seconds</para>
121                                 </parameter>
122                                 <parameter name="ReportCount">
123                                         <para>The number of reports that were received.</para>
124                                         <para>The report count determines the number of ReportX headers in
125                                         the message. The X for each set of report headers will range from 0 to
126                                         <literal>ReportCount - 1</literal>.</para>
127                                 </parameter>
128                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='RTCPSent']/managerEventInstance/syntax/parameter[@name='SentNTP'])" />
129                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='RTCPSent']/managerEventInstance/syntax/parameter[@name='SentRTP'])" />
130                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='RTCPSent']/managerEventInstance/syntax/parameter[@name='SentPackets'])" />
131                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='RTCPSent']/managerEventInstance/syntax/parameter[@name='SentOctets'])" />
132                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='RTCPSent']/managerEventInstance/syntax/parameter[contains(@name, 'ReportX')])" />
133                         </syntax>
134                 </managerEventInstance>
135         </managerEvent>
136  ***/
137
138 #include "asterisk.h"
139
140 ASTERISK_REGISTER_FILE()
141
142 #include <math.h>
143
144 #include "asterisk/channel.h"
145 #include "asterisk/frame.h"
146 #include "asterisk/module.h"
147 #include "asterisk/rtp_engine.h"
148 #include "asterisk/manager.h"
149 #include "asterisk/options.h"
150 #include "asterisk/astobj2.h"
151 #include "asterisk/pbx.h"
152 #include "asterisk/translate.h"
153 #include "asterisk/netsock2.h"
154 #include "asterisk/_private.h"
155 #include "asterisk/framehook.h"
156 #include "asterisk/stasis.h"
157 #include "asterisk/json.h"
158 #include "asterisk/stasis_channels.h"
159
160 struct ast_srtp_res *res_srtp = NULL;
161 struct ast_srtp_policy_res *res_srtp_policy = NULL;
162
163 /*! Structure that represents an RTP session (instance) */
164 struct ast_rtp_instance {
165         /*! Engine that is handling this RTP instance */
166         struct ast_rtp_engine *engine;
167         /*! Data unique to the RTP engine */
168         void *data;
169         /*! RTP properties that have been set and their value */
170         int properties[AST_RTP_PROPERTY_MAX];
171         /*! Address that we are expecting RTP to come in to */
172         struct ast_sockaddr local_address;
173         /*! The original source address */
174         struct ast_sockaddr requested_target_address;
175         /*! Address that we are sending RTP to */
176         struct ast_sockaddr incoming_source_address;
177         /*! Instance that we are bridged to if doing remote or local bridging */
178         struct ast_rtp_instance *bridged;
179         /*! Payload and packetization information */
180         struct ast_rtp_codecs codecs;
181         /*! RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
182         int timeout;
183         /*! RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
184         int holdtimeout;
185         /*! RTP keepalive interval */
186         int keepalive;
187         /*! Glue currently in use */
188         struct ast_rtp_glue *glue;
189         /*! SRTP info associated with the instance */
190         struct ast_srtp *srtp;
191         /*! Channel unique ID */
192         char channel_uniqueid[AST_MAX_UNIQUEID];
193         /*! Time of last packet sent */
194         time_t last_tx;
195         /*! Time of last packet received */
196         time_t last_rx;
197 };
198
199 /*! List of RTP engines that are currently registered */
200 static AST_RWLIST_HEAD_STATIC(engines, ast_rtp_engine);
201
202 /*! List of RTP glues */
203 static AST_RWLIST_HEAD_STATIC(glues, ast_rtp_glue);
204
205 #define MAX_RTP_MIME_TYPES 128
206
207 /*! The following array defines the MIME Media type (and subtype) for each
208    of our codecs, or RTP-specific data type. */
209 static struct ast_rtp_mime_type {
210         /*! \brief A mapping object between the Asterisk codec and this RTP payload */
211         struct ast_rtp_payload_type payload_type;
212         /*! \brief The media type */
213         char type[16];
214         /*! \brief The format type */
215         char subtype[64];
216         /*! \brief Expected sample rate of the /c subtype */
217         unsigned int sample_rate;
218 } ast_rtp_mime_types[128]; /* This will Likely not need to grow any time soon. */
219 static ast_rwlock_t mime_types_lock;
220 static int mime_types_len = 0;
221
222 /*!
223  * \brief Mapping between Asterisk codecs and rtp payload types
224  *
225  * Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
226  * also, our own choices for dynamic payload types.  This is our master
227  * table for transmission
228  *
229  * See http://www.iana.org/assignments/rtp-parameters for a list of
230  * assigned values
231  */
232 static struct ast_rtp_payload_type *static_RTP_PT[AST_RTP_MAX_PT];
233 static ast_rwlock_t static_RTP_PT_lock;
234
235 /*! \brief \ref stasis topic for RTP related messages */
236 static struct stasis_topic *rtp_topic;
237
238
239 /*!
240  * \internal
241  * \brief Destructor for \c ast_rtp_payload_type
242  */
243 static void rtp_payload_type_dtor(void *obj)
244 {
245         struct ast_rtp_payload_type *payload = obj;
246
247         ao2_cleanup(payload->format);
248 }
249
250 struct ast_rtp_payload_type *ast_rtp_engine_alloc_payload_type(void)
251 {
252         struct ast_rtp_payload_type *payload;
253
254         payload = ao2_alloc_options(sizeof(*payload), rtp_payload_type_dtor,
255                 AO2_ALLOC_OPT_LOCK_NOLOCK);
256
257         return payload;
258 }
259
260 int ast_rtp_engine_register2(struct ast_rtp_engine *engine, struct ast_module *module)
261 {
262         struct ast_rtp_engine *current_engine;
263
264         /* Perform a sanity check on the engine structure to make sure it has the basics */
265         if (ast_strlen_zero(engine->name) || !engine->new || !engine->destroy || !engine->write || !engine->read) {
266                 ast_log(LOG_WARNING, "RTP Engine '%s' failed sanity check so it was not registered.\n", !ast_strlen_zero(engine->name) ? engine->name : "Unknown");
267                 return -1;
268         }
269
270         /* Link owner module to the RTP engine for reference counting purposes */
271         engine->mod = module;
272
273         AST_RWLIST_WRLOCK(&engines);
274
275         /* Ensure that no two modules with the same name are registered at the same time */
276         AST_RWLIST_TRAVERSE(&engines, current_engine, entry) {
277                 if (!strcmp(current_engine->name, engine->name)) {
278                         ast_log(LOG_WARNING, "An RTP engine with the name '%s' has already been registered.\n", engine->name);
279                         AST_RWLIST_UNLOCK(&engines);
280                         return -1;
281                 }
282         }
283
284         /* The engine survived our critique. Off to the list it goes to be used */
285         AST_RWLIST_INSERT_TAIL(&engines, engine, entry);
286
287         AST_RWLIST_UNLOCK(&engines);
288
289         ast_verb(2, "Registered RTP engine '%s'\n", engine->name);
290
291         return 0;
292 }
293
294 int ast_rtp_engine_unregister(struct ast_rtp_engine *engine)
295 {
296         struct ast_rtp_engine *current_engine = NULL;
297
298         AST_RWLIST_WRLOCK(&engines);
299
300         if ((current_engine = AST_RWLIST_REMOVE(&engines, engine, entry))) {
301                 ast_verb(2, "Unregistered RTP engine '%s'\n", engine->name);
302         }
303
304         AST_RWLIST_UNLOCK(&engines);
305
306         return current_engine ? 0 : -1;
307 }
308
309 int ast_rtp_glue_register2(struct ast_rtp_glue *glue, struct ast_module *module)
310 {
311         struct ast_rtp_glue *current_glue = NULL;
312
313         if (ast_strlen_zero(glue->type)) {
314                 return -1;
315         }
316
317         glue->mod = module;
318
319         AST_RWLIST_WRLOCK(&glues);
320
321         AST_RWLIST_TRAVERSE(&glues, current_glue, entry) {
322                 if (!strcasecmp(current_glue->type, glue->type)) {
323                         ast_log(LOG_WARNING, "RTP glue with the name '%s' has already been registered.\n", glue->type);
324                         AST_RWLIST_UNLOCK(&glues);
325                         return -1;
326                 }
327         }
328
329         AST_RWLIST_INSERT_TAIL(&glues, glue, entry);
330
331         AST_RWLIST_UNLOCK(&glues);
332
333         ast_verb(2, "Registered RTP glue '%s'\n", glue->type);
334
335         return 0;
336 }
337
338 int ast_rtp_glue_unregister(struct ast_rtp_glue *glue)
339 {
340         struct ast_rtp_glue *current_glue = NULL;
341
342         AST_RWLIST_WRLOCK(&glues);
343
344         if ((current_glue = AST_RWLIST_REMOVE(&glues, glue, entry))) {
345                 ast_verb(2, "Unregistered RTP glue '%s'\n", glue->type);
346         }
347
348         AST_RWLIST_UNLOCK(&glues);
349
350         return current_glue ? 0 : -1;
351 }
352
353 static void instance_destructor(void *obj)
354 {
355         struct ast_rtp_instance *instance = obj;
356
357         /* Pass us off to the engine to destroy */
358         if (instance->data && instance->engine->destroy(instance)) {
359                 ast_debug(1, "Engine '%s' failed to destroy RTP instance '%p'\n", instance->engine->name, instance);
360                 return;
361         }
362
363         if (instance->srtp) {
364                 res_srtp->destroy(instance->srtp);
365         }
366
367         ast_rtp_codecs_payloads_destroy(&instance->codecs);
368
369         /* Drop our engine reference */
370         ast_module_unref(instance->engine->mod);
371
372         ast_debug(1, "Destroyed RTP instance '%p'\n", instance);
373 }
374
375 int ast_rtp_instance_destroy(struct ast_rtp_instance *instance)
376 {
377         ao2_ref(instance, -1);
378
379         return 0;
380 }
381
382 struct ast_rtp_instance *ast_rtp_instance_new(const char *engine_name,
383                 struct ast_sched_context *sched, const struct ast_sockaddr *sa,
384                 void *data)
385 {
386         struct ast_sockaddr address = {{0,}};
387         struct ast_rtp_instance *instance = NULL;
388         struct ast_rtp_engine *engine = NULL;
389
390         AST_RWLIST_RDLOCK(&engines);
391
392         /* If an engine name was specified try to use it or otherwise use the first one registered */
393         if (!ast_strlen_zero(engine_name)) {
394                 AST_RWLIST_TRAVERSE(&engines, engine, entry) {
395                         if (!strcmp(engine->name, engine_name)) {
396                                 break;
397                         }
398                 }
399         } else {
400                 engine = AST_RWLIST_FIRST(&engines);
401         }
402
403         /* If no engine was actually found bail out now */
404         if (!engine) {
405                 ast_log(LOG_ERROR, "No RTP engine was found. Do you have one loaded?\n");
406                 AST_RWLIST_UNLOCK(&engines);
407                 return NULL;
408         }
409
410         /* Bump up the reference count before we return so the module can not be unloaded */
411         ast_module_ref(engine->mod);
412
413         AST_RWLIST_UNLOCK(&engines);
414
415         /* Allocate a new RTP instance */
416         if (!(instance = ao2_alloc(sizeof(*instance), instance_destructor))) {
417                 ast_module_unref(engine->mod);
418                 return NULL;
419         }
420         instance->engine = engine;
421         ast_sockaddr_copy(&instance->local_address, sa);
422         ast_sockaddr_copy(&address, sa);
423
424         if (ast_rtp_codecs_payloads_initialize(&instance->codecs)) {
425                 ao2_ref(instance, -1);
426                 return NULL;
427         }
428
429         ast_debug(1, "Using engine '%s' for RTP instance '%p'\n", engine->name, instance);
430
431         /* And pass it off to the engine to setup */
432         if (instance->engine->new(instance, sched, &address, data)) {
433                 ast_debug(1, "Engine '%s' failed to setup RTP instance '%p'\n", engine->name, instance);
434                 ao2_ref(instance, -1);
435                 return NULL;
436         }
437
438         ast_debug(1, "RTP instance '%p' is setup and ready to go\n", instance);
439
440         return instance;
441 }
442
443 const char *ast_rtp_instance_get_channel_id(struct ast_rtp_instance *instance)
444 {
445         return instance->channel_uniqueid;
446 }
447
448 void ast_rtp_instance_set_channel_id(struct ast_rtp_instance *instance, const char *uniqueid)
449 {
450         ast_copy_string(instance->channel_uniqueid, uniqueid, sizeof(instance->channel_uniqueid));
451 }
452
453 void ast_rtp_instance_set_data(struct ast_rtp_instance *instance, void *data)
454 {
455         instance->data = data;
456 }
457
458 void *ast_rtp_instance_get_data(struct ast_rtp_instance *instance)
459 {
460         return instance->data;
461 }
462
463 int ast_rtp_instance_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
464 {
465         return instance->engine->write(instance, frame);
466 }
467
468 struct ast_frame *ast_rtp_instance_read(struct ast_rtp_instance *instance, int rtcp)
469 {
470         return instance->engine->read(instance, rtcp);
471 }
472
473 int ast_rtp_instance_set_local_address(struct ast_rtp_instance *instance,
474                 const struct ast_sockaddr *address)
475 {
476         ast_sockaddr_copy(&instance->local_address, address);
477         return 0;
478 }
479
480 int ast_rtp_instance_set_incoming_source_address(struct ast_rtp_instance *instance,
481                                                  const struct ast_sockaddr *address)
482 {
483         ast_sockaddr_copy(&instance->incoming_source_address, address);
484
485         /* moo */
486
487         if (instance->engine->remote_address_set) {
488                 instance->engine->remote_address_set(instance, &instance->incoming_source_address);
489         }
490
491         return 0;
492 }
493
494 int ast_rtp_instance_set_requested_target_address(struct ast_rtp_instance *instance,
495                                                   const struct ast_sockaddr *address)
496 {
497         ast_sockaddr_copy(&instance->requested_target_address, address);
498
499         return ast_rtp_instance_set_incoming_source_address(instance, address);
500 }
501
502 int ast_rtp_instance_get_and_cmp_local_address(struct ast_rtp_instance *instance,
503                 struct ast_sockaddr *address)
504 {
505         if (ast_sockaddr_cmp(address, &instance->local_address) != 0) {
506                 ast_sockaddr_copy(address, &instance->local_address);
507                 return 1;
508         }
509
510         return 0;
511 }
512
513 void ast_rtp_instance_get_local_address(struct ast_rtp_instance *instance,
514                 struct ast_sockaddr *address)
515 {
516         ast_sockaddr_copy(address, &instance->local_address);
517 }
518
519 int ast_rtp_instance_get_and_cmp_requested_target_address(struct ast_rtp_instance *instance,
520                 struct ast_sockaddr *address)
521 {
522         if (ast_sockaddr_cmp(address, &instance->requested_target_address) != 0) {
523                 ast_sockaddr_copy(address, &instance->requested_target_address);
524                 return 1;
525         }
526
527         return 0;
528 }
529
530 void ast_rtp_instance_get_incoming_source_address(struct ast_rtp_instance *instance,
531                                                   struct ast_sockaddr *address)
532 {
533         ast_sockaddr_copy(address, &instance->incoming_source_address);
534 }
535
536 void ast_rtp_instance_get_requested_target_address(struct ast_rtp_instance *instance,
537                                                    struct ast_sockaddr *address)
538 {
539         ast_sockaddr_copy(address, &instance->requested_target_address);
540 }
541
542 void ast_rtp_instance_set_extended_prop(struct ast_rtp_instance *instance, int property, void *value)
543 {
544         if (instance->engine->extended_prop_set) {
545                 instance->engine->extended_prop_set(instance, property, value);
546         }
547 }
548
549 void *ast_rtp_instance_get_extended_prop(struct ast_rtp_instance *instance, int property)
550 {
551         if (instance->engine->extended_prop_get) {
552                 return instance->engine->extended_prop_get(instance, property);
553         }
554
555         return NULL;
556 }
557
558 void ast_rtp_instance_set_prop(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value)
559 {
560         instance->properties[property] = value;
561
562         if (instance->engine->prop_set) {
563                 instance->engine->prop_set(instance, property, value);
564         }
565 }
566
567 int ast_rtp_instance_get_prop(struct ast_rtp_instance *instance, enum ast_rtp_property property)
568 {
569         return instance->properties[property];
570 }
571
572 struct ast_rtp_codecs *ast_rtp_instance_get_codecs(struct ast_rtp_instance *instance)
573 {
574         return &instance->codecs;
575 }
576
577 int ast_rtp_codecs_payloads_initialize(struct ast_rtp_codecs *codecs)
578 {
579         int res;
580
581         codecs->framing = 0;
582         ast_rwlock_init(&codecs->codecs_lock);
583         res = AST_VECTOR_INIT(&codecs->payload_mapping_rx, AST_RTP_MAX_PT);
584         res |= AST_VECTOR_INIT(&codecs->payload_mapping_tx, AST_RTP_MAX_PT);
585         if (res) {
586                 AST_VECTOR_FREE(&codecs->payload_mapping_rx);
587                 AST_VECTOR_FREE(&codecs->payload_mapping_tx);
588         }
589
590         return res;
591 }
592
593 void ast_rtp_codecs_payloads_destroy(struct ast_rtp_codecs *codecs)
594 {
595         int idx;
596         struct ast_rtp_payload_type *type;
597
598         for (idx = 0; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_rx); ++idx) {
599                 type = AST_VECTOR_GET(&codecs->payload_mapping_rx, idx);
600                 ao2_t_cleanup(type, "destroying ast_rtp_codec rx mapping");
601         }
602         AST_VECTOR_FREE(&codecs->payload_mapping_rx);
603
604         for (idx = 0; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_tx); ++idx) {
605                 type = AST_VECTOR_GET(&codecs->payload_mapping_tx, idx);
606                 ao2_t_cleanup(type, "destroying ast_rtp_codec tx mapping");
607         }
608         AST_VECTOR_FREE(&codecs->payload_mapping_tx);
609
610         ast_rwlock_destroy(&codecs->codecs_lock);
611 }
612
613 void ast_rtp_codecs_payloads_clear(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance)
614 {
615         ast_rtp_codecs_payloads_destroy(codecs);
616         ast_rtp_codecs_payloads_initialize(codecs);
617
618         if (instance && instance->engine && instance->engine->payload_set) {
619                 int i;
620                 for (i = 0; i < AST_RTP_MAX_PT; i++) {
621                         instance->engine->payload_set(instance, i, 0, NULL, 0);
622                 }
623         }
624 }
625
626 /*!
627  * \internal
628  * \brief Clear the rx primary mapping flag on all other matching mappings.
629  * \since 14.0.0
630  *
631  * \param codecs Codecs that need rx clearing.
632  * \param to_match Payload type object to compare against.
633  *
634  * \note It is assumed that codecs is write locked before calling.
635  *
636  * \return Nothing
637  */
638 static void payload_mapping_rx_clear_primary(struct ast_rtp_codecs *codecs, struct ast_rtp_payload_type *to_match)
639 {
640         int idx;
641         struct ast_rtp_payload_type *current;
642         struct ast_rtp_payload_type *new_type;
643         struct timeval now;
644
645         if (!to_match->primary_mapping) {
646                 return;
647         }
648
649         now = ast_tvnow();
650         for (idx = 0; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_rx); ++idx) {
651                 current = AST_VECTOR_GET(&codecs->payload_mapping_rx, idx);
652
653                 if (!current || current == to_match || !current->primary_mapping) {
654                         continue;
655                 }
656                 if (current->asterisk_format && to_match->asterisk_format) {
657                         if (ast_format_cmp(current->format, to_match->format) == AST_FORMAT_CMP_NOT_EQUAL) {
658                                 continue;
659                         }
660                 } else if (!current->asterisk_format && !to_match->asterisk_format) {
661                         if (current->rtp_code != to_match->rtp_code) {
662                                 continue;
663                         }
664                 } else {
665                         continue;
666                 }
667
668                 /* Replace current with non-primary marked version */
669                 new_type = ast_rtp_engine_alloc_payload_type();
670                 if (!new_type) {
671                         continue;
672                 }
673                 *new_type = *current;
674                 new_type->primary_mapping = 0;
675                 new_type->when_retired = now;
676                 ao2_bump(new_type->format);
677                 AST_VECTOR_REPLACE(&codecs->payload_mapping_rx, idx, new_type);
678                 ao2_ref(current, -1);
679         }
680 }
681
682 /*!
683  * \internal
684  * \brief Put the new_type into the rx payload type mapping.
685  * \since 14.0.0
686  *
687  * \param codecs Codecs structure to put new_type into
688  * \param payload type position to replace.
689  * \param new_type RTP payload mapping object to store.
690  *
691  * \note It is assumed that codecs is write locked before calling.
692  *
693  * \return Nothing
694  */
695 static void rtp_codecs_payload_replace_rx(struct ast_rtp_codecs *codecs, int payload, struct ast_rtp_payload_type *new_type)
696 {
697         ao2_ref(new_type, +1);
698         if (payload < AST_VECTOR_SIZE(&codecs->payload_mapping_rx)) {
699                 ao2_t_cleanup(AST_VECTOR_GET(&codecs->payload_mapping_rx, payload),
700                         "cleaning up rx mapping vector element about to be replaced");
701         }
702         AST_VECTOR_REPLACE(&codecs->payload_mapping_rx, payload, new_type);
703
704         payload_mapping_rx_clear_primary(codecs, new_type);
705 }
706
707 /*!
708  * \internal
709  * \brief Copy the rx payload type mapping to the destination.
710  * \since 14.0.0
711  *
712  * \param src The source codecs structure
713  * \param dest The destination codecs structure that the values from src will be copied to
714  * \param instance Optionally the instance that the dst codecs structure belongs to
715  *
716  * \note It is assumed that src is at least read locked before calling.
717  * \note It is assumed that dest is write locked before calling.
718  *
719  * \return Nothing
720  */
721 static void rtp_codecs_payloads_copy_rx(struct ast_rtp_codecs *src, struct ast_rtp_codecs *dest, struct ast_rtp_instance *instance)
722 {
723         int idx;
724         struct ast_rtp_payload_type *type;
725
726         for (idx = 0; idx < AST_VECTOR_SIZE(&src->payload_mapping_rx); ++idx) {
727                 type = AST_VECTOR_GET(&src->payload_mapping_rx, idx);
728                 if (!type) {
729                         continue;
730                 }
731
732                 ast_debug(2, "Copying rx payload mapping %d (%p) from %p to %p\n",
733                         idx, type, src, dest);
734                 rtp_codecs_payload_replace_rx(dest, idx, type);
735
736                 if (instance && instance->engine && instance->engine->payload_set) {
737                         instance->engine->payload_set(instance, idx, type->asterisk_format, type->format, type->rtp_code);
738                 }
739         }
740 }
741
742 /*!
743  * \internal
744  * \brief Remove other matching payload mappings.
745  * \since 14.0.0
746  *
747  * \param codecs Codecs that need tx mappings removed.
748  * \param instance RTP instance to notify of any payloads removed.
749  * \param to_match Payload type object to compare against.
750  *
751  * \note It is assumed that codecs is write locked before calling.
752  *
753  * \return Nothing
754  */
755 static void payload_mapping_tx_remove_other_mappings(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, struct ast_rtp_payload_type *to_match)
756 {
757         int idx;
758         struct ast_rtp_payload_type *current;
759
760         for (idx = 0; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_tx); ++idx) {
761                 current = AST_VECTOR_GET(&codecs->payload_mapping_tx, idx);
762
763                 if (!current || current == to_match) {
764                         continue;
765                 }
766                 if (current->asterisk_format && to_match->asterisk_format) {
767                         if (ast_format_cmp(current->format, to_match->format) == AST_FORMAT_CMP_NOT_EQUAL) {
768                                 continue;
769                         }
770                 } else if (!current->asterisk_format && !to_match->asterisk_format) {
771                         if (current->rtp_code != to_match->rtp_code) {
772                                 continue;
773                         }
774                 } else {
775                         continue;
776                 }
777
778                 /* Remove other mapping */
779                 AST_VECTOR_REPLACE(&codecs->payload_mapping_tx, idx, NULL);
780                 ao2_ref(current, -1);
781                 if (instance && instance->engine && instance->engine->payload_set) {
782                         instance->engine->payload_set(instance, idx, 0, NULL, 0);
783                 }
784         }
785 }
786
787 /*!
788  * \internal
789  * \brief Copy the tx payload type mapping to the destination.
790  * \since 14.0.0
791  *
792  * \param src The source codecs structure
793  * \param dest The destination codecs structure that the values from src will be copied to
794  * \param instance Optionally the instance that the dst codecs structure belongs to
795  *
796  * \note It is assumed that src is at least read locked before calling.
797  * \note It is assumed that dest is write locked before calling.
798  *
799  * \return Nothing
800  */
801 static void rtp_codecs_payloads_copy_tx(struct ast_rtp_codecs *src, struct ast_rtp_codecs *dest, struct ast_rtp_instance *instance)
802 {
803         int idx;
804         struct ast_rtp_payload_type *type;
805
806         for (idx = 0; idx < AST_VECTOR_SIZE(&src->payload_mapping_tx); ++idx) {
807                 type = AST_VECTOR_GET(&src->payload_mapping_tx, idx);
808                 if (!type) {
809                         continue;
810                 }
811
812                 ast_debug(2, "Copying tx payload mapping %d (%p) from %p to %p\n",
813                         idx, type, src, dest);
814                 ao2_ref(type, +1);
815                 if (idx < AST_VECTOR_SIZE(&dest->payload_mapping_tx)) {
816                         ao2_t_cleanup(AST_VECTOR_GET(&dest->payload_mapping_tx, idx),
817                                 "cleaning up tx mapping vector element about to be replaced");
818                 }
819                 AST_VECTOR_REPLACE(&dest->payload_mapping_tx, idx, type);
820
821                 if (instance && instance->engine && instance->engine->payload_set) {
822                         instance->engine->payload_set(instance, idx, type->asterisk_format, type->format, type->rtp_code);
823                 }
824
825                 payload_mapping_tx_remove_other_mappings(dest, instance, type);
826         }
827 }
828
829 void ast_rtp_codecs_payloads_copy(struct ast_rtp_codecs *src, struct ast_rtp_codecs *dest, struct ast_rtp_instance *instance)
830 {
831         ast_rwlock_wrlock(&dest->codecs_lock);
832
833         /* Deadlock avoidance because of held write lock. */
834         while (ast_rwlock_tryrdlock(&src->codecs_lock)) {
835                 ast_rwlock_unlock(&dest->codecs_lock);
836                 sched_yield();
837                 ast_rwlock_wrlock(&dest->codecs_lock);
838         }
839
840         rtp_codecs_payloads_copy_rx(src, dest, instance);
841         rtp_codecs_payloads_copy_tx(src, dest, instance);
842         dest->framing = src->framing;
843
844         ast_rwlock_unlock(&src->codecs_lock);
845         ast_rwlock_unlock(&dest->codecs_lock);
846 }
847
848 void ast_rtp_codecs_payloads_xover(struct ast_rtp_codecs *src, struct ast_rtp_codecs *dest, struct ast_rtp_instance *instance)
849 {
850         int idx;
851         struct ast_rtp_payload_type *type;
852
853         ast_rwlock_wrlock(&dest->codecs_lock);
854         if (src != dest) {
855                 /* Deadlock avoidance because of held write lock. */
856                 while (ast_rwlock_tryrdlock(&src->codecs_lock)) {
857                         ast_rwlock_unlock(&dest->codecs_lock);
858                         sched_yield();
859                         ast_rwlock_wrlock(&dest->codecs_lock);
860                 }
861         }
862
863         /* Crossover copy payload type tx mapping to rx mapping. */
864         for (idx = 0; idx < AST_VECTOR_SIZE(&src->payload_mapping_tx); ++idx) {
865                 type = AST_VECTOR_GET(&src->payload_mapping_tx, idx);
866                 if (!type) {
867                         continue;
868                 }
869
870                 /* All tx mapping elements should have the primary flag set. */
871                 ast_assert(type->primary_mapping);
872
873                 ast_debug(2, "Crossover copying tx to rx payload mapping %d (%p) from %p to %p\n",
874                         idx, type, src, dest);
875                 rtp_codecs_payload_replace_rx(dest, idx, type);
876
877                 if (instance && instance->engine && instance->engine->payload_set) {
878                         instance->engine->payload_set(instance, idx, type->asterisk_format, type->format, type->rtp_code);
879                 }
880         }
881
882         dest->framing = src->framing;
883
884         if (src != dest) {
885                 ast_rwlock_unlock(&src->codecs_lock);
886         }
887         ast_rwlock_unlock(&dest->codecs_lock);
888 }
889
890 void ast_rtp_codecs_payloads_set_m_type(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, int payload)
891 {
892         struct ast_rtp_payload_type *new_type;
893
894         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
895                 return;
896         }
897
898         ast_rwlock_rdlock(&static_RTP_PT_lock);
899         new_type = ao2_bump(static_RTP_PT[payload]);
900         ast_rwlock_unlock(&static_RTP_PT_lock);
901         if (!new_type) {
902                 ast_debug(1, "Don't have a default tx payload type %d format for m type on %p\n",
903                         payload, codecs);
904                 return;
905         }
906
907         ast_debug(1, "Setting tx payload type %d based on m type on %p\n",
908                 payload, codecs);
909
910         ast_rwlock_wrlock(&codecs->codecs_lock);
911
912         if (payload < AST_VECTOR_SIZE(&codecs->payload_mapping_tx)) {
913                 ao2_t_cleanup(AST_VECTOR_GET(&codecs->payload_mapping_tx, payload),
914                         "cleaning up replaced tx payload type");
915         }
916         AST_VECTOR_REPLACE(&codecs->payload_mapping_tx, payload, new_type);
917
918         if (instance && instance->engine && instance->engine->payload_set) {
919                 instance->engine->payload_set(instance, payload, new_type->asterisk_format, new_type->format, new_type->rtp_code);
920         }
921
922         payload_mapping_tx_remove_other_mappings(codecs, instance, new_type);
923
924         ast_rwlock_unlock(&codecs->codecs_lock);
925 }
926
927 int ast_rtp_codecs_payloads_set_rtpmap_type_rate(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, int pt,
928                                  char *mimetype, char *mimesubtype,
929                                  enum ast_rtp_options options,
930                                  unsigned int sample_rate)
931 {
932         unsigned int idx;
933         int found = 0;
934
935         if (pt < 0 || pt >= AST_RTP_MAX_PT) {
936                 return -1; /* bogus payload type */
937         }
938
939         ast_rwlock_rdlock(&mime_types_lock);
940         ast_rwlock_wrlock(&codecs->codecs_lock);
941
942         for (idx = 0; idx < mime_types_len; ++idx) {
943                 const struct ast_rtp_mime_type *t = &ast_rtp_mime_types[idx];
944                 struct ast_rtp_payload_type *new_type;
945
946                 if (strcasecmp(mimesubtype, t->subtype)) {
947                         continue;
948                 }
949
950                 if (strcasecmp(mimetype, t->type)) {
951                         continue;
952                 }
953
954                 /* if both sample rates have been supplied, and they don't match,
955                  * then this not a match; if one has not been supplied, then the
956                  * rates are not compared */
957                 if (sample_rate && t->sample_rate &&
958                     (sample_rate != t->sample_rate)) {
959                         continue;
960                 }
961
962                 found = 1;
963
964                 new_type = ast_rtp_engine_alloc_payload_type();
965                 if (!new_type) {
966                         continue;
967                 }
968
969                 new_type->asterisk_format = t->payload_type.asterisk_format;
970                 new_type->rtp_code = t->payload_type.rtp_code;
971                 new_type->payload = pt;
972                 new_type->primary_mapping = 1;
973                 if (t->payload_type.asterisk_format
974                         && ast_format_cmp(t->payload_type.format, ast_format_g726) == AST_FORMAT_CMP_EQUAL
975                         && (options & AST_RTP_OPT_G726_NONSTANDARD)) {
976                         new_type->format = ast_format_g726_aal2;
977                 } else {
978                         new_type->format = t->payload_type.format;
979                 }
980                 if (new_type->format) {
981                         /* SDP parsing automatically increases the reference count */
982                         new_type->format = ast_format_parse_sdp_fmtp(new_type->format, "");
983                 }
984
985                 if (pt < AST_VECTOR_SIZE(&codecs->payload_mapping_tx)) {
986                         ao2_t_cleanup(AST_VECTOR_GET(&codecs->payload_mapping_tx, pt),
987                                 "cleaning up replaced tx payload type");
988                 }
989                 AST_VECTOR_REPLACE(&codecs->payload_mapping_tx, pt, new_type);
990
991                 if (instance && instance->engine && instance->engine->payload_set) {
992                         instance->engine->payload_set(instance, pt, new_type->asterisk_format, new_type->format, new_type->rtp_code);
993                 }
994
995                 payload_mapping_tx_remove_other_mappings(codecs, instance, new_type);
996                 break;
997         }
998
999         ast_rwlock_unlock(&codecs->codecs_lock);
1000         ast_rwlock_unlock(&mime_types_lock);
1001
1002         return (found ? 0 : -2);
1003 }
1004
1005 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)
1006 {
1007         return ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, instance, payload, mimetype, mimesubtype, options, 0);
1008 }
1009
1010 void ast_rtp_codecs_payloads_unset(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, int payload)
1011 {
1012         struct ast_rtp_payload_type *type;
1013
1014         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
1015                 return;
1016         }
1017
1018         ast_debug(2, "Unsetting payload %d on %p\n", payload, codecs);
1019
1020         ast_rwlock_wrlock(&codecs->codecs_lock);
1021
1022         if (payload < AST_VECTOR_SIZE(&codecs->payload_mapping_tx)) {
1023                 type = AST_VECTOR_GET(&codecs->payload_mapping_tx, payload);
1024                 ao2_cleanup(type);
1025                 AST_VECTOR_REPLACE(&codecs->payload_mapping_tx, payload, NULL);
1026         }
1027
1028         if (instance && instance->engine && instance->engine->payload_set) {
1029                 instance->engine->payload_set(instance, payload, 0, NULL, 0);
1030         }
1031
1032         ast_rwlock_unlock(&codecs->codecs_lock);
1033 }
1034
1035 struct ast_rtp_payload_type *ast_rtp_codecs_get_payload(struct ast_rtp_codecs *codecs, int payload)
1036 {
1037         struct ast_rtp_payload_type *type = NULL;
1038
1039         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
1040                 return NULL;
1041         }
1042
1043         ast_rwlock_rdlock(&codecs->codecs_lock);
1044         if (payload < AST_VECTOR_SIZE(&codecs->payload_mapping_rx)) {
1045                 type = AST_VECTOR_GET(&codecs->payload_mapping_rx, payload);
1046                 ao2_bump(type);
1047         }
1048         ast_rwlock_unlock(&codecs->codecs_lock);
1049
1050         if (!type) {
1051                 ast_rwlock_rdlock(&static_RTP_PT_lock);
1052                 type = ao2_bump(static_RTP_PT[payload]);
1053                 ast_rwlock_unlock(&static_RTP_PT_lock);
1054         }
1055
1056         return type;
1057 }
1058
1059 int ast_rtp_codecs_payload_replace_format(struct ast_rtp_codecs *codecs, int payload, struct ast_format *format)
1060 {
1061         struct ast_rtp_payload_type *type;
1062
1063         if (payload < 0 || payload >= AST_RTP_MAX_PT || !format) {
1064                 return -1;
1065         }
1066
1067         type = ast_rtp_engine_alloc_payload_type();
1068         if (!type) {
1069                 return -1;
1070         }
1071         ao2_ref(format, +1);
1072         type->format = format;
1073         type->asterisk_format = 1;
1074         type->payload = payload;
1075         type->primary_mapping = 1;
1076
1077         ast_rwlock_wrlock(&codecs->codecs_lock);
1078         if (payload < AST_VECTOR_SIZE(&codecs->payload_mapping_tx)) {
1079                 ao2_cleanup(AST_VECTOR_GET(&codecs->payload_mapping_tx, payload));
1080         }
1081         AST_VECTOR_REPLACE(&codecs->payload_mapping_tx, payload, type);
1082         payload_mapping_tx_remove_other_mappings(codecs, NULL, type);
1083         ast_rwlock_unlock(&codecs->codecs_lock);
1084
1085         return 0;
1086 }
1087
1088 struct ast_format *ast_rtp_codecs_get_payload_format(struct ast_rtp_codecs *codecs, int payload)
1089 {
1090         struct ast_rtp_payload_type *type;
1091         struct ast_format *format = NULL;
1092
1093         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
1094                 return NULL;
1095         }
1096
1097         ast_rwlock_rdlock(&codecs->codecs_lock);
1098         if (payload < AST_VECTOR_SIZE(&codecs->payload_mapping_tx)) {
1099                 type = AST_VECTOR_GET(&codecs->payload_mapping_tx, payload);
1100                 if (type && type->asterisk_format) {
1101                         format = ao2_bump(type->format);
1102                 }
1103         }
1104         ast_rwlock_unlock(&codecs->codecs_lock);
1105
1106         return format;
1107 }
1108
1109 void ast_rtp_codecs_set_framing(struct ast_rtp_codecs *codecs, unsigned int framing)
1110 {
1111         if (!framing) {
1112                 return;
1113         }
1114
1115         ast_rwlock_wrlock(&codecs->codecs_lock);
1116         codecs->framing = framing;
1117         ast_rwlock_unlock(&codecs->codecs_lock);
1118 }
1119
1120 unsigned int ast_rtp_codecs_get_framing(struct ast_rtp_codecs *codecs)
1121 {
1122         unsigned int framing;
1123
1124         ast_rwlock_rdlock(&codecs->codecs_lock);
1125         framing = codecs->framing;
1126         ast_rwlock_unlock(&codecs->codecs_lock);
1127
1128         return framing;
1129 }
1130
1131 void ast_rtp_codecs_payload_formats(struct ast_rtp_codecs *codecs, struct ast_format_cap *astformats, int *nonastformats)
1132 {
1133         int idx;
1134
1135         ast_format_cap_remove_by_type(astformats, AST_MEDIA_TYPE_UNKNOWN);
1136         *nonastformats = 0;
1137
1138         ast_rwlock_rdlock(&codecs->codecs_lock);
1139
1140         for (idx = 0; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_tx); ++idx) {
1141                 struct ast_rtp_payload_type *type;
1142
1143                 type = AST_VECTOR_GET(&codecs->payload_mapping_tx, idx);
1144                 if (!type) {
1145                         continue;
1146                 }
1147
1148                 if (type->asterisk_format) {
1149                         ast_format_cap_append(astformats, type->format, 0);
1150                 } else {
1151                         *nonastformats |= type->rtp_code;
1152                 }
1153         }
1154         if (codecs->framing) {
1155                 ast_format_cap_set_framing(astformats, codecs->framing);
1156         }
1157
1158         ast_rwlock_unlock(&codecs->codecs_lock);
1159 }
1160
1161 /*!
1162  * \internal
1163  * \brief Find the static payload type mapping for the format.
1164  * \since 14.0.0
1165  *
1166  * \param asterisk_format Non-zero if the given Asterisk format is present
1167  * \param format Asterisk format to look for
1168  * \param code The non-Asterisk format code to look for
1169  *
1170  * \note It is assumed that static_RTP_PT_lock is at least read locked before calling.
1171  *
1172  * \retval Numerical payload type
1173  * \retval -1 if not found.
1174  */
1175 static int find_static_payload_type(int asterisk_format, const struct ast_format *format, int code)
1176 {
1177         int idx;
1178         int payload = -1;
1179
1180         if (!asterisk_format) {
1181                 for (idx = 0; idx < AST_RTP_MAX_PT; ++idx) {
1182                         if (static_RTP_PT[idx]
1183                                 && !static_RTP_PT[idx]->asterisk_format
1184                                 && static_RTP_PT[idx]->rtp_code == code) {
1185                                 payload = idx;
1186                                 break;
1187                         }
1188                 }
1189         } else if (format) {
1190                 for (idx = 0; idx < AST_RTP_MAX_PT; ++idx) {
1191                         if (static_RTP_PT[idx]
1192                                 && static_RTP_PT[idx]->asterisk_format
1193                                 && ast_format_cmp(format, static_RTP_PT[idx]->format)
1194                                         != AST_FORMAT_CMP_NOT_EQUAL) {
1195                                 payload = idx;
1196                                 break;
1197                         }
1198                 }
1199         }
1200
1201         return payload;
1202 }
1203
1204 /*!
1205  * \internal
1206  * \brief Find the first unused dynamic rx payload type.
1207  * \since 14.0.0
1208  *
1209  * \param codecs Codecs structure to look in
1210  *
1211  * \note It is assumed that codecs is at least read locked before calling.
1212  *
1213  * \retval Numerical payload type
1214  * \retval -1 if not found.
1215  */
1216 static int rtp_codecs_find_empty_dynamic_rx(struct ast_rtp_codecs *codecs)
1217 {
1218         struct ast_rtp_payload_type *type;
1219         int idx;
1220         int payload = -1;
1221
1222         idx = AST_RTP_PT_FIRST_DYNAMIC;
1223         for (; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_rx); ++idx) {
1224                 type = AST_VECTOR_GET(&codecs->payload_mapping_rx, idx);
1225                 if (!type) {
1226                         payload = idx;
1227                         break;
1228                 }
1229         }
1230         return payload;
1231 }
1232
1233 /*!
1234  * \internal
1235  * \brief Find the oldest non-primary dynamic rx payload type.
1236  * \since 14.0.0
1237  *
1238  * \param codecs Codecs structure to look in
1239  *
1240  * \note It is assumed that codecs is at least read locked before calling.
1241  *
1242  * \retval Numerical payload type
1243  * \retval -1 if not found.
1244  */
1245 static int rtp_codecs_find_non_primary_dynamic_rx(struct ast_rtp_codecs *codecs)
1246 {
1247         struct ast_rtp_payload_type *type;
1248         struct timeval oldest;
1249         int idx;
1250         int payload = -1;
1251
1252         idx = AST_RTP_PT_FIRST_DYNAMIC;
1253         for (; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_rx); ++idx) {
1254                 type = AST_VECTOR_GET(&codecs->payload_mapping_rx, idx);
1255                 if (type
1256                         && !type->primary_mapping
1257                         && (payload == -1
1258                                 || ast_tvdiff_ms(type->when_retired, oldest) < 0)) {
1259                         oldest = type->when_retired;
1260                         payload = idx;
1261                 }
1262         }
1263         return payload;
1264 }
1265
1266 /*!
1267  * \internal
1268  * \brief Assign a payload type for the rx mapping.
1269  * \since 14.0.0
1270  *
1271  * \param codecs Codecs structure to look in
1272  * \param asterisk_format Non-zero if the given Asterisk format is present
1273  * \param format Asterisk format to look for
1274  * \param code The format to look for
1275  *
1276  * \note It is assumed that static_RTP_PT_lock is at least read locked before calling.
1277  *
1278  * \retval Numerical payload type
1279  * \retval -1 if could not assign.
1280  */
1281 static int rtp_codecs_assign_payload_code_rx(struct ast_rtp_codecs *codecs, int asterisk_format, struct ast_format *format, int code)
1282 {
1283         int payload;
1284         struct ast_rtp_payload_type *new_type;
1285
1286         payload = find_static_payload_type(asterisk_format, format, code);
1287         if (payload < 0) {
1288                 return payload;
1289         }
1290
1291         new_type = ast_rtp_engine_alloc_payload_type();
1292         if (!new_type) {
1293                 return -1;
1294         }
1295         new_type->format = ao2_bump(format);
1296         new_type->asterisk_format = asterisk_format;
1297         new_type->rtp_code = code;
1298         new_type->payload = payload;
1299         new_type->primary_mapping = 1;
1300
1301         ast_rwlock_wrlock(&codecs->codecs_lock);
1302         if (payload < AST_RTP_PT_FIRST_DYNAMIC
1303                 || AST_VECTOR_SIZE(&codecs->payload_mapping_rx) <= payload
1304                 || !AST_VECTOR_GET(&codecs->payload_mapping_rx, payload)) {
1305                 /*
1306                  * The payload type is a static assignment
1307                  * or our default dynamic position is available.
1308                  */
1309                 rtp_codecs_payload_replace_rx(codecs, payload, new_type);
1310         } else if (-1 < (payload = rtp_codecs_find_empty_dynamic_rx(codecs))
1311                 || -1 < (payload = rtp_codecs_find_non_primary_dynamic_rx(codecs))) {
1312                 /*
1313                  * We found the first available empty dynamic position
1314                  * or we found a mapping that should no longer be
1315                  * actively used.
1316                  */
1317                 new_type->payload = payload;
1318                 rtp_codecs_payload_replace_rx(codecs, payload, new_type);
1319         } else {
1320                 /*
1321                  * There are no empty or non-primary dynamic positions
1322                  * left.  Sadness.
1323                  *
1324                  * I don't think this is really possible.
1325                  */
1326                 ast_log(LOG_WARNING, "No dynamic RTP payload type values available!\n");
1327         }
1328         ast_rwlock_unlock(&codecs->codecs_lock);
1329
1330         ao2_ref(new_type, -1);
1331
1332         return payload;
1333 }
1334
1335 int ast_rtp_codecs_payload_code(struct ast_rtp_codecs *codecs, int asterisk_format, struct ast_format *format, int code)
1336 {
1337         struct ast_rtp_payload_type *type;
1338         int idx;
1339         int payload = -1;
1340
1341         ast_rwlock_rdlock(&static_RTP_PT_lock);
1342         if (!asterisk_format) {
1343                 ast_rwlock_rdlock(&codecs->codecs_lock);
1344                 for (idx = 0; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_rx); ++idx) {
1345                         type = AST_VECTOR_GET(&codecs->payload_mapping_rx, idx);
1346                         if (!type) {
1347                                 continue;
1348                         }
1349
1350                         if (!type->asterisk_format
1351                                 && type->primary_mapping
1352                                 && type->rtp_code == code) {
1353                                 payload = idx;
1354                                 break;
1355                         }
1356                 }
1357                 ast_rwlock_unlock(&codecs->codecs_lock);
1358         } else if (format) {
1359                 ast_rwlock_rdlock(&codecs->codecs_lock);
1360                 for (idx = 0; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_rx); ++idx) {
1361                         type = AST_VECTOR_GET(&codecs->payload_mapping_rx, idx);
1362                         if (!type) {
1363                                 continue;
1364                         }
1365
1366                         if (type->asterisk_format
1367                                 && type->primary_mapping
1368                                 && ast_format_cmp(format, type->format) == AST_FORMAT_CMP_EQUAL) {
1369                                 payload = idx;
1370                                 break;
1371                         }
1372                 }
1373                 ast_rwlock_unlock(&codecs->codecs_lock);
1374         }
1375
1376         if (payload < 0) {
1377                 payload = rtp_codecs_assign_payload_code_rx(codecs, asterisk_format, format,
1378                         code);
1379         }
1380         ast_rwlock_unlock(&static_RTP_PT_lock);
1381
1382         return payload;
1383 }
1384
1385 int ast_rtp_codecs_payload_code_tx(struct ast_rtp_codecs *codecs, int asterisk_format, const struct ast_format *format, int code)
1386 {
1387         struct ast_rtp_payload_type *type;
1388         int idx;
1389         int payload = -1;
1390
1391         if (!asterisk_format) {
1392                 ast_rwlock_rdlock(&codecs->codecs_lock);
1393                 for (idx = 0; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_tx); ++idx) {
1394                         type = AST_VECTOR_GET(&codecs->payload_mapping_tx, idx);
1395                         if (!type) {
1396                                 continue;
1397                         }
1398
1399                         if (!type->asterisk_format
1400                                 && type->rtp_code == code) {
1401                                 payload = idx;
1402                                 break;
1403                         }
1404                 }
1405                 ast_rwlock_unlock(&codecs->codecs_lock);
1406         } else if (format) {
1407                 ast_rwlock_rdlock(&codecs->codecs_lock);
1408                 for (idx = 0; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_tx); ++idx) {
1409                         type = AST_VECTOR_GET(&codecs->payload_mapping_tx, idx);
1410                         if (!type) {
1411                                 continue;
1412                         }
1413
1414                         if (type->asterisk_format
1415                                 && ast_format_cmp(format, type->format) == AST_FORMAT_CMP_EQUAL) {
1416                                 payload = idx;
1417                                 break;
1418                         }
1419                 }
1420                 ast_rwlock_unlock(&codecs->codecs_lock);
1421         }
1422
1423         if (payload < 0) {
1424                 ast_rwlock_rdlock(&static_RTP_PT_lock);
1425                 payload = find_static_payload_type(asterisk_format, format, code);
1426                 ast_rwlock_unlock(&static_RTP_PT_lock);
1427         }
1428
1429         return payload;
1430 }
1431
1432 int ast_rtp_codecs_find_payload_code(struct ast_rtp_codecs *codecs, int payload)
1433 {
1434         struct ast_rtp_payload_type *type;
1435         int res = -1;
1436
1437         ast_rwlock_rdlock(&codecs->codecs_lock);
1438         if (payload < AST_VECTOR_SIZE(&codecs->payload_mapping_tx)) {
1439                 type = AST_VECTOR_GET(&codecs->payload_mapping_tx, payload);
1440                 if (type) {
1441                         res = payload;
1442                 }
1443         }
1444         ast_rwlock_unlock(&codecs->codecs_lock);
1445
1446         return res;
1447 }
1448
1449 const char *ast_rtp_lookup_mime_subtype2(const int asterisk_format, struct ast_format *format, int code, enum ast_rtp_options options)
1450 {
1451         int i;
1452         const char *res = "";
1453
1454         ast_rwlock_rdlock(&mime_types_lock);
1455         for (i = 0; i < mime_types_len; i++) {
1456                 if (ast_rtp_mime_types[i].payload_type.asterisk_format && asterisk_format && format &&
1457                         (ast_format_cmp(format, ast_rtp_mime_types[i].payload_type.format) != AST_FORMAT_CMP_NOT_EQUAL)) {
1458                         if ((ast_format_cmp(format, ast_format_g726_aal2) == AST_FORMAT_CMP_EQUAL) &&
1459                                         (options & AST_RTP_OPT_G726_NONSTANDARD)) {
1460                                 res = "G726-32";
1461                                 break;
1462                         } else {
1463                                 res = ast_rtp_mime_types[i].subtype;
1464                                 break;
1465                         }
1466                 } else if (!ast_rtp_mime_types[i].payload_type.asterisk_format && !asterisk_format &&
1467                         ast_rtp_mime_types[i].payload_type.rtp_code == code) {
1468
1469                         res = ast_rtp_mime_types[i].subtype;
1470                         break;
1471                 }
1472         }
1473         ast_rwlock_unlock(&mime_types_lock);
1474
1475         return res;
1476 }
1477
1478 unsigned int ast_rtp_lookup_sample_rate2(int asterisk_format, struct ast_format *format, int code)
1479 {
1480         unsigned int i;
1481         unsigned int res = 0;
1482
1483         ast_rwlock_rdlock(&mime_types_lock);
1484         for (i = 0; i < mime_types_len; ++i) {
1485                 if (ast_rtp_mime_types[i].payload_type.asterisk_format && asterisk_format && format &&
1486                         (ast_format_cmp(format, ast_rtp_mime_types[i].payload_type.format) != AST_FORMAT_CMP_NOT_EQUAL)) {
1487                         res = ast_rtp_mime_types[i].sample_rate;
1488                         break;
1489                 } else if (!ast_rtp_mime_types[i].payload_type.asterisk_format && !asterisk_format &&
1490                         ast_rtp_mime_types[i].payload_type.rtp_code == code) {
1491                         res = ast_rtp_mime_types[i].sample_rate;
1492                         break;
1493                 }
1494         }
1495         ast_rwlock_unlock(&mime_types_lock);
1496
1497         return res;
1498 }
1499
1500 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)
1501 {
1502         int found = 0;
1503         const char *name;
1504         if (!buf) {
1505                 return NULL;
1506         }
1507
1508
1509         if (asterisk_format) {
1510                 int x;
1511                 struct ast_format *tmp_fmt;
1512                 for (x = 0; x < ast_format_cap_count(ast_format_capability); x++) {
1513                         tmp_fmt = ast_format_cap_get_format(ast_format_capability, x);
1514                         name = ast_rtp_lookup_mime_subtype2(asterisk_format, tmp_fmt, 0, options);
1515                         ao2_ref(tmp_fmt, -1);
1516                         ast_str_append(&buf, 0, "%s|", name);
1517                         found = 1;
1518                 }
1519         } else {
1520                 int x;
1521                 ast_str_append(&buf, 0, "0x%x (", (unsigned int) rtp_capability);
1522                 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
1523                         if (rtp_capability & x) {
1524                                 name = ast_rtp_lookup_mime_subtype2(asterisk_format, NULL, x, options);
1525                                 ast_str_append(&buf, 0, "%s|", name);
1526                                 found = 1;
1527                         }
1528                 }
1529         }
1530
1531         ast_str_append(&buf, 0, "%s", found ? ")" : "nothing)");
1532
1533         return ast_str_buffer(buf);
1534 }
1535
1536 int ast_rtp_instance_dtmf_begin(struct ast_rtp_instance *instance, char digit)
1537 {
1538         return instance->engine->dtmf_begin ? instance->engine->dtmf_begin(instance, digit) : -1;
1539 }
1540
1541 int ast_rtp_instance_dtmf_end(struct ast_rtp_instance *instance, char digit)
1542 {
1543         return instance->engine->dtmf_end ? instance->engine->dtmf_end(instance, digit) : -1;
1544 }
1545 int ast_rtp_instance_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
1546 {
1547         return instance->engine->dtmf_end_with_duration ? instance->engine->dtmf_end_with_duration(instance, digit, duration) : -1;
1548 }
1549
1550 int ast_rtp_instance_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
1551 {
1552         return (!instance->engine->dtmf_mode_set || instance->engine->dtmf_mode_set(instance, dtmf_mode)) ? -1 : 0;
1553 }
1554
1555 enum ast_rtp_dtmf_mode ast_rtp_instance_dtmf_mode_get(struct ast_rtp_instance *instance)
1556 {
1557         return instance->engine->dtmf_mode_get ? instance->engine->dtmf_mode_get(instance) : 0;
1558 }
1559
1560 void ast_rtp_instance_update_source(struct ast_rtp_instance *instance)
1561 {
1562         if (instance->engine->update_source) {
1563                 instance->engine->update_source(instance);
1564         }
1565 }
1566
1567 void ast_rtp_instance_change_source(struct ast_rtp_instance *instance)
1568 {
1569         if (instance->engine->change_source) {
1570                 instance->engine->change_source(instance);
1571         }
1572 }
1573
1574 int ast_rtp_instance_set_qos(struct ast_rtp_instance *instance, int tos, int cos, const char *desc)
1575 {
1576         return instance->engine->qos ? instance->engine->qos(instance, tos, cos, desc) : -1;
1577 }
1578
1579 void ast_rtp_instance_stop(struct ast_rtp_instance *instance)
1580 {
1581         if (instance->engine->stop) {
1582                 instance->engine->stop(instance);
1583         }
1584 }
1585
1586 int ast_rtp_instance_fd(struct ast_rtp_instance *instance, int rtcp)
1587 {
1588         return instance->engine->fd ? instance->engine->fd(instance, rtcp) : -1;
1589 }
1590
1591 struct ast_rtp_glue *ast_rtp_instance_get_glue(const char *type)
1592 {
1593         struct ast_rtp_glue *glue = NULL;
1594
1595         AST_RWLIST_RDLOCK(&glues);
1596
1597         AST_RWLIST_TRAVERSE(&glues, glue, entry) {
1598                 if (!strcasecmp(glue->type, type)) {
1599                         break;
1600                 }
1601         }
1602
1603         AST_RWLIST_UNLOCK(&glues);
1604
1605         return glue;
1606 }
1607
1608 /*!
1609  * \brief Conditionally unref an rtp instance
1610  */
1611 static void unref_instance_cond(struct ast_rtp_instance **instance)
1612 {
1613         if (*instance) {
1614                 ao2_ref(*instance, -1);
1615                 *instance = NULL;
1616         }
1617 }
1618
1619 struct ast_rtp_instance *ast_rtp_instance_get_bridged(struct ast_rtp_instance *instance)
1620 {
1621         return instance->bridged;
1622 }
1623
1624 void ast_rtp_instance_set_bridged(struct ast_rtp_instance *instance, struct ast_rtp_instance *bridged)
1625 {
1626         instance->bridged = bridged;
1627 }
1628
1629 void ast_rtp_instance_early_bridge_make_compatible(struct ast_channel *c_dst, struct ast_channel *c_src)
1630 {
1631         struct ast_rtp_instance *instance_dst = NULL, *instance_src = NULL,
1632                 *vinstance_dst = NULL, *vinstance_src = NULL,
1633                 *tinstance_dst = NULL, *tinstance_src = NULL;
1634         struct ast_rtp_glue *glue_dst, *glue_src;
1635         enum ast_rtp_glue_result audio_glue_dst_res = AST_RTP_GLUE_RESULT_FORBID, video_glue_dst_res = AST_RTP_GLUE_RESULT_FORBID;
1636         enum ast_rtp_glue_result audio_glue_src_res = AST_RTP_GLUE_RESULT_FORBID, video_glue_src_res = AST_RTP_GLUE_RESULT_FORBID;
1637         struct ast_format_cap *cap_dst = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1638         struct ast_format_cap *cap_src = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1639
1640         /* Lock both channels so we can look for the glue that binds them together */
1641         ast_channel_lock_both(c_dst, c_src);
1642
1643         if (!cap_src || !cap_dst) {
1644                 goto done;
1645         }
1646
1647         /* Grab glue that binds each channel to something using the RTP engine */
1648         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))) {
1649                 ast_debug(1, "Can't find native functions for channel '%s'\n", glue_dst ? ast_channel_name(c_src) : ast_channel_name(c_dst));
1650                 goto done;
1651         }
1652
1653         audio_glue_dst_res = glue_dst->get_rtp_info(c_dst, &instance_dst);
1654         video_glue_dst_res = glue_dst->get_vrtp_info ? glue_dst->get_vrtp_info(c_dst, &vinstance_dst) : AST_RTP_GLUE_RESULT_FORBID;
1655
1656         audio_glue_src_res = glue_src->get_rtp_info(c_src, &instance_src);
1657         video_glue_src_res = glue_src->get_vrtp_info ? glue_src->get_vrtp_info(c_src, &vinstance_src) : AST_RTP_GLUE_RESULT_FORBID;
1658
1659         /* If we are carrying video, and both sides are not going to remotely bridge... fail the native bridge */
1660         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)) {
1661                 audio_glue_dst_res = AST_RTP_GLUE_RESULT_FORBID;
1662         }
1663         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)) {
1664                 audio_glue_src_res = AST_RTP_GLUE_RESULT_FORBID;
1665         }
1666         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) {
1667                 glue_dst->get_codec(c_dst, cap_dst);
1668         }
1669         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) {
1670                 glue_src->get_codec(c_src, cap_src);
1671         }
1672
1673         /* If any sort of bridge is forbidden just completely bail out and go back to generic bridging */
1674         if (audio_glue_dst_res != AST_RTP_GLUE_RESULT_REMOTE || audio_glue_src_res != AST_RTP_GLUE_RESULT_REMOTE) {
1675                 goto done;
1676         }
1677
1678         /* Make sure we have matching codecs */
1679         if (!ast_format_cap_iscompatible(cap_dst, cap_src)) {
1680                 goto done;
1681         }
1682
1683         ast_rtp_codecs_payloads_xover(&instance_src->codecs, &instance_dst->codecs, instance_dst);
1684
1685         if (vinstance_dst && vinstance_src) {
1686                 ast_rtp_codecs_payloads_xover(&vinstance_src->codecs, &vinstance_dst->codecs, vinstance_dst);
1687         }
1688         if (tinstance_dst && tinstance_src) {
1689                 ast_rtp_codecs_payloads_xover(&tinstance_src->codecs, &tinstance_dst->codecs, tinstance_dst);
1690         }
1691
1692         if (glue_dst->update_peer(c_dst, instance_src, vinstance_src, tinstance_src, cap_src, 0)) {
1693                 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n",
1694                         ast_channel_name(c_dst), ast_channel_name(c_src));
1695         } else {
1696                 ast_debug(1, "Seeded SDP of '%s' with that of '%s'\n",
1697                         ast_channel_name(c_dst), ast_channel_name(c_src));
1698         }
1699
1700 done:
1701         ast_channel_unlock(c_dst);
1702         ast_channel_unlock(c_src);
1703
1704         ao2_cleanup(cap_dst);
1705         ao2_cleanup(cap_src);
1706
1707         unref_instance_cond(&instance_dst);
1708         unref_instance_cond(&instance_src);
1709         unref_instance_cond(&vinstance_dst);
1710         unref_instance_cond(&vinstance_src);
1711         unref_instance_cond(&tinstance_dst);
1712         unref_instance_cond(&tinstance_src);
1713 }
1714
1715 int ast_rtp_instance_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
1716 {
1717         struct ast_rtp_instance *instance0 = NULL, *instance1 = NULL,
1718                         *vinstance0 = NULL, *vinstance1 = NULL,
1719                         *tinstance0 = NULL, *tinstance1 = NULL;
1720         struct ast_rtp_glue *glue0, *glue1;
1721         enum ast_rtp_glue_result audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID, video_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1722         enum ast_rtp_glue_result audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID, video_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1723         struct ast_format_cap *cap0 = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1724         struct ast_format_cap *cap1 = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1725
1726         /* If there is no second channel just immediately bail out, we are of no use in that scenario */
1727         if (!c1 || !cap1 || !cap0) {
1728                 ao2_cleanup(cap0);
1729                 ao2_cleanup(cap1);
1730                 return -1;
1731         }
1732
1733         /* Lock both channels so we can look for the glue that binds them together */
1734         ast_channel_lock_both(c0, c1);
1735
1736         /* Grab glue that binds each channel to something using the RTP engine */
1737         if (!(glue0 = ast_rtp_instance_get_glue(ast_channel_tech(c0)->type)) || !(glue1 = ast_rtp_instance_get_glue(ast_channel_tech(c1)->type))) {
1738                 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", glue0 ? ast_channel_name(c1) : ast_channel_name(c0));
1739                 goto done;
1740         }
1741
1742         audio_glue0_res = glue0->get_rtp_info(c0, &instance0);
1743         video_glue0_res = glue0->get_vrtp_info ? glue0->get_vrtp_info(c0, &vinstance0) : AST_RTP_GLUE_RESULT_FORBID;
1744
1745         audio_glue1_res = glue1->get_rtp_info(c1, &instance1);
1746         video_glue1_res = glue1->get_vrtp_info ? glue1->get_vrtp_info(c1, &vinstance1) : AST_RTP_GLUE_RESULT_FORBID;
1747
1748         /* If we are carrying video, and both sides are not going to remotely bridge... fail the native bridge */
1749         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)) {
1750                 audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1751         }
1752         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)) {
1753                 audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1754         }
1755         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) {
1756                 glue0->get_codec(c0, cap0);
1757         }
1758         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) {
1759                 glue1->get_codec(c1, cap1);
1760         }
1761
1762         /* If any sort of bridge is forbidden just completely bail out and go back to generic bridging */
1763         if (audio_glue0_res != AST_RTP_GLUE_RESULT_REMOTE || audio_glue1_res != AST_RTP_GLUE_RESULT_REMOTE) {
1764                 goto done;
1765         }
1766
1767         /* Make sure we have matching codecs */
1768         if (!ast_format_cap_iscompatible(cap0, cap1)) {
1769                 goto done;
1770         }
1771
1772         /* Bridge media early */
1773         if (glue0->update_peer(c0, instance1, vinstance1, tinstance1, cap1, 0)) {
1774                 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", ast_channel_name(c0), c1 ? ast_channel_name(c1) : "<unspecified>");
1775         }
1776
1777 done:
1778         ast_channel_unlock(c0);
1779         ast_channel_unlock(c1);
1780
1781         ao2_cleanup(cap0);
1782         ao2_cleanup(cap1);
1783
1784         unref_instance_cond(&instance0);
1785         unref_instance_cond(&instance1);
1786         unref_instance_cond(&vinstance0);
1787         unref_instance_cond(&vinstance1);
1788         unref_instance_cond(&tinstance0);
1789         unref_instance_cond(&tinstance1);
1790
1791         ast_debug(1, "Setting early bridge SDP of '%s' with that of '%s'\n", ast_channel_name(c0), c1 ? ast_channel_name(c1) : "<unspecified>");
1792
1793         return 0;
1794 }
1795
1796 int ast_rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations)
1797 {
1798         return instance->engine->red_init ? instance->engine->red_init(instance, buffer_time, payloads, generations) : -1;
1799 }
1800
1801 int ast_rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame)
1802 {
1803         return instance->engine->red_buffer ? instance->engine->red_buffer(instance, frame) : -1;
1804 }
1805
1806 int ast_rtp_instance_get_stats(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat)
1807 {
1808         return instance->engine->get_stat ? instance->engine->get_stat(instance, stats, stat) : -1;
1809 }
1810
1811 char *ast_rtp_instance_get_quality(struct ast_rtp_instance *instance, enum ast_rtp_instance_stat_field field, char *buf, size_t size)
1812 {
1813         struct ast_rtp_instance_stats stats = { 0, };
1814         enum ast_rtp_instance_stat stat;
1815
1816         /* Determine what statistics we will need to retrieve based on field passed in */
1817         if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY) {
1818                 stat = AST_RTP_INSTANCE_STAT_ALL;
1819         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER) {
1820                 stat = AST_RTP_INSTANCE_STAT_COMBINED_JITTER;
1821         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS) {
1822                 stat = AST_RTP_INSTANCE_STAT_COMBINED_LOSS;
1823         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT) {
1824                 stat = AST_RTP_INSTANCE_STAT_COMBINED_RTT;
1825         } else {
1826                 return NULL;
1827         }
1828
1829         /* Attempt to actually retrieve the statistics we need to generate the quality string */
1830         if (ast_rtp_instance_get_stats(instance, &stats, stat)) {
1831                 return NULL;
1832         }
1833
1834         /* Now actually fill the buffer with the good information */
1835         if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY) {
1836                 snprintf(buf, size, "ssrc=%u;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f",
1837                          stats.local_ssrc, stats.remote_ssrc, stats.rxploss, stats.rxjitter, stats.rxcount, stats.txjitter, stats.txcount, stats.txploss, stats.rtt);
1838         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER) {
1839                 snprintf(buf, size, "minrxjitter=%f;maxrxjitter=%f;avgrxjitter=%f;stdevrxjitter=%f;reported_minjitter=%f;reported_maxjitter=%f;reported_avgjitter=%f;reported_stdevjitter=%f;",
1840                          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));
1841         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS) {
1842                 snprintf(buf, size, "minrxlost=%f;maxrxlost=%f;avgrxlost=%f;stdevrxlost=%f;reported_minlost=%f;reported_maxlost=%f;reported_avglost=%f;reported_stdevlost=%f;",
1843                          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));
1844         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT) {
1845                 snprintf(buf, size, "minrtt=%f;maxrtt=%f;avgrtt=%f;stdevrtt=%f;", stats.minrtt, stats.maxrtt, stats.normdevrtt, stats.stdevrtt);
1846         }
1847
1848         return buf;
1849 }
1850
1851 void ast_rtp_instance_set_stats_vars(struct ast_channel *chan, struct ast_rtp_instance *instance)
1852 {
1853         char quality_buf[AST_MAX_USER_FIELD];
1854         char *quality;
1855         struct ast_channel *bridge = ast_channel_bridge_peer(chan);
1856
1857         ast_channel_lock(chan);
1858         ast_channel_stage_snapshot(chan);
1859         ast_channel_unlock(chan);
1860         if (bridge) {
1861                 ast_channel_lock(bridge);
1862                 ast_channel_stage_snapshot(bridge);
1863                 ast_channel_unlock(bridge);
1864         }
1865
1866         quality = ast_rtp_instance_get_quality(instance, AST_RTP_INSTANCE_STAT_FIELD_QUALITY,
1867                 quality_buf, sizeof(quality_buf));
1868         if (quality) {
1869                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOS", quality);
1870                 if (bridge) {
1871                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSBRIDGED", quality);
1872                 }
1873         }
1874
1875         quality = ast_rtp_instance_get_quality(instance,
1876                 AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf));
1877         if (quality) {
1878                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSJITTER", quality);
1879                 if (bridge) {
1880                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSJITTERBRIDGED", quality);
1881                 }
1882         }
1883
1884         quality = ast_rtp_instance_get_quality(instance,
1885                 AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf));
1886         if (quality) {
1887                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSLOSS", quality);
1888                 if (bridge) {
1889                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSLOSSBRIDGED", quality);
1890                 }
1891         }
1892
1893         quality = ast_rtp_instance_get_quality(instance,
1894                 AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf));
1895         if (quality) {
1896                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSRTT", quality);
1897                 if (bridge) {
1898                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSRTTBRIDGED", quality);
1899                 }
1900         }
1901
1902         ast_channel_lock(chan);
1903         ast_channel_stage_snapshot_done(chan);
1904         ast_channel_unlock(chan);
1905         if (bridge) {
1906                 ast_channel_lock(bridge);
1907                 ast_channel_stage_snapshot_done(bridge);
1908                 ast_channel_unlock(bridge);
1909                 ast_channel_unref(bridge);
1910         }
1911 }
1912
1913 int ast_rtp_instance_set_read_format(struct ast_rtp_instance *instance, struct ast_format *format)
1914 {
1915         return instance->engine->set_read_format ? instance->engine->set_read_format(instance, format) : -1;
1916 }
1917
1918 int ast_rtp_instance_set_write_format(struct ast_rtp_instance *instance, struct ast_format *format)
1919 {
1920         return instance->engine->set_write_format ? instance->engine->set_write_format(instance, format) : -1;
1921 }
1922
1923 int ast_rtp_instance_make_compatible(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_channel *peer)
1924 {
1925         struct ast_rtp_glue *glue;
1926         struct ast_rtp_instance *peer_instance = NULL;
1927         int res = -1;
1928
1929         if (!instance->engine->make_compatible) {
1930                 return -1;
1931         }
1932
1933         ast_channel_lock(peer);
1934
1935         if (!(glue = ast_rtp_instance_get_glue(ast_channel_tech(peer)->type))) {
1936                 ast_channel_unlock(peer);
1937                 return -1;
1938         }
1939
1940         glue->get_rtp_info(peer, &peer_instance);
1941         if (!peer_instance) {
1942                 ast_log(LOG_ERROR, "Unable to get_rtp_info for peer type %s\n", glue->type);
1943                 ast_channel_unlock(peer);
1944                 return -1;
1945         }
1946         if (peer_instance->engine != instance->engine) {
1947                 ast_log(LOG_ERROR, "Peer engine mismatch for type %s\n", glue->type);
1948                 ast_channel_unlock(peer);
1949                 ao2_ref(peer_instance, -1);
1950                 return -1;
1951         }
1952
1953         res = instance->engine->make_compatible(chan, instance, peer, peer_instance);
1954
1955         ast_channel_unlock(peer);
1956
1957         ao2_ref(peer_instance, -1);
1958         peer_instance = NULL;
1959
1960         return res;
1961 }
1962
1963 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)
1964 {
1965         if (instance->engine->available_formats) {
1966                 instance->engine->available_formats(instance, to_endpoint, to_asterisk, result);
1967                 if (ast_format_cap_count(result)) {
1968                         return;
1969                 }
1970         }
1971
1972         ast_translate_available_formats(to_endpoint, to_asterisk, result);
1973 }
1974
1975 int ast_rtp_instance_activate(struct ast_rtp_instance *instance)
1976 {
1977         return instance->engine->activate ? instance->engine->activate(instance) : 0;
1978 }
1979
1980 void ast_rtp_instance_stun_request(struct ast_rtp_instance *instance,
1981                                    struct ast_sockaddr *suggestion,
1982                                    const char *username)
1983 {
1984         if (instance->engine->stun_request) {
1985                 instance->engine->stun_request(instance, suggestion, username);
1986         }
1987 }
1988
1989 void ast_rtp_instance_set_timeout(struct ast_rtp_instance *instance, int timeout)
1990 {
1991         instance->timeout = timeout;
1992 }
1993
1994 void ast_rtp_instance_set_hold_timeout(struct ast_rtp_instance *instance, int timeout)
1995 {
1996         instance->holdtimeout = timeout;
1997 }
1998
1999 void ast_rtp_instance_set_keepalive(struct ast_rtp_instance *instance, int interval)
2000 {
2001         instance->keepalive = interval;
2002 }
2003
2004 int ast_rtp_instance_get_timeout(struct ast_rtp_instance *instance)
2005 {
2006         return instance->timeout;
2007 }
2008
2009 int ast_rtp_instance_get_hold_timeout(struct ast_rtp_instance *instance)
2010 {
2011         return instance->holdtimeout;
2012 }
2013
2014 int ast_rtp_instance_get_keepalive(struct ast_rtp_instance *instance)
2015 {
2016         return instance->keepalive;
2017 }
2018
2019 struct ast_rtp_engine *ast_rtp_instance_get_engine(struct ast_rtp_instance *instance)
2020 {
2021         return instance->engine;
2022 }
2023
2024 struct ast_rtp_glue *ast_rtp_instance_get_active_glue(struct ast_rtp_instance *instance)
2025 {
2026         return instance->glue;
2027 }
2028
2029 int ast_rtp_engine_register_srtp(struct ast_srtp_res *srtp_res, struct ast_srtp_policy_res *policy_res)
2030 {
2031         if (res_srtp || res_srtp_policy) {
2032                 return -1;
2033         }
2034         if (!srtp_res || !policy_res) {
2035                 return -1;
2036         }
2037
2038         res_srtp = srtp_res;
2039         res_srtp_policy = policy_res;
2040
2041         return 0;
2042 }
2043
2044 void ast_rtp_engine_unregister_srtp(void)
2045 {
2046         res_srtp = NULL;
2047         res_srtp_policy = NULL;
2048 }
2049
2050 int ast_rtp_engine_srtp_is_registered(void)
2051 {
2052         return res_srtp && res_srtp_policy;
2053 }
2054
2055 int ast_rtp_instance_add_srtp_policy(struct ast_rtp_instance *instance, struct ast_srtp_policy *remote_policy, struct ast_srtp_policy *local_policy)
2056 {
2057         int res = 0;
2058
2059         if (!res_srtp) {
2060                 return -1;
2061         }
2062
2063         if (!instance->srtp) {
2064                 res = res_srtp->create(&instance->srtp, instance, remote_policy);
2065         } else {
2066                 res = res_srtp->replace(&instance->srtp, instance, remote_policy);
2067         }
2068         if (!res) {
2069                 res = res_srtp->add_stream(instance->srtp, local_policy);
2070         }
2071
2072         return res;
2073 }
2074
2075 struct ast_srtp *ast_rtp_instance_get_srtp(struct ast_rtp_instance *instance)
2076 {
2077         return instance->srtp;
2078 }
2079
2080 int ast_rtp_instance_sendcng(struct ast_rtp_instance *instance, int level)
2081 {
2082         if (instance->engine->sendcng) {
2083                 return instance->engine->sendcng(instance, level);
2084         }
2085
2086         return -1;
2087 }
2088
2089 struct ast_rtp_engine_ice *ast_rtp_instance_get_ice(struct ast_rtp_instance *instance)
2090 {
2091         return instance->engine->ice;
2092 }
2093
2094 struct ast_rtp_engine_dtls *ast_rtp_instance_get_dtls(struct ast_rtp_instance *instance)
2095 {
2096         return instance->engine->dtls;
2097 }
2098
2099 int ast_rtp_dtls_cfg_parse(struct ast_rtp_dtls_cfg *dtls_cfg, const char *name, const char *value)
2100 {
2101         if (!strcasecmp(name, "dtlsenable")) {
2102                 dtls_cfg->enabled = ast_true(value) ? 1 : 0;
2103         } else if (!strcasecmp(name, "dtlsverify")) {
2104                 if (!strcasecmp(value, "yes")) {
2105                         dtls_cfg->verify = AST_RTP_DTLS_VERIFY_FINGERPRINT | AST_RTP_DTLS_VERIFY_CERTIFICATE;
2106                 } else if (!strcasecmp(value, "fingerprint")) {
2107                         dtls_cfg->verify = AST_RTP_DTLS_VERIFY_FINGERPRINT;
2108                 } else if (!strcasecmp(value, "certificate")) {
2109                         dtls_cfg->verify = AST_RTP_DTLS_VERIFY_CERTIFICATE;
2110                 } else if (!strcasecmp(value, "no")) {
2111                         dtls_cfg->verify = AST_RTP_DTLS_VERIFY_NONE;
2112                 } else {
2113                         return -1;
2114                 }
2115         } else if (!strcasecmp(name, "dtlsrekey")) {
2116                 if (sscanf(value, "%30u", &dtls_cfg->rekey) != 1) {
2117                         return -1;
2118                 }
2119         } else if (!strcasecmp(name, "dtlscertfile")) {
2120                 ast_free(dtls_cfg->certfile);
2121                 dtls_cfg->certfile = ast_strdup(value);
2122         } else if (!strcasecmp(name, "dtlsprivatekey")) {
2123                 ast_free(dtls_cfg->pvtfile);
2124                 dtls_cfg->pvtfile = ast_strdup(value);
2125         } else if (!strcasecmp(name, "dtlscipher")) {
2126                 ast_free(dtls_cfg->cipher);
2127                 dtls_cfg->cipher = ast_strdup(value);
2128         } else if (!strcasecmp(name, "dtlscafile")) {
2129                 ast_free(dtls_cfg->cafile);
2130                 dtls_cfg->cafile = ast_strdup(value);
2131         } else if (!strcasecmp(name, "dtlscapath") || !strcasecmp(name, "dtlscadir")) {
2132                 ast_free(dtls_cfg->capath);
2133                 dtls_cfg->capath = ast_strdup(value);
2134         } else if (!strcasecmp(name, "dtlssetup")) {
2135                 if (!strcasecmp(value, "active")) {
2136                         dtls_cfg->default_setup = AST_RTP_DTLS_SETUP_ACTIVE;
2137                 } else if (!strcasecmp(value, "passive")) {
2138                         dtls_cfg->default_setup = AST_RTP_DTLS_SETUP_PASSIVE;
2139                 } else if (!strcasecmp(value, "actpass")) {
2140                         dtls_cfg->default_setup = AST_RTP_DTLS_SETUP_ACTPASS;
2141                 }
2142         } else if (!strcasecmp(name, "dtlsfingerprint")) {
2143                 if (!strcasecmp(value, "sha-256")) {
2144                         dtls_cfg->hash = AST_RTP_DTLS_HASH_SHA256;
2145                 } else if (!strcasecmp(value, "sha-1")) {
2146                         dtls_cfg->hash = AST_RTP_DTLS_HASH_SHA1;
2147                 }
2148         } else {
2149                 return -1;
2150         }
2151
2152         return 0;
2153 }
2154
2155 void ast_rtp_dtls_cfg_copy(const struct ast_rtp_dtls_cfg *src_cfg, struct ast_rtp_dtls_cfg *dst_cfg)
2156 {
2157         ast_rtp_dtls_cfg_free(dst_cfg);         /* Prevent a double-call leaking memory via ast_strdup */
2158
2159         dst_cfg->enabled = src_cfg->enabled;
2160         dst_cfg->verify = src_cfg->verify;
2161         dst_cfg->rekey = src_cfg->rekey;
2162         dst_cfg->suite = src_cfg->suite;
2163         dst_cfg->hash = src_cfg->hash;
2164         dst_cfg->certfile = ast_strdup(src_cfg->certfile);
2165         dst_cfg->pvtfile = ast_strdup(src_cfg->pvtfile);
2166         dst_cfg->cipher = ast_strdup(src_cfg->cipher);
2167         dst_cfg->cafile = ast_strdup(src_cfg->cafile);
2168         dst_cfg->capath = ast_strdup(src_cfg->capath);
2169         dst_cfg->default_setup = src_cfg->default_setup;
2170 }
2171
2172 void ast_rtp_dtls_cfg_free(struct ast_rtp_dtls_cfg *dtls_cfg)
2173 {
2174         ast_free(dtls_cfg->certfile);
2175         dtls_cfg->certfile = NULL;
2176         ast_free(dtls_cfg->pvtfile);
2177         dtls_cfg->pvtfile = NULL;
2178         ast_free(dtls_cfg->cipher);
2179         dtls_cfg->cipher = NULL;
2180         ast_free(dtls_cfg->cafile);
2181         dtls_cfg->cafile = NULL;
2182         ast_free(dtls_cfg->capath);
2183         dtls_cfg->capath = NULL;
2184 }
2185
2186 /*! \internal
2187  * \brief Small helper routine that cleans up entry i in
2188  * \c ast_rtp_mime_types.
2189  */
2190 static void rtp_engine_mime_type_cleanup(int i)
2191 {
2192         ao2_cleanup(ast_rtp_mime_types[i].payload_type.format);
2193         memset(&ast_rtp_mime_types[i], 0, sizeof(struct ast_rtp_mime_type));
2194 }
2195
2196 static void set_next_mime_type(struct ast_format *format, int rtp_code, const char *type, const char *subtype, unsigned int sample_rate)
2197 {
2198         int x;
2199
2200         ast_rwlock_wrlock(&mime_types_lock);
2201
2202         x = mime_types_len;
2203         if (ARRAY_LEN(ast_rtp_mime_types) <= x) {
2204                 ast_rwlock_unlock(&mime_types_lock);
2205                 return;
2206         }
2207
2208         /* Make sure any previous value in ast_rtp_mime_types is cleaned up */
2209         memset(&ast_rtp_mime_types[x], 0, sizeof(struct ast_rtp_mime_type));    
2210         if (format) {
2211                 ast_rtp_mime_types[x].payload_type.asterisk_format = 1;
2212                 ast_rtp_mime_types[x].payload_type.format = ao2_bump(format);
2213         } else {
2214                 ast_rtp_mime_types[x].payload_type.rtp_code = rtp_code;
2215         }
2216         ast_copy_string(ast_rtp_mime_types[x].type, type, sizeof(ast_rtp_mime_types[x].type));
2217         ast_copy_string(ast_rtp_mime_types[x].subtype, subtype, sizeof(ast_rtp_mime_types[x].subtype));
2218         ast_rtp_mime_types[x].sample_rate = sample_rate;
2219         mime_types_len++;
2220
2221         ast_rwlock_unlock(&mime_types_lock);
2222 }
2223
2224 static void add_static_payload(int map, struct ast_format *format, int rtp_code)
2225 {
2226         int x;
2227         struct ast_rtp_payload_type *type;
2228
2229         ast_assert(map < ARRAY_LEN(static_RTP_PT));
2230
2231         ast_rwlock_wrlock(&static_RTP_PT_lock);
2232         if (map < 0) {
2233                 /* find next available dynamic payload slot */
2234                 for (x = AST_RTP_PT_FIRST_DYNAMIC; x < AST_RTP_MAX_PT; ++x) {
2235                         if (!static_RTP_PT[x]) {
2236                                 map = x;
2237                                 break;
2238                         }
2239                 }
2240                 if (map < 0) {
2241                         if (format) {
2242                                 ast_log(LOG_WARNING, "No Dynamic RTP mapping available for format %s\n",
2243                                         ast_format_get_name(format));
2244                         } else {
2245                                 ast_log(LOG_WARNING, "No Dynamic RTP mapping available for RTP code %d\n",
2246                                         rtp_code);
2247                         }
2248                         ast_rwlock_unlock(&static_RTP_PT_lock);
2249                         return;
2250                 }
2251         }
2252
2253         type = ast_rtp_engine_alloc_payload_type();
2254         if (type) {
2255                 if (format) {
2256                         ao2_ref(format, +1);
2257                         type->format = format;
2258                         type->asterisk_format = 1;
2259                 } else {
2260                         type->rtp_code = rtp_code;
2261                 }
2262                 type->payload = map;
2263                 type->primary_mapping = 1;
2264                 ao2_cleanup(static_RTP_PT[map]);
2265                 static_RTP_PT[map] = type;
2266         }
2267         ast_rwlock_unlock(&static_RTP_PT_lock);
2268 }
2269
2270 int ast_rtp_engine_load_format(struct ast_format *format)
2271 {
2272         char *codec_name = ast_strdupa(ast_format_get_name(format));
2273
2274         codec_name = ast_str_to_upper(codec_name);
2275
2276         set_next_mime_type(format,
2277                 0,
2278                 ast_codec_media_type2str(ast_format_get_type(format)),
2279                 codec_name,
2280                 ast_format_get_sample_rate(format));
2281         add_static_payload(-1, format, 0);
2282
2283         return 0;
2284 }
2285
2286 int ast_rtp_engine_unload_format(struct ast_format *format)
2287 {
2288         int x;
2289         int y = 0;
2290
2291         ast_rwlock_wrlock(&static_RTP_PT_lock);
2292         /* remove everything pertaining to this format id from the lists */
2293         for (x = 0; x < AST_RTP_MAX_PT; x++) {
2294                 if (static_RTP_PT[x]
2295                         && ast_format_cmp(static_RTP_PT[x]->format, format) == AST_FORMAT_CMP_EQUAL) {
2296                         ao2_ref(static_RTP_PT[x], -1);
2297                         static_RTP_PT[x] = NULL;
2298                 }
2299         }
2300         ast_rwlock_unlock(&static_RTP_PT_lock);
2301
2302         ast_rwlock_wrlock(&mime_types_lock);
2303         /* rebuild the list skipping the items matching this id */
2304         for (x = 0; x < mime_types_len; x++) {
2305                 if (ast_format_cmp(ast_rtp_mime_types[x].payload_type.format, format) == AST_FORMAT_CMP_EQUAL) {
2306                         rtp_engine_mime_type_cleanup(x);
2307                         continue;
2308                 }
2309                 if (x != y) {
2310                         ast_rtp_mime_types[y] = ast_rtp_mime_types[x];
2311                 }
2312                 y++;
2313         }
2314         mime_types_len = y;
2315         ast_rwlock_unlock(&mime_types_lock);
2316         return 0;
2317 }
2318
2319 /*!
2320  * \internal
2321  * \brief \ref stasis message payload for RTCP messages
2322  */
2323 struct rtcp_message_payload {
2324         struct ast_channel_snapshot *snapshot;  /*< The channel snapshot, if available */
2325         struct ast_rtp_rtcp_report *report;     /*< The RTCP report */
2326         struct ast_json *blob;                  /*< Extra JSON data to publish */
2327 };
2328
2329 static void rtcp_message_payload_dtor(void *obj)
2330 {
2331         struct rtcp_message_payload *payload = obj;
2332
2333         ao2_cleanup(payload->report);
2334         ao2_cleanup(payload->snapshot);
2335         ast_json_unref(payload->blob);
2336 }
2337
2338 static struct ast_manager_event_blob *rtcp_report_to_ami(struct stasis_message *msg)
2339 {
2340         struct rtcp_message_payload *payload = stasis_message_data(msg);
2341         RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
2342         RAII_VAR(struct ast_str *, packet_string, ast_str_create(512), ast_free);
2343         unsigned int ssrc = payload->report->ssrc;
2344         unsigned int type = payload->report->type;
2345         unsigned int report_count = payload->report->reception_report_count;
2346         int i;
2347
2348         if (!packet_string) {
2349                 return NULL;
2350         }
2351
2352         if (payload->snapshot) {
2353                 channel_string = ast_manager_build_channel_state_string(payload->snapshot);
2354                 if (!channel_string) {
2355                         return NULL;
2356                 }
2357         }
2358
2359         if (payload->blob) {
2360                 /* Optional data */
2361                 struct ast_json *to = ast_json_object_get(payload->blob, "to");
2362                 struct ast_json *from = ast_json_object_get(payload->blob, "from");
2363                 struct ast_json *rtt = ast_json_object_get(payload->blob, "rtt");
2364                 if (to) {
2365                         ast_str_append(&packet_string, 0, "To: %s\r\n", ast_json_string_get(to));
2366                 }
2367                 if (from) {
2368                         ast_str_append(&packet_string, 0, "From: %s\r\n", ast_json_string_get(from));
2369                 }
2370                 if (rtt) {
2371                         ast_str_append(&packet_string, 0, "RTT: %4.4f\r\n", ast_json_real_get(rtt));
2372                 }
2373         }
2374
2375         ast_str_append(&packet_string, 0, "SSRC: 0x%.8x\r\n", ssrc);
2376         ast_str_append(&packet_string, 0, "PT: %u(%s)\r\n", type, type== AST_RTP_RTCP_SR ? "SR" : "RR");
2377         ast_str_append(&packet_string, 0, "ReportCount: %u\r\n", report_count);
2378         if (type == AST_RTP_RTCP_SR) {
2379                 ast_str_append(&packet_string, 0, "SentNTP: %lu.%06lu\r\n",
2380                         (unsigned long)payload->report->sender_information.ntp_timestamp.tv_sec,
2381                         (unsigned long)payload->report->sender_information.ntp_timestamp.tv_usec * 4096);
2382                 ast_str_append(&packet_string, 0, "SentRTP: %u\r\n",
2383                                 payload->report->sender_information.rtp_timestamp);
2384                 ast_str_append(&packet_string, 0, "SentPackets: %u\r\n",
2385                                 payload->report->sender_information.packet_count);
2386                 ast_str_append(&packet_string, 0, "SentOctets: %u\r\n",
2387                                 payload->report->sender_information.octet_count);
2388         }
2389
2390         for (i = 0; i < report_count; i++) {
2391                 RAII_VAR(struct ast_str *, report_string, NULL, ast_free);
2392
2393                 if (!payload->report->report_block[i]) {
2394                         break;
2395                 }
2396
2397                 report_string = ast_str_create(256);
2398                 if (!report_string) {
2399                         return NULL;
2400                 }
2401
2402                 ast_str_append(&report_string, 0, "Report%dSourceSSRC: 0x%.8x\r\n",
2403                                 i, payload->report->report_block[i]->source_ssrc);
2404                 ast_str_append(&report_string, 0, "Report%dFractionLost: %d\r\n",
2405                                 i, payload->report->report_block[i]->lost_count.fraction);
2406                 ast_str_append(&report_string, 0, "Report%dCumulativeLost: %u\r\n",
2407                                 i, payload->report->report_block[i]->lost_count.packets);
2408                 ast_str_append(&report_string, 0, "Report%dHighestSequence: %u\r\n",
2409                                 i, payload->report->report_block[i]->highest_seq_no & 0xffff);
2410                 ast_str_append(&report_string, 0, "Report%dSequenceNumberCycles: %u\r\n",
2411                                 i, payload->report->report_block[i]->highest_seq_no >> 16);
2412                 ast_str_append(&report_string, 0, "Report%dIAJitter: %u\r\n",
2413                                 i, payload->report->report_block[i]->ia_jitter);
2414                 ast_str_append(&report_string, 0, "Report%dLSR: %u\r\n",
2415                                 i, payload->report->report_block[i]->lsr);
2416                 ast_str_append(&report_string, 0, "Report%dDLSR: %4.4f\r\n",
2417                                 i, ((double)payload->report->report_block[i]->dlsr) / 65536);
2418                 ast_str_append(&packet_string, 0, "%s", ast_str_buffer(report_string));
2419         }
2420
2421         return ast_manager_event_blob_create(EVENT_FLAG_REPORTING,
2422                 stasis_message_type(msg) == ast_rtp_rtcp_received_type() ? "RTCPReceived" : "RTCPSent",
2423                 "%s%s",
2424                 AS_OR(channel_string, ""),
2425                 ast_str_buffer(packet_string));
2426 }
2427
2428 static struct ast_json *rtcp_report_to_json(struct stasis_message *msg,
2429         const struct stasis_message_sanitizer *sanitize)
2430 {
2431         struct rtcp_message_payload *payload = stasis_message_data(msg);
2432         RAII_VAR(struct ast_json *, json_rtcp_report, NULL, ast_json_unref);
2433         RAII_VAR(struct ast_json *, json_rtcp_report_blocks, NULL, ast_json_unref);
2434         RAII_VAR(struct ast_json *, json_rtcp_sender_info, NULL, ast_json_unref);
2435         RAII_VAR(struct ast_json *, json_channel, NULL, ast_json_unref);
2436         int i;
2437
2438         json_rtcp_report_blocks = ast_json_array_create();
2439         if (!json_rtcp_report_blocks) {
2440                 return NULL;
2441         }
2442
2443         for (i = 0; i < payload->report->reception_report_count && payload->report->report_block[i]; i++) {
2444                 struct ast_json *json_report_block;
2445                 char str_lsr[32];
2446                 snprintf(str_lsr, sizeof(str_lsr), "%u", payload->report->report_block[i]->lsr);
2447                 json_report_block = ast_json_pack("{s: i, s: i, s: i, s: i, s: i, s: s, s: i}",
2448                                 "source_ssrc", payload->report->report_block[i]->source_ssrc,
2449                                 "fraction_lost", payload->report->report_block[i]->lost_count.fraction,
2450                                 "packets_lost", payload->report->report_block[i]->lost_count.packets,
2451                                 "highest_seq_no", payload->report->report_block[i]->highest_seq_no,
2452                                 "ia_jitter", payload->report->report_block[i]->ia_jitter,
2453                                 "lsr", str_lsr,
2454                                 "dlsr", payload->report->report_block[i]->dlsr);
2455                 if (!json_report_block) {
2456                         return NULL;
2457                 }
2458
2459                 if (ast_json_array_append(json_rtcp_report_blocks, json_report_block)) {
2460                         return NULL;
2461                 }
2462         }
2463
2464         if (payload->report->type == AST_RTP_RTCP_SR) {
2465                 char sec[32];
2466                 char usec[32];
2467                 snprintf(sec, sizeof(sec), "%lu", (unsigned long)payload->report->sender_information.ntp_timestamp.tv_sec);
2468                 snprintf(usec, sizeof(usec), "%lu", (unsigned long)payload->report->sender_information.ntp_timestamp.tv_usec);
2469                 json_rtcp_sender_info = ast_json_pack("{s: s, s: s, s: i, s: i, s: i}",
2470                                 "ntp_timestamp_sec", sec,
2471                                 "ntp_timestamp_usec", usec,
2472                                 "rtp_timestamp", payload->report->sender_information.rtp_timestamp,
2473                                 "packets", payload->report->sender_information.packet_count,
2474                                 "octets", payload->report->sender_information.octet_count);
2475                 if (!json_rtcp_sender_info) {
2476                         return NULL;
2477                 }
2478         }
2479
2480         json_rtcp_report = ast_json_pack("{s: i, s: i, s: i, s: O, s: O}",
2481                         "ssrc", payload->report->ssrc,
2482                         "type", payload->report->type,
2483                         "report_count", payload->report->reception_report_count,
2484                         "sender_information", json_rtcp_sender_info ? json_rtcp_sender_info : ast_json_null(),
2485                         "report_blocks", json_rtcp_report_blocks);
2486         if (!json_rtcp_report) {
2487                 return NULL;
2488         }
2489
2490         if (payload->snapshot) {
2491                 json_channel = ast_channel_snapshot_to_json(payload->snapshot, sanitize);
2492                 if (!json_channel) {
2493                         return NULL;
2494                 }
2495         }
2496
2497         return ast_json_pack("{s: O, s: O, s: O}",
2498                 "channel", payload->snapshot ? json_channel : ast_json_null(),
2499                 "rtcp_report", json_rtcp_report,
2500                 "blob", payload->blob);
2501 }
2502
2503 static void rtp_rtcp_report_dtor(void *obj)
2504 {
2505         int i;
2506         struct ast_rtp_rtcp_report *rtcp_report = obj;
2507
2508         for (i = 0; i < rtcp_report->reception_report_count; i++) {
2509                 ast_free(rtcp_report->report_block[i]);
2510         }
2511 }
2512
2513 struct ast_rtp_rtcp_report *ast_rtp_rtcp_report_alloc(unsigned int report_blocks)
2514 {
2515         struct ast_rtp_rtcp_report *rtcp_report;
2516
2517         /* Size of object is sizeof the report + the number of report_blocks * sizeof pointer */
2518         rtcp_report = ao2_alloc((sizeof(*rtcp_report) + report_blocks * sizeof(struct ast_rtp_rtcp_report_block *)),
2519                 rtp_rtcp_report_dtor);
2520
2521         return rtcp_report;
2522 }
2523
2524 void ast_rtp_publish_rtcp_message(struct ast_rtp_instance *rtp,
2525                 struct stasis_message_type *message_type,
2526                 struct ast_rtp_rtcp_report *report,
2527                 struct ast_json *blob)
2528 {
2529         RAII_VAR(struct rtcp_message_payload *, payload, NULL, ao2_cleanup);
2530         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
2531
2532         if (!message_type) {
2533                 return;
2534         }
2535
2536         payload = ao2_alloc(sizeof(*payload), rtcp_message_payload_dtor);
2537         if (!payload || !report) {
2538                 return;
2539         }
2540
2541         if (!ast_strlen_zero(rtp->channel_uniqueid)) {
2542                 payload->snapshot = ast_channel_snapshot_get_latest(rtp->channel_uniqueid);
2543         }
2544         if (blob) {
2545                 payload->blob = blob;
2546                 ast_json_ref(blob);
2547         }
2548         ao2_ref(report, +1);
2549         payload->report = report;
2550
2551         message = stasis_message_create(message_type, payload);
2552         if (!message) {
2553                 return;
2554         }
2555
2556         stasis_publish(ast_rtp_topic(), message);
2557 }
2558
2559 /*!
2560  * @{ \brief Define RTCP/RTP message types.
2561  */
2562 STASIS_MESSAGE_TYPE_DEFN(ast_rtp_rtcp_sent_type,
2563                 .to_ami = rtcp_report_to_ami,
2564                 .to_json = rtcp_report_to_json,);
2565 STASIS_MESSAGE_TYPE_DEFN(ast_rtp_rtcp_received_type,
2566                 .to_ami = rtcp_report_to_ami,
2567                 .to_json = rtcp_report_to_json,);
2568 /*! @} */
2569
2570 struct stasis_topic *ast_rtp_topic(void)
2571 {
2572         return rtp_topic;
2573 }
2574
2575 static void rtp_engine_shutdown(void)
2576 {
2577         int x;
2578
2579         ao2_cleanup(rtp_topic);
2580         rtp_topic = NULL;
2581         STASIS_MESSAGE_TYPE_CLEANUP(ast_rtp_rtcp_received_type);
2582         STASIS_MESSAGE_TYPE_CLEANUP(ast_rtp_rtcp_sent_type);
2583
2584         ast_rwlock_wrlock(&static_RTP_PT_lock);
2585         for (x = 0; x < AST_RTP_MAX_PT; x++) {
2586                 ao2_cleanup(static_RTP_PT[x]);
2587                 static_RTP_PT[x] = NULL;
2588         }
2589         ast_rwlock_unlock(&static_RTP_PT_lock);
2590
2591         ast_rwlock_wrlock(&mime_types_lock);
2592         for (x = 0; x < mime_types_len; x++) {
2593                 if (ast_rtp_mime_types[x].payload_type.format) {
2594                         rtp_engine_mime_type_cleanup(x);
2595                 }
2596         }
2597         mime_types_len = 0;
2598         ast_rwlock_unlock(&mime_types_lock);
2599 }
2600
2601 int ast_rtp_engine_init(void)
2602 {
2603         ast_rwlock_init(&mime_types_lock);
2604         ast_rwlock_init(&static_RTP_PT_lock);
2605
2606         rtp_topic = stasis_topic_create("rtp_topic");
2607         if (!rtp_topic) {
2608                 return -1;
2609         }
2610         STASIS_MESSAGE_TYPE_INIT(ast_rtp_rtcp_sent_type);
2611         STASIS_MESSAGE_TYPE_INIT(ast_rtp_rtcp_received_type);
2612         ast_register_cleanup(rtp_engine_shutdown);
2613
2614         /* Define all the RTP mime types available */
2615         set_next_mime_type(ast_format_g723, 0, "audio", "G723", 8000);
2616         set_next_mime_type(ast_format_gsm, 0, "audio", "GSM", 8000);
2617         set_next_mime_type(ast_format_ulaw, 0, "audio", "PCMU", 8000);
2618         set_next_mime_type(ast_format_ulaw, 0, "audio", "G711U", 8000);
2619         set_next_mime_type(ast_format_alaw, 0, "audio", "PCMA", 8000);
2620         set_next_mime_type(ast_format_alaw, 0, "audio", "G711A", 8000);
2621         set_next_mime_type(ast_format_g726, 0, "audio", "G726-32", 8000);
2622         set_next_mime_type(ast_format_adpcm, 0, "audio", "DVI4", 8000);
2623         set_next_mime_type(ast_format_slin, 0, "audio", "L16", 8000);
2624         set_next_mime_type(ast_format_slin16, 0, "audio", "L16", 16000);
2625         set_next_mime_type(ast_format_slin16, 0, "audio", "L16-256", 16000);
2626         set_next_mime_type(ast_format_slin12, 0, "audio", "L16", 12000);
2627         set_next_mime_type(ast_format_slin24, 0, "audio", "L16", 24000);
2628         set_next_mime_type(ast_format_slin32, 0, "audio", "L16", 32000);
2629         set_next_mime_type(ast_format_slin44, 0, "audio", "L16", 44000);
2630         set_next_mime_type(ast_format_slin48, 0, "audio", "L16", 48000);
2631         set_next_mime_type(ast_format_slin96, 0, "audio", "L16", 96000);
2632         set_next_mime_type(ast_format_slin192, 0, "audio", "L16", 192000);
2633         set_next_mime_type(ast_format_lpc10, 0, "audio", "LPC", 8000);
2634         set_next_mime_type(ast_format_g729, 0, "audio", "G729", 8000);
2635         set_next_mime_type(ast_format_g729, 0, "audio", "G729A", 8000);
2636         set_next_mime_type(ast_format_g729, 0, "audio", "G.729", 8000);
2637         set_next_mime_type(ast_format_speex, 0, "audio", "speex", 8000);
2638         set_next_mime_type(ast_format_speex16, 0,  "audio", "speex", 16000);
2639         set_next_mime_type(ast_format_speex32, 0,  "audio", "speex", 32000);
2640         set_next_mime_type(ast_format_ilbc, 0, "audio", "iLBC", 8000);
2641         /* this is the sample rate listed in the RTP profile for the G.722 codec, *NOT* the actual sample rate of the media stream */
2642         set_next_mime_type(ast_format_g722, 0, "audio", "G722", 8000);
2643         set_next_mime_type(ast_format_g726_aal2, 0, "audio", "AAL2-G726-32", 8000);
2644         set_next_mime_type(NULL, AST_RTP_DTMF, "audio", "telephone-event", 8000);
2645         set_next_mime_type(NULL, AST_RTP_CISCO_DTMF, "audio", "cisco-telephone-event", 8000);
2646         set_next_mime_type(NULL, AST_RTP_CN, "audio", "CN", 8000);
2647         set_next_mime_type(ast_format_jpeg, 0, "video", "JPEG", 90000);
2648         set_next_mime_type(ast_format_png, 0, "video", "PNG", 90000);
2649         set_next_mime_type(ast_format_h261, 0, "video", "H261", 90000);
2650         set_next_mime_type(ast_format_h263, 0, "video", "H263", 90000);
2651         set_next_mime_type(ast_format_h263p, 0, "video", "h263-1998", 90000);
2652         set_next_mime_type(ast_format_h264, 0, "video", "H264", 90000);
2653         set_next_mime_type(ast_format_mp4, 0, "video", "MP4V-ES", 90000);
2654         set_next_mime_type(ast_format_t140_red, 0, "text", "RED", 1000);
2655         set_next_mime_type(ast_format_t140, 0, "text", "T140", 1000);
2656         set_next_mime_type(ast_format_siren7, 0, "audio", "G7221", 16000);
2657         set_next_mime_type(ast_format_siren14, 0, "audio", "G7221", 32000);
2658         set_next_mime_type(ast_format_g719, 0, "audio", "G719", 48000);
2659         /* Opus and VP8 */
2660         set_next_mime_type(ast_format_opus, 0,  "audio", "opus", 48000);
2661         set_next_mime_type(ast_format_vp8, 0,  "video", "VP8", 90000);
2662
2663         /* Define the static rtp payload mappings */
2664         add_static_payload(0, ast_format_ulaw, 0);
2665         #ifdef USE_DEPRECATED_G726
2666         add_static_payload(2, ast_format_g726, 0);/* Technically this is G.721, but if Cisco can do it, so can we... */
2667         #endif
2668         add_static_payload(3, ast_format_gsm, 0);
2669         add_static_payload(4, ast_format_g723, 0);
2670         add_static_payload(5, ast_format_adpcm, 0);/* 8 kHz */
2671         add_static_payload(6, ast_format_adpcm, 0); /* 16 kHz */
2672         add_static_payload(7, ast_format_lpc10, 0);
2673         add_static_payload(8, ast_format_alaw, 0);
2674         add_static_payload(9, ast_format_g722, 0);
2675         add_static_payload(10, ast_format_slin, 0); /* 2 channels */
2676         add_static_payload(11, ast_format_slin, 0); /* 1 channel */
2677         add_static_payload(13, NULL, AST_RTP_CN);
2678         add_static_payload(16, ast_format_adpcm, 0); /* 11.025 kHz */
2679         add_static_payload(17, ast_format_adpcm, 0); /* 22.050 kHz */
2680         add_static_payload(18, ast_format_g729, 0);
2681         add_static_payload(19, NULL, AST_RTP_CN);         /* Also used for CN */
2682         add_static_payload(26, ast_format_jpeg, 0);
2683         add_static_payload(31, ast_format_h261, 0);
2684         add_static_payload(34, ast_format_h263, 0);
2685         add_static_payload(97, ast_format_ilbc, 0);
2686         add_static_payload(98, ast_format_h263p, 0);
2687         add_static_payload(99, ast_format_h264, 0);
2688         add_static_payload(101, NULL, AST_RTP_DTMF);
2689         add_static_payload(102, ast_format_siren7, 0);
2690         add_static_payload(103, ast_format_h263p, 0);
2691         add_static_payload(104, ast_format_mp4, 0);
2692         add_static_payload(105, ast_format_t140_red, 0);   /* Real time text chat (with redundancy encoding) */
2693         add_static_payload(106, ast_format_t140, 0);     /* Real time text chat */
2694         add_static_payload(110, ast_format_speex, 0);
2695         add_static_payload(111, ast_format_g726, 0);
2696         add_static_payload(112, ast_format_g726_aal2, 0);
2697         add_static_payload(115, ast_format_siren14, 0);
2698         add_static_payload(116, ast_format_g719, 0);
2699         add_static_payload(117, ast_format_speex16, 0);
2700         add_static_payload(118, ast_format_slin16, 0); /* 16 Khz signed linear */
2701         add_static_payload(119, ast_format_speex32, 0);
2702         add_static_payload(121, NULL, AST_RTP_CISCO_DTMF);   /* Must be type 121 */
2703         add_static_payload(122, ast_format_slin12, 0);
2704         add_static_payload(123, ast_format_slin24, 0);
2705         add_static_payload(124, ast_format_slin32, 0);
2706         add_static_payload(125, ast_format_slin44, 0);
2707         add_static_payload(126, ast_format_slin48, 0);
2708         add_static_payload(127, ast_format_slin96, 0);
2709         /* payload types above 127 are not valid */
2710         add_static_payload(96, ast_format_slin192, 0);
2711         /* Opus and VP8 */
2712         add_static_payload(100, ast_format_vp8, 0);
2713         add_static_payload(107, ast_format_opus, 0);
2714
2715         return 0;
2716 }
2717
2718 time_t ast_rtp_instance_get_last_tx(const struct ast_rtp_instance *rtp)
2719 {
2720         return rtp->last_tx;
2721 }
2722
2723 void ast_rtp_instance_set_last_tx(struct ast_rtp_instance *rtp, time_t time)
2724 {
2725         rtp->last_tx = time;
2726 }
2727
2728 time_t ast_rtp_instance_get_last_rx(const struct ast_rtp_instance *rtp)
2729 {
2730         return rtp->last_rx;
2731 }
2732
2733 void ast_rtp_instance_set_last_rx(struct ast_rtp_instance *rtp, time_t time)
2734 {
2735         rtp->last_rx = time;
2736 }