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