ARI: Add ability to raise arbitrary User Events
[asterisk/asterisk.git] / main / rtp_engine.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2008, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Pluggable RTP Architecture
22  *
23  * \author Joshua Colp <jcolp@digium.com>
24  */
25
26 /*** MODULEINFO
27         <support_level>core</support_level>
28 ***/
29
30 /*** DOCUMENTATION
31         <managerEvent language="en_US" name="RTCPSent">
32                 <managerEventInstance class="EVENT_FLAG_REPORTING">
33                         <synopsis>Raised when an RTCP packet is sent.</synopsis>
34                         <syntax>
35                                 <channel_snapshot/>
36                                 <parameter name="SSRC">
37                                         <para>The SSRC identifier for our stream</para>
38                                 </parameter>
39                                 <parameter name="PT">
40                                         <para>The type of packet for this RTCP report.</para>
41                                         <enumlist>
42                                                 <enum name="200(SR)"/>
43                                                 <enum name="201(RR)"/>
44                                         </enumlist>
45                                 </parameter>
46                                 <parameter name="To">
47                                         <para>The address the report is sent to.</para>
48                                 </parameter>
49                                 <parameter name="ReportCount">
50                                         <para>The number of reports that were sent.</para>
51                                         <para>The report count determines the number of ReportX headers in
52                                         the message. The X for each set of report headers will range from 0 to
53                                         <literal>ReportCount - 1</literal>.</para>
54                                 </parameter>
55                                 <parameter name="SentNTP" required="false">
56                                         <para>The time the sender generated the report. Only valid when
57                                         PT is <literal>200(SR)</literal>.</para>
58                                 </parameter>
59                                 <parameter name="SentRTP" required="false">
60                                         <para>The sender's last RTP timestamp. Only valid when PT is
61                                         <literal>200(SR)</literal>.</para>
62                                 </parameter>
63                                 <parameter name="SentPackets" required="false">
64                                         <para>The number of packets the sender has sent. Only valid when PT
65                                         is <literal>200(SR)</literal>.</para>
66                                 </parameter>
67                                 <parameter name="SentOctets" required="false">
68                                         <para>The number of bytes the sender has sent. Only valid when PT is
69                                         <literal>200(SR)</literal>.</para>
70                                 </parameter>
71                                 <parameter name="ReportXSourceSSRC">
72                                         <para>The SSRC for the source of this report block.</para>
73                                 </parameter>
74                                 <parameter name="ReportXFractionLost">
75                                         <para>The fraction of RTP data packets from <literal>ReportXSourceSSRC</literal>
76                                         lost since the previous SR or RR report was sent.</para>
77                                 </parameter>
78                                 <parameter name="ReportXCumulativeLost">
79                                         <para>The total number of RTP data packets from <literal>ReportXSourceSSRC</literal>
80                                         lost since the beginning of reception.</para>
81                                 </parameter>
82                                 <parameter name="ReportXHighestSequence">
83                                         <para>The highest sequence number received in an RTP data packet from
84                                         <literal>ReportXSourceSSRC</literal>.</para>
85                                 </parameter>
86                                 <parameter name="ReportXSequenceNumberCycles">
87                                         <para>The number of sequence number cycles seen for the RTP data
88                                         received from <literal>ReportXSourceSSRC</literal>.</para>
89                                 </parameter>
90                                 <parameter name="ReportXIAJitter">
91                                         <para>An estimate of the statistical variance of the RTP data packet
92                                         interarrival time, measured in timestamp units.</para>
93                                 </parameter>
94                                 <parameter name="ReportXLSR">
95                                         <para>The last SR timestamp received from <literal>ReportXSourceSSRC</literal>.
96                                         If no SR has been received from <literal>ReportXSourceSSRC</literal>,
97                                         then 0.</para>
98                                 </parameter>
99                                 <parameter name="ReportXDLSR">
100                                         <para>The delay, expressed in units of 1/65536 seconds, between
101                                         receiving the last SR packet from <literal>ReportXSourceSSRC</literal>
102                                         and sending this report.</para>
103                                 </parameter>
104                         </syntax>
105                 </managerEventInstance>
106         </managerEvent>
107         <managerEvent language="en_US" name="RTCPReceived">
108                 <managerEventInstance class="EVENT_FLAG_REPORTING">
109                         <synopsis>Raised when an RTCP packet is received.</synopsis>
110                         <syntax>
111                                 <channel_snapshot/>
112                                 <parameter name="SSRC">
113                                         <para>The SSRC identifier for the remote system</para>
114                                 </parameter>
115                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='RTCPSent']/managerEventInstance/syntax/parameter[@name='PT'])" />
116                                 <parameter name="From">
117                                         <para>The address the report was received from.</para>
118                                 </parameter>
119                                 <parameter name="RTT">
120                                         <para>Calculated Round-Trip Time in seconds</para>
121                                 </parameter>
122                                 <parameter name="ReportCount">
123                                         <para>The number of reports that were received.</para>
124                                         <para>The report count determines the number of ReportX headers in
125                                         the message. The X for each set of report headers will range from 0 to
126                                         <literal>ReportCount - 1</literal>.</para>
127                                 </parameter>
128                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='RTCPSent']/managerEventInstance/syntax/parameter[@name='SentNTP'])" />
129                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='RTCPSent']/managerEventInstance/syntax/parameter[@name='SentRTP'])" />
130                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='RTCPSent']/managerEventInstance/syntax/parameter[@name='SentPackets'])" />
131                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='RTCPSent']/managerEventInstance/syntax/parameter[@name='SentOctets'])" />
132                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='RTCPSent']/managerEventInstance/syntax/parameter[contains(@name, 'ReportX')])" />
133                         </syntax>
134                 </managerEventInstance>
135         </managerEvent>
136  ***/
137
138 #include "asterisk.h"
139
140 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
141
142 #include <math.h>
143
144 #include "asterisk/channel.h"
145 #include "asterisk/frame.h"
146 #include "asterisk/module.h"
147 #include "asterisk/rtp_engine.h"
148 #include "asterisk/manager.h"
149 #include "asterisk/options.h"
150 #include "asterisk/astobj2.h"
151 #include "asterisk/pbx.h"
152 #include "asterisk/translate.h"
153 #include "asterisk/netsock2.h"
154 #include "asterisk/_private.h"
155 #include "asterisk/framehook.h"
156 #include "asterisk/stasis.h"
157 #include "asterisk/json.h"
158 #include "asterisk/stasis_channels.h"
159
160 struct ast_srtp_res *res_srtp = NULL;
161 struct ast_srtp_policy_res *res_srtp_policy = NULL;
162
163 /*! Structure that represents an RTP session (instance) */
164 struct ast_rtp_instance {
165         /*! Engine that is handling this RTP instance */
166         struct ast_rtp_engine *engine;
167         /*! Data unique to the RTP engine */
168         void *data;
169         /*! RTP properties that have been set and their value */
170         int properties[AST_RTP_PROPERTY_MAX];
171         /*! Address that we are expecting RTP to come in to */
172         struct ast_sockaddr local_address;
173         /*! Address that we are sending RTP to */
174         struct ast_sockaddr remote_address;
175         /*! Instance that we are bridged to if doing remote or local bridging */
176         struct ast_rtp_instance *bridged;
177         /*! Payload and packetization information */
178         struct ast_rtp_codecs codecs;
179         /*! RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
180         int timeout;
181         /*! RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
182         int holdtimeout;
183         /*! RTP keepalive interval */
184         int keepalive;
185         /*! Glue currently in use */
186         struct ast_rtp_glue *glue;
187         /*! SRTP info associated with the instance */
188         struct ast_srtp *srtp;
189         /*! Channel unique ID */
190         char channel_uniqueid[AST_MAX_UNIQUEID];
191 };
192
193 /*! List of RTP engines that are currently registered */
194 static AST_RWLIST_HEAD_STATIC(engines, ast_rtp_engine);
195
196 /*! List of RTP glues */
197 static AST_RWLIST_HEAD_STATIC(glues, ast_rtp_glue);
198
199 /*! The following array defines the MIME Media type (and subtype) for each
200    of our codecs, or RTP-specific data type. */
201 static struct ast_rtp_mime_type {
202         struct ast_rtp_payload_type payload_type;
203         char *type;
204         char *subtype;
205         unsigned int sample_rate;
206 } ast_rtp_mime_types[128]; /* This will Likely not need to grow any time soon. */
207 static ast_rwlock_t mime_types_lock;
208 static int mime_types_len = 0;
209
210 /*!
211  * \brief Mapping between Asterisk codecs and rtp payload types
212  *
213  * Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
214  * also, our own choices for dynamic payload types.  This is our master
215  * table for transmission
216  *
217  * See http://www.iana.org/assignments/rtp-parameters for a list of
218  * assigned values
219  */
220 static struct ast_rtp_payload_type static_RTP_PT[AST_RTP_MAX_PT];
221 static ast_rwlock_t static_RTP_PT_lock;
222
223 /*! \brief \ref stasis topic for RTP related messages */
224 static struct stasis_topic *rtp_topic;
225
226 int ast_rtp_engine_register2(struct ast_rtp_engine *engine, struct ast_module *module)
227 {
228         struct ast_rtp_engine *current_engine;
229
230         /* Perform a sanity check on the engine structure to make sure it has the basics */
231         if (ast_strlen_zero(engine->name) || !engine->new || !engine->destroy || !engine->write || !engine->read) {
232                 ast_log(LOG_WARNING, "RTP Engine '%s' failed sanity check so it was not registered.\n", !ast_strlen_zero(engine->name) ? engine->name : "Unknown");
233                 return -1;
234         }
235
236         /* Link owner module to the RTP engine for reference counting purposes */
237         engine->mod = module;
238
239         AST_RWLIST_WRLOCK(&engines);
240
241         /* Ensure that no two modules with the same name are registered at the same time */
242         AST_RWLIST_TRAVERSE(&engines, current_engine, entry) {
243                 if (!strcmp(current_engine->name, engine->name)) {
244                         ast_log(LOG_WARNING, "An RTP engine with the name '%s' has already been registered.\n", engine->name);
245                         AST_RWLIST_UNLOCK(&engines);
246                         return -1;
247                 }
248         }
249
250         /* The engine survived our critique. Off to the list it goes to be used */
251         AST_RWLIST_INSERT_TAIL(&engines, engine, entry);
252
253         AST_RWLIST_UNLOCK(&engines);
254
255         ast_verb(2, "Registered RTP engine '%s'\n", engine->name);
256
257         return 0;
258 }
259
260 int ast_rtp_engine_unregister(struct ast_rtp_engine *engine)
261 {
262         struct ast_rtp_engine *current_engine = NULL;
263
264         AST_RWLIST_WRLOCK(&engines);
265
266         if ((current_engine = AST_RWLIST_REMOVE(&engines, engine, entry))) {
267                 ast_verb(2, "Unregistered RTP engine '%s'\n", engine->name);
268         }
269
270         AST_RWLIST_UNLOCK(&engines);
271
272         return current_engine ? 0 : -1;
273 }
274
275 int ast_rtp_glue_register2(struct ast_rtp_glue *glue, struct ast_module *module)
276 {
277         struct ast_rtp_glue *current_glue = NULL;
278
279         if (ast_strlen_zero(glue->type)) {
280                 return -1;
281         }
282
283         glue->mod = module;
284
285         AST_RWLIST_WRLOCK(&glues);
286
287         AST_RWLIST_TRAVERSE(&glues, current_glue, entry) {
288                 if (!strcasecmp(current_glue->type, glue->type)) {
289                         ast_log(LOG_WARNING, "RTP glue with the name '%s' has already been registered.\n", glue->type);
290                         AST_RWLIST_UNLOCK(&glues);
291                         return -1;
292                 }
293         }
294
295         AST_RWLIST_INSERT_TAIL(&glues, glue, entry);
296
297         AST_RWLIST_UNLOCK(&glues);
298
299         ast_verb(2, "Registered RTP glue '%s'\n", glue->type);
300
301         return 0;
302 }
303
304 int ast_rtp_glue_unregister(struct ast_rtp_glue *glue)
305 {
306         struct ast_rtp_glue *current_glue = NULL;
307
308         AST_RWLIST_WRLOCK(&glues);
309
310         if ((current_glue = AST_RWLIST_REMOVE(&glues, glue, entry))) {
311                 ast_verb(2, "Unregistered RTP glue '%s'\n", glue->type);
312         }
313
314         AST_RWLIST_UNLOCK(&glues);
315
316         return current_glue ? 0 : -1;
317 }
318
319 static void instance_destructor(void *obj)
320 {
321         struct ast_rtp_instance *instance = obj;
322
323         /* Pass us off to the engine to destroy */
324         if (instance->data && instance->engine->destroy(instance)) {
325                 ast_debug(1, "Engine '%s' failed to destroy RTP instance '%p'\n", instance->engine->name, instance);
326                 return;
327         }
328
329         if (instance->srtp) {
330                 res_srtp->destroy(instance->srtp);
331         }
332
333         ast_rtp_codecs_payloads_destroy(&instance->codecs);
334
335         /* Drop our engine reference */
336         ast_module_unref(instance->engine->mod);
337
338         ast_debug(1, "Destroyed RTP instance '%p'\n", instance);
339 }
340
341 int ast_rtp_instance_destroy(struct ast_rtp_instance *instance)
342 {
343         ao2_ref(instance, -1);
344
345         return 0;
346 }
347
348 struct ast_rtp_instance *ast_rtp_instance_new(const char *engine_name,
349                 struct ast_sched_context *sched, const struct ast_sockaddr *sa,
350                 void *data)
351 {
352         struct ast_sockaddr address = {{0,}};
353         struct ast_rtp_instance *instance = NULL;
354         struct ast_rtp_engine *engine = NULL;
355
356         AST_RWLIST_RDLOCK(&engines);
357
358         /* If an engine name was specified try to use it or otherwise use the first one registered */
359         if (!ast_strlen_zero(engine_name)) {
360                 AST_RWLIST_TRAVERSE(&engines, engine, entry) {
361                         if (!strcmp(engine->name, engine_name)) {
362                                 break;
363                         }
364                 }
365         } else {
366                 engine = AST_RWLIST_FIRST(&engines);
367         }
368
369         /* If no engine was actually found bail out now */
370         if (!engine) {
371                 ast_log(LOG_ERROR, "No RTP engine was found. Do you have one loaded?\n");
372                 AST_RWLIST_UNLOCK(&engines);
373                 return NULL;
374         }
375
376         /* Bump up the reference count before we return so the module can not be unloaded */
377         ast_module_ref(engine->mod);
378
379         AST_RWLIST_UNLOCK(&engines);
380
381         /* Allocate a new RTP instance */
382         if (!(instance = ao2_alloc(sizeof(*instance), instance_destructor))) {
383                 ast_module_unref(engine->mod);
384                 return NULL;
385         }
386         instance->engine = engine;
387         ast_sockaddr_copy(&instance->local_address, sa);
388         ast_sockaddr_copy(&address, sa);
389
390         if (ast_rtp_codecs_payloads_initialize(&instance->codecs)) {
391                 ao2_ref(instance, -1);
392                 return NULL;
393         }
394
395         ast_debug(1, "Using engine '%s' for RTP instance '%p'\n", engine->name, instance);
396
397         /* And pass it off to the engine to setup */
398         if (instance->engine->new(instance, sched, &address, data)) {
399                 ast_debug(1, "Engine '%s' failed to setup RTP instance '%p'\n", engine->name, instance);
400                 ao2_ref(instance, -1);
401                 return NULL;
402         }
403
404         ast_debug(1, "RTP instance '%p' is setup and ready to go\n", instance);
405
406         return instance;
407 }
408
409 const char *ast_rtp_instance_get_channel_id(struct ast_rtp_instance *instance)
410 {
411         return instance->channel_uniqueid;
412 }
413
414 void ast_rtp_instance_set_channel_id(struct ast_rtp_instance *instance, const char *uniqueid)
415 {
416         ast_copy_string(instance->channel_uniqueid, uniqueid, sizeof(instance->channel_uniqueid));
417 }
418
419 void ast_rtp_instance_set_data(struct ast_rtp_instance *instance, void *data)
420 {
421         instance->data = data;
422 }
423
424 void *ast_rtp_instance_get_data(struct ast_rtp_instance *instance)
425 {
426         return instance->data;
427 }
428
429 int ast_rtp_instance_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
430 {
431         return instance->engine->write(instance, frame);
432 }
433
434 struct ast_frame *ast_rtp_instance_read(struct ast_rtp_instance *instance, int rtcp)
435 {
436         return instance->engine->read(instance, rtcp);
437 }
438
439 int ast_rtp_instance_set_local_address(struct ast_rtp_instance *instance,
440                 const struct ast_sockaddr *address)
441 {
442         ast_sockaddr_copy(&instance->local_address, address);
443         return 0;
444 }
445
446 int ast_rtp_instance_set_remote_address(struct ast_rtp_instance *instance,
447                 const struct ast_sockaddr *address)
448 {
449         ast_sockaddr_copy(&instance->remote_address, address);
450
451         /* moo */
452
453         if (instance->engine->remote_address_set) {
454                 instance->engine->remote_address_set(instance, &instance->remote_address);
455         }
456
457         return 0;
458 }
459
460 int ast_rtp_instance_get_and_cmp_local_address(struct ast_rtp_instance *instance,
461                 struct ast_sockaddr *address)
462 {
463         if (ast_sockaddr_cmp(address, &instance->local_address) != 0) {
464                 ast_sockaddr_copy(address, &instance->local_address);
465                 return 1;
466         }
467
468         return 0;
469 }
470
471 void ast_rtp_instance_get_local_address(struct ast_rtp_instance *instance,
472                 struct ast_sockaddr *address)
473 {
474         ast_sockaddr_copy(address, &instance->local_address);
475 }
476
477 int ast_rtp_instance_get_and_cmp_remote_address(struct ast_rtp_instance *instance,
478                 struct ast_sockaddr *address)
479 {
480         if (ast_sockaddr_cmp(address, &instance->remote_address) != 0) {
481                 ast_sockaddr_copy(address, &instance->remote_address);
482                 return 1;
483         }
484
485         return 0;
486 }
487
488 void ast_rtp_instance_get_remote_address(struct ast_rtp_instance *instance,
489                 struct ast_sockaddr *address)
490 {
491         ast_sockaddr_copy(address, &instance->remote_address);
492 }
493
494 void ast_rtp_instance_set_extended_prop(struct ast_rtp_instance *instance, int property, void *value)
495 {
496         if (instance->engine->extended_prop_set) {
497                 instance->engine->extended_prop_set(instance, property, value);
498         }
499 }
500
501 void *ast_rtp_instance_get_extended_prop(struct ast_rtp_instance *instance, int property)
502 {
503         if (instance->engine->extended_prop_get) {
504                 return instance->engine->extended_prop_get(instance, property);
505         }
506
507         return NULL;
508 }
509
510 void ast_rtp_instance_set_prop(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value)
511 {
512         instance->properties[property] = value;
513
514         if (instance->engine->prop_set) {
515                 instance->engine->prop_set(instance, property, value);
516         }
517 }
518
519 int ast_rtp_instance_get_prop(struct ast_rtp_instance *instance, enum ast_rtp_property property)
520 {
521         return instance->properties[property];
522 }
523
524 struct ast_rtp_codecs *ast_rtp_instance_get_codecs(struct ast_rtp_instance *instance)
525 {
526         return &instance->codecs;
527 }
528
529 static int rtp_payload_type_hash(const void *obj, const int flags)
530 {
531         const struct ast_rtp_payload_type *type = obj;
532         const int *payload = obj;
533
534         return (flags & OBJ_KEY) ? *payload : type->payload;
535 }
536
537 static int rtp_payload_type_cmp(void *obj, void *arg, int flags)
538 {
539         struct ast_rtp_payload_type *type1 = obj, *type2 = arg;
540         const int *payload = arg;
541
542         return (type1->payload == (OBJ_KEY ? *payload : type2->payload)) ? CMP_MATCH | CMP_STOP : 0;
543 }
544
545 int ast_rtp_codecs_payloads_initialize(struct ast_rtp_codecs *codecs)
546 {
547         if (!(codecs->payloads = ao2_container_alloc(AST_RTP_MAX_PT, rtp_payload_type_hash, rtp_payload_type_cmp))) {
548                 return -1;
549         }
550
551         return 0;
552 }
553
554 void ast_rtp_codecs_payloads_destroy(struct ast_rtp_codecs *codecs)
555 {
556         ao2_cleanup(codecs->payloads);
557 }
558
559 void ast_rtp_codecs_payloads_clear(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance)
560 {
561         ast_rtp_codecs_payloads_destroy(codecs);
562
563         if (instance && instance->engine && instance->engine->payload_set) {
564                 int i;
565                 for (i = 0; i < AST_RTP_MAX_PT; i++) {
566                         instance->engine->payload_set(instance, i, 0, NULL, 0);
567                 }
568         }
569
570         ast_rtp_codecs_payloads_initialize(codecs);
571 }
572
573 void ast_rtp_codecs_payloads_default(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance)
574 {
575         int i;
576
577         ast_rwlock_rdlock(&static_RTP_PT_lock);
578         for (i = 0; i < AST_RTP_MAX_PT; i++) {
579                 if (static_RTP_PT[i].rtp_code || static_RTP_PT[i].asterisk_format) {
580                         struct ast_rtp_payload_type *type;
581
582                         if (!(type = ao2_alloc(sizeof(*type), NULL))) {
583                                 /* Unfortunately if this occurs the payloads container will not contain all possible default payloads
584                                  * but we err on the side of doing what we can in the hopes that the extreme memory conditions which
585                                  * caused this to occur will go away.
586                                  */
587                                 continue;
588                         }
589
590                         type->payload = i;
591                         type->asterisk_format = static_RTP_PT[i].asterisk_format;
592                         type->rtp_code = static_RTP_PT[i].rtp_code;
593                         ast_format_copy(&type->format, &static_RTP_PT[i].format);
594
595                         ao2_link_flags(codecs->payloads, type, OBJ_NOLOCK);
596
597                         if (instance && instance->engine && instance->engine->payload_set) {
598                                 instance->engine->payload_set(instance, i, type->asterisk_format, &type->format, type->rtp_code);
599                         }
600
601                         ao2_ref(type, -1);
602                 }
603         }
604         ast_rwlock_unlock(&static_RTP_PT_lock);
605 }
606
607 void ast_rtp_codecs_payloads_copy(struct ast_rtp_codecs *src, struct ast_rtp_codecs *dest, struct ast_rtp_instance *instance)
608 {
609         int i;
610         struct ast_rtp_payload_type *type;
611
612         for (i = 0; i < AST_RTP_MAX_PT; i++) {
613                 struct ast_rtp_payload_type *new_type;
614
615                 if (!(type = ao2_find(src->payloads, &i, OBJ_KEY | OBJ_NOLOCK))) {
616                         continue;
617                 }
618
619                 if (!(new_type = ao2_alloc(sizeof(*new_type), NULL))) {
620                         continue;
621                 }
622
623                 ast_debug(2, "Copying payload %d from %p to %p\n", i, src, dest);
624
625                 new_type->payload = i;
626                 *new_type = *type;
627
628                 ao2_link_flags(dest->payloads, new_type, OBJ_NOLOCK);
629
630                 ao2_ref(new_type, -1);
631
632                 if (instance && instance->engine && instance->engine->payload_set) {
633                         instance->engine->payload_set(instance, i, type->asterisk_format, &type->format, type->rtp_code);
634                 }
635
636                 ao2_ref(type, -1);
637         }
638 }
639
640 void ast_rtp_codecs_payloads_set_m_type(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, int payload)
641 {
642         struct ast_rtp_payload_type *type;
643
644         ast_rwlock_rdlock(&static_RTP_PT_lock);
645
646         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
647                 ast_rwlock_unlock(&static_RTP_PT_lock);
648                 return;
649         }
650
651         if (!(type = ao2_find(codecs->payloads, &payload, OBJ_KEY | OBJ_NOLOCK))) {
652                 if (!(type = ao2_alloc(sizeof(*type), NULL))) {
653                         ast_rwlock_unlock(&static_RTP_PT_lock);
654                         return;
655                 }
656                 type->payload = payload;
657                 ao2_link_flags(codecs->payloads, type, OBJ_NOLOCK);
658         }
659
660         type->asterisk_format = static_RTP_PT[payload].asterisk_format;
661         type->rtp_code = static_RTP_PT[payload].rtp_code;
662         type->payload = payload;
663         ast_format_copy(&type->format, &static_RTP_PT[payload].format);
664
665         ast_debug(1, "Setting payload %d based on m type on %p\n", payload, codecs);
666
667         if (instance && instance->engine && instance->engine->payload_set) {
668                 instance->engine->payload_set(instance, payload, type->asterisk_format, &type->format, type->rtp_code);
669         }
670
671         ao2_ref(type, -1);
672
673         ast_rwlock_unlock(&static_RTP_PT_lock);
674 }
675
676 int ast_rtp_codecs_payloads_set_rtpmap_type_rate(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, int pt,
677                                  char *mimetype, char *mimesubtype,
678                                  enum ast_rtp_options options,
679                                  unsigned int sample_rate)
680 {
681         unsigned int i;
682         int found = 0;
683
684         if (pt < 0 || pt >= AST_RTP_MAX_PT)
685                 return -1; /* bogus payload type */
686
687         ast_rwlock_rdlock(&mime_types_lock);
688         for (i = 0; i < mime_types_len; ++i) {
689                 const struct ast_rtp_mime_type *t = &ast_rtp_mime_types[i];
690                 struct ast_rtp_payload_type *type;
691
692                 if (strcasecmp(mimesubtype, t->subtype)) {
693                         continue;
694                 }
695
696                 if (strcasecmp(mimetype, t->type)) {
697                         continue;
698                 }
699
700                 /* if both sample rates have been supplied, and they don't match,
701                  * then this not a match; if one has not been supplied, then the
702                  * rates are not compared */
703                 if (sample_rate && t->sample_rate &&
704                     (sample_rate != t->sample_rate)) {
705                         continue;
706                 }
707
708                 found = 1;
709
710                 if (!(type = ao2_find(codecs->payloads, &pt, OBJ_KEY | OBJ_NOLOCK))) {
711                         if (!(type = ao2_alloc(sizeof(*type), NULL))) {
712                                 continue;
713                         }
714                         type->payload = pt;
715                         ao2_link_flags(codecs->payloads, type, OBJ_NOLOCK);
716                 }
717
718                 *type = t->payload_type;
719                 type->payload = pt;
720
721                 if ((t->payload_type.format.id == AST_FORMAT_G726) && t->payload_type.asterisk_format && (options & AST_RTP_OPT_G726_NONSTANDARD)) {
722                         ast_format_set(&type->format, AST_FORMAT_G726_AAL2, 0);
723                 }
724
725                 if (instance && instance->engine && instance->engine->payload_set) {
726                         instance->engine->payload_set(instance, pt, type->asterisk_format, &type->format, type->rtp_code);
727                 }
728
729                 ao2_ref(type, -1);
730
731                 break;
732         }
733         ast_rwlock_unlock(&mime_types_lock);
734
735         return (found ? 0 : -2);
736 }
737
738 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)
739 {
740         return ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, instance, payload, mimetype, mimesubtype, options, 0);
741 }
742
743 void ast_rtp_codecs_payloads_unset(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, int payload)
744 {
745         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
746                 return;
747         }
748
749         ast_debug(2, "Unsetting payload %d on %p\n", payload, codecs);
750
751         ao2_find(codecs->payloads, &payload, OBJ_KEY | OBJ_NOLOCK | OBJ_NODATA | OBJ_UNLINK);
752
753         if (instance && instance->engine && instance->engine->payload_set) {
754                 instance->engine->payload_set(instance, payload, 0, NULL, 0);
755         }
756 }
757
758 struct ast_rtp_payload_type ast_rtp_codecs_payload_lookup(struct ast_rtp_codecs *codecs, int payload)
759 {
760         struct ast_rtp_payload_type result = { .asterisk_format = 0, }, *type;
761
762         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
763                 return result;
764         }
765
766         if ((type = ao2_find(codecs->payloads, &payload, OBJ_KEY | OBJ_NOLOCK))) {
767                 result = *type;
768                 ao2_ref(type, -1);
769         }
770
771         if (!result.rtp_code && !result.asterisk_format) {
772                 ast_rwlock_rdlock(&static_RTP_PT_lock);
773                 result = static_RTP_PT[payload];
774                 ast_rwlock_unlock(&static_RTP_PT_lock);
775         }
776
777         return result;
778 }
779
780
781 struct ast_format *ast_rtp_codecs_get_payload_format(struct ast_rtp_codecs *codecs, int payload)
782 {
783         struct ast_rtp_payload_type *type;
784         struct ast_format *format;
785
786         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
787                 return NULL;
788         }
789
790         if (!(type = ao2_find(codecs->payloads, &payload, OBJ_KEY | OBJ_NOLOCK))) {
791                 return NULL;
792         }
793
794         format = type->asterisk_format ? &type->format : NULL;
795
796         ao2_ref(type, -1);
797
798         return format;
799 }
800
801 static int rtp_payload_type_add_ast(void *obj, void *arg, int flags)
802 {
803         struct ast_rtp_payload_type *type = obj;
804         struct ast_format_cap *astformats = arg;
805
806         if (type->asterisk_format) {
807                 ast_format_cap_add(astformats, &type->format);
808         }
809
810         return 0;
811 }
812
813 static int rtp_payload_type_add_nonast(void *obj, void *arg, int flags)
814 {
815         struct ast_rtp_payload_type *type = obj;
816         int *nonastformats = arg;
817
818         if (!type->asterisk_format) {
819                 *nonastformats |= type->rtp_code;
820         }
821
822         return 0;
823 }
824
825 void ast_rtp_codecs_payload_formats(struct ast_rtp_codecs *codecs, struct ast_format_cap *astformats, int *nonastformats)
826 {
827         ast_format_cap_remove_all(astformats);
828         *nonastformats = 0;
829
830         ao2_callback(codecs->payloads, OBJ_NODATA | OBJ_MULTIPLE | OBJ_NOLOCK, rtp_payload_type_add_ast, astformats);
831         ao2_callback(codecs->payloads, OBJ_NODATA | OBJ_MULTIPLE | OBJ_NOLOCK, rtp_payload_type_add_nonast, nonastformats);
832 }
833
834 static int rtp_payload_type_find_format(void *obj, void *arg, int flags)
835 {
836         struct ast_rtp_payload_type *type = obj;
837         struct ast_format *format = arg;
838
839         return (type->asterisk_format && (ast_format_cmp(&type->format, format) != AST_FORMAT_CMP_NOT_EQUAL)) ? CMP_MATCH | CMP_STOP : 0;
840 }
841
842 static int rtp_payload_type_find_nonast_format(void *obj, void *arg, int flags)
843 {
844         struct ast_rtp_payload_type *type = obj;
845         int *rtp_code = arg;
846
847         return ((!type->asterisk_format && (type->rtp_code == *rtp_code)) ? CMP_MATCH | CMP_STOP : 0);
848 }
849
850 int ast_rtp_codecs_payload_code(struct ast_rtp_codecs *codecs, int asterisk_format, const struct ast_format *format, int code)
851 {
852         struct ast_rtp_payload_type *type;
853         int i, res = -1;
854
855         if (asterisk_format && format && (type = ao2_callback(codecs->payloads, OBJ_NOLOCK, rtp_payload_type_find_format, (void*)format))) {
856                 res = type->payload;
857                 ao2_ref(type, -1);
858                 return res;
859         } else if (!asterisk_format && (type = ao2_callback(codecs->payloads, OBJ_NOLOCK, rtp_payload_type_find_nonast_format, (void*)&code))) {
860                 res = type->payload;
861                 ao2_ref(type, -1);
862                 return res;
863         }
864
865         ast_rwlock_rdlock(&static_RTP_PT_lock);
866         for (i = 0; i < AST_RTP_MAX_PT; i++) {
867                 if (static_RTP_PT[i].asterisk_format && asterisk_format && format &&
868                         (ast_format_cmp(format, &static_RTP_PT[i].format) != AST_FORMAT_CMP_NOT_EQUAL)) {
869                         res = i;
870                         break;
871                 } else if (!static_RTP_PT[i].asterisk_format && !asterisk_format &&
872                         (static_RTP_PT[i].rtp_code == code)) {
873                         res = i;
874                         break;
875                 }
876         }
877         ast_rwlock_unlock(&static_RTP_PT_lock);
878
879         return res;
880 }
881 int ast_rtp_codecs_find_payload_code(struct ast_rtp_codecs *codecs, int code)
882 {
883         struct ast_rtp_payload_type *type;
884         int res = -1;
885
886         /* Search the payload type in the codecs passed */
887         if ((type = ao2_find(codecs->payloads, &code, OBJ_NOLOCK | OBJ_KEY)))
888         {
889                 res = type->payload;
890                 ao2_ref(type, -1);
891                 return res;
892         }
893
894         return res;
895 }
896 const char *ast_rtp_lookup_mime_subtype2(const int asterisk_format, struct ast_format *format, int code, enum ast_rtp_options options)
897 {
898         int i;
899         const char *res = "";
900
901         ast_rwlock_rdlock(&mime_types_lock);
902         for (i = 0; i < mime_types_len; i++) {
903                 if (ast_rtp_mime_types[i].payload_type.asterisk_format && asterisk_format && format &&
904                         (ast_format_cmp(format, &ast_rtp_mime_types[i].payload_type.format) != AST_FORMAT_CMP_NOT_EQUAL)) {
905                         if ((format->id == AST_FORMAT_G726_AAL2) && (options & AST_RTP_OPT_G726_NONSTANDARD)) {
906                                 res = "G726-32";
907                                 break;
908                         } else {
909                                 res = ast_rtp_mime_types[i].subtype;
910                                 break;
911                         }
912                 } else if (!ast_rtp_mime_types[i].payload_type.asterisk_format && !asterisk_format &&
913                         ast_rtp_mime_types[i].payload_type.rtp_code == code) {
914
915                         res = ast_rtp_mime_types[i].subtype;
916                         break;
917                 }
918         }
919         ast_rwlock_unlock(&mime_types_lock);
920
921         return res;
922 }
923
924 unsigned int ast_rtp_lookup_sample_rate2(int asterisk_format, struct ast_format *format, int code)
925 {
926         unsigned int i;
927         unsigned int res = 0;
928
929         ast_rwlock_rdlock(&mime_types_lock);
930         for (i = 0; i < mime_types_len; ++i) {
931                 if (ast_rtp_mime_types[i].payload_type.asterisk_format && asterisk_format && format &&
932                         (ast_format_cmp(format, &ast_rtp_mime_types[i].payload_type.format) != AST_FORMAT_CMP_NOT_EQUAL)) {
933                         res = ast_rtp_mime_types[i].sample_rate;
934                         break;
935                 } else if (!ast_rtp_mime_types[i].payload_type.asterisk_format && !asterisk_format &&
936                         ast_rtp_mime_types[i].payload_type.rtp_code == code) {
937                         res = ast_rtp_mime_types[i].sample_rate;
938                         break;
939                 }
940         }
941         ast_rwlock_unlock(&mime_types_lock);
942
943         return res;
944 }
945
946 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)
947 {
948         int found = 0;
949         const char *name;
950         if (!buf) {
951                 return NULL;
952         }
953
954
955         if (asterisk_format) {
956                 struct ast_format tmp_fmt;
957                 ast_format_cap_iter_start(ast_format_capability);
958                 while (!ast_format_cap_iter_next(ast_format_capability, &tmp_fmt)) {
959                         name = ast_rtp_lookup_mime_subtype2(asterisk_format, &tmp_fmt, 0, options);
960                         ast_str_append(&buf, 0, "%s|", name);
961                         found = 1;
962                 }
963                 ast_format_cap_iter_end(ast_format_capability);
964
965         } else {
966                 int x;
967                 ast_str_append(&buf, 0, "0x%x (", (unsigned int) rtp_capability);
968                 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
969                         if (rtp_capability & x) {
970                                 name = ast_rtp_lookup_mime_subtype2(asterisk_format, NULL, x, options);
971                                 ast_str_append(&buf, 0, "%s|", name);
972                                 found = 1;
973                         }
974                 }
975         }
976
977         ast_str_append(&buf, 0, "%s", found ? ")" : "nothing)");
978
979         return ast_str_buffer(buf);
980 }
981
982 void ast_rtp_codecs_packetization_set(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, struct ast_codec_pref *prefs)
983 {
984         codecs->pref = *prefs;
985
986         if (instance && instance->engine->packetization_set) {
987                 instance->engine->packetization_set(instance, &instance->codecs.pref);
988         }
989 }
990
991 int ast_rtp_instance_dtmf_begin(struct ast_rtp_instance *instance, char digit)
992 {
993         return instance->engine->dtmf_begin ? instance->engine->dtmf_begin(instance, digit) : -1;
994 }
995
996 int ast_rtp_instance_dtmf_end(struct ast_rtp_instance *instance, char digit)
997 {
998         return instance->engine->dtmf_end ? instance->engine->dtmf_end(instance, digit) : -1;
999 }
1000 int ast_rtp_instance_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
1001 {
1002         return instance->engine->dtmf_end_with_duration ? instance->engine->dtmf_end_with_duration(instance, digit, duration) : -1;
1003 }
1004
1005 int ast_rtp_instance_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
1006 {
1007         return (!instance->engine->dtmf_mode_set || instance->engine->dtmf_mode_set(instance, dtmf_mode)) ? -1 : 0;
1008 }
1009
1010 enum ast_rtp_dtmf_mode ast_rtp_instance_dtmf_mode_get(struct ast_rtp_instance *instance)
1011 {
1012         return instance->engine->dtmf_mode_get ? instance->engine->dtmf_mode_get(instance) : 0;
1013 }
1014
1015 void ast_rtp_instance_update_source(struct ast_rtp_instance *instance)
1016 {
1017         if (instance->engine->update_source) {
1018                 instance->engine->update_source(instance);
1019         }
1020 }
1021
1022 void ast_rtp_instance_change_source(struct ast_rtp_instance *instance)
1023 {
1024         if (instance->engine->change_source) {
1025                 instance->engine->change_source(instance);
1026         }
1027 }
1028
1029 int ast_rtp_instance_set_qos(struct ast_rtp_instance *instance, int tos, int cos, const char *desc)
1030 {
1031         return instance->engine->qos ? instance->engine->qos(instance, tos, cos, desc) : -1;
1032 }
1033
1034 void ast_rtp_instance_stop(struct ast_rtp_instance *instance)
1035 {
1036         if (instance->engine->stop) {
1037                 instance->engine->stop(instance);
1038         }
1039 }
1040
1041 int ast_rtp_instance_fd(struct ast_rtp_instance *instance, int rtcp)
1042 {
1043         return instance->engine->fd ? instance->engine->fd(instance, rtcp) : -1;
1044 }
1045
1046 struct ast_rtp_glue *ast_rtp_instance_get_glue(const char *type)
1047 {
1048         struct ast_rtp_glue *glue = NULL;
1049
1050         AST_RWLIST_RDLOCK(&glues);
1051
1052         AST_RWLIST_TRAVERSE(&glues, glue, entry) {
1053                 if (!strcasecmp(glue->type, type)) {
1054                         break;
1055                 }
1056         }
1057
1058         AST_RWLIST_UNLOCK(&glues);
1059
1060         return glue;
1061 }
1062
1063 /*!
1064  * \brief Conditionally unref an rtp instance
1065  */
1066 static void unref_instance_cond(struct ast_rtp_instance **instance)
1067 {
1068         if (*instance) {
1069                 ao2_ref(*instance, -1);
1070                 *instance = NULL;
1071         }
1072 }
1073
1074 struct ast_rtp_instance *ast_rtp_instance_get_bridged(struct ast_rtp_instance *instance)
1075 {
1076         return instance->bridged;
1077 }
1078
1079 void ast_rtp_instance_set_bridged(struct ast_rtp_instance *instance, struct ast_rtp_instance *bridged)
1080 {
1081         instance->bridged = bridged;
1082 }
1083
1084 void ast_rtp_instance_early_bridge_make_compatible(struct ast_channel *c_dst, struct ast_channel *c_src)
1085 {
1086         struct ast_rtp_instance *instance_dst = NULL, *instance_src = NULL,
1087                 *vinstance_dst = NULL, *vinstance_src = NULL,
1088                 *tinstance_dst = NULL, *tinstance_src = NULL;
1089         struct ast_rtp_glue *glue_dst, *glue_src;
1090         enum ast_rtp_glue_result audio_glue_dst_res = AST_RTP_GLUE_RESULT_FORBID, video_glue_dst_res = AST_RTP_GLUE_RESULT_FORBID;
1091         enum ast_rtp_glue_result audio_glue_src_res = AST_RTP_GLUE_RESULT_FORBID, video_glue_src_res = AST_RTP_GLUE_RESULT_FORBID;
1092         struct ast_format_cap *cap_dst = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
1093         struct ast_format_cap *cap_src = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
1094
1095         /* Lock both channels so we can look for the glue that binds them together */
1096         ast_channel_lock_both(c_dst, c_src);
1097
1098         if (!cap_src || !cap_dst) {
1099                 goto done;
1100         }
1101
1102         /* Grab glue that binds each channel to something using the RTP engine */
1103         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))) {
1104                 ast_debug(1, "Can't find native functions for channel '%s'\n", glue_dst ? ast_channel_name(c_src) : ast_channel_name(c_dst));
1105                 goto done;
1106         }
1107
1108         audio_glue_dst_res = glue_dst->get_rtp_info(c_dst, &instance_dst);
1109         video_glue_dst_res = glue_dst->get_vrtp_info ? glue_dst->get_vrtp_info(c_dst, &vinstance_dst) : AST_RTP_GLUE_RESULT_FORBID;
1110
1111         audio_glue_src_res = glue_src->get_rtp_info(c_src, &instance_src);
1112         video_glue_src_res = glue_src->get_vrtp_info ? glue_src->get_vrtp_info(c_src, &vinstance_src) : AST_RTP_GLUE_RESULT_FORBID;
1113
1114         /* If we are carrying video, and both sides are not going to remotely bridge... fail the native bridge */
1115         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)) {
1116                 audio_glue_dst_res = AST_RTP_GLUE_RESULT_FORBID;
1117         }
1118         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)) {
1119                 audio_glue_src_res = AST_RTP_GLUE_RESULT_FORBID;
1120         }
1121         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) {
1122                 glue_dst->get_codec(c_dst, cap_dst);
1123         }
1124         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) {
1125                 glue_src->get_codec(c_src, cap_src);
1126         }
1127
1128         /* If any sort of bridge is forbidden just completely bail out and go back to generic bridging */
1129         if (audio_glue_dst_res != AST_RTP_GLUE_RESULT_REMOTE || audio_glue_src_res != AST_RTP_GLUE_RESULT_REMOTE) {
1130                 goto done;
1131         }
1132
1133         /* Make sure we have matching codecs */
1134         if (!ast_format_cap_has_joint(cap_dst, cap_src)) {
1135                 goto done;
1136         }
1137
1138         ast_rtp_codecs_payloads_copy(&instance_src->codecs, &instance_dst->codecs, instance_dst);
1139
1140         if (vinstance_dst && vinstance_src) {
1141                 ast_rtp_codecs_payloads_copy(&vinstance_src->codecs, &vinstance_dst->codecs, vinstance_dst);
1142         }
1143         if (tinstance_dst && tinstance_src) {
1144                 ast_rtp_codecs_payloads_copy(&tinstance_src->codecs, &tinstance_dst->codecs, tinstance_dst);
1145         }
1146
1147         if (glue_dst->update_peer(c_dst, instance_src, vinstance_src, tinstance_src, cap_src, 0)) {
1148                 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n",
1149                         ast_channel_name(c_dst), ast_channel_name(c_src));
1150         } else {
1151                 ast_debug(1, "Seeded SDP of '%s' with that of '%s'\n",
1152                         ast_channel_name(c_dst), ast_channel_name(c_src));
1153         }
1154
1155 done:
1156         ast_channel_unlock(c_dst);
1157         ast_channel_unlock(c_src);
1158
1159         ast_format_cap_destroy(cap_dst);
1160         ast_format_cap_destroy(cap_src);
1161
1162         unref_instance_cond(&instance_dst);
1163         unref_instance_cond(&instance_src);
1164         unref_instance_cond(&vinstance_dst);
1165         unref_instance_cond(&vinstance_src);
1166         unref_instance_cond(&tinstance_dst);
1167         unref_instance_cond(&tinstance_src);
1168 }
1169
1170 int ast_rtp_instance_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
1171 {
1172         struct ast_rtp_instance *instance0 = NULL, *instance1 = NULL,
1173                         *vinstance0 = NULL, *vinstance1 = NULL,
1174                         *tinstance0 = NULL, *tinstance1 = NULL;
1175         struct ast_rtp_glue *glue0, *glue1;
1176         enum ast_rtp_glue_result audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID, video_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1177         enum ast_rtp_glue_result audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID, video_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1178         struct ast_format_cap *cap0 = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
1179         struct ast_format_cap *cap1 = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
1180
1181         /* If there is no second channel just immediately bail out, we are of no use in that scenario */
1182         if (!c1 || !cap1 || !cap0) {
1183                 ast_format_cap_destroy(cap0);
1184                 ast_format_cap_destroy(cap1);
1185                 return -1;
1186         }
1187
1188         /* Lock both channels so we can look for the glue that binds them together */
1189         ast_channel_lock_both(c0, c1);
1190
1191         /* Grab glue that binds each channel to something using the RTP engine */
1192         if (!(glue0 = ast_rtp_instance_get_glue(ast_channel_tech(c0)->type)) || !(glue1 = ast_rtp_instance_get_glue(ast_channel_tech(c1)->type))) {
1193                 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", glue0 ? ast_channel_name(c1) : ast_channel_name(c0));
1194                 goto done;
1195         }
1196
1197         audio_glue0_res = glue0->get_rtp_info(c0, &instance0);
1198         video_glue0_res = glue0->get_vrtp_info ? glue0->get_vrtp_info(c0, &vinstance0) : AST_RTP_GLUE_RESULT_FORBID;
1199
1200         audio_glue1_res = glue1->get_rtp_info(c1, &instance1);
1201         video_glue1_res = glue1->get_vrtp_info ? glue1->get_vrtp_info(c1, &vinstance1) : AST_RTP_GLUE_RESULT_FORBID;
1202
1203         /* If we are carrying video, and both sides are not going to remotely bridge... fail the native bridge */
1204         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)) {
1205                 audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1206         }
1207         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)) {
1208                 audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1209         }
1210         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) {
1211                 glue0->get_codec(c0, cap0);
1212         }
1213         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) {
1214                 glue1->get_codec(c1, cap1);
1215         }
1216
1217         /* If any sort of bridge is forbidden just completely bail out and go back to generic bridging */
1218         if (audio_glue0_res != AST_RTP_GLUE_RESULT_REMOTE || audio_glue1_res != AST_RTP_GLUE_RESULT_REMOTE) {
1219                 goto done;
1220         }
1221
1222         /* Make sure we have matching codecs */
1223         if (!ast_format_cap_has_joint(cap0, cap1)) {
1224                 goto done;
1225         }
1226
1227         /* Bridge media early */
1228         if (glue0->update_peer(c0, instance1, vinstance1, tinstance1, cap1, 0)) {
1229                 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", ast_channel_name(c0), c1 ? ast_channel_name(c1) : "<unspecified>");
1230         }
1231
1232 done:
1233         ast_channel_unlock(c0);
1234         ast_channel_unlock(c1);
1235
1236         ast_format_cap_destroy(cap0);
1237         ast_format_cap_destroy(cap1);
1238
1239         unref_instance_cond(&instance0);
1240         unref_instance_cond(&instance1);
1241         unref_instance_cond(&vinstance0);
1242         unref_instance_cond(&vinstance1);
1243         unref_instance_cond(&tinstance0);
1244         unref_instance_cond(&tinstance1);
1245
1246         ast_debug(1, "Setting early bridge SDP of '%s' with that of '%s'\n", ast_channel_name(c0), c1 ? ast_channel_name(c1) : "<unspecified>");
1247
1248         return 0;
1249 }
1250
1251 int ast_rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations)
1252 {
1253         return instance->engine->red_init ? instance->engine->red_init(instance, buffer_time, payloads, generations) : -1;
1254 }
1255
1256 int ast_rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame)
1257 {
1258         return instance->engine->red_buffer ? instance->engine->red_buffer(instance, frame) : -1;
1259 }
1260
1261 int ast_rtp_instance_get_stats(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat)
1262 {
1263         return instance->engine->get_stat ? instance->engine->get_stat(instance, stats, stat) : -1;
1264 }
1265
1266 char *ast_rtp_instance_get_quality(struct ast_rtp_instance *instance, enum ast_rtp_instance_stat_field field, char *buf, size_t size)
1267 {
1268         struct ast_rtp_instance_stats stats = { 0, };
1269         enum ast_rtp_instance_stat stat;
1270
1271         /* Determine what statistics we will need to retrieve based on field passed in */
1272         if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY) {
1273                 stat = AST_RTP_INSTANCE_STAT_ALL;
1274         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER) {
1275                 stat = AST_RTP_INSTANCE_STAT_COMBINED_JITTER;
1276         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS) {
1277                 stat = AST_RTP_INSTANCE_STAT_COMBINED_LOSS;
1278         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT) {
1279                 stat = AST_RTP_INSTANCE_STAT_COMBINED_RTT;
1280         } else {
1281                 return NULL;
1282         }
1283
1284         /* Attempt to actually retrieve the statistics we need to generate the quality string */
1285         if (ast_rtp_instance_get_stats(instance, &stats, stat)) {
1286                 return NULL;
1287         }
1288
1289         /* Now actually fill the buffer with the good information */
1290         if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY) {
1291                 snprintf(buf, size, "ssrc=%u;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f",
1292                          stats.local_ssrc, stats.remote_ssrc, stats.rxploss, stats.rxjitter, stats.rxcount, stats.txjitter, stats.txcount, stats.txploss, stats.rtt);
1293         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER) {
1294                 snprintf(buf, size, "minrxjitter=%f;maxrxjitter=%f;avgrxjitter=%f;stdevrxjitter=%f;reported_minjitter=%f;reported_maxjitter=%f;reported_avgjitter=%f;reported_stdevjitter=%f;",
1295                          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));
1296         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS) {
1297                 snprintf(buf, size, "minrxlost=%f;maxrxlost=%f;avgrxlost=%f;stdevrxlost=%f;reported_minlost=%f;reported_maxlost=%f;reported_avglost=%f;reported_stdevlost=%f;",
1298                          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));
1299         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT) {
1300                 snprintf(buf, size, "minrtt=%f;maxrtt=%f;avgrtt=%f;stdevrtt=%f;", stats.minrtt, stats.maxrtt, stats.normdevrtt, stats.stdevrtt);
1301         }
1302
1303         return buf;
1304 }
1305
1306 void ast_rtp_instance_set_stats_vars(struct ast_channel *chan, struct ast_rtp_instance *instance)
1307 {
1308         char quality_buf[AST_MAX_USER_FIELD];
1309         char *quality;
1310         struct ast_channel *bridge = ast_channel_bridge_peer(chan);
1311
1312         ast_channel_lock(chan);
1313         ast_channel_stage_snapshot(chan);
1314         ast_channel_unlock(chan);
1315         if (bridge) {
1316                 ast_channel_lock(bridge);
1317                 ast_channel_stage_snapshot(bridge);
1318                 ast_channel_unlock(bridge);
1319         }
1320
1321         quality = ast_rtp_instance_get_quality(instance, AST_RTP_INSTANCE_STAT_FIELD_QUALITY,
1322                 quality_buf, sizeof(quality_buf));
1323         if (quality) {
1324                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOS", quality);
1325                 if (bridge) {
1326                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSBRIDGED", quality);
1327                 }
1328         }
1329
1330         quality = ast_rtp_instance_get_quality(instance,
1331                 AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf));
1332         if (quality) {
1333                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSJITTER", quality);
1334                 if (bridge) {
1335                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSJITTERBRIDGED", quality);
1336                 }
1337         }
1338
1339         quality = ast_rtp_instance_get_quality(instance,
1340                 AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf));
1341         if (quality) {
1342                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSLOSS", quality);
1343                 if (bridge) {
1344                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSLOSSBRIDGED", quality);
1345                 }
1346         }
1347
1348         quality = ast_rtp_instance_get_quality(instance,
1349                 AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf));
1350         if (quality) {
1351                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSRTT", quality);
1352                 if (bridge) {
1353                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSRTTBRIDGED", quality);
1354                 }
1355         }
1356
1357         ast_channel_lock(chan);
1358         ast_channel_stage_snapshot_done(chan);
1359         ast_channel_unlock(chan);
1360         if (bridge) {
1361                 ast_channel_lock(bridge);
1362                 ast_channel_stage_snapshot_done(bridge);
1363                 ast_channel_unlock(bridge);
1364                 ast_channel_unref(bridge);
1365         }
1366 }
1367
1368 int ast_rtp_instance_set_read_format(struct ast_rtp_instance *instance, struct ast_format *format)
1369 {
1370         return instance->engine->set_read_format ? instance->engine->set_read_format(instance, format) : -1;
1371 }
1372
1373 int ast_rtp_instance_set_write_format(struct ast_rtp_instance *instance, struct ast_format *format)
1374 {
1375         return instance->engine->set_write_format ? instance->engine->set_write_format(instance, format) : -1;
1376 }
1377
1378 int ast_rtp_instance_make_compatible(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_channel *peer)
1379 {
1380         struct ast_rtp_glue *glue;
1381         struct ast_rtp_instance *peer_instance = NULL;
1382         int res = -1;
1383
1384         if (!instance->engine->make_compatible) {
1385                 return -1;
1386         }
1387
1388         ast_channel_lock(peer);
1389
1390         if (!(glue = ast_rtp_instance_get_glue(ast_channel_tech(peer)->type))) {
1391                 ast_channel_unlock(peer);
1392                 return -1;
1393         }
1394
1395         glue->get_rtp_info(peer, &peer_instance);
1396         if (!peer_instance) {
1397                 ast_log(LOG_ERROR, "Unable to get_rtp_info for peer type %s\n", glue->type);
1398                 ast_channel_unlock(peer);
1399                 return -1;
1400         }
1401         if (peer_instance->engine != instance->engine) {
1402                 ast_log(LOG_ERROR, "Peer engine mismatch for type %s\n", glue->type);
1403                 ast_channel_unlock(peer);
1404                 ao2_ref(peer_instance, -1);
1405                 return -1;
1406         }
1407
1408         res = instance->engine->make_compatible(chan, instance, peer, peer_instance);
1409
1410         ast_channel_unlock(peer);
1411
1412         ao2_ref(peer_instance, -1);
1413         peer_instance = NULL;
1414
1415         return res;
1416 }
1417
1418 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)
1419 {
1420         if (instance->engine->available_formats) {
1421                 instance->engine->available_formats(instance, to_endpoint, to_asterisk, result);
1422                 if (!ast_format_cap_is_empty(result)) {
1423                         return;
1424                 }
1425         }
1426
1427         ast_translate_available_formats(to_endpoint, to_asterisk, result);
1428 }
1429
1430 int ast_rtp_instance_activate(struct ast_rtp_instance *instance)
1431 {
1432         return instance->engine->activate ? instance->engine->activate(instance) : 0;
1433 }
1434
1435 void ast_rtp_instance_stun_request(struct ast_rtp_instance *instance,
1436                                    struct ast_sockaddr *suggestion,
1437                                    const char *username)
1438 {
1439         if (instance->engine->stun_request) {
1440                 instance->engine->stun_request(instance, suggestion, username);
1441         }
1442 }
1443
1444 void ast_rtp_instance_set_timeout(struct ast_rtp_instance *instance, int timeout)
1445 {
1446         instance->timeout = timeout;
1447 }
1448
1449 void ast_rtp_instance_set_hold_timeout(struct ast_rtp_instance *instance, int timeout)
1450 {
1451         instance->holdtimeout = timeout;
1452 }
1453
1454 void ast_rtp_instance_set_keepalive(struct ast_rtp_instance *instance, int interval)
1455 {
1456         instance->keepalive = interval;
1457 }
1458
1459 int ast_rtp_instance_get_timeout(struct ast_rtp_instance *instance)
1460 {
1461         return instance->timeout;
1462 }
1463
1464 int ast_rtp_instance_get_hold_timeout(struct ast_rtp_instance *instance)
1465 {
1466         return instance->holdtimeout;
1467 }
1468
1469 int ast_rtp_instance_get_keepalive(struct ast_rtp_instance *instance)
1470 {
1471         return instance->keepalive;
1472 }
1473
1474 struct ast_rtp_engine *ast_rtp_instance_get_engine(struct ast_rtp_instance *instance)
1475 {
1476         return instance->engine;
1477 }
1478
1479 struct ast_rtp_glue *ast_rtp_instance_get_active_glue(struct ast_rtp_instance *instance)
1480 {
1481         return instance->glue;
1482 }
1483
1484 int ast_rtp_engine_register_srtp(struct ast_srtp_res *srtp_res, struct ast_srtp_policy_res *policy_res)
1485 {
1486         if (res_srtp || res_srtp_policy) {
1487                 return -1;
1488         }
1489         if (!srtp_res || !policy_res) {
1490                 return -1;
1491         }
1492
1493         res_srtp = srtp_res;
1494         res_srtp_policy = policy_res;
1495
1496         return 0;
1497 }
1498
1499 void ast_rtp_engine_unregister_srtp(void)
1500 {
1501         res_srtp = NULL;
1502         res_srtp_policy = NULL;
1503 }
1504
1505 int ast_rtp_engine_srtp_is_registered(void)
1506 {
1507         return res_srtp && res_srtp_policy;
1508 }
1509
1510 int ast_rtp_instance_add_srtp_policy(struct ast_rtp_instance *instance, struct ast_srtp_policy *remote_policy, struct ast_srtp_policy *local_policy)
1511 {
1512         int res = 0;
1513
1514         if (!res_srtp) {
1515                 return -1;
1516         }
1517
1518         if (!instance->srtp) {
1519                 res = res_srtp->create(&instance->srtp, instance, remote_policy);
1520         } else {
1521                 res = res_srtp->replace(&instance->srtp, instance, remote_policy);
1522         }
1523         if (!res) {
1524                 res = res_srtp->add_stream(instance->srtp, local_policy);
1525         }
1526
1527         return res;
1528 }
1529
1530 struct ast_srtp *ast_rtp_instance_get_srtp(struct ast_rtp_instance *instance)
1531 {
1532         return instance->srtp;
1533 }
1534
1535 int ast_rtp_instance_sendcng(struct ast_rtp_instance *instance, int level)
1536 {
1537         if (instance->engine->sendcng) {
1538                 return instance->engine->sendcng(instance, level);
1539         }
1540
1541         return -1;
1542 }
1543
1544 struct ast_rtp_engine_ice *ast_rtp_instance_get_ice(struct ast_rtp_instance *instance)
1545 {
1546         return instance->engine->ice;
1547 }
1548
1549 struct ast_rtp_engine_dtls *ast_rtp_instance_get_dtls(struct ast_rtp_instance *instance)
1550 {
1551         return instance->engine->dtls;
1552 }
1553
1554 int ast_rtp_dtls_cfg_parse(struct ast_rtp_dtls_cfg *dtls_cfg, const char *name, const char *value)
1555 {
1556         if (!strcasecmp(name, "dtlsenable")) {
1557                 dtls_cfg->enabled = ast_true(value) ? 1 : 0;
1558         } else if (!strcasecmp(name, "dtlsverify")) {
1559                 dtls_cfg->verify = ast_true(value) ? 1 : 0;
1560         } else if (!strcasecmp(name, "dtlsrekey")) {
1561                 if (sscanf(value, "%30u", &dtls_cfg->rekey) != 1) {
1562                         return -1;
1563                 }
1564         } else if (!strcasecmp(name, "dtlscertfile")) {
1565                 ast_free(dtls_cfg->certfile);
1566                 dtls_cfg->certfile = ast_strdup(value);
1567         } else if (!strcasecmp(name, "dtlsprivatekey")) {
1568                 ast_free(dtls_cfg->pvtfile);
1569                 dtls_cfg->pvtfile = ast_strdup(value);
1570         } else if (!strcasecmp(name, "dtlscipher")) {
1571                 ast_free(dtls_cfg->cipher);
1572                 dtls_cfg->cipher = ast_strdup(value);
1573         } else if (!strcasecmp(name, "dtlscafile")) {
1574                 ast_free(dtls_cfg->cafile);
1575                 dtls_cfg->cafile = ast_strdup(value);
1576         } else if (!strcasecmp(name, "dtlscapath") || !strcasecmp(name, "dtlscadir")) {
1577                 ast_free(dtls_cfg->capath);
1578                 dtls_cfg->capath = ast_strdup(value);
1579         } else if (!strcasecmp(name, "dtlssetup")) {
1580                 if (!strcasecmp(value, "active")) {
1581                         dtls_cfg->default_setup = AST_RTP_DTLS_SETUP_ACTIVE;
1582                 } else if (!strcasecmp(value, "passive")) {
1583                         dtls_cfg->default_setup = AST_RTP_DTLS_SETUP_PASSIVE;
1584                 } else if (!strcasecmp(value, "actpass")) {
1585                         dtls_cfg->default_setup = AST_RTP_DTLS_SETUP_ACTPASS;
1586                 }
1587         } else {
1588                 return -1;
1589         }
1590
1591         return 0;
1592 }
1593
1594 void ast_rtp_dtls_cfg_copy(const struct ast_rtp_dtls_cfg *src_cfg, struct ast_rtp_dtls_cfg *dst_cfg)
1595 {
1596         dst_cfg->enabled = src_cfg->enabled;
1597         dst_cfg->verify = src_cfg->verify;
1598         dst_cfg->rekey = src_cfg->rekey;
1599         dst_cfg->suite = src_cfg->suite;
1600         dst_cfg->certfile = ast_strdup(src_cfg->certfile);
1601         dst_cfg->pvtfile = ast_strdup(src_cfg->pvtfile);
1602         dst_cfg->cipher = ast_strdup(src_cfg->cipher);
1603         dst_cfg->cafile = ast_strdup(src_cfg->cafile);
1604         dst_cfg->capath = ast_strdup(src_cfg->capath);
1605         dst_cfg->default_setup = src_cfg->default_setup;
1606 }
1607
1608 void ast_rtp_dtls_cfg_free(struct ast_rtp_dtls_cfg *dtls_cfg)
1609 {
1610         ast_free(dtls_cfg->certfile);
1611         ast_free(dtls_cfg->pvtfile);
1612         ast_free(dtls_cfg->cipher);
1613         ast_free(dtls_cfg->cafile);
1614         ast_free(dtls_cfg->capath);
1615 }
1616
1617 static void set_next_mime_type(const struct ast_format *format, int rtp_code, char *type, char *subtype, unsigned int sample_rate)
1618 {
1619         int x = mime_types_len;
1620         if (ARRAY_LEN(ast_rtp_mime_types) == mime_types_len) {
1621                 return;
1622         }
1623
1624         ast_rwlock_wrlock(&mime_types_lock);
1625         if (format) {
1626                 ast_rtp_mime_types[x].payload_type.asterisk_format = 1;
1627                 ast_format_copy(&ast_rtp_mime_types[x].payload_type.format, format);
1628         } else {
1629                 ast_rtp_mime_types[x].payload_type.rtp_code = rtp_code;
1630         }
1631         ast_rtp_mime_types[x].type = type;
1632         ast_rtp_mime_types[x].subtype = subtype;
1633         ast_rtp_mime_types[x].sample_rate = sample_rate;
1634         mime_types_len++;
1635         ast_rwlock_unlock(&mime_types_lock);
1636 }
1637
1638 static void add_static_payload(int map, const struct ast_format *format, int rtp_code)
1639 {
1640         int x;
1641         ast_rwlock_wrlock(&static_RTP_PT_lock);
1642         if (map < 0) {
1643                 /* find next available dynamic payload slot */
1644                 for (x = 96; x < 127; x++) {
1645                         if (!static_RTP_PT[x].asterisk_format && !static_RTP_PT[x].rtp_code) {
1646                                 map = x;
1647                                 break;
1648                         }
1649                 }
1650         }
1651
1652         if (map < 0) {
1653                 ast_log(LOG_WARNING, "No Dynamic RTP mapping available for format %s\n" ,ast_getformatname(format));
1654                 ast_rwlock_unlock(&static_RTP_PT_lock);
1655                 return;
1656         }
1657
1658         if (format) {
1659                 static_RTP_PT[map].asterisk_format = 1;
1660                 ast_format_copy(&static_RTP_PT[map].format, format);
1661         } else {
1662                 static_RTP_PT[map].rtp_code = rtp_code;
1663         }
1664         ast_rwlock_unlock(&static_RTP_PT_lock);
1665 }
1666
1667 int ast_rtp_engine_load_format(const struct ast_format *format)
1668 {
1669         switch (format->id) {
1670         case AST_FORMAT_SILK:
1671                 set_next_mime_type(format, 0, "audio", "SILK", ast_format_rate(format));
1672                 add_static_payload(-1, format, 0);
1673                 break;
1674         case AST_FORMAT_CELT:
1675                 set_next_mime_type(format, 0, "audio", "CELT", ast_format_rate(format));
1676                 add_static_payload(-1, format, 0);
1677                 break;
1678         default:
1679                 break;
1680         }
1681
1682         return 0;
1683 }
1684
1685 int ast_rtp_engine_unload_format(const struct ast_format *format)
1686 {
1687         int x;
1688         int y = 0;
1689
1690         ast_rwlock_wrlock(&static_RTP_PT_lock);
1691         /* remove everything pertaining to this format id from the lists */
1692         for (x = 0; x < AST_RTP_MAX_PT; x++) {
1693                 if (ast_format_cmp(&static_RTP_PT[x].format, format) == AST_FORMAT_CMP_EQUAL) {
1694                         memset(&static_RTP_PT[x], 0, sizeof(struct ast_rtp_payload_type));
1695                 }
1696         }
1697         ast_rwlock_unlock(&static_RTP_PT_lock);
1698
1699
1700         ast_rwlock_wrlock(&mime_types_lock);
1701         /* rebuild the list skipping the items matching this id */
1702         for (x = 0; x < mime_types_len; x++) {
1703                 if (ast_format_cmp(&ast_rtp_mime_types[x].payload_type.format, format) == AST_FORMAT_CMP_EQUAL) {
1704                         continue;
1705                 }
1706                 ast_rtp_mime_types[y] = ast_rtp_mime_types[x];
1707                 y++;
1708         }
1709         mime_types_len = y;
1710         ast_rwlock_unlock(&mime_types_lock);
1711         return 0;
1712 }
1713
1714 /*!
1715  * \internal
1716  * \brief \ref stasis message payload for RTCP messages
1717  */
1718 struct rtcp_message_payload {
1719         struct ast_channel_snapshot *snapshot;  /*< The channel snapshot, if available */
1720         struct ast_rtp_rtcp_report *report;     /*< The RTCP report */
1721         struct ast_json *blob;                  /*< Extra JSON data to publish */
1722 };
1723
1724 static void rtcp_message_payload_dtor(void *obj)
1725 {
1726         struct rtcp_message_payload *payload = obj;
1727
1728         ao2_cleanup(payload->report);
1729         ao2_cleanup(payload->snapshot);
1730         ast_json_unref(payload->blob);
1731 }
1732
1733 static struct ast_manager_event_blob *rtcp_report_to_ami(struct stasis_message *msg)
1734 {
1735         struct rtcp_message_payload *payload = stasis_message_data(msg);
1736         RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
1737         RAII_VAR(struct ast_str *, packet_string, ast_str_create(512), ast_free);
1738         unsigned int ssrc = payload->report->ssrc;
1739         unsigned int type = payload->report->type;
1740         unsigned int report_count = payload->report->reception_report_count;
1741         int i;
1742
1743         if (!packet_string) {
1744                 return NULL;
1745         }
1746
1747         if (payload->snapshot) {
1748                 channel_string = ast_manager_build_channel_state_string(payload->snapshot);
1749                 if (!channel_string) {
1750                         return NULL;
1751                 }
1752         }
1753
1754         if (payload->blob) {
1755                 /* Optional data */
1756                 struct ast_json *to = ast_json_object_get(payload->blob, "to");
1757                 struct ast_json *from = ast_json_object_get(payload->blob, "from");
1758                 struct ast_json *rtt = ast_json_object_get(payload->blob, "rtt");
1759                 if (to) {
1760                         ast_str_append(&packet_string, 0, "To: %s\r\n", ast_json_string_get(to));
1761                 }
1762                 if (from) {
1763                         ast_str_append(&packet_string, 0, "From: %s\r\n", ast_json_string_get(from));
1764                 }
1765                 if (rtt) {
1766                         ast_str_append(&packet_string, 0, "RTT: %4.4f\r\n", ast_json_real_get(rtt));
1767                 }
1768         }
1769
1770         ast_str_append(&packet_string, 0, "SSRC: 0x%.8x\r\n", ssrc);
1771         ast_str_append(&packet_string, 0, "PT: %u(%s)\r\n", type, type== AST_RTP_RTCP_SR ? "SR" : "RR");
1772         ast_str_append(&packet_string, 0, "ReportCount: %u\r\n", report_count);
1773         if (type == AST_RTP_RTCP_SR) {
1774                 ast_str_append(&packet_string, 0, "SentNTP: %lu.%06lu\r\n",
1775                         (unsigned long)payload->report->sender_information.ntp_timestamp.tv_sec,
1776                         (unsigned long)payload->report->sender_information.ntp_timestamp.tv_usec * 4096);
1777                 ast_str_append(&packet_string, 0, "SentRTP: %u\r\n",
1778                                 payload->report->sender_information.rtp_timestamp);
1779                 ast_str_append(&packet_string, 0, "SentPackets: %u\r\n",
1780                                 payload->report->sender_information.packet_count);
1781                 ast_str_append(&packet_string, 0, "SentOctets: %u\r\n",
1782                                 payload->report->sender_information.octet_count);
1783         }
1784
1785         for (i = 0; i < report_count; i++) {
1786                 RAII_VAR(struct ast_str *, report_string, NULL, ast_free);
1787
1788                 if (!payload->report->report_block[i]) {
1789                         break;
1790                 }
1791
1792                 report_string = ast_str_create(256);
1793                 if (!report_string) {
1794                         return NULL;
1795                 }
1796
1797                 ast_str_append(&report_string, 0, "Report%dSourceSSRC: 0x%.8x\r\n",
1798                                 i, payload->report->report_block[i]->source_ssrc);
1799                 ast_str_append(&report_string, 0, "Report%dFractionLost: %d\r\n",
1800                                 i, payload->report->report_block[i]->lost_count.fraction);
1801                 ast_str_append(&report_string, 0, "Report%dCumulativeLost: %u\r\n",
1802                                 i, payload->report->report_block[i]->lost_count.packets);
1803                 ast_str_append(&report_string, 0, "Report%dHighestSequence: %u\r\n",
1804                                 i, payload->report->report_block[i]->highest_seq_no & 0xffff);
1805                 ast_str_append(&report_string, 0, "Report%dSequenceNumberCycles: %u\r\n",
1806                                 i, payload->report->report_block[i]->highest_seq_no >> 16);
1807                 ast_str_append(&report_string, 0, "Report%dIAJitter: %u\r\n",
1808                                 i, payload->report->report_block[i]->ia_jitter);
1809                 ast_str_append(&report_string, 0, "Report%dLSR: %u\r\n",
1810                                 i, payload->report->report_block[i]->lsr);
1811                 ast_str_append(&report_string, 0, "Report%dDLSR: %4.4f\r\n",
1812                                 i, ((double)payload->report->report_block[i]->dlsr) / 65536);
1813                 ast_str_append(&packet_string, 0, "%s", ast_str_buffer(report_string));
1814         }
1815
1816         return ast_manager_event_blob_create(EVENT_FLAG_REPORTING,
1817                 stasis_message_type(msg) == ast_rtp_rtcp_received_type() ? "RTCPReceived" : "RTCPSent",
1818                 "%s%s",
1819                 AS_OR(channel_string, ""),
1820                 ast_str_buffer(packet_string));
1821 }
1822
1823 static struct ast_json *rtcp_report_to_json(struct stasis_message *msg,
1824         const struct stasis_message_sanitizer *sanitize)
1825 {
1826         struct rtcp_message_payload *payload = stasis_message_data(msg);
1827         RAII_VAR(struct ast_json *, json_rtcp_report, NULL, ast_json_unref);
1828         RAII_VAR(struct ast_json *, json_rtcp_report_blocks, NULL, ast_json_unref);
1829         RAII_VAR(struct ast_json *, json_rtcp_sender_info, NULL, ast_json_unref);
1830         RAII_VAR(struct ast_json *, json_channel, NULL, ast_json_unref);
1831         int i;
1832
1833         json_rtcp_report_blocks = ast_json_array_create();
1834         if (!json_rtcp_report_blocks) {
1835                 return NULL;
1836         }
1837
1838         for (i = 0; i < payload->report->reception_report_count; i++) {
1839                 struct ast_json *json_report_block;
1840                 json_report_block = ast_json_pack("{s: i, s: i, s: i, s: i, s: i, s: i, s: i}",
1841                                 "source_ssrc", payload->report->report_block[i]->source_ssrc,
1842                                 "fraction_lost", payload->report->report_block[i]->lost_count.fraction,
1843                                 "packets_lost", payload->report->report_block[i]->lost_count.packets,
1844                                 "highest_seq_no", payload->report->report_block[i]->highest_seq_no,
1845                                 "ia_jitter", payload->report->report_block[i]->ia_jitter,
1846                                 "lsr", payload->report->report_block[i]->lsr,
1847                                 "dlsr", payload->report->report_block[i]->dlsr);
1848                 if (!json_report_block) {
1849                         return NULL;
1850                 }
1851
1852                 if (ast_json_array_append(json_rtcp_report_blocks, json_report_block)) {
1853                         return NULL;
1854                 }
1855         }
1856
1857         if (payload->report->type == AST_RTP_RTCP_SR) {
1858                 json_rtcp_sender_info = ast_json_pack("{s: i, s: i, s: i, s: i, s: i}",
1859                                 "ntp_timestamp_sec", payload->report->sender_information.ntp_timestamp.tv_sec,
1860                                 "ntp_timestamp_usec", payload->report->sender_information.ntp_timestamp.tv_usec,
1861                                 "rtp_timestamp", payload->report->sender_information.rtp_timestamp,
1862                                 "packets", payload->report->sender_information.packet_count,
1863                                 "octets", payload->report->sender_information.octet_count);
1864                 if (!json_rtcp_sender_info) {
1865                         return NULL;
1866                 }
1867         }
1868
1869         json_rtcp_report = ast_json_pack("{s: i, s: i, s: i, s: O, s: O}",
1870                         "ssrc", payload->report->ssrc,
1871                         "type", payload->report->type,
1872                         "report_count", payload->report->reception_report_count,
1873                         "sender_information", json_rtcp_sender_info ? json_rtcp_sender_info : ast_json_null(),
1874                         "report_blocks", json_rtcp_report_blocks);
1875         if (!json_rtcp_report) {
1876                 return NULL;
1877         }
1878
1879         if (payload->snapshot) {
1880                 json_channel = ast_channel_snapshot_to_json(payload->snapshot, sanitize);
1881                 if (!json_channel) {
1882                         return NULL;
1883                 }
1884         }
1885
1886         return ast_json_pack("{s: O, s: O, s: O}",
1887                 "channel", payload->snapshot ? json_channel : ast_json_null(),
1888                 "rtcp_report", json_rtcp_report,
1889                 "blob", payload->blob);
1890 }
1891
1892 static void rtp_rtcp_report_dtor(void *obj)
1893 {
1894         int i;
1895         struct ast_rtp_rtcp_report *rtcp_report = obj;
1896
1897         for (i = 0; i < rtcp_report->reception_report_count; i++) {
1898                 ast_free(rtcp_report->report_block[i]);
1899         }
1900 }
1901
1902 struct ast_rtp_rtcp_report *ast_rtp_rtcp_report_alloc(unsigned int report_blocks)
1903 {
1904         struct ast_rtp_rtcp_report *rtcp_report;
1905
1906         /* Size of object is sizeof the report + the number of report_blocks * sizeof pointer */
1907         rtcp_report = ao2_alloc((sizeof(*rtcp_report) + report_blocks * sizeof(struct ast_rtp_rtcp_report_block *)),
1908                 rtp_rtcp_report_dtor);
1909
1910         return rtcp_report;
1911 }
1912
1913 void ast_rtp_publish_rtcp_message(struct ast_rtp_instance *rtp,
1914                 struct stasis_message_type *message_type,
1915                 struct ast_rtp_rtcp_report *report,
1916                 struct ast_json *blob)
1917 {
1918         RAII_VAR(struct rtcp_message_payload *, payload, NULL, ao2_cleanup);
1919         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1920
1921         payload = ao2_alloc(sizeof(*payload), rtcp_message_payload_dtor);
1922         if (!payload || !report) {
1923                 return;
1924         }
1925
1926         if (!ast_strlen_zero(rtp->channel_uniqueid)) {
1927                 payload->snapshot = ast_channel_snapshot_get_latest(rtp->channel_uniqueid);
1928         }
1929         if (blob) {
1930                 payload->blob = blob;
1931                 ast_json_ref(blob);
1932         }
1933         ao2_ref(report, +1);
1934         payload->report = report;
1935
1936         message = stasis_message_create(message_type, payload);
1937         if (!message) {
1938                 return;
1939         }
1940
1941         stasis_publish(ast_rtp_topic(), message);
1942 }
1943
1944 /*!
1945  * @{ \brief Define RTCP/RTP message types.
1946  */
1947 STASIS_MESSAGE_TYPE_DEFN(ast_rtp_rtcp_sent_type,
1948                 .to_ami = rtcp_report_to_ami,
1949                 .to_json = rtcp_report_to_json,);
1950 STASIS_MESSAGE_TYPE_DEFN(ast_rtp_rtcp_received_type,
1951                 .to_ami = rtcp_report_to_ami,
1952                 .to_json = rtcp_report_to_json,);
1953 /*! @} */
1954
1955 struct stasis_topic *ast_rtp_topic(void)
1956 {
1957         return rtp_topic;
1958 }
1959
1960 static void rtp_engine_shutdown(void)
1961 {
1962         ao2_cleanup(rtp_topic);
1963         rtp_topic = NULL;
1964         STASIS_MESSAGE_TYPE_CLEANUP(ast_rtp_rtcp_received_type);
1965         STASIS_MESSAGE_TYPE_CLEANUP(ast_rtp_rtcp_sent_type);
1966 }
1967
1968 int ast_rtp_engine_init()
1969 {
1970         struct ast_format tmpfmt;
1971
1972         ast_rwlock_init(&mime_types_lock);
1973         ast_rwlock_init(&static_RTP_PT_lock);
1974
1975         rtp_topic = stasis_topic_create("rtp_topic");
1976         if (!rtp_topic) {
1977                 return -1;
1978         }
1979         STASIS_MESSAGE_TYPE_INIT(ast_rtp_rtcp_sent_type);
1980         STASIS_MESSAGE_TYPE_INIT(ast_rtp_rtcp_received_type);
1981         ast_register_atexit(rtp_engine_shutdown);
1982
1983         /* Define all the RTP mime types available */
1984         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G723_1, 0), 0, "audio", "G723", 8000);
1985         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_GSM, 0), 0, "audio", "GSM", 8000);
1986         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0), 0, "audio", "PCMU", 8000);
1987         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0), 0, "audio", "G711U", 8000);
1988         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ALAW, 0), 0, "audio", "PCMA", 8000);
1989         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ALAW, 0), 0, "audio", "G711A", 8000);
1990         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G726, 0), 0, "audio", "G726-32", 8000);
1991         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0, "audio", "DVI4", 8000);
1992         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR, 0), 0, "audio", "L16", 8000);
1993         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR16, 0), 0, "audio", "L16", 16000);
1994         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR16, 0), 0, "audio", "L16-256", 16000);
1995         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_LPC10, 0), 0, "audio", "LPC", 8000);
1996         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G729A, 0), 0, "audio", "G729", 8000);
1997         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G729A, 0), 0, "audio", "G729A", 8000);
1998         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G729A, 0), 0, "audio", "G.729", 8000);
1999         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SPEEX, 0), 0, "audio", "speex", 8000);
2000         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SPEEX16, 0), 0,  "audio", "speex", 16000);
2001         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SPEEX32, 0), 0,  "audio", "speex", 32000);
2002         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ILBC, 0), 0, "audio", "iLBC", 8000);
2003         /* this is the sample rate listed in the RTP profile for the G.722 codec, *NOT* the actual sample rate of the media stream */
2004         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G722, 0), 0, "audio", "G722", 8000);
2005         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G726_AAL2, 0), 0, "audio", "AAL2-G726-32", 8000);
2006         set_next_mime_type(NULL, AST_RTP_DTMF, "audio", "telephone-event", 8000);
2007         set_next_mime_type(NULL, AST_RTP_CISCO_DTMF, "audio", "cisco-telephone-event", 8000);
2008         set_next_mime_type(NULL, AST_RTP_CN, "audio", "CN", 8000);
2009         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_JPEG, 0), 0, "video", "JPEG", 90000);
2010         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_PNG, 0), 0, "video", "PNG", 90000);
2011         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_H261, 0), 0, "video", "H261", 90000);
2012         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_H263, 0), 0, "video", "H263", 90000);
2013         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_H263_PLUS, 0), 0, "video", "H263-1998", 90000);
2014         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_H264, 0), 0, "video", "H264", 90000);
2015         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_MP4_VIDEO, 0), 0, "video", "MP4V-ES", 90000);
2016         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_T140RED, 0), 0, "text", "RED", 1000);
2017         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_T140, 0), 0, "text", "T140", 1000);
2018         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SIREN7, 0), 0, "audio", "G7221", 16000);
2019         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SIREN14, 0), 0, "audio", "G7221", 32000);
2020         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G719, 0), 0, "audio", "G719", 48000);
2021         /* Opus and VP8 */
2022         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_OPUS, 0), 0,  "audio", "opus", 48000);
2023         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_VP8, 0), 0,  "video", "VP8", 90000);
2024
2025         /* Define the static rtp payload mappings */
2026         add_static_payload(0, ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0), 0);
2027         #ifdef USE_DEPRECATED_G726
2028         add_static_payload(2, ast_format_set(&tmpfmt, AST_FORMAT_G726, 0), 0);/* Technically this is G.721, but if Cisco can do it, so can we... */
2029         #endif
2030         add_static_payload(3, ast_format_set(&tmpfmt, AST_FORMAT_GSM, 0), 0);
2031         add_static_payload(4, ast_format_set(&tmpfmt, AST_FORMAT_G723_1, 0), 0);
2032         add_static_payload(5, ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0);/* 8 kHz */
2033         add_static_payload(6, ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0); /* 16 kHz */
2034         add_static_payload(7, ast_format_set(&tmpfmt, AST_FORMAT_LPC10, 0), 0);
2035         add_static_payload(8, ast_format_set(&tmpfmt, AST_FORMAT_ALAW, 0), 0);
2036         add_static_payload(9, ast_format_set(&tmpfmt, AST_FORMAT_G722, 0), 0);
2037         add_static_payload(10, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR, 0), 0); /* 2 channels */
2038         add_static_payload(11, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR, 0), 0); /* 1 channel */
2039         add_static_payload(13, NULL, AST_RTP_CN);
2040         add_static_payload(16, ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0); /* 11.025 kHz */
2041         add_static_payload(17, ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0); /* 22.050 kHz */
2042         add_static_payload(18, ast_format_set(&tmpfmt, AST_FORMAT_G729A, 0), 0);
2043         add_static_payload(19, NULL, AST_RTP_CN);         /* Also used for CN */
2044         add_static_payload(26, ast_format_set(&tmpfmt, AST_FORMAT_JPEG, 0), 0);
2045         add_static_payload(31, ast_format_set(&tmpfmt, AST_FORMAT_H261, 0), 0);
2046         add_static_payload(34, ast_format_set(&tmpfmt, AST_FORMAT_H263, 0), 0);
2047         add_static_payload(97, ast_format_set(&tmpfmt, AST_FORMAT_ILBC, 0), 0);
2048         add_static_payload(98, ast_format_set(&tmpfmt, AST_FORMAT_H263_PLUS, 0), 0);
2049         add_static_payload(99, ast_format_set(&tmpfmt, AST_FORMAT_H264, 0), 0);
2050         add_static_payload(101, NULL, AST_RTP_DTMF);
2051         add_static_payload(102, ast_format_set(&tmpfmt, AST_FORMAT_SIREN7, 0), 0);
2052         add_static_payload(103, ast_format_set(&tmpfmt, AST_FORMAT_H263_PLUS, 0), 0);
2053         add_static_payload(104, ast_format_set(&tmpfmt, AST_FORMAT_MP4_VIDEO, 0), 0);
2054         add_static_payload(105, ast_format_set(&tmpfmt, AST_FORMAT_T140RED, 0), 0);   /* Real time text chat (with redundancy encoding) */
2055         add_static_payload(106, ast_format_set(&tmpfmt, AST_FORMAT_T140, 0), 0);     /* Real time text chat */
2056         add_static_payload(110, ast_format_set(&tmpfmt, AST_FORMAT_SPEEX, 0), 0);
2057         add_static_payload(111, ast_format_set(&tmpfmt, AST_FORMAT_G726, 0), 0);
2058         add_static_payload(112, ast_format_set(&tmpfmt, AST_FORMAT_G726_AAL2, 0), 0);
2059         add_static_payload(115, ast_format_set(&tmpfmt, AST_FORMAT_SIREN14, 0), 0);
2060         add_static_payload(116, ast_format_set(&tmpfmt, AST_FORMAT_G719, 0), 0);
2061         add_static_payload(117, ast_format_set(&tmpfmt, AST_FORMAT_SPEEX16, 0), 0);
2062         add_static_payload(118, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR16, 0), 0); /* 16 Khz signed linear */
2063         add_static_payload(119, ast_format_set(&tmpfmt, AST_FORMAT_SPEEX32, 0), 0);
2064         add_static_payload(121, NULL, AST_RTP_CISCO_DTMF);   /* Must be type 121 */
2065         /* Opus and VP8 */
2066         add_static_payload(100, ast_format_set(&tmpfmt, AST_FORMAT_VP8, 0), 0);
2067         add_static_payload(107, ast_format_set(&tmpfmt, AST_FORMAT_OPUS, 0), 0);
2068
2069         return 0;
2070 }