Fix documentation replication issues
[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 int ast_rtp_codecs_payload_code(struct ast_rtp_codecs *codecs, int asterisk_format, const struct ast_format *format, int code)
843 {
844         struct ast_rtp_payload_type *type;
845         int i, res = -1;
846
847         if (asterisk_format && format && (type = ao2_callback(codecs->payloads, OBJ_NOLOCK, rtp_payload_type_find_format, (void*)format))) {
848                 res = type->payload;
849                 ao2_ref(type, -1);
850                 return res;
851         } else if (!asterisk_format && (type = ao2_find(codecs->payloads, &code, OBJ_NOLOCK | OBJ_KEY))) {
852                 res = type->payload;
853                 ao2_ref(type, -1);
854                 return res;
855         }
856
857         ast_rwlock_rdlock(&static_RTP_PT_lock);
858         for (i = 0; i < AST_RTP_MAX_PT; i++) {
859                 if (static_RTP_PT[i].asterisk_format && asterisk_format && format &&
860                         (ast_format_cmp(format, &static_RTP_PT[i].format) != AST_FORMAT_CMP_NOT_EQUAL)) {
861                         res = i;
862                         break;
863                 } else if (!static_RTP_PT[i].asterisk_format && !asterisk_format &&
864                         (static_RTP_PT[i].rtp_code == code)) {
865                         res = i;
866                         break;
867                 }
868         }
869         ast_rwlock_unlock(&static_RTP_PT_lock);
870
871         return res;
872 }
873 int ast_rtp_codecs_find_payload_code(struct ast_rtp_codecs *codecs, int code)
874 {
875         struct ast_rtp_payload_type *type;
876         int res = -1;
877
878         /* Search the payload type in the codecs passed */
879         if ((type = ao2_find(codecs->payloads, &code, OBJ_NOLOCK | OBJ_KEY)))
880         {
881                 res = type->payload;
882                 ao2_ref(type, -1);
883                 return res;
884         }
885
886         return res;
887 }
888 const char *ast_rtp_lookup_mime_subtype2(const int asterisk_format, struct ast_format *format, int code, enum ast_rtp_options options)
889 {
890         int i;
891         const char *res = "";
892
893         ast_rwlock_rdlock(&mime_types_lock);
894         for (i = 0; i < mime_types_len; i++) {
895                 if (ast_rtp_mime_types[i].payload_type.asterisk_format && asterisk_format && format &&
896                         (ast_format_cmp(format, &ast_rtp_mime_types[i].payload_type.format) != AST_FORMAT_CMP_NOT_EQUAL)) {
897                         if ((format->id == AST_FORMAT_G726_AAL2) && (options & AST_RTP_OPT_G726_NONSTANDARD)) {
898                                 res = "G726-32";
899                                 break;
900                         } else {
901                                 res = ast_rtp_mime_types[i].subtype;
902                                 break;
903                         }
904                 } else if (!ast_rtp_mime_types[i].payload_type.asterisk_format && !asterisk_format &&
905                         ast_rtp_mime_types[i].payload_type.rtp_code == code) {
906
907                         res = ast_rtp_mime_types[i].subtype;
908                         break;
909                 }
910         }
911         ast_rwlock_unlock(&mime_types_lock);
912
913         return res;
914 }
915
916 unsigned int ast_rtp_lookup_sample_rate2(int asterisk_format, struct ast_format *format, int code)
917 {
918         unsigned int i;
919         unsigned int res = 0;
920
921         ast_rwlock_rdlock(&mime_types_lock);
922         for (i = 0; i < mime_types_len; ++i) {
923                 if (ast_rtp_mime_types[i].payload_type.asterisk_format && asterisk_format && format &&
924                         (ast_format_cmp(format, &ast_rtp_mime_types[i].payload_type.format) != AST_FORMAT_CMP_NOT_EQUAL)) {
925                         res = ast_rtp_mime_types[i].sample_rate;
926                         break;
927                 } else if (!ast_rtp_mime_types[i].payload_type.asterisk_format && !asterisk_format &&
928                         ast_rtp_mime_types[i].payload_type.rtp_code == code) {
929                         res = ast_rtp_mime_types[i].sample_rate;
930                         break;
931                 }
932         }
933         ast_rwlock_unlock(&mime_types_lock);
934
935         return res;
936 }
937
938 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)
939 {
940         int found = 0;
941         const char *name;
942         if (!buf) {
943                 return NULL;
944         }
945
946
947         if (asterisk_format) {
948                 struct ast_format tmp_fmt;
949                 ast_format_cap_iter_start(ast_format_capability);
950                 while (!ast_format_cap_iter_next(ast_format_capability, &tmp_fmt)) {
951                         name = ast_rtp_lookup_mime_subtype2(asterisk_format, &tmp_fmt, 0, options);
952                         ast_str_append(&buf, 0, "%s|", name);
953                         found = 1;
954                 }
955                 ast_format_cap_iter_end(ast_format_capability);
956
957         } else {
958                 int x;
959                 ast_str_append(&buf, 0, "0x%x (", (unsigned int) rtp_capability);
960                 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
961                         if (rtp_capability & x) {
962                                 name = ast_rtp_lookup_mime_subtype2(asterisk_format, NULL, x, options);
963                                 ast_str_append(&buf, 0, "%s|", name);
964                                 found = 1;
965                         }
966                 }
967         }
968
969         ast_str_append(&buf, 0, "%s", found ? ")" : "nothing)");
970
971         return ast_str_buffer(buf);
972 }
973
974 void ast_rtp_codecs_packetization_set(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, struct ast_codec_pref *prefs)
975 {
976         codecs->pref = *prefs;
977
978         if (instance && instance->engine->packetization_set) {
979                 instance->engine->packetization_set(instance, &instance->codecs.pref);
980         }
981 }
982
983 int ast_rtp_instance_dtmf_begin(struct ast_rtp_instance *instance, char digit)
984 {
985         return instance->engine->dtmf_begin ? instance->engine->dtmf_begin(instance, digit) : -1;
986 }
987
988 int ast_rtp_instance_dtmf_end(struct ast_rtp_instance *instance, char digit)
989 {
990         return instance->engine->dtmf_end ? instance->engine->dtmf_end(instance, digit) : -1;
991 }
992 int ast_rtp_instance_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
993 {
994         return instance->engine->dtmf_end_with_duration ? instance->engine->dtmf_end_with_duration(instance, digit, duration) : -1;
995 }
996
997 int ast_rtp_instance_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
998 {
999         return (!instance->engine->dtmf_mode_set || instance->engine->dtmf_mode_set(instance, dtmf_mode)) ? -1 : 0;
1000 }
1001
1002 enum ast_rtp_dtmf_mode ast_rtp_instance_dtmf_mode_get(struct ast_rtp_instance *instance)
1003 {
1004         return instance->engine->dtmf_mode_get ? instance->engine->dtmf_mode_get(instance) : 0;
1005 }
1006
1007 void ast_rtp_instance_update_source(struct ast_rtp_instance *instance)
1008 {
1009         if (instance->engine->update_source) {
1010                 instance->engine->update_source(instance);
1011         }
1012 }
1013
1014 void ast_rtp_instance_change_source(struct ast_rtp_instance *instance)
1015 {
1016         if (instance->engine->change_source) {
1017                 instance->engine->change_source(instance);
1018         }
1019 }
1020
1021 int ast_rtp_instance_set_qos(struct ast_rtp_instance *instance, int tos, int cos, const char *desc)
1022 {
1023         return instance->engine->qos ? instance->engine->qos(instance, tos, cos, desc) : -1;
1024 }
1025
1026 void ast_rtp_instance_stop(struct ast_rtp_instance *instance)
1027 {
1028         if (instance->engine->stop) {
1029                 instance->engine->stop(instance);
1030         }
1031 }
1032
1033 int ast_rtp_instance_fd(struct ast_rtp_instance *instance, int rtcp)
1034 {
1035         return instance->engine->fd ? instance->engine->fd(instance, rtcp) : -1;
1036 }
1037
1038 struct ast_rtp_glue *ast_rtp_instance_get_glue(const char *type)
1039 {
1040         struct ast_rtp_glue *glue = NULL;
1041
1042         AST_RWLIST_RDLOCK(&glues);
1043
1044         AST_RWLIST_TRAVERSE(&glues, glue, entry) {
1045                 if (!strcasecmp(glue->type, type)) {
1046                         break;
1047                 }
1048         }
1049
1050         AST_RWLIST_UNLOCK(&glues);
1051
1052         return glue;
1053 }
1054
1055 /*!
1056  * \brief Conditionally unref an rtp instance
1057  */
1058 static void unref_instance_cond(struct ast_rtp_instance **instance)
1059 {
1060         if (*instance) {
1061                 ao2_ref(*instance, -1);
1062                 *instance = NULL;
1063         }
1064 }
1065
1066 struct ast_rtp_instance *ast_rtp_instance_get_bridged(struct ast_rtp_instance *instance)
1067 {
1068         return instance->bridged;
1069 }
1070
1071 void ast_rtp_instance_set_bridged(struct ast_rtp_instance *instance, struct ast_rtp_instance *bridged)
1072 {
1073         instance->bridged = bridged;
1074 }
1075
1076 void ast_rtp_instance_early_bridge_make_compatible(struct ast_channel *c0, struct ast_channel *c1)
1077 {
1078         struct ast_rtp_instance *instance0 = NULL, *instance1 = NULL,
1079                 *vinstance0 = NULL, *vinstance1 = NULL,
1080                 *tinstance0 = NULL, *tinstance1 = NULL;
1081         struct ast_rtp_glue *glue0, *glue1;
1082         enum ast_rtp_glue_result audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID, video_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1083         enum ast_rtp_glue_result audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID, video_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1084         struct ast_format_cap *cap0 = ast_format_cap_alloc_nolock();
1085         struct ast_format_cap *cap1 = ast_format_cap_alloc_nolock();
1086
1087         /* Lock both channels so we can look for the glue that binds them together */
1088         ast_channel_lock_both(c0, c1);
1089
1090         if (!cap1 || !cap0) {
1091                 goto done;
1092         }
1093
1094         /* Grab glue that binds each channel to something using the RTP engine */
1095         if (!(glue0 = ast_rtp_instance_get_glue(ast_channel_tech(c0)->type)) || !(glue1 = ast_rtp_instance_get_glue(ast_channel_tech(c1)->type))) {
1096                 ast_debug(1, "Can't find native functions for channel '%s'\n", glue0 ? ast_channel_name(c1) : ast_channel_name(c0));
1097                 goto done;
1098         }
1099
1100         audio_glue0_res = glue0->get_rtp_info(c0, &instance0);
1101         video_glue0_res = glue0->get_vrtp_info ? glue0->get_vrtp_info(c0, &vinstance0) : AST_RTP_GLUE_RESULT_FORBID;
1102
1103         audio_glue1_res = glue1->get_rtp_info(c1, &instance1);
1104         video_glue1_res = glue1->get_vrtp_info ? glue1->get_vrtp_info(c1, &vinstance1) : AST_RTP_GLUE_RESULT_FORBID;
1105
1106         /* If we are carrying video, and both sides are not going to remotely bridge... fail the native bridge */
1107         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)) {
1108                 audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1109         }
1110         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)) {
1111                 audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1112         }
1113         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) {
1114                 glue0->get_codec(c0, cap0);
1115         }
1116         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) {
1117                 glue1->get_codec(c1, cap1);
1118         }
1119
1120         /* If any sort of bridge is forbidden just completely bail out and go back to generic bridging */
1121         if (audio_glue0_res != AST_RTP_GLUE_RESULT_REMOTE || audio_glue1_res != AST_RTP_GLUE_RESULT_REMOTE) {
1122                 goto done;
1123         }
1124
1125         /* Make sure we have matching codecs */
1126         if (!ast_format_cap_has_joint(cap0, cap1)) {
1127                 goto done;
1128         }
1129
1130         ast_rtp_codecs_payloads_copy(&instance0->codecs, &instance1->codecs, instance1);
1131
1132         if (vinstance0 && vinstance1) {
1133                 ast_rtp_codecs_payloads_copy(&vinstance0->codecs, &vinstance1->codecs, vinstance1);
1134         }
1135         if (tinstance0 && tinstance1) {
1136                 ast_rtp_codecs_payloads_copy(&tinstance0->codecs, &tinstance1->codecs, tinstance1);
1137         }
1138
1139         if (glue0->update_peer(c0, instance1, vinstance1, tinstance1, cap1, 0)) {
1140                 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n",
1141                         ast_channel_name(c0), ast_channel_name(c1));
1142         } else {
1143                 ast_debug(1, "Seeded SDP of '%s' with that of '%s'\n",
1144                         ast_channel_name(c0), ast_channel_name(c1));
1145         }
1146
1147 done:
1148         ast_channel_unlock(c0);
1149         ast_channel_unlock(c1);
1150
1151         ast_format_cap_destroy(cap0);
1152         ast_format_cap_destroy(cap1);
1153
1154         unref_instance_cond(&instance0);
1155         unref_instance_cond(&instance1);
1156         unref_instance_cond(&vinstance0);
1157         unref_instance_cond(&vinstance1);
1158         unref_instance_cond(&tinstance0);
1159         unref_instance_cond(&tinstance1);
1160 }
1161
1162 int ast_rtp_instance_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
1163 {
1164         struct ast_rtp_instance *instance0 = NULL, *instance1 = NULL,
1165                         *vinstance0 = NULL, *vinstance1 = NULL,
1166                         *tinstance0 = NULL, *tinstance1 = NULL;
1167         struct ast_rtp_glue *glue0, *glue1;
1168         enum ast_rtp_glue_result audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID, video_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1169         enum ast_rtp_glue_result audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID, video_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1170         struct ast_format_cap *cap0 = ast_format_cap_alloc_nolock();
1171         struct ast_format_cap *cap1 = ast_format_cap_alloc_nolock();
1172
1173         /* If there is no second channel just immediately bail out, we are of no use in that scenario */
1174         if (!c1 || !cap1 || !cap0) {
1175                 ast_format_cap_destroy(cap0);
1176                 ast_format_cap_destroy(cap1);
1177                 return -1;
1178         }
1179
1180         /* Lock both channels so we can look for the glue that binds them together */
1181         ast_channel_lock_both(c0, c1);
1182
1183         /* Grab glue that binds each channel to something using the RTP engine */
1184         if (!(glue0 = ast_rtp_instance_get_glue(ast_channel_tech(c0)->type)) || !(glue1 = ast_rtp_instance_get_glue(ast_channel_tech(c1)->type))) {
1185                 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", glue0 ? ast_channel_name(c1) : ast_channel_name(c0));
1186                 goto done;
1187         }
1188
1189         audio_glue0_res = glue0->get_rtp_info(c0, &instance0);
1190         video_glue0_res = glue0->get_vrtp_info ? glue0->get_vrtp_info(c0, &vinstance0) : AST_RTP_GLUE_RESULT_FORBID;
1191
1192         audio_glue1_res = glue1->get_rtp_info(c1, &instance1);
1193         video_glue1_res = glue1->get_vrtp_info ? glue1->get_vrtp_info(c1, &vinstance1) : AST_RTP_GLUE_RESULT_FORBID;
1194
1195         /* If we are carrying video, and both sides are not going to remotely bridge... fail the native bridge */
1196         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)) {
1197                 audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1198         }
1199         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)) {
1200                 audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1201         }
1202         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) {
1203                 glue0->get_codec(c0, cap0);
1204         }
1205         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) {
1206                 glue1->get_codec(c1, cap1);
1207         }
1208
1209         /* If any sort of bridge is forbidden just completely bail out and go back to generic bridging */
1210         if (audio_glue0_res != AST_RTP_GLUE_RESULT_REMOTE || audio_glue1_res != AST_RTP_GLUE_RESULT_REMOTE) {
1211                 goto done;
1212         }
1213
1214         /* Make sure we have matching codecs */
1215         if (!ast_format_cap_has_joint(cap0, cap1)) {
1216                 goto done;
1217         }
1218
1219         /* Bridge media early */
1220         if (glue0->update_peer(c0, instance1, vinstance1, tinstance1, cap1, 0)) {
1221                 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", ast_channel_name(c0), c1 ? ast_channel_name(c1) : "<unspecified>");
1222         }
1223
1224 done:
1225         ast_channel_unlock(c0);
1226         ast_channel_unlock(c1);
1227
1228         ast_format_cap_destroy(cap0);
1229         ast_format_cap_destroy(cap1);
1230
1231         unref_instance_cond(&instance0);
1232         unref_instance_cond(&instance1);
1233         unref_instance_cond(&vinstance0);
1234         unref_instance_cond(&vinstance1);
1235         unref_instance_cond(&tinstance0);
1236         unref_instance_cond(&tinstance1);
1237
1238         ast_debug(1, "Setting early bridge SDP of '%s' with that of '%s'\n", ast_channel_name(c0), c1 ? ast_channel_name(c1) : "<unspecified>");
1239
1240         return 0;
1241 }
1242
1243 int ast_rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations)
1244 {
1245         return instance->engine->red_init ? instance->engine->red_init(instance, buffer_time, payloads, generations) : -1;
1246 }
1247
1248 int ast_rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame)
1249 {
1250         return instance->engine->red_buffer ? instance->engine->red_buffer(instance, frame) : -1;
1251 }
1252
1253 int ast_rtp_instance_get_stats(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat)
1254 {
1255         return instance->engine->get_stat ? instance->engine->get_stat(instance, stats, stat) : -1;
1256 }
1257
1258 char *ast_rtp_instance_get_quality(struct ast_rtp_instance *instance, enum ast_rtp_instance_stat_field field, char *buf, size_t size)
1259 {
1260         struct ast_rtp_instance_stats stats = { 0, };
1261         enum ast_rtp_instance_stat stat;
1262
1263         /* Determine what statistics we will need to retrieve based on field passed in */
1264         if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY) {
1265                 stat = AST_RTP_INSTANCE_STAT_ALL;
1266         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER) {
1267                 stat = AST_RTP_INSTANCE_STAT_COMBINED_JITTER;
1268         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS) {
1269                 stat = AST_RTP_INSTANCE_STAT_COMBINED_LOSS;
1270         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT) {
1271                 stat = AST_RTP_INSTANCE_STAT_COMBINED_RTT;
1272         } else {
1273                 return NULL;
1274         }
1275
1276         /* Attempt to actually retrieve the statistics we need to generate the quality string */
1277         if (ast_rtp_instance_get_stats(instance, &stats, stat)) {
1278                 return NULL;
1279         }
1280
1281         /* Now actually fill the buffer with the good information */
1282         if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY) {
1283                 snprintf(buf, size, "ssrc=%i;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f",
1284                          stats.local_ssrc, stats.remote_ssrc, stats.rxploss, stats.txjitter, stats.rxcount, stats.rxjitter, stats.txcount, stats.txploss, stats.rtt);
1285         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER) {
1286                 snprintf(buf, size, "minrxjitter=%f;maxrxjitter=%f;avgrxjitter=%f;stdevrxjitter=%f;reported_minjitter=%f;reported_maxjitter=%f;reported_avgjitter=%f;reported_stdevjitter=%f;",
1287                          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));
1288         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS) {
1289                 snprintf(buf, size, "minrxlost=%f;maxrxlost=%f;avgrxlost=%f;stdevrxlost=%f;reported_minlost=%f;reported_maxlost=%f;reported_avglost=%f;reported_stdevlost=%f;",
1290                          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));
1291         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT) {
1292                 snprintf(buf, size, "minrtt=%f;maxrtt=%f;avgrtt=%f;stdevrtt=%f;", stats.minrtt, stats.maxrtt, stats.normdevrtt, stats.stdevrtt);
1293         }
1294
1295         return buf;
1296 }
1297
1298 void ast_rtp_instance_set_stats_vars(struct ast_channel *chan, struct ast_rtp_instance *instance)
1299 {
1300         char quality_buf[AST_MAX_USER_FIELD], *quality;
1301         struct ast_channel *bridge = ast_bridged_channel(chan);
1302
1303         if ((quality = ast_rtp_instance_get_quality(instance, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
1304                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOS", quality);
1305                 if (bridge) {
1306                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSBRIDGED", quality);
1307                 }
1308         }
1309
1310         if ((quality = ast_rtp_instance_get_quality(instance, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf)))) {
1311                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSJITTER", quality);
1312                 if (bridge) {
1313                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSJITTERBRIDGED", quality);
1314                 }
1315         }
1316
1317         if ((quality = ast_rtp_instance_get_quality(instance, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf)))) {
1318                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSLOSS", quality);
1319                 if (bridge) {
1320                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSLOSSBRIDGED", quality);
1321                 }
1322         }
1323
1324         if ((quality = ast_rtp_instance_get_quality(instance, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf)))) {
1325                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSRTT", quality);
1326                 if (bridge) {
1327                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSRTTBRIDGED", quality);
1328                 }
1329         }
1330 }
1331
1332 int ast_rtp_instance_set_read_format(struct ast_rtp_instance *instance, struct ast_format *format)
1333 {
1334         return instance->engine->set_read_format ? instance->engine->set_read_format(instance, format) : -1;
1335 }
1336
1337 int ast_rtp_instance_set_write_format(struct ast_rtp_instance *instance, struct ast_format *format)
1338 {
1339         return instance->engine->set_write_format ? instance->engine->set_write_format(instance, format) : -1;
1340 }
1341
1342 int ast_rtp_instance_make_compatible(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_channel *peer)
1343 {
1344         struct ast_rtp_glue *glue;
1345         struct ast_rtp_instance *peer_instance = NULL;
1346         int res = -1;
1347
1348         if (!instance->engine->make_compatible) {
1349                 return -1;
1350         }
1351
1352         ast_channel_lock(peer);
1353
1354         if (!(glue = ast_rtp_instance_get_glue(ast_channel_tech(peer)->type))) {
1355                 ast_channel_unlock(peer);
1356                 return -1;
1357         }
1358
1359         glue->get_rtp_info(peer, &peer_instance);
1360
1361         if (!peer_instance || peer_instance->engine != instance->engine) {
1362                 ast_channel_unlock(peer);
1363                 ao2_ref(peer_instance, -1);
1364                 peer_instance = NULL;
1365                 return -1;
1366         }
1367
1368         res = instance->engine->make_compatible(chan, instance, peer, peer_instance);
1369
1370         ast_channel_unlock(peer);
1371
1372         ao2_ref(peer_instance, -1);
1373         peer_instance = NULL;
1374
1375         return res;
1376 }
1377
1378 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)
1379 {
1380         if (instance->engine->available_formats) {
1381                 instance->engine->available_formats(instance, to_endpoint, to_asterisk, result);
1382                 if (!ast_format_cap_is_empty(result)) {
1383                         return;
1384                 }
1385         }
1386
1387         ast_translate_available_formats(to_endpoint, to_asterisk, result);
1388 }
1389
1390 int ast_rtp_instance_activate(struct ast_rtp_instance *instance)
1391 {
1392         return instance->engine->activate ? instance->engine->activate(instance) : 0;
1393 }
1394
1395 void ast_rtp_instance_stun_request(struct ast_rtp_instance *instance,
1396                                    struct ast_sockaddr *suggestion,
1397                                    const char *username)
1398 {
1399         if (instance->engine->stun_request) {
1400                 instance->engine->stun_request(instance, suggestion, username);
1401         }
1402 }
1403
1404 void ast_rtp_instance_set_timeout(struct ast_rtp_instance *instance, int timeout)
1405 {
1406         instance->timeout = timeout;
1407 }
1408
1409 void ast_rtp_instance_set_hold_timeout(struct ast_rtp_instance *instance, int timeout)
1410 {
1411         instance->holdtimeout = timeout;
1412 }
1413
1414 void ast_rtp_instance_set_keepalive(struct ast_rtp_instance *instance, int interval)
1415 {
1416         instance->keepalive = interval;
1417 }
1418
1419 int ast_rtp_instance_get_timeout(struct ast_rtp_instance *instance)
1420 {
1421         return instance->timeout;
1422 }
1423
1424 int ast_rtp_instance_get_hold_timeout(struct ast_rtp_instance *instance)
1425 {
1426         return instance->holdtimeout;
1427 }
1428
1429 int ast_rtp_instance_get_keepalive(struct ast_rtp_instance *instance)
1430 {
1431         return instance->keepalive;
1432 }
1433
1434 struct ast_rtp_engine *ast_rtp_instance_get_engine(struct ast_rtp_instance *instance)
1435 {
1436         return instance->engine;
1437 }
1438
1439 struct ast_rtp_glue *ast_rtp_instance_get_active_glue(struct ast_rtp_instance *instance)
1440 {
1441         return instance->glue;
1442 }
1443
1444 int ast_rtp_engine_register_srtp(struct ast_srtp_res *srtp_res, struct ast_srtp_policy_res *policy_res)
1445 {
1446         if (res_srtp || res_srtp_policy) {
1447                 return -1;
1448         }
1449         if (!srtp_res || !policy_res) {
1450                 return -1;
1451         }
1452
1453         res_srtp = srtp_res;
1454         res_srtp_policy = policy_res;
1455
1456         return 0;
1457 }
1458
1459 void ast_rtp_engine_unregister_srtp(void)
1460 {
1461         res_srtp = NULL;
1462         res_srtp_policy = NULL;
1463 }
1464
1465 int ast_rtp_engine_srtp_is_registered(void)
1466 {
1467         return res_srtp && res_srtp_policy;
1468 }
1469
1470 int ast_rtp_instance_add_srtp_policy(struct ast_rtp_instance *instance, struct ast_srtp_policy *remote_policy, struct ast_srtp_policy *local_policy)
1471 {
1472         int res = 0;
1473
1474         if (!res_srtp) {
1475                 return -1;
1476         }
1477
1478         if (!instance->srtp) {
1479                 res = res_srtp->create(&instance->srtp, instance, remote_policy);
1480         } else {
1481                 res = res_srtp->replace(&instance->srtp, instance, remote_policy);
1482         }
1483         if (!res) {
1484                 res = res_srtp->add_stream(instance->srtp, local_policy);
1485         }
1486
1487         return res;
1488 }
1489
1490 struct ast_srtp *ast_rtp_instance_get_srtp(struct ast_rtp_instance *instance)
1491 {
1492         return instance->srtp;
1493 }
1494
1495 int ast_rtp_instance_sendcng(struct ast_rtp_instance *instance, int level)
1496 {
1497         if (instance->engine->sendcng) {
1498                 return instance->engine->sendcng(instance, level);
1499         }
1500
1501         return -1;
1502 }
1503
1504 struct ast_rtp_engine_ice *ast_rtp_instance_get_ice(struct ast_rtp_instance *instance)
1505 {
1506         return instance->engine->ice;
1507 }
1508
1509 struct ast_rtp_engine_dtls *ast_rtp_instance_get_dtls(struct ast_rtp_instance *instance)
1510 {
1511         return instance->engine->dtls;
1512 }
1513
1514 int ast_rtp_dtls_cfg_parse(struct ast_rtp_dtls_cfg *dtls_cfg, const char *name, const char *value)
1515 {
1516         if (!strcasecmp(name, "dtlsenable")) {
1517                 dtls_cfg->enabled = ast_true(value) ? 1 : 0;
1518         } else if (!strcasecmp(name, "dtlsverify")) {
1519                 dtls_cfg->verify = ast_true(value) ? 1 : 0;
1520         } else if (!strcasecmp(name, "dtlsrekey")) {
1521                 if (sscanf(value, "%30u", &dtls_cfg->rekey) != 1) {
1522                         return -1;
1523                 }
1524         } else if (!strcasecmp(name, "dtlscertfile")) {
1525                 ast_free(dtls_cfg->certfile);
1526                 dtls_cfg->certfile = ast_strdup(value);
1527         } else if (!strcasecmp(name, "dtlsprivatekey")) {
1528                 ast_free(dtls_cfg->pvtfile);
1529                 dtls_cfg->pvtfile = ast_strdup(value);
1530         } else if (!strcasecmp(name, "dtlscipher")) {
1531                 ast_free(dtls_cfg->cipher);
1532                 dtls_cfg->cipher = ast_strdup(value);
1533         } else if (!strcasecmp(name, "dtlscafile")) {
1534                 ast_free(dtls_cfg->cafile);
1535                 dtls_cfg->cafile = ast_strdup(value);
1536         } else if (!strcasecmp(name, "dtlscapath") || !strcasecmp(name, "dtlscadir")) {
1537                 ast_free(dtls_cfg->capath);
1538                 dtls_cfg->capath = ast_strdup(value);
1539         } else if (!strcasecmp(name, "dtlssetup")) {
1540                 if (!strcasecmp(value, "active")) {
1541                         dtls_cfg->default_setup = AST_RTP_DTLS_SETUP_ACTIVE;
1542                 } else if (!strcasecmp(value, "passive")) {
1543                         dtls_cfg->default_setup = AST_RTP_DTLS_SETUP_PASSIVE;
1544                 } else if (!strcasecmp(value, "actpass")) {
1545                         dtls_cfg->default_setup = AST_RTP_DTLS_SETUP_ACTPASS;
1546                 }
1547         } else {
1548                 return -1;
1549         }
1550
1551         return 0;
1552 }
1553
1554 void ast_rtp_dtls_cfg_copy(const struct ast_rtp_dtls_cfg *src_cfg, struct ast_rtp_dtls_cfg *dst_cfg)
1555 {
1556         dst_cfg->enabled = src_cfg->enabled;
1557         dst_cfg->verify = src_cfg->verify;
1558         dst_cfg->rekey = src_cfg->rekey;
1559         dst_cfg->suite = src_cfg->suite;
1560         dst_cfg->certfile = ast_strdup(src_cfg->certfile);
1561         dst_cfg->pvtfile = ast_strdup(src_cfg->pvtfile);
1562         dst_cfg->cipher = ast_strdup(src_cfg->cipher);
1563         dst_cfg->cafile = ast_strdup(src_cfg->cafile);
1564         dst_cfg->capath = ast_strdup(src_cfg->capath);
1565         dst_cfg->default_setup = src_cfg->default_setup;
1566 }
1567
1568 void ast_rtp_dtls_cfg_free(struct ast_rtp_dtls_cfg *dtls_cfg)
1569 {
1570         ast_free(dtls_cfg->certfile);
1571         ast_free(dtls_cfg->pvtfile);
1572         ast_free(dtls_cfg->cipher);
1573         ast_free(dtls_cfg->cafile);
1574         ast_free(dtls_cfg->capath);
1575 }
1576
1577 static void set_next_mime_type(const struct ast_format *format, int rtp_code, char *type, char *subtype, unsigned int sample_rate)
1578 {
1579         int x = mime_types_len;
1580         if (ARRAY_LEN(ast_rtp_mime_types) == mime_types_len) {
1581                 return;
1582         }
1583
1584         ast_rwlock_wrlock(&mime_types_lock);
1585         if (format) {
1586                 ast_rtp_mime_types[x].payload_type.asterisk_format = 1;
1587                 ast_format_copy(&ast_rtp_mime_types[x].payload_type.format, format);
1588         } else {
1589                 ast_rtp_mime_types[x].payload_type.rtp_code = rtp_code;
1590         }
1591         ast_rtp_mime_types[x].type = type;
1592         ast_rtp_mime_types[x].subtype = subtype;
1593         ast_rtp_mime_types[x].sample_rate = sample_rate;
1594         mime_types_len++;
1595         ast_rwlock_unlock(&mime_types_lock);
1596 }
1597
1598 static void add_static_payload(int map, const struct ast_format *format, int rtp_code)
1599 {
1600         int x;
1601         ast_rwlock_wrlock(&static_RTP_PT_lock);
1602         if (map < 0) {
1603                 /* find next available dynamic payload slot */
1604                 for (x = 96; x < 127; x++) {
1605                         if (!static_RTP_PT[x].asterisk_format && !static_RTP_PT[x].rtp_code) {
1606                                 map = x;
1607                                 break;
1608                         }
1609                 }
1610         }
1611
1612         if (map < 0) {
1613                 ast_log(LOG_WARNING, "No Dynamic RTP mapping avaliable for format %s\n" ,ast_getformatname(format));
1614                 ast_rwlock_unlock(&static_RTP_PT_lock);
1615                 return;
1616         }
1617
1618         if (format) {
1619                 static_RTP_PT[map].asterisk_format = 1;
1620                 ast_format_copy(&static_RTP_PT[map].format, format);
1621         } else {
1622                 static_RTP_PT[map].rtp_code = rtp_code;
1623         }
1624         ast_rwlock_unlock(&static_RTP_PT_lock);
1625 }
1626
1627 int ast_rtp_engine_load_format(const struct ast_format *format)
1628 {
1629         switch (format->id) {
1630         case AST_FORMAT_SILK:
1631                 set_next_mime_type(format, 0, "audio", "SILK", ast_format_rate(format));
1632                 add_static_payload(-1, format, 0);
1633                 break;
1634         case AST_FORMAT_CELT:
1635                 set_next_mime_type(format, 0, "audio", "CELT", ast_format_rate(format));
1636                 add_static_payload(-1, format, 0);
1637                 break;
1638         default:
1639                 break;
1640         }
1641
1642         return 0;
1643 }
1644
1645 int ast_rtp_engine_unload_format(const struct ast_format *format)
1646 {
1647         int x;
1648         int y = 0;
1649
1650         ast_rwlock_wrlock(&static_RTP_PT_lock);
1651         /* remove everything pertaining to this format id from the lists */
1652         for (x = 0; x < AST_RTP_MAX_PT; x++) {
1653                 if (ast_format_cmp(&static_RTP_PT[x].format, format) == AST_FORMAT_CMP_EQUAL) {
1654                         memset(&static_RTP_PT[x], 0, sizeof(struct ast_rtp_payload_type));
1655                 }
1656         }
1657         ast_rwlock_unlock(&static_RTP_PT_lock);
1658
1659
1660         ast_rwlock_wrlock(&mime_types_lock);
1661         /* rebuild the list skipping the items matching this id */
1662         for (x = 0; x < mime_types_len; x++) {
1663                 if (ast_format_cmp(&ast_rtp_mime_types[x].payload_type.format, format) == AST_FORMAT_CMP_EQUAL) {
1664                         continue;
1665                 }
1666                 ast_rtp_mime_types[y] = ast_rtp_mime_types[x];
1667                 y++;
1668         }
1669         mime_types_len = y;
1670         ast_rwlock_unlock(&mime_types_lock);
1671         return 0;
1672 }
1673
1674 /*! \internal \brief \ref stasis message payload for RTCP messages */
1675 struct rtcp_message_payload {
1676         struct ast_channel_snapshot *snapshot;  /*< The channel snapshot, if available */
1677         struct ast_rtp_rtcp_report *report;     /*< The RTCP report */
1678         struct ast_json *blob;                  /*< Extra JSON data to publish */
1679 };
1680
1681 static void rtcp_message_payload_dtor(void *obj)
1682 {
1683         struct rtcp_message_payload *payload = obj;
1684
1685         ao2_cleanup(payload->report);
1686         ao2_cleanup(payload->snapshot);
1687         ast_json_unref(payload->blob);
1688 }
1689
1690 static struct ast_manager_event_blob *rtcp_report_to_ami(struct stasis_message *msg)
1691 {
1692         struct rtcp_message_payload *payload = stasis_message_data(msg);
1693         RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
1694         RAII_VAR(struct ast_str *, packet_string, ast_str_create(512), ast_free);
1695         unsigned int ssrc = payload->report->ssrc;
1696         unsigned int type = payload->report->type;
1697         unsigned int report_count = payload->report->reception_report_count;
1698         int i;
1699
1700         if (!packet_string) {
1701                 return NULL;
1702         }
1703
1704         if (payload->snapshot) {
1705                 channel_string = ast_manager_build_channel_state_string(payload->snapshot);
1706                 if (!channel_string) {
1707                         return NULL;
1708                 }
1709         }
1710
1711         if (payload->blob) {
1712                 /* Optional data */
1713                 struct ast_json *to = ast_json_object_get(payload->blob, "to");
1714                 struct ast_json *from = ast_json_object_get(payload->blob, "from");
1715                 struct ast_json *rtt = ast_json_object_get(payload->blob, "rtt");
1716                 if (to) {
1717                         ast_str_append(&packet_string, 0, "To: %s\r\n", ast_json_string_get(to));
1718                 }
1719                 if (from) {
1720                         ast_str_append(&packet_string, 0, "From: %s\r\n", ast_json_string_get(from));
1721                 }
1722                 if (rtt) {
1723                         ast_str_append(&packet_string, 0, "RTT: %4.4f\r\n", ast_json_real_get(rtt));
1724                 }
1725         }
1726
1727         ast_str_append(&packet_string, 0, "SSRC: 0x%.8x\r\n", ssrc);
1728         ast_str_append(&packet_string, 0, "PT: %u(%s)\r\n", type, type== AST_RTP_RTCP_SR ? "SR" : "RR");
1729         ast_str_append(&packet_string, 0, "ReportCount: %u\r\n", report_count);
1730         if (type == AST_RTP_RTCP_SR) {
1731                 ast_str_append(&packet_string, 0, "SentNTP: %lu.%06lu\r\n",
1732                         (unsigned long)payload->report->sender_information.ntp_timestamp.tv_sec,
1733                         (unsigned long)payload->report->sender_information.ntp_timestamp.tv_usec * 4096);
1734                 ast_str_append(&packet_string, 0, "SentRTP: %u\r\n",
1735                                 payload->report->sender_information.rtp_timestamp);
1736                 ast_str_append(&packet_string, 0, "SentPackets: %u\r\n",
1737                                 payload->report->sender_information.packet_count);
1738                 ast_str_append(&packet_string, 0, "SentOctets: %u\r\n",
1739                                 payload->report->sender_information.octet_count);
1740         }
1741
1742         for (i = 0; i < report_count; i++) {
1743                 RAII_VAR(struct ast_str *, report_string, NULL, ast_free);
1744
1745                 if (!payload->report->report_block[i]) {
1746                         break;
1747                 }
1748
1749                 report_string = ast_str_create(256);
1750                 if (!report_string) {
1751                         return NULL;
1752                 }
1753
1754                 ast_str_append(&report_string, 0, "Report%dSourceSSRC: 0x%.8x\r\n",
1755                                 i, payload->report->report_block[i]->source_ssrc);
1756                 ast_str_append(&report_string, 0, "Report%dFractionLost: %u\r\n",
1757                                 i, payload->report->report_block[i]->lost_count.fraction);
1758                 ast_str_append(&report_string, 0, "Report%dCumulativeLost: %u\r\n",
1759                                 i, payload->report->report_block[i]->lost_count.packets);
1760                 ast_str_append(&report_string, 0, "Report%dHighestSequence: %u\r\n",
1761                                 i, payload->report->report_block[i]->highest_seq_no & 0xffff);
1762                 ast_str_append(&report_string, 0, "Report%dSequenceNumberCycles: %u\r\n",
1763                                 i, payload->report->report_block[i]->highest_seq_no >> 16);
1764                 ast_str_append(&report_string, 0, "Report%dIAJitter: %u\r\n",
1765                                 i, payload->report->report_block[i]->ia_jitter);
1766                 ast_str_append(&report_string, 0, "Report%dLSR: %u\r\n",
1767                                 i, payload->report->report_block[i]->lsr);
1768                 ast_str_append(&report_string, 0, "Report%dDLSR: %4.4f\r\n",
1769                                 i, ((double)payload->report->report_block[i]->dlsr) / 65536);
1770                 ast_str_append(&packet_string, 0, "%s", ast_str_buffer(report_string));
1771         }
1772
1773         return ast_manager_event_blob_create(EVENT_FLAG_REPORTING,
1774                 stasis_message_type(msg) == ast_rtp_rtcp_received_type() ? "RTCPReceived" : "RTCPSent",
1775                 "%s%s",
1776                 AS_OR(channel_string, ""),
1777                 ast_str_buffer(packet_string));
1778 }
1779
1780 static struct ast_json *rtcp_report_to_json(struct stasis_message *msg)
1781 {
1782         struct rtcp_message_payload *payload = stasis_message_data(msg);
1783         RAII_VAR(struct ast_json *, json_rtcp_report, NULL, ast_json_unref);
1784         RAII_VAR(struct ast_json *, json_rtcp_report_blocks, NULL, ast_json_unref);
1785         RAII_VAR(struct ast_json *, json_rtcp_sender_info, NULL, ast_json_unref);
1786         struct ast_json * json_payload;
1787         int i;
1788
1789         json_rtcp_report_blocks = ast_json_array_create();
1790         if (!json_rtcp_report_blocks) {
1791                 return NULL;
1792         }
1793
1794         for (i = 0; i < payload->report->reception_report_count; i++) {
1795                 struct ast_json *json_report_block;
1796                 json_report_block = ast_json_pack("{s: i, s: i, s: i, s: i, s: i, s: i, s: i}",
1797                                 "source_ssrc", payload->report->report_block[i]->source_ssrc,
1798                                 "fraction_lost", payload->report->report_block[i]->lost_count.fraction,
1799                                 "packets_lost", payload->report->report_block[i]->lost_count.packets,
1800                                 "highest_seq_no", payload->report->report_block[i]->highest_seq_no,
1801                                 "ia_jitter", payload->report->report_block[i]->ia_jitter,
1802                                 "lsr", payload->report->report_block[i]->lsr,
1803                                 "dlsr", payload->report->report_block[i]->dlsr);
1804                 if (!json_report_block) {
1805                         return NULL;
1806                 }
1807
1808                 if (ast_json_array_append(json_rtcp_report_blocks, json_report_block)) {
1809                         return NULL;
1810                 }
1811         }
1812
1813         if (payload->report->type == AST_RTP_RTCP_SR) {
1814                 json_rtcp_sender_info = ast_json_pack("{s: i, s: i, s: i, s: i, s: i}",
1815                                 "ntp_timestamp_sec", payload->report->sender_information.ntp_timestamp.tv_sec,
1816                                 "ntp_timestamp_usec", payload->report->sender_information.ntp_timestamp.tv_usec,
1817                                 "rtp_timestamp", payload->report->sender_information.rtp_timestamp,
1818                                 "packets", payload->report->sender_information.packet_count,
1819                                 "octets", payload->report->sender_information.octet_count);
1820                 if (!json_rtcp_sender_info) {
1821                         return NULL;
1822                 }
1823         }
1824
1825         json_rtcp_report = ast_json_pack("{s: i, s: i, s: i, s: O, s: O}",
1826                         "ssrc", payload->report->ssrc,
1827                         "type", payload->report->type,
1828                         "report_count", payload->report->reception_report_count,
1829                         "sender_information", json_rtcp_sender_info ? json_rtcp_sender_info : ast_json_null(),
1830                         "report_blocks", json_rtcp_report_blocks);
1831         if (!json_rtcp_report) {
1832                 return NULL;
1833         }
1834
1835         json_payload = ast_json_pack("{s: O, s: O, s: O}",
1836                 "channel", payload->snapshot ? ast_channel_snapshot_to_json(payload->snapshot) : ast_json_null(),
1837                 "rtcp_report", json_rtcp_report,
1838                 "blob", payload->blob);
1839         return json_payload;
1840 }
1841
1842 static void rtp_rtcp_report_dtor(void *obj)
1843 {
1844         int i;
1845         struct ast_rtp_rtcp_report *rtcp_report = obj;
1846
1847         for (i = 0; i < rtcp_report->reception_report_count; i++) {
1848                 ast_free(rtcp_report->report_block[i]);
1849         }
1850 }
1851
1852 struct ast_rtp_rtcp_report *ast_rtp_rtcp_report_alloc(unsigned int report_blocks)
1853 {
1854         struct ast_rtp_rtcp_report *rtcp_report;
1855
1856         /* Size of object is sizeof the report + the number of report_blocks * sizeof pointer */
1857         rtcp_report = ao2_alloc((sizeof(*rtcp_report) + report_blocks * sizeof(struct ast_rtp_rtcp_report_block *)),
1858                 rtp_rtcp_report_dtor);
1859
1860         return rtcp_report;
1861 }
1862
1863 void ast_rtp_publish_rtcp_message(struct ast_rtp_instance *rtp,
1864                 struct stasis_message_type *message_type,
1865                 struct ast_rtp_rtcp_report *report,
1866                 struct ast_json *blob)
1867 {
1868         RAII_VAR(struct rtcp_message_payload *, payload,
1869                         ao2_alloc(sizeof(*payload), rtcp_message_payload_dtor), ao2_cleanup);
1870         RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
1871         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1872
1873         if (!payload || !report) {
1874                 return;
1875         }
1876
1877         if (!ast_strlen_zero(rtp->channel_uniqueid)) {
1878                 snapshot = ast_channel_snapshot_get_latest(rtp->channel_uniqueid);
1879                 if (snapshot) {
1880                         ao2_ref(snapshot, +1);
1881                 }
1882         }
1883
1884         if (blob) {
1885                 ast_json_ref(blob);
1886         }
1887         ao2_ref(report, 1);
1888         payload->snapshot = snapshot;
1889         payload->blob = blob;
1890         payload->report = report;
1891
1892         message = stasis_message_create(message_type, payload);
1893         if (!message) {
1894                 return;
1895         }
1896
1897         stasis_publish(ast_rtp_topic(), message);
1898 }
1899
1900 /*!
1901  * @{ \brief Define RTCP/RTP message types.
1902  */
1903 STASIS_MESSAGE_TYPE_DEFN(ast_rtp_rtcp_sent_type,
1904                 .to_ami = rtcp_report_to_ami,
1905                 .to_json = rtcp_report_to_json,);
1906 STASIS_MESSAGE_TYPE_DEFN(ast_rtp_rtcp_received_type,
1907                 .to_ami = rtcp_report_to_ami,
1908                 .to_json = rtcp_report_to_json,);
1909 /*! @} */
1910
1911 struct stasis_topic *ast_rtp_topic(void)
1912 {
1913         return rtp_topic;
1914 }
1915
1916 static void rtp_engine_shutdown(void)
1917 {
1918         ao2_cleanup(rtp_topic);
1919         rtp_topic = NULL;
1920         STASIS_MESSAGE_TYPE_CLEANUP(ast_rtp_rtcp_received_type);
1921         STASIS_MESSAGE_TYPE_CLEANUP(ast_rtp_rtcp_sent_type);
1922 }
1923
1924 int ast_rtp_engine_init()
1925 {
1926         struct ast_format tmpfmt;
1927
1928         ast_rwlock_init(&mime_types_lock);
1929         ast_rwlock_init(&static_RTP_PT_lock);
1930
1931         rtp_topic = stasis_topic_create("rtp_topic");
1932         if (!rtp_topic) {
1933                 return -1;
1934         }
1935         STASIS_MESSAGE_TYPE_INIT(ast_rtp_rtcp_sent_type);
1936         STASIS_MESSAGE_TYPE_INIT(ast_rtp_rtcp_received_type);
1937         ast_register_atexit(rtp_engine_shutdown);
1938
1939         /* Define all the RTP mime types available */
1940         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G723_1, 0), 0, "audio", "G723", 8000);
1941         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_GSM, 0), 0, "audio", "GSM", 8000);
1942         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0), 0, "audio", "PCMU", 8000);
1943         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0), 0, "audio", "G711U", 8000);
1944         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ALAW, 0), 0, "audio", "PCMA", 8000);
1945         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ALAW, 0), 0, "audio", "G711A", 8000);
1946         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G726, 0), 0, "audio", "G726-32", 8000);
1947         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0, "audio", "DVI4", 8000);
1948         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR, 0), 0, "audio", "L16", 8000);
1949         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR16, 0), 0, "audio", "L16", 16000);
1950         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR16, 0), 0, "audio", "L16-256", 16000);
1951         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_LPC10, 0), 0, "audio", "LPC", 8000);
1952         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G729A, 0), 0, "audio", "G729", 8000);
1953         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G729A, 0), 0, "audio", "G729A", 8000);
1954         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G729A, 0), 0, "audio", "G.729", 8000);
1955         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SPEEX, 0), 0, "audio", "speex", 8000);
1956         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SPEEX16, 0), 0,  "audio", "speex", 16000);
1957         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SPEEX32, 0), 0,  "audio", "speex", 32000);
1958         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ILBC, 0), 0, "audio", "iLBC", 8000);
1959         /* this is the sample rate listed in the RTP profile for the G.722 codec, *NOT* the actual sample rate of the media stream */
1960         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G722, 0), 0, "audio", "G722", 8000);
1961         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G726_AAL2, 0), 0, "audio", "AAL2-G726-32", 8000);
1962         set_next_mime_type(NULL, AST_RTP_DTMF, "audio", "telephone-event", 8000);
1963         set_next_mime_type(NULL, AST_RTP_CISCO_DTMF, "audio", "cisco-telephone-event", 8000);
1964         set_next_mime_type(NULL, AST_RTP_CN, "audio", "CN", 8000);
1965         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_JPEG, 0), 0, "video", "JPEG", 90000);
1966         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_PNG, 0), 0, "video", "PNG", 90000);
1967         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_H261, 0), 0, "video", "H261", 90000);
1968         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_H263, 0), 0, "video", "H263", 90000);
1969         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_H263_PLUS, 0), 0, "video", "h263-1998", 90000);
1970         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_H264, 0), 0, "video", "H264", 90000);
1971         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_MP4_VIDEO, 0), 0, "video", "MP4V-ES", 90000);
1972         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_T140RED, 0), 0, "text", "RED", 1000);
1973         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_T140, 0), 0, "text", "T140", 1000);
1974         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SIREN7, 0), 0, "audio", "G7221", 16000);
1975         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SIREN14, 0), 0, "audio", "G7221", 32000);
1976         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G719, 0), 0, "audio", "G719", 48000);
1977
1978         /* Define the static rtp payload mappings */
1979         add_static_payload(0, ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0), 0);
1980         #ifdef USE_DEPRECATED_G726
1981         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... */
1982         #endif
1983         add_static_payload(3, ast_format_set(&tmpfmt, AST_FORMAT_GSM, 0), 0);
1984         add_static_payload(4, ast_format_set(&tmpfmt, AST_FORMAT_G723_1, 0), 0);
1985         add_static_payload(5, ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0);/* 8 kHz */
1986         add_static_payload(6, ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0); /* 16 kHz */
1987         add_static_payload(7, ast_format_set(&tmpfmt, AST_FORMAT_LPC10, 0), 0);
1988         add_static_payload(8, ast_format_set(&tmpfmt, AST_FORMAT_ALAW, 0), 0);
1989         add_static_payload(9, ast_format_set(&tmpfmt, AST_FORMAT_G722, 0), 0);
1990         add_static_payload(10, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR, 0), 0); /* 2 channels */
1991         add_static_payload(11, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR, 0), 0); /* 1 channel */
1992         add_static_payload(13, NULL, AST_RTP_CN);
1993         add_static_payload(16, ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0); /* 11.025 kHz */
1994         add_static_payload(17, ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0); /* 22.050 kHz */
1995         add_static_payload(18, ast_format_set(&tmpfmt, AST_FORMAT_G729A, 0), 0);
1996         add_static_payload(19, NULL, AST_RTP_CN);         /* Also used for CN */
1997         add_static_payload(26, ast_format_set(&tmpfmt, AST_FORMAT_JPEG, 0), 0);
1998         add_static_payload(31, ast_format_set(&tmpfmt, AST_FORMAT_H261, 0), 0);
1999         add_static_payload(34, ast_format_set(&tmpfmt, AST_FORMAT_H263, 0), 0);
2000         add_static_payload(97, ast_format_set(&tmpfmt, AST_FORMAT_ILBC, 0), 0);
2001         add_static_payload(98, ast_format_set(&tmpfmt, AST_FORMAT_H263_PLUS, 0), 0);
2002         add_static_payload(99, ast_format_set(&tmpfmt, AST_FORMAT_H264, 0), 0);
2003         add_static_payload(101, NULL, AST_RTP_DTMF);
2004         add_static_payload(102, ast_format_set(&tmpfmt, AST_FORMAT_SIREN7, 0), 0);
2005         add_static_payload(103, ast_format_set(&tmpfmt, AST_FORMAT_H263_PLUS, 0), 0);
2006         add_static_payload(104, ast_format_set(&tmpfmt, AST_FORMAT_MP4_VIDEO, 0), 0);
2007         add_static_payload(105, ast_format_set(&tmpfmt, AST_FORMAT_T140RED, 0), 0);   /* Real time text chat (with redundancy encoding) */
2008         add_static_payload(106, ast_format_set(&tmpfmt, AST_FORMAT_T140, 0), 0);     /* Real time text chat */
2009         add_static_payload(110, ast_format_set(&tmpfmt, AST_FORMAT_SPEEX, 0), 0);
2010         add_static_payload(111, ast_format_set(&tmpfmt, AST_FORMAT_G726, 0), 0);
2011         add_static_payload(112, ast_format_set(&tmpfmt, AST_FORMAT_G726_AAL2, 0), 0);
2012         add_static_payload(115, ast_format_set(&tmpfmt, AST_FORMAT_SIREN14, 0), 0);
2013         add_static_payload(116, ast_format_set(&tmpfmt, AST_FORMAT_G719, 0), 0);
2014         add_static_payload(117, ast_format_set(&tmpfmt, AST_FORMAT_SPEEX16, 0), 0);
2015         add_static_payload(118, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR16, 0), 0); /* 16 Khz signed linear */
2016         add_static_payload(119, ast_format_set(&tmpfmt, AST_FORMAT_SPEEX32, 0), 0);
2017         add_static_payload(121, NULL, AST_RTP_CISCO_DTMF);   /* Must be type 121 */
2018
2019         return 0;
2020 }