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