90e1abb45462bbacbe78cdaf327ab84d886bfe97
[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 #include "asterisk.h"
31
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
33
34 #include <math.h>
35
36 #include "asterisk/channel.h"
37 #include "asterisk/frame.h"
38 #include "asterisk/module.h"
39 #include "asterisk/rtp_engine.h"
40 #include "asterisk/manager.h"
41 #include "asterisk/options.h"
42 #include "asterisk/astobj2.h"
43 #include "asterisk/pbx.h"
44 #include "asterisk/translate.h"
45 #include "asterisk/netsock2.h"
46 #include "asterisk/_private.h"
47 #include "asterisk/framehook.h"
48
49 struct ast_srtp_res *res_srtp = NULL;
50 struct ast_srtp_policy_res *res_srtp_policy = NULL;
51
52 /*! Structure that represents an RTP session (instance) */
53 struct ast_rtp_instance {
54         /*! Engine that is handling this RTP instance */
55         struct ast_rtp_engine *engine;
56         /*! Data unique to the RTP engine */
57         void *data;
58         /*! RTP properties that have been set and their value */
59         int properties[AST_RTP_PROPERTY_MAX];
60         /*! Address that we are expecting RTP to come in to */
61         struct ast_sockaddr local_address;
62         /*! Address that we are sending RTP to */
63         struct ast_sockaddr remote_address;
64         /*! Alternate address that we are receiving RTP from */
65         struct ast_sockaddr alt_remote_address;
66         /*! Instance that we are bridged to if doing remote or local bridging */
67         struct ast_rtp_instance *bridged;
68         /*! Payload and packetization information */
69         struct ast_rtp_codecs codecs;
70         /*! RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
71         int timeout;
72         /*! RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
73         int holdtimeout;
74         /*! RTP keepalive interval */
75         int keepalive;
76         /*! Glue currently in use */
77         struct ast_rtp_glue *glue;
78         /*! Channel associated with the instance */
79         struct ast_channel *chan;
80         /*! SRTP info associated with the instance */
81         struct ast_srtp *srtp;
82 };
83
84 /*! List of RTP engines that are currently registered */
85 static AST_RWLIST_HEAD_STATIC(engines, ast_rtp_engine);
86
87 /*! List of RTP glues */
88 static AST_RWLIST_HEAD_STATIC(glues, ast_rtp_glue);
89
90 /*! The following array defines the MIME Media type (and subtype) for each
91    of our codecs, or RTP-specific data type. */
92 static struct ast_rtp_mime_type {
93         struct ast_rtp_payload_type payload_type;
94         char *type;
95         char *subtype;
96         unsigned int sample_rate;
97 } ast_rtp_mime_types[128]; /* This will Likely not need to grow any time soon. */
98 static ast_rwlock_t mime_types_lock;
99 static int mime_types_len = 0;
100
101 /*!
102  * \brief Mapping between Asterisk codecs and rtp payload types
103  *
104  * Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
105  * also, our own choices for dynamic payload types.  This is our master
106  * table for transmission
107  *
108  * See http://www.iana.org/assignments/rtp-parameters for a list of
109  * assigned values
110  */
111 static struct ast_rtp_payload_type static_RTP_PT[AST_RTP_MAX_PT];
112 static ast_rwlock_t static_RTP_PT_lock;
113
114 int ast_rtp_engine_register2(struct ast_rtp_engine *engine, struct ast_module *module)
115 {
116         struct ast_rtp_engine *current_engine;
117
118         /* Perform a sanity check on the engine structure to make sure it has the basics */
119         if (ast_strlen_zero(engine->name) || !engine->new || !engine->destroy || !engine->write || !engine->read) {
120                 ast_log(LOG_WARNING, "RTP Engine '%s' failed sanity check so it was not registered.\n", !ast_strlen_zero(engine->name) ? engine->name : "Unknown");
121                 return -1;
122         }
123
124         /* Link owner module to the RTP engine for reference counting purposes */
125         engine->mod = module;
126
127         AST_RWLIST_WRLOCK(&engines);
128
129         /* Ensure that no two modules with the same name are registered at the same time */
130         AST_RWLIST_TRAVERSE(&engines, current_engine, entry) {
131                 if (!strcmp(current_engine->name, engine->name)) {
132                         ast_log(LOG_WARNING, "An RTP engine with the name '%s' has already been registered.\n", engine->name);
133                         AST_RWLIST_UNLOCK(&engines);
134                         return -1;
135                 }
136         }
137
138         /* The engine survived our critique. Off to the list it goes to be used */
139         AST_RWLIST_INSERT_TAIL(&engines, engine, entry);
140
141         AST_RWLIST_UNLOCK(&engines);
142
143         ast_verb(2, "Registered RTP engine '%s'\n", engine->name);
144
145         return 0;
146 }
147
148 int ast_rtp_engine_unregister(struct ast_rtp_engine *engine)
149 {
150         struct ast_rtp_engine *current_engine = NULL;
151
152         AST_RWLIST_WRLOCK(&engines);
153
154         if ((current_engine = AST_RWLIST_REMOVE(&engines, engine, entry))) {
155                 ast_verb(2, "Unregistered RTP engine '%s'\n", engine->name);
156         }
157
158         AST_RWLIST_UNLOCK(&engines);
159
160         return current_engine ? 0 : -1;
161 }
162
163 int ast_rtp_glue_register2(struct ast_rtp_glue *glue, struct ast_module *module)
164 {
165         struct ast_rtp_glue *current_glue = NULL;
166
167         if (ast_strlen_zero(glue->type)) {
168                 return -1;
169         }
170
171         glue->mod = module;
172
173         AST_RWLIST_WRLOCK(&glues);
174
175         AST_RWLIST_TRAVERSE(&glues, current_glue, entry) {
176                 if (!strcasecmp(current_glue->type, glue->type)) {
177                         ast_log(LOG_WARNING, "RTP glue with the name '%s' has already been registered.\n", glue->type);
178                         AST_RWLIST_UNLOCK(&glues);
179                         return -1;
180                 }
181         }
182
183         AST_RWLIST_INSERT_TAIL(&glues, glue, entry);
184
185         AST_RWLIST_UNLOCK(&glues);
186
187         ast_verb(2, "Registered RTP glue '%s'\n", glue->type);
188
189         return 0;
190 }
191
192 int ast_rtp_glue_unregister(struct ast_rtp_glue *glue)
193 {
194         struct ast_rtp_glue *current_glue = NULL;
195
196         AST_RWLIST_WRLOCK(&glues);
197
198         if ((current_glue = AST_RWLIST_REMOVE(&glues, glue, entry))) {
199                 ast_verb(2, "Unregistered RTP glue '%s'\n", glue->type);
200         }
201
202         AST_RWLIST_UNLOCK(&glues);
203
204         return current_glue ? 0 : -1;
205 }
206
207 static void instance_destructor(void *obj)
208 {
209         struct ast_rtp_instance *instance = obj;
210
211         /* Pass us off to the engine to destroy */
212         if (instance->data && instance->engine->destroy(instance)) {
213                 ast_debug(1, "Engine '%s' failed to destroy RTP instance '%p'\n", instance->engine->name, instance);
214                 return;
215         }
216
217         if (instance->srtp) {
218                 res_srtp->destroy(instance->srtp);
219         }
220
221         ast_rtp_codecs_payloads_destroy(&instance->codecs);
222
223         /* Drop our engine reference */
224         ast_module_unref(instance->engine->mod);
225
226         ast_debug(1, "Destroyed RTP instance '%p'\n", instance);
227 }
228
229 int ast_rtp_instance_destroy(struct ast_rtp_instance *instance)
230 {
231         ao2_ref(instance, -1);
232
233         return 0;
234 }
235
236 struct ast_rtp_instance *ast_rtp_instance_new(const char *engine_name,
237                 struct ast_sched_context *sched, const struct ast_sockaddr *sa,
238                 void *data)
239 {
240         struct ast_sockaddr address = {{0,}};
241         struct ast_rtp_instance *instance = NULL;
242         struct ast_rtp_engine *engine = NULL;
243
244         AST_RWLIST_RDLOCK(&engines);
245
246         /* If an engine name was specified try to use it or otherwise use the first one registered */
247         if (!ast_strlen_zero(engine_name)) {
248                 AST_RWLIST_TRAVERSE(&engines, engine, entry) {
249                         if (!strcmp(engine->name, engine_name)) {
250                                 break;
251                         }
252                 }
253         } else {
254                 engine = AST_RWLIST_FIRST(&engines);
255         }
256
257         /* If no engine was actually found bail out now */
258         if (!engine) {
259                 ast_log(LOG_ERROR, "No RTP engine was found. Do you have one loaded?\n");
260                 AST_RWLIST_UNLOCK(&engines);
261                 return NULL;
262         }
263
264         /* Bump up the reference count before we return so the module can not be unloaded */
265         ast_module_ref(engine->mod);
266
267         AST_RWLIST_UNLOCK(&engines);
268
269         /* Allocate a new RTP instance */
270         if (!(instance = ao2_alloc(sizeof(*instance), instance_destructor))) {
271                 ast_module_unref(engine->mod);
272                 return NULL;
273         }
274         instance->engine = engine;
275         ast_sockaddr_copy(&instance->local_address, sa);
276         ast_sockaddr_copy(&address, sa);
277
278         if (ast_rtp_codecs_payloads_initialize(&instance->codecs)) {
279                 ao2_ref(instance, -1);
280                 return NULL;
281         }
282
283         ast_debug(1, "Using engine '%s' for RTP instance '%p'\n", engine->name, instance);
284
285         /* And pass it off to the engine to setup */
286         if (instance->engine->new(instance, sched, &address, data)) {
287                 ast_debug(1, "Engine '%s' failed to setup RTP instance '%p'\n", engine->name, instance);
288                 ao2_ref(instance, -1);
289                 return NULL;
290         }
291
292         ast_debug(1, "RTP instance '%p' is setup and ready to go\n", instance);
293
294         return instance;
295 }
296
297 void ast_rtp_instance_set_data(struct ast_rtp_instance *instance, void *data)
298 {
299         instance->data = data;
300 }
301
302 void *ast_rtp_instance_get_data(struct ast_rtp_instance *instance)
303 {
304         return instance->data;
305 }
306
307 int ast_rtp_instance_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
308 {
309         return instance->engine->write(instance, frame);
310 }
311
312 struct ast_frame *ast_rtp_instance_read(struct ast_rtp_instance *instance, int rtcp)
313 {
314         return instance->engine->read(instance, rtcp);
315 }
316
317 int ast_rtp_instance_set_local_address(struct ast_rtp_instance *instance,
318                 const struct ast_sockaddr *address)
319 {
320         ast_sockaddr_copy(&instance->local_address, address);
321         return 0;
322 }
323
324 int ast_rtp_instance_set_remote_address(struct ast_rtp_instance *instance,
325                 const struct ast_sockaddr *address)
326 {
327         ast_sockaddr_copy(&instance->remote_address, address);
328
329         /* moo */
330
331         if (instance->engine->remote_address_set) {
332                 instance->engine->remote_address_set(instance, &instance->remote_address);
333         }
334
335         return 0;
336 }
337
338 int ast_rtp_instance_set_alt_remote_address(struct ast_rtp_instance *instance,
339                 const struct ast_sockaddr *address)
340 {
341         ast_sockaddr_copy(&instance->alt_remote_address, address);
342
343         /* oink */
344
345         if (instance->engine->alt_remote_address_set) {
346                 instance->engine->alt_remote_address_set(instance, &instance->alt_remote_address);
347         }
348
349         return 0;
350 }
351
352 int ast_rtp_instance_get_and_cmp_local_address(struct ast_rtp_instance *instance,
353                 struct ast_sockaddr *address)
354 {
355         if (ast_sockaddr_cmp(address, &instance->local_address) != 0) {
356                 ast_sockaddr_copy(address, &instance->local_address);
357                 return 1;
358         }
359
360         return 0;
361 }
362
363 void ast_rtp_instance_get_local_address(struct ast_rtp_instance *instance,
364                 struct ast_sockaddr *address)
365 {
366         ast_sockaddr_copy(address, &instance->local_address);
367 }
368
369 int ast_rtp_instance_get_and_cmp_remote_address(struct ast_rtp_instance *instance,
370                 struct ast_sockaddr *address)
371 {
372         if (ast_sockaddr_cmp(address, &instance->remote_address) != 0) {
373                 ast_sockaddr_copy(address, &instance->remote_address);
374                 return 1;
375         }
376
377         return 0;
378 }
379
380 void ast_rtp_instance_get_remote_address(struct ast_rtp_instance *instance,
381                 struct ast_sockaddr *address)
382 {
383         ast_sockaddr_copy(address, &instance->remote_address);
384 }
385
386 void ast_rtp_instance_set_extended_prop(struct ast_rtp_instance *instance, int property, void *value)
387 {
388         if (instance->engine->extended_prop_set) {
389                 instance->engine->extended_prop_set(instance, property, value);
390         }
391 }
392
393 void *ast_rtp_instance_get_extended_prop(struct ast_rtp_instance *instance, int property)
394 {
395         if (instance->engine->extended_prop_get) {
396                 return instance->engine->extended_prop_get(instance, property);
397         }
398
399         return NULL;
400 }
401
402 void ast_rtp_instance_set_prop(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value)
403 {
404         instance->properties[property] = value;
405
406         if (instance->engine->prop_set) {
407                 instance->engine->prop_set(instance, property, value);
408         }
409 }
410
411 int ast_rtp_instance_get_prop(struct ast_rtp_instance *instance, enum ast_rtp_property property)
412 {
413         return instance->properties[property];
414 }
415
416 struct ast_rtp_codecs *ast_rtp_instance_get_codecs(struct ast_rtp_instance *instance)
417 {
418         return &instance->codecs;
419 }
420
421 static int rtp_payload_type_hash(const void *obj, const int flags)
422 {
423         const struct ast_rtp_payload_type *type = obj;
424         const int *payload = obj;
425
426         return (flags & OBJ_KEY) ? *payload : type->payload;
427 }
428
429 static int rtp_payload_type_cmp(void *obj, void *arg, int flags)
430 {
431         struct ast_rtp_payload_type *type1 = obj, *type2 = arg;
432         const int *payload = arg;
433
434         return (type1->payload == (OBJ_KEY ? *payload : type2->payload)) ? CMP_MATCH | CMP_STOP : 0;
435 }
436
437 int ast_rtp_codecs_payloads_initialize(struct ast_rtp_codecs *codecs)
438 {
439         if (!(codecs->payloads = ao2_container_alloc(AST_RTP_MAX_PT, rtp_payload_type_hash, rtp_payload_type_cmp))) {
440                 return -1;
441         }
442
443         return 0;
444 }
445
446 void ast_rtp_codecs_payloads_destroy(struct ast_rtp_codecs *codecs)
447 {
448         ao2_cleanup(codecs->payloads);
449 }
450
451 void ast_rtp_codecs_payloads_clear(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance)
452 {
453         ast_rtp_codecs_payloads_destroy(codecs);
454
455         if (instance && instance->engine && instance->engine->payload_set) {
456                 int i;
457                 for (i = 0; i < AST_RTP_MAX_PT; i++) {
458                         instance->engine->payload_set(instance, i, 0, NULL, 0);
459                 }
460         }
461
462         ast_rtp_codecs_payloads_initialize(codecs);
463 }
464
465 void ast_rtp_codecs_payloads_default(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance)
466 {
467         int i;
468
469         ast_rwlock_rdlock(&static_RTP_PT_lock);
470         for (i = 0; i < AST_RTP_MAX_PT; i++) {
471                 if (static_RTP_PT[i].rtp_code || static_RTP_PT[i].asterisk_format) {
472                         struct ast_rtp_payload_type *type;
473
474                         if (!(type = ao2_alloc(sizeof(*type), NULL))) {
475                                 /* Unfortunately if this occurs the payloads container will not contain all possible default payloads
476                                  * but we err on the side of doing what we can in the hopes that the extreme memory conditions which
477                                  * caused this to occur will go away.
478                                  */
479                                 continue;
480                         }
481
482                         type->payload = i;
483                         type->asterisk_format = static_RTP_PT[i].asterisk_format;
484                         type->rtp_code = static_RTP_PT[i].rtp_code;
485                         ast_format_copy(&type->format, &static_RTP_PT[i].format);
486
487                         ao2_link_flags(codecs->payloads, type, OBJ_NOLOCK);
488
489                         if (instance && instance->engine && instance->engine->payload_set) {
490                                 instance->engine->payload_set(instance, i, type->asterisk_format, &type->format, type->rtp_code);
491                         }
492
493                         ao2_ref(type, -1);
494                 }
495         }
496         ast_rwlock_unlock(&static_RTP_PT_lock);
497 }
498
499 void ast_rtp_codecs_payloads_copy(struct ast_rtp_codecs *src, struct ast_rtp_codecs *dest, struct ast_rtp_instance *instance)
500 {
501         int i;
502         struct ast_rtp_payload_type *type;
503
504         for (i = 0; i < AST_RTP_MAX_PT; i++) {
505                 struct ast_rtp_payload_type *new_type;
506
507                 if (!(type = ao2_find(src->payloads, &i, OBJ_KEY | OBJ_NOLOCK))) {
508                         continue;
509                 }
510
511                 if (!(new_type = ao2_alloc(sizeof(*new_type), NULL))) {
512                         continue;
513                 }
514
515                 ast_debug(2, "Copying payload %d from %p to %p\n", i, src, dest);
516
517                 new_type->payload = i;
518                 *new_type = *type;
519
520                 ao2_link_flags(dest->payloads, new_type, OBJ_NOLOCK);
521
522                 ao2_ref(new_type, -1);
523
524                 if (instance && instance->engine && instance->engine->payload_set) {
525                         instance->engine->payload_set(instance, i, type->asterisk_format, &type->format, type->rtp_code);
526                 }
527
528                 ao2_ref(type, -1);
529         }
530 }
531
532 void ast_rtp_codecs_payloads_set_m_type(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, int payload)
533 {
534         struct ast_rtp_payload_type *type;
535
536         ast_rwlock_rdlock(&static_RTP_PT_lock);
537
538         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
539                 ast_rwlock_unlock(&static_RTP_PT_lock);
540                 return;
541         }
542
543         if (!(type = ao2_find(codecs->payloads, &payload, OBJ_KEY | OBJ_NOLOCK))) {
544                 if (!(type = ao2_alloc(sizeof(*type), NULL))) {
545                         ast_rwlock_unlock(&static_RTP_PT_lock);
546                         return;
547                 }
548                 type->payload = payload;
549                 ao2_link_flags(codecs->payloads, type, OBJ_NOLOCK);
550         }
551
552         type->asterisk_format = static_RTP_PT[payload].asterisk_format;
553         type->rtp_code = static_RTP_PT[payload].rtp_code;
554         type->payload = payload;
555         ast_format_copy(&type->format, &static_RTP_PT[payload].format);
556
557         ast_debug(1, "Setting payload %d based on m type on %p\n", payload, codecs);
558
559         if (instance && instance->engine && instance->engine->payload_set) {
560                 instance->engine->payload_set(instance, payload, type->asterisk_format, &type->format, type->rtp_code);
561         }
562
563         ao2_ref(type, -1);
564
565         ast_rwlock_unlock(&static_RTP_PT_lock);
566 }
567
568 int ast_rtp_codecs_payloads_set_rtpmap_type_rate(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, int pt,
569                                  char *mimetype, char *mimesubtype,
570                                  enum ast_rtp_options options,
571                                  unsigned int sample_rate)
572 {
573         unsigned int i;
574         int found = 0;
575
576         if (pt < 0 || pt >= AST_RTP_MAX_PT)
577                 return -1; /* bogus payload type */
578
579         ast_rwlock_rdlock(&mime_types_lock);
580         for (i = 0; i < mime_types_len; ++i) {
581                 const struct ast_rtp_mime_type *t = &ast_rtp_mime_types[i];
582                 struct ast_rtp_payload_type *type;
583
584                 if (strcasecmp(mimesubtype, t->subtype)) {
585                         continue;
586                 }
587
588                 if (strcasecmp(mimetype, t->type)) {
589                         continue;
590                 }
591
592                 /* if both sample rates have been supplied, and they don't match,
593                  * then this not a match; if one has not been supplied, then the
594                  * rates are not compared */
595                 if (sample_rate && t->sample_rate &&
596                     (sample_rate != t->sample_rate)) {
597                         continue;
598                 }
599
600                 found = 1;
601
602                 if (!(type = ao2_find(codecs->payloads, &pt, OBJ_KEY | OBJ_NOLOCK))) {
603                         if (!(type = ao2_alloc(sizeof(*type), NULL))) {
604                                 continue;
605                         }
606                         type->payload = pt;
607                         ao2_link_flags(codecs->payloads, type, OBJ_NOLOCK);
608                 }
609
610                 *type = t->payload_type;
611                 type->payload = pt;
612
613                 if ((t->payload_type.format.id == AST_FORMAT_G726) && t->payload_type.asterisk_format && (options & AST_RTP_OPT_G726_NONSTANDARD)) {
614                         ast_format_set(&type->format, AST_FORMAT_G726_AAL2, 0);
615                 }
616
617                 if (instance && instance->engine && instance->engine->payload_set) {
618                         instance->engine->payload_set(instance, pt, type->asterisk_format, &type->format, type->rtp_code);
619                 }
620
621                 ao2_ref(type, -1);
622
623                 break;
624         }
625         ast_rwlock_unlock(&mime_types_lock);
626
627         return (found ? 0 : -2);
628 }
629
630 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)
631 {
632         return ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, instance, payload, mimetype, mimesubtype, options, 0);
633 }
634
635 void ast_rtp_codecs_payloads_unset(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, int payload)
636 {
637         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
638                 return;
639         }
640
641         ast_debug(2, "Unsetting payload %d on %p\n", payload, codecs);
642
643         ao2_find(codecs->payloads, &payload, OBJ_KEY | OBJ_NOLOCK | OBJ_NODATA | OBJ_UNLINK);
644
645         if (instance && instance->engine && instance->engine->payload_set) {
646                 instance->engine->payload_set(instance, payload, 0, NULL, 0);
647         }
648 }
649
650 struct ast_rtp_payload_type ast_rtp_codecs_payload_lookup(struct ast_rtp_codecs *codecs, int payload)
651 {
652         struct ast_rtp_payload_type result = { .asterisk_format = 0, }, *type;
653
654         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
655                 return result;
656         }
657
658         if ((type = ao2_find(codecs->payloads, &payload, OBJ_KEY | OBJ_NOLOCK))) {
659                 result = *type;
660                 ao2_ref(type, -1);
661         }
662
663         if (!result.rtp_code && !result.asterisk_format) {
664                 ast_rwlock_rdlock(&static_RTP_PT_lock);
665                 result = static_RTP_PT[payload];
666                 ast_rwlock_unlock(&static_RTP_PT_lock);
667         }
668
669         return result;
670 }
671
672
673 struct ast_format *ast_rtp_codecs_get_payload_format(struct ast_rtp_codecs *codecs, int payload)
674 {
675         struct ast_rtp_payload_type *type;
676         struct ast_format *format;
677
678         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
679                 return NULL;
680         }
681
682         if (!(type = ao2_find(codecs->payloads, &payload, OBJ_KEY | OBJ_NOLOCK))) {
683                 return NULL;
684         }
685
686         format = type->asterisk_format ? &type->format : NULL;
687
688         ao2_ref(type, -1);
689
690         return format;
691 }
692
693 static int rtp_payload_type_add_ast(void *obj, void *arg, int flags)
694 {
695         struct ast_rtp_payload_type *type = obj;
696         struct ast_format_cap *astformats = arg;
697
698         if (type->asterisk_format) {
699                 ast_format_cap_add(astformats, &type->format);
700         }
701
702         return 0;
703 }
704
705 static int rtp_payload_type_add_nonast(void *obj, void *arg, int flags)
706 {
707         struct ast_rtp_payload_type *type = obj;
708         int *nonastformats = arg;
709
710         if (!type->asterisk_format) {
711                 *nonastformats |= type->rtp_code;
712         }
713
714         return 0;
715 }
716
717 void ast_rtp_codecs_payload_formats(struct ast_rtp_codecs *codecs, struct ast_format_cap *astformats, int *nonastformats)
718 {
719         ast_format_cap_remove_all(astformats);
720         *nonastformats = 0;
721
722         ao2_callback(codecs->payloads, OBJ_NODATA | OBJ_MULTIPLE | OBJ_NOLOCK, rtp_payload_type_add_ast, astformats);
723         ao2_callback(codecs->payloads, OBJ_NODATA | OBJ_MULTIPLE | OBJ_NOLOCK, rtp_payload_type_add_nonast, nonastformats);
724 }
725
726 static int rtp_payload_type_find_format(void *obj, void *arg, int flags)
727 {
728         struct ast_rtp_payload_type *type = obj;
729         struct ast_format *format = arg;
730
731         return (type->asterisk_format && (ast_format_cmp(&type->format, format) != AST_FORMAT_CMP_NOT_EQUAL)) ? CMP_MATCH | CMP_STOP : 0;
732 }
733
734 int ast_rtp_codecs_payload_code(struct ast_rtp_codecs *codecs, int asterisk_format, const struct ast_format *format, int code)
735 {
736         struct ast_rtp_payload_type *type;
737         int i, res = -1;
738
739         if (asterisk_format && format && (type = ao2_callback(codecs->payloads, OBJ_NOLOCK, rtp_payload_type_find_format, (void*)format))) {
740                 res = type->payload;
741                 ao2_ref(type, -1);
742                 return res;
743         } else if (!asterisk_format && (type = ao2_find(codecs->payloads, &code, OBJ_NOLOCK | OBJ_KEY))) {
744                 res = type->payload;
745                 ao2_ref(type, -1);
746                 return res;
747         }
748
749         ast_rwlock_rdlock(&static_RTP_PT_lock);
750         for (i = 0; i < AST_RTP_MAX_PT; i++) {
751                 if (static_RTP_PT[i].asterisk_format && asterisk_format && format &&
752                         (ast_format_cmp(format, &static_RTP_PT[i].format) != AST_FORMAT_CMP_NOT_EQUAL)) {
753                         res = i;
754                         break;
755                 } else if (!static_RTP_PT[i].asterisk_format && !asterisk_format &&
756                         (static_RTP_PT[i].rtp_code == code)) {
757                         res = i;
758                         break;
759                 }
760         }
761         ast_rwlock_unlock(&static_RTP_PT_lock);
762
763         return res;
764 }
765 int ast_rtp_codecs_find_payload_code(struct ast_rtp_codecs *codecs, int code)
766 {
767         struct ast_rtp_payload_type *type;
768         int res = -1;
769
770         /* Search the payload type in the codecs passed */
771         if ((type = ao2_find(codecs->payloads, &code, OBJ_NOLOCK | OBJ_KEY)))
772         {
773                 res = type->payload;
774                 ao2_ref(type, -1);
775                 return res;
776         }
777
778         return res;
779 }
780 const char *ast_rtp_lookup_mime_subtype2(const int asterisk_format, struct ast_format *format, int code, enum ast_rtp_options options)
781 {
782         int i;
783         const char *res = "";
784
785         ast_rwlock_rdlock(&mime_types_lock);
786         for (i = 0; i < mime_types_len; i++) {
787                 if (ast_rtp_mime_types[i].payload_type.asterisk_format && asterisk_format && format &&
788                         (ast_format_cmp(format, &ast_rtp_mime_types[i].payload_type.format) != AST_FORMAT_CMP_NOT_EQUAL)) {
789                         if ((format->id == AST_FORMAT_G726_AAL2) && (options & AST_RTP_OPT_G726_NONSTANDARD)) {
790                                 res = "G726-32";
791                                 break;
792                         } else {
793                                 res = ast_rtp_mime_types[i].subtype;
794                                 break;
795                         }
796                 } else if (!ast_rtp_mime_types[i].payload_type.asterisk_format && !asterisk_format &&
797                         ast_rtp_mime_types[i].payload_type.rtp_code == code) {
798
799                         res = ast_rtp_mime_types[i].subtype;
800                         break;
801                 }
802         }
803         ast_rwlock_unlock(&mime_types_lock);
804
805         return res;
806 }
807
808 unsigned int ast_rtp_lookup_sample_rate2(int asterisk_format, struct ast_format *format, int code)
809 {
810         unsigned int i;
811         unsigned int res = 0;
812
813         ast_rwlock_rdlock(&mime_types_lock);
814         for (i = 0; i < mime_types_len; ++i) {
815                 if (ast_rtp_mime_types[i].payload_type.asterisk_format && asterisk_format && format &&
816                         (ast_format_cmp(format, &ast_rtp_mime_types[i].payload_type.format) != AST_FORMAT_CMP_NOT_EQUAL)) {
817                         res = ast_rtp_mime_types[i].sample_rate;
818                         break;
819                 } else if (!ast_rtp_mime_types[i].payload_type.asterisk_format && !asterisk_format &&
820                         ast_rtp_mime_types[i].payload_type.rtp_code == code) {
821                         res = ast_rtp_mime_types[i].sample_rate;
822                         break;
823                 }
824         }
825         ast_rwlock_unlock(&mime_types_lock);
826
827         return res;
828 }
829
830 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)
831 {
832         int found = 0;
833         const char *name;
834         if (!buf) {
835                 return NULL;
836         }
837
838
839         if (asterisk_format) {
840                 struct ast_format tmp_fmt;
841                 ast_format_cap_iter_start(ast_format_capability);
842                 while (!ast_format_cap_iter_next(ast_format_capability, &tmp_fmt)) {
843                         name = ast_rtp_lookup_mime_subtype2(asterisk_format, &tmp_fmt, 0, options);
844                         ast_str_append(&buf, 0, "%s|", name);
845                         found = 1;
846                 }
847                 ast_format_cap_iter_end(ast_format_capability);
848
849         } else {
850                 int x;
851                 ast_str_append(&buf, 0, "0x%x (", (unsigned int) rtp_capability);
852                 for (x = 1; x < AST_RTP_MAX; x <<= 1) {
853                         if (rtp_capability & x) {
854                                 name = ast_rtp_lookup_mime_subtype2(asterisk_format, NULL, x, options);
855                                 ast_str_append(&buf, 0, "%s|", name);
856                                 found = 1;
857                         }
858                 }
859         }
860
861         ast_str_append(&buf, 0, "%s", found ? ")" : "nothing)");
862
863         return ast_str_buffer(buf);
864 }
865
866 void ast_rtp_codecs_packetization_set(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, struct ast_codec_pref *prefs)
867 {
868         codecs->pref = *prefs;
869
870         if (instance && instance->engine->packetization_set) {
871                 instance->engine->packetization_set(instance, &instance->codecs.pref);
872         }
873 }
874
875 int ast_rtp_instance_dtmf_begin(struct ast_rtp_instance *instance, char digit)
876 {
877         return instance->engine->dtmf_begin ? instance->engine->dtmf_begin(instance, digit) : -1;
878 }
879
880 int ast_rtp_instance_dtmf_end(struct ast_rtp_instance *instance, char digit)
881 {
882         return instance->engine->dtmf_end ? instance->engine->dtmf_end(instance, digit) : -1;
883 }
884 int ast_rtp_instance_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
885 {
886         return instance->engine->dtmf_end_with_duration ? instance->engine->dtmf_end_with_duration(instance, digit, duration) : -1;
887 }
888
889 int ast_rtp_instance_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
890 {
891         return (!instance->engine->dtmf_mode_set || instance->engine->dtmf_mode_set(instance, dtmf_mode)) ? -1 : 0;
892 }
893
894 enum ast_rtp_dtmf_mode ast_rtp_instance_dtmf_mode_get(struct ast_rtp_instance *instance)
895 {
896         return instance->engine->dtmf_mode_get ? instance->engine->dtmf_mode_get(instance) : 0;
897 }
898
899 void ast_rtp_instance_update_source(struct ast_rtp_instance *instance)
900 {
901         if (instance->engine->update_source) {
902                 instance->engine->update_source(instance);
903         }
904 }
905
906 void ast_rtp_instance_change_source(struct ast_rtp_instance *instance)
907 {
908         if (instance->engine->change_source) {
909                 instance->engine->change_source(instance);
910         }
911 }
912
913 int ast_rtp_instance_set_qos(struct ast_rtp_instance *instance, int tos, int cos, const char *desc)
914 {
915         return instance->engine->qos ? instance->engine->qos(instance, tos, cos, desc) : -1;
916 }
917
918 void ast_rtp_instance_stop(struct ast_rtp_instance *instance)
919 {
920         if (instance->engine->stop) {
921                 instance->engine->stop(instance);
922         }
923 }
924
925 int ast_rtp_instance_fd(struct ast_rtp_instance *instance, int rtcp)
926 {
927         return instance->engine->fd ? instance->engine->fd(instance, rtcp) : -1;
928 }
929
930 struct ast_rtp_glue *ast_rtp_instance_get_glue(const char *type)
931 {
932         struct ast_rtp_glue *glue = NULL;
933
934         AST_RWLIST_RDLOCK(&glues);
935
936         AST_RWLIST_TRAVERSE(&glues, glue, entry) {
937                 if (!strcasecmp(glue->type, type)) {
938                         break;
939                 }
940         }
941
942         AST_RWLIST_UNLOCK(&glues);
943
944         return glue;
945 }
946
947 static enum ast_bridge_result local_bridge_loop(struct ast_channel *c0, struct ast_channel *c1, struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1, int timeoutms, int flags, struct ast_frame **fo, struct ast_channel **rc, void *pvt0, void *pvt1)
948 {
949         enum ast_bridge_result res = AST_BRIDGE_FAILED;
950         struct ast_channel *who = NULL, *other = NULL, *cs[3] = { NULL, };
951         struct ast_frame *fr = NULL;
952
953         /* Start locally bridging both instances */
954         if (instance0->engine->local_bridge && instance0->engine->local_bridge(instance0, instance1)) {
955                 ast_debug(1, "Failed to locally bridge %s to %s, backing out.\n", ast_channel_name(c0), ast_channel_name(c1));
956                 ast_channel_unlock(c0);
957                 ast_channel_unlock(c1);
958                 return AST_BRIDGE_FAILED_NOWARN;
959         }
960         if (instance1->engine->local_bridge && instance1->engine->local_bridge(instance1, instance0)) {
961                 ast_debug(1, "Failed to locally bridge %s to %s, backing out.\n", ast_channel_name(c1), ast_channel_name(c0));
962                 if (instance0->engine->local_bridge) {
963                         instance0->engine->local_bridge(instance0, NULL);
964                 }
965                 ast_channel_unlock(c0);
966                 ast_channel_unlock(c1);
967                 return AST_BRIDGE_FAILED_NOWARN;
968         }
969
970         ast_channel_unlock(c0);
971         ast_channel_unlock(c1);
972
973         instance0->bridged = instance1;
974         instance1->bridged = instance0;
975
976         ast_poll_channel_add(c0, c1);
977
978         /* Hop into a loop waiting for a frame from either channel */
979         cs[0] = c0;
980         cs[1] = c1;
981         cs[2] = NULL;
982         for (;;) {
983                 /* If the underlying formats have changed force this bridge to break */
984                 if ((ast_format_cmp(ast_channel_rawreadformat(c0), ast_channel_rawwriteformat(c1)) == AST_FORMAT_CMP_NOT_EQUAL) ||
985                         (ast_format_cmp(ast_channel_rawreadformat(c1), ast_channel_rawwriteformat(c0)) == AST_FORMAT_CMP_NOT_EQUAL)) {
986                         ast_debug(1, "rtp-engine-local-bridge: Oooh, formats changed, backing out\n");
987                         res = AST_BRIDGE_FAILED_NOWARN;
988                         break;
989                 }
990                 /* Check if anything changed */
991                 if ((ast_channel_tech_pvt(c0) != pvt0) ||
992                     (ast_channel_tech_pvt(c1) != pvt1) ||
993                     (ast_channel_masq(c0) || ast_channel_masqr(c0) || ast_channel_masq(c1) || ast_channel_masqr(c1)) ||
994                     (ast_channel_monitor(c0) || ast_channel_audiohooks(c0) || ast_channel_monitor(c1) || ast_channel_audiohooks(c1)) ||
995                     (!ast_framehook_list_is_empty(ast_channel_framehooks(c0)) || !ast_framehook_list_is_empty(ast_channel_framehooks(c1)))) {
996                         ast_debug(1, "rtp-engine-local-bridge: Oooh, something is weird, backing out\n");
997                         /* If a masquerade needs to happen we have to try to read in a frame so that it actually happens. Without this we risk being called again and going into a loop */
998                         if ((ast_channel_masq(c0) || ast_channel_masqr(c0)) && (fr = ast_read(c0))) {
999                                 ast_frfree(fr);
1000                         }
1001                         if ((ast_channel_masq(c1) || ast_channel_masqr(c1)) && (fr = ast_read(c1))) {
1002                                 ast_frfree(fr);
1003                         }
1004                         res = AST_BRIDGE_RETRY;
1005                         break;
1006                 }
1007                 /* Wait on a channel to feed us a frame */
1008                 if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
1009                         if (!timeoutms) {
1010                                 res = AST_BRIDGE_RETRY;
1011                                 break;
1012                         }
1013                         ast_debug(2, "rtp-engine-local-bridge: Ooh, empty read...\n");
1014                         if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
1015                                 break;
1016                         }
1017                         continue;
1018                 }
1019                 /* Read in frame from channel */
1020                 fr = ast_read(who);
1021                 other = (who == c0) ? c1 : c0;
1022                 /* Depending on the frame we may need to break out of our bridge */
1023                 if (!fr || ((fr->frametype == AST_FRAME_DTMF_BEGIN || fr->frametype == AST_FRAME_DTMF_END) &&
1024                             ((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) |
1025                             ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)))) {
1026                         /* Record received frame and who */
1027                         *fo = fr;
1028                         *rc = who;
1029                         ast_debug(1, "rtp-engine-local-bridge: Ooh, got a %s\n", fr ? "digit" : "hangup");
1030                         res = AST_BRIDGE_COMPLETE;
1031                         break;
1032                 } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1033                         if ((fr->subclass.integer == AST_CONTROL_HOLD) ||
1034                             (fr->subclass.integer == AST_CONTROL_UNHOLD) ||
1035                             (fr->subclass.integer == AST_CONTROL_VIDUPDATE) ||
1036                             (fr->subclass.integer == AST_CONTROL_SRCUPDATE) ||
1037                             (fr->subclass.integer == AST_CONTROL_T38_PARAMETERS) ||
1038                             (fr->subclass.integer == AST_CONTROL_UPDATE_RTP_PEER)) {
1039                                 /* If we are going on hold, then break callback mode and P2P bridging */
1040                                 if (fr->subclass.integer == AST_CONTROL_HOLD) {
1041                                         if (instance0->engine->local_bridge) {
1042                                                 instance0->engine->local_bridge(instance0, NULL);
1043                                         }
1044                                         if (instance1->engine->local_bridge) {
1045                                                 instance1->engine->local_bridge(instance1, NULL);
1046                                         }
1047                                         instance0->bridged = NULL;
1048                                         instance1->bridged = NULL;
1049                                 } else if (fr->subclass.integer == AST_CONTROL_UNHOLD) {
1050                                         if (instance0->engine->local_bridge) {
1051                                                 instance0->engine->local_bridge(instance0, instance1);
1052                                         }
1053                                         if (instance1->engine->local_bridge) {
1054                                                 instance1->engine->local_bridge(instance1, instance0);
1055                                         }
1056                                         instance0->bridged = instance1;
1057                                         instance1->bridged = instance0;
1058                                 }
1059                                 /* Since UPDATE_BRIDGE_PEER is only used by the bridging code, don't forward it */
1060                                 if (fr->subclass.integer != AST_CONTROL_UPDATE_RTP_PEER) {
1061                                         ast_indicate_data(other, fr->subclass.integer, fr->data.ptr, fr->datalen);
1062                                 }
1063                                 ast_frfree(fr);
1064                         } else if (fr->subclass.integer == AST_CONTROL_CONNECTED_LINE) {
1065                                 if (ast_channel_connected_line_sub(who, other, fr, 1) &&
1066                                         ast_channel_connected_line_macro(who, other, fr, other == c0, 1)) {
1067                                         ast_indicate_data(other, fr->subclass.integer, fr->data.ptr, fr->datalen);
1068                                 }
1069                                 ast_frfree(fr);
1070                         } else if (fr->subclass.integer == AST_CONTROL_REDIRECTING) {
1071                                 if (ast_channel_redirecting_sub(who, other, fr, 1) &&
1072                                         ast_channel_redirecting_macro(who, other, fr, other == c0, 1)) {
1073                                         ast_indicate_data(other, fr->subclass.integer, fr->data.ptr, fr->datalen);
1074                                 }
1075                                 ast_frfree(fr);
1076                         } else if (fr->subclass.integer == AST_CONTROL_PVT_CAUSE_CODE) {
1077                                 ast_channel_hangupcause_hash_set(other, fr->data.ptr, fr->datalen);
1078                                 ast_frfree(fr);
1079                         } else {
1080                                 *fo = fr;
1081                                 *rc = who;
1082                                 ast_debug(1, "rtp-engine-local-bridge: Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass.integer, ast_channel_name(who));
1083                                 res = AST_BRIDGE_COMPLETE;
1084                                 break;
1085                         }
1086                 } else {
1087                         if ((fr->frametype == AST_FRAME_DTMF_BEGIN) ||
1088                             (fr->frametype == AST_FRAME_DTMF_END) ||
1089                             (fr->frametype == AST_FRAME_VOICE) ||
1090                             (fr->frametype == AST_FRAME_VIDEO) ||
1091                             (fr->frametype == AST_FRAME_IMAGE) ||
1092                             (fr->frametype == AST_FRAME_HTML) ||
1093                             (fr->frametype == AST_FRAME_MODEM) ||
1094                             (fr->frametype == AST_FRAME_TEXT)) {
1095                                 ast_write(other, fr);
1096                         }
1097
1098                         ast_frfree(fr);
1099                 }
1100                 /* Swap priority */
1101                 cs[2] = cs[0];
1102                 cs[0] = cs[1];
1103                 cs[1] = cs[2];
1104         }
1105
1106         /* Stop locally bridging both instances */
1107         if (instance0->engine->local_bridge) {
1108                 instance0->engine->local_bridge(instance0, NULL);
1109         }
1110         if (instance1->engine->local_bridge) {
1111                 instance1->engine->local_bridge(instance1, NULL);
1112         }
1113
1114         instance0->bridged = NULL;
1115         instance1->bridged = NULL;
1116
1117         ast_poll_channel_del(c0, c1);
1118
1119         return res;
1120 }
1121
1122 static enum ast_bridge_result remote_bridge_loop(struct ast_channel *c0,
1123         struct ast_channel *c1,
1124         struct ast_rtp_instance *instance0,
1125         struct ast_rtp_instance *instance1,
1126         struct ast_rtp_instance *vinstance0,
1127         struct ast_rtp_instance *vinstance1,
1128         struct ast_rtp_instance *tinstance0,
1129         struct ast_rtp_instance *tinstance1,
1130         struct ast_rtp_glue *glue0,
1131         struct ast_rtp_glue *glue1,
1132         struct ast_format_cap *cap0,
1133         struct ast_format_cap *cap1,
1134         int timeoutms,
1135         int flags,
1136         struct ast_frame **fo,
1137         struct ast_channel **rc,
1138         void *pvt0,
1139         void *pvt1)
1140 {
1141         enum ast_bridge_result res = AST_BRIDGE_FAILED;
1142         struct ast_channel *who = NULL, *other = NULL, *cs[3] = { NULL, };
1143         struct ast_format_cap *oldcap0 = ast_format_cap_dup(cap0);
1144         struct ast_format_cap *oldcap1 = ast_format_cap_dup(cap1);
1145         struct ast_sockaddr ac1 = {{0,}}, vac1 = {{0,}}, tac1 = {{0,}}, ac0 = {{0,}}, vac0 = {{0,}}, tac0 = {{0,}};
1146         struct ast_sockaddr t1 = {{0,}}, vt1 = {{0,}}, tt1 = {{0,}}, t0 = {{0,}}, vt0 = {{0,}}, tt0 = {{0,}};
1147         struct ast_frame *fr = NULL;
1148
1149         if (!oldcap0 || !oldcap1) {
1150                 ast_channel_unlock(c0);
1151                 ast_channel_unlock(c1);
1152                 goto remote_bridge_cleanup;
1153         }
1154         /* Test the first channel */
1155         if (!(glue0->update_peer(c0, instance1, vinstance1, tinstance1, cap1, 0))) {
1156                 ast_rtp_instance_get_remote_address(instance1, &ac1);
1157                 if (vinstance1) {
1158                         ast_rtp_instance_get_remote_address(vinstance1, &vac1);
1159                 }
1160                 if (tinstance1) {
1161                         ast_rtp_instance_get_remote_address(tinstance1, &tac1);
1162                 }
1163         } else {
1164                 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", ast_channel_name(c0), ast_channel_name(c1));
1165         }
1166
1167         /* Test the second channel */
1168         if (!(glue1->update_peer(c1, instance0, vinstance0, tinstance0, cap0, 0))) {
1169                 ast_rtp_instance_get_remote_address(instance0, &ac0);
1170                 if (vinstance0) {
1171                         ast_rtp_instance_get_remote_address(instance0, &vac0);
1172                 }
1173                 if (tinstance0) {
1174                         ast_rtp_instance_get_remote_address(instance0, &tac0);
1175                 }
1176         } else {
1177                 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", ast_channel_name(c1), ast_channel_name(c0));
1178         }
1179
1180         ast_channel_unlock(c0);
1181         ast_channel_unlock(c1);
1182
1183         instance0->bridged = instance1;
1184         instance1->bridged = instance0;
1185
1186         ast_poll_channel_add(c0, c1);
1187
1188         /* Go into a loop handling any stray frames that may come in */
1189         cs[0] = c0;
1190         cs[1] = c1;
1191         cs[2] = NULL;
1192         for (;;) {
1193                 /* Check if anything changed */
1194                 if ((ast_channel_tech_pvt(c0) != pvt0) ||
1195                     (ast_channel_tech_pvt(c1) != pvt1) ||
1196                     (ast_channel_masq(c0) || ast_channel_masqr(c0) || ast_channel_masq(c1) || ast_channel_masqr(c1)) ||
1197                     (ast_channel_monitor(c0) || ast_channel_audiohooks(c0) || ast_channel_monitor(c1) || ast_channel_audiohooks(c1)) ||
1198                     (!ast_framehook_list_is_empty(ast_channel_framehooks(c0)) || !ast_framehook_list_is_empty(ast_channel_framehooks(c1)))) {
1199                         ast_debug(1, "Oooh, something is weird, backing out\n");
1200                         res = AST_BRIDGE_RETRY;
1201                         break;
1202                 }
1203
1204                 /* Check if they have changed their address */
1205                 ast_rtp_instance_get_remote_address(instance1, &t1);
1206                 if (vinstance1) {
1207                         ast_rtp_instance_get_remote_address(vinstance1, &vt1);
1208                 }
1209                 if (tinstance1) {
1210                         ast_rtp_instance_get_remote_address(tinstance1, &tt1);
1211                 }
1212                 if (glue1->get_codec) {
1213                         ast_format_cap_remove_all(cap1);
1214                         glue1->get_codec(c1, cap1);
1215                 }
1216
1217                 ast_rtp_instance_get_remote_address(instance0, &t0);
1218                 if (vinstance0) {
1219                         ast_rtp_instance_get_remote_address(vinstance0, &vt0);
1220                 }
1221                 if (tinstance0) {
1222                         ast_rtp_instance_get_remote_address(tinstance0, &tt0);
1223                 }
1224                 if (glue0->get_codec) {
1225                         ast_format_cap_remove_all(cap0);
1226                         glue0->get_codec(c0, cap0);
1227                 }
1228
1229                 if ((ast_sockaddr_cmp(&t1, &ac1)) ||
1230                     (vinstance1 && ast_sockaddr_cmp(&vt1, &vac1)) ||
1231                     (tinstance1 && ast_sockaddr_cmp(&tt1, &tac1)) ||
1232                     (!ast_format_cap_identical(cap1, oldcap1))) {
1233                         char tmp_buf[512] = { 0, };
1234                         ast_debug(1, "Oooh, '%s' changed end address to %s (format %s)\n",
1235                                   ast_channel_name(c1), ast_sockaddr_stringify(&t1),
1236                                   ast_getformatname_multiple(tmp_buf, sizeof(tmp_buf), cap1));
1237                         ast_debug(1, "Oooh, '%s' changed end vaddress to %s (format %s)\n",
1238                                   ast_channel_name(c1), ast_sockaddr_stringify(&vt1),
1239                                   ast_getformatname_multiple(tmp_buf, sizeof(tmp_buf), cap1));
1240                         ast_debug(1, "Oooh, '%s' changed end taddress to %s (format %s)\n",
1241                                   ast_channel_name(c1), ast_sockaddr_stringify(&tt1),
1242                                   ast_getformatname_multiple(tmp_buf, sizeof(tmp_buf), cap1));
1243                         ast_debug(1, "Oooh, '%s' was %s/(format %s)\n",
1244                                   ast_channel_name(c1), ast_sockaddr_stringify(&ac1),
1245                                   ast_getformatname_multiple(tmp_buf, sizeof(tmp_buf), oldcap1));
1246                         ast_debug(1, "Oooh, '%s' was %s/(format %s)\n",
1247                                   ast_channel_name(c1), ast_sockaddr_stringify(&vac1),
1248                                   ast_getformatname_multiple(tmp_buf, sizeof(tmp_buf), oldcap1));
1249                         ast_debug(1, "Oooh, '%s' was %s/(format %s)\n",
1250                                   ast_channel_name(c1), ast_sockaddr_stringify(&tac1),
1251                                   ast_getformatname_multiple(tmp_buf, sizeof(tmp_buf), oldcap1));
1252                         if (glue0->update_peer(c0,
1253                                                ast_sockaddr_isnull(&t1)  ? NULL : instance1,
1254                                                ast_sockaddr_isnull(&vt1) ? NULL : vinstance1,
1255                                                ast_sockaddr_isnull(&tt1) ? NULL : tinstance1,
1256                                                cap1, 0)) {
1257                                 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", ast_channel_name(c0), ast_channel_name(c1));
1258                         }
1259                         ast_sockaddr_copy(&ac1, &t1);
1260                         ast_sockaddr_copy(&vac1, &vt1);
1261                         ast_sockaddr_copy(&tac1, &tt1);
1262                         ast_format_cap_copy(oldcap1, cap1);
1263                 }
1264                 if ((ast_sockaddr_cmp(&t0, &ac0)) ||
1265                     (vinstance0 && ast_sockaddr_cmp(&vt0, &vac0)) ||
1266                     (tinstance0 && ast_sockaddr_cmp(&tt0, &tac0)) ||
1267                     (!ast_format_cap_identical(cap0, oldcap0))) {
1268                         char tmp_buf[512] = { 0, };
1269                         ast_debug(1, "Oooh, '%s' changed end address to %s (format %s)\n",
1270                                   ast_channel_name(c0), ast_sockaddr_stringify(&t0),
1271                                   ast_getformatname_multiple(tmp_buf, sizeof(tmp_buf), cap0));
1272                         ast_debug(1, "Oooh, '%s' was %s/(format %s)\n",
1273                                   ast_channel_name(c0), ast_sockaddr_stringify(&ac0),
1274                                   ast_getformatname_multiple(tmp_buf, sizeof(tmp_buf), oldcap0));
1275                         if (glue1->update_peer(c1, t0.len ? instance0 : NULL,
1276                                                 vt0.len ? vinstance0 : NULL,
1277                                                 tt0.len ? tinstance0 : NULL,
1278                                                 cap0, 0)) {
1279                                 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", ast_channel_name(c1), ast_channel_name(c0));
1280                         }
1281                         ast_sockaddr_copy(&ac0, &t0);
1282                         ast_sockaddr_copy(&vac0, &vt0);
1283                         ast_sockaddr_copy(&tac0, &tt0);
1284                         ast_format_cap_copy(oldcap0, cap0);
1285                 }
1286
1287                 /* Wait for frame to come in on the channels */
1288                 if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
1289                         if (!timeoutms) {
1290                                 res = AST_BRIDGE_RETRY;
1291                                 break;
1292                         }
1293                         ast_debug(1, "Ooh, empty read...\n");
1294                         if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
1295                                 break;
1296                         }
1297                         continue;
1298                 }
1299                 fr = ast_read(who);
1300                 other = (who == c0) ? c1 : c0;
1301                 if (!fr || ((fr->frametype == AST_FRAME_DTMF_BEGIN || fr->frametype == AST_FRAME_DTMF_END) &&
1302                             (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
1303                              ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
1304                         /* Break out of bridge */
1305                         *fo = fr;
1306                         *rc = who;
1307                         ast_debug(1, "Oooh, got a %s\n", fr ? "digit" : "hangup");
1308                         res = AST_BRIDGE_COMPLETE;
1309                         break;
1310                 } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1311                         if ((fr->subclass.integer == AST_CONTROL_HOLD) ||
1312                             (fr->subclass.integer == AST_CONTROL_UNHOLD) ||
1313                             (fr->subclass.integer == AST_CONTROL_VIDUPDATE) ||
1314                             (fr->subclass.integer == AST_CONTROL_SRCUPDATE) ||
1315                             (fr->subclass.integer == AST_CONTROL_T38_PARAMETERS) ||
1316                                 (fr->subclass.integer == AST_CONTROL_UPDATE_RTP_PEER)) {
1317                                 if (fr->subclass.integer == AST_CONTROL_HOLD) {
1318                                         /* If we someone went on hold we want the other side to reinvite back to us */
1319                                         if (who == c0) {
1320                                                 glue1->update_peer(c1, NULL, NULL, NULL, 0, 0);
1321                                         } else {
1322                                                 glue0->update_peer(c0, NULL, NULL, NULL, 0, 0);
1323                                         }
1324                                 } else if (fr->subclass.integer == AST_CONTROL_UNHOLD ||
1325                                         fr->subclass.integer == AST_CONTROL_UPDATE_RTP_PEER) {
1326                                         /* If they went off hold they should go back to being direct, or if we have
1327                                          * been told to force a peer update, go ahead and do it. */
1328                                         if (who == c0) {
1329                                                 glue1->update_peer(c1, instance0, vinstance0, tinstance0, cap0, 0);
1330                                         } else {
1331                                                 glue0->update_peer(c0, instance1, vinstance1, tinstance1, cap1, 0);
1332                                         }
1333                                 }
1334                                 /* Update local address information */
1335                                 ast_rtp_instance_get_remote_address(instance0, &t0);
1336                                 ast_sockaddr_copy(&ac0, &t0);
1337                                 ast_rtp_instance_get_remote_address(instance1, &t1);
1338                                 ast_sockaddr_copy(&ac1, &t1);
1339                                 /* Update codec information */
1340                                 if (glue0->get_codec && ast_channel_tech_pvt(c0)) {
1341                                         ast_format_cap_remove_all(cap0);
1342                                         ast_format_cap_remove_all(oldcap0);
1343                                         glue0->get_codec(c0, cap0);
1344                                         ast_format_cap_append(oldcap0, cap0);
1345
1346                                 }
1347                                 if (glue1->get_codec && ast_channel_tech_pvt(c1)) {
1348                                         ast_format_cap_remove_all(cap1);
1349                                         ast_format_cap_remove_all(oldcap1);
1350                                         glue1->get_codec(c1, cap1);
1351                                         ast_format_cap_append(oldcap1, cap1);
1352                                 }
1353                                 /* Since UPDATE_BRIDGE_PEER is only used by the bridging code, don't forward it */
1354                                 if (fr->subclass.integer != AST_CONTROL_UPDATE_RTP_PEER) {
1355                                         ast_indicate_data(other, fr->subclass.integer, fr->data.ptr, fr->datalen);
1356                                 }
1357                                 ast_frfree(fr);
1358                         } else if (fr->subclass.integer == AST_CONTROL_CONNECTED_LINE) {
1359                                 if (ast_channel_connected_line_sub(who, other, fr, 1) &&
1360                                         ast_channel_connected_line_macro(who, other, fr, other == c0, 1)) {
1361                                         ast_indicate_data(other, fr->subclass.integer, fr->data.ptr, fr->datalen);
1362                                 }
1363                                 ast_frfree(fr);
1364                         } else if (fr->subclass.integer == AST_CONTROL_REDIRECTING) {
1365                                 if (ast_channel_redirecting_sub(who, other, fr, 1) &&
1366                                         ast_channel_redirecting_macro(who, other, fr, other == c0, 1)) {
1367                                         ast_indicate_data(other, fr->subclass.integer, fr->data.ptr, fr->datalen);
1368                                 }
1369                                 ast_frfree(fr);
1370                         } else if (fr->subclass.integer == AST_CONTROL_PVT_CAUSE_CODE) {
1371                                 ast_channel_hangupcause_hash_set(other, fr->data.ptr, fr->datalen);
1372                                 ast_frfree(fr);
1373                         } else {
1374                                 *fo = fr;
1375                                 *rc = who;
1376                                 ast_debug(1, "Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass.integer, ast_channel_name(who));
1377                                 res = AST_BRIDGE_COMPLETE;
1378                                 goto remote_bridge_cleanup;
1379                         }
1380                 } else {
1381                         if ((fr->frametype == AST_FRAME_DTMF_BEGIN) ||
1382                             (fr->frametype == AST_FRAME_DTMF_END) ||
1383                             (fr->frametype == AST_FRAME_VOICE) ||
1384                             (fr->frametype == AST_FRAME_VIDEO) ||
1385                             (fr->frametype == AST_FRAME_IMAGE) ||
1386                             (fr->frametype == AST_FRAME_HTML) ||
1387                             (fr->frametype == AST_FRAME_MODEM) ||
1388                             (fr->frametype == AST_FRAME_TEXT)) {
1389                                 ast_write(other, fr);
1390                         }
1391                         ast_frfree(fr);
1392                 }
1393                 /* Swap priority */
1394                 cs[2] = cs[0];
1395                 cs[0] = cs[1];
1396                 cs[1] = cs[2];
1397         }
1398
1399         if (ast_test_flag(ast_channel_flags(c0), AST_FLAG_ZOMBIE)) {
1400                 ast_debug(1, "Channel '%s' Zombie cleardown from bridge\n", ast_channel_name(c0));
1401         } else if (ast_channel_tech_pvt(c0) != pvt0) {
1402                 ast_debug(1, "Channel c0->'%s' pvt changed, in bridge with c1->'%s'\n", ast_channel_name(c0), ast_channel_name(c1));
1403         } else if (glue0 != ast_rtp_instance_get_glue(ast_channel_tech(c0)->type)) {
1404                 ast_debug(1, "Channel c0->'%s' technology changed, in bridge with c1->'%s'\n", ast_channel_name(c0), ast_channel_name(c1));
1405         } else if (glue0->update_peer(c0, NULL, NULL, NULL, 0, 0)) {
1406                 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", ast_channel_name(c0));
1407         }
1408         if (ast_test_flag(ast_channel_flags(c1), AST_FLAG_ZOMBIE)) {
1409                 ast_debug(1, "Channel '%s' Zombie cleardown from bridge\n", ast_channel_name(c1));
1410         } else if (ast_channel_tech_pvt(c1) != pvt1) {
1411                 ast_debug(1, "Channel c1->'%s' pvt changed, in bridge with c0->'%s'\n", ast_channel_name(c1), ast_channel_name(c0));
1412         } else if (glue1 != ast_rtp_instance_get_glue(ast_channel_tech(c1)->type)) {
1413                 ast_debug(1, "Channel c1->'%s' technology changed, in bridge with c0->'%s'\n", ast_channel_name(c1), ast_channel_name(c0));
1414         } else if (glue1->update_peer(c1, NULL, NULL, NULL, 0, 0)) {
1415                 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", ast_channel_name(c1));
1416         }
1417
1418         instance0->bridged = NULL;
1419         instance1->bridged = NULL;
1420
1421         ast_poll_channel_del(c0, c1);
1422
1423 remote_bridge_cleanup:
1424         ast_format_cap_destroy(oldcap0);
1425         ast_format_cap_destroy(oldcap1);
1426
1427         return res;
1428 }
1429
1430 /*!
1431  * \brief Conditionally unref an rtp instance
1432  */
1433 static void unref_instance_cond(struct ast_rtp_instance **instance)
1434 {
1435         if (*instance) {
1436                 ao2_ref(*instance, -1);
1437                 *instance = NULL;
1438         }
1439 }
1440
1441 enum ast_bridge_result ast_rtp_instance_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
1442 {
1443         struct ast_rtp_instance *instance0 = NULL, *instance1 = NULL,
1444                         *vinstance0 = NULL, *vinstance1 = NULL,
1445                         *tinstance0 = NULL, *tinstance1 = NULL;
1446         struct ast_rtp_glue *glue0, *glue1;
1447         struct ast_sockaddr addr1 = { {0, }, }, addr2 = { {0, }, };
1448         enum ast_rtp_glue_result audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID, video_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1449         enum ast_rtp_glue_result audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID, video_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1450         enum ast_bridge_result res = AST_BRIDGE_FAILED;
1451         enum ast_rtp_dtmf_mode dmode;
1452         struct ast_format_cap *cap0 = ast_format_cap_alloc_nolock();
1453         struct ast_format_cap *cap1 = ast_format_cap_alloc_nolock();
1454         int unlock_chans = 1;
1455
1456         if (!cap0 || !cap1) {
1457                 unlock_chans = 0;
1458                 goto done;
1459         }
1460
1461         /* Lock both channels so we can look for the glue that binds them together */
1462         ast_channel_lock(c0);
1463         while (ast_channel_trylock(c1)) {
1464                 ast_channel_unlock(c0);
1465                 usleep(1);
1466                 ast_channel_lock(c0);
1467         }
1468
1469         /* Ensure neither channel got hungup during lock avoidance */
1470         if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
1471                 ast_log(LOG_WARNING, "Got hangup while attempting to bridge '%s' and '%s'\n", ast_channel_name(c0), ast_channel_name(c1));
1472                 goto done;
1473         }
1474
1475         /* Grab glue that binds each channel to something using the RTP engine */
1476         if (!(glue0 = ast_rtp_instance_get_glue(ast_channel_tech(c0)->type)) || !(glue1 = ast_rtp_instance_get_glue(ast_channel_tech(c1)->type))) {
1477                 ast_debug(1, "Can't find native functions for channel '%s'\n", glue0 ? ast_channel_name(c1) : ast_channel_name(c0));
1478                 goto done;
1479         }
1480
1481         audio_glue0_res = glue0->get_rtp_info(c0, &instance0);
1482         video_glue0_res = glue0->get_vrtp_info ? glue0->get_vrtp_info(c0, &vinstance0) : AST_RTP_GLUE_RESULT_FORBID;
1483
1484         audio_glue1_res = glue1->get_rtp_info(c1, &instance1);
1485         video_glue1_res = glue1->get_vrtp_info ? glue1->get_vrtp_info(c1, &vinstance1) : AST_RTP_GLUE_RESULT_FORBID;
1486
1487         /* If the channels are of the same technology, they might have limitations on remote bridging */
1488         if (ast_channel_tech(c0) == ast_channel_tech(c1)) {
1489                 if (audio_glue0_res == audio_glue1_res && audio_glue1_res == AST_RTP_GLUE_RESULT_REMOTE) {
1490                         if (glue0->allow_rtp_remote && !(glue0->allow_rtp_remote(c0, c1))) {
1491                                 /* If the allow_rtp_remote indicates that remote isn't allowed, revert to local bridge */
1492                                 audio_glue0_res = audio_glue1_res = AST_RTP_GLUE_RESULT_LOCAL;
1493                         }
1494                 }
1495                 if (video_glue0_res == video_glue1_res && video_glue1_res == AST_RTP_GLUE_RESULT_REMOTE) {
1496                         if (glue0->allow_vrtp_remote && !(glue0->allow_vrtp_remote(c0, c1))) {
1497                                 /* if the allow_vrtp_remote indicates that remote isn't allowed, revert to local bridge */
1498                                 video_glue0_res = video_glue1_res = AST_RTP_GLUE_RESULT_LOCAL;
1499                         }
1500                 }
1501         }
1502
1503         /* If we are carrying video, and both sides are not going to remotely bridge... fail the native bridge */
1504         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)) {
1505                 audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1506         }
1507         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)) {
1508                 audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1509         }
1510
1511         /* If any sort of bridge is forbidden just completely bail out and go back to generic bridging */
1512         if (audio_glue0_res == AST_RTP_GLUE_RESULT_FORBID || audio_glue1_res == AST_RTP_GLUE_RESULT_FORBID) {
1513                 res = AST_BRIDGE_FAILED_NOWARN;
1514                 goto done;
1515         }
1516
1517
1518         /* If address families differ, force a local bridge */
1519         ast_rtp_instance_get_remote_address(instance0, &addr1);
1520         ast_rtp_instance_get_remote_address(instance1, &addr2);
1521
1522         if (addr1.ss.ss_family != addr2.ss.ss_family ||
1523            (ast_sockaddr_is_ipv4_mapped(&addr1) != ast_sockaddr_is_ipv4_mapped(&addr2))) {
1524                 audio_glue0_res = AST_RTP_GLUE_RESULT_LOCAL;
1525                 audio_glue1_res = AST_RTP_GLUE_RESULT_LOCAL;
1526         }
1527
1528         /* If we need to get DTMF see if we can do it outside of the RTP stream itself */
1529         dmode = ast_rtp_instance_dtmf_mode_get(instance0);
1530         if ((flags & AST_BRIDGE_DTMF_CHANNEL_0) && dmode) {
1531                 res = AST_BRIDGE_FAILED_NOWARN;
1532                 goto done;
1533         }
1534         dmode = ast_rtp_instance_dtmf_mode_get(instance1);
1535         if ((flags & AST_BRIDGE_DTMF_CHANNEL_1) && dmode) {
1536                 res = AST_BRIDGE_FAILED_NOWARN;
1537                 goto done;
1538         }
1539
1540         /* If we have gotten to a local bridge make sure that both sides have the same local bridge callback and that they are DTMF compatible */
1541         if ((audio_glue0_res == AST_RTP_GLUE_RESULT_LOCAL || audio_glue1_res == AST_RTP_GLUE_RESULT_LOCAL) && ((instance0->engine->local_bridge != instance1->engine->local_bridge) || (instance0->engine->dtmf_compatible && !instance0->engine->dtmf_compatible(c0, instance0, c1, instance1)))) {
1542                 res = AST_BRIDGE_FAILED_NOWARN;
1543                 goto done;
1544         }
1545
1546         /* Make sure that codecs match */
1547         if (glue0->get_codec){
1548                 glue0->get_codec(c0, cap0);
1549         }
1550         if (glue1->get_codec) {
1551                 glue1->get_codec(c1, cap1);
1552         }
1553         if (!ast_format_cap_is_empty(cap0) && !ast_format_cap_is_empty(cap1) && !ast_format_cap_has_joint(cap0, cap1)) {
1554                 char tmp0[256] = { 0, };
1555                 char tmp1[256] = { 0, };
1556                 ast_debug(1, "Channel codec0 = %s is not codec1 = %s, cannot native bridge in RTP.\n",
1557                         ast_getformatname_multiple(tmp0, sizeof(tmp0), cap0),
1558                         ast_getformatname_multiple(tmp1, sizeof(tmp1), cap1));
1559                 res = AST_BRIDGE_FAILED_NOWARN;
1560                 goto done;
1561         }
1562
1563         instance0->glue = glue0;
1564         instance1->glue = glue1;
1565         instance0->chan = c0;
1566         instance1->chan = c1;
1567
1568         /* Depending on the end result for bridging either do a local bridge or remote bridge */
1569         if (audio_glue0_res == AST_RTP_GLUE_RESULT_LOCAL || audio_glue1_res == AST_RTP_GLUE_RESULT_LOCAL) {
1570                 ast_verb(3, "Locally bridging %s and %s\n", ast_channel_name(c0), ast_channel_name(c1));
1571                 res = local_bridge_loop(c0, c1, instance0, instance1, timeoutms, flags, fo, rc, ast_channel_tech_pvt(c0), ast_channel_tech_pvt(c1));
1572         } else {
1573                 ast_verb(3, "Remotely bridging %s and %s\n", ast_channel_name(c0), ast_channel_name(c1));
1574                 res = remote_bridge_loop(c0, c1, instance0, instance1, vinstance0, vinstance1,
1575                                 tinstance0, tinstance1, glue0, glue1, cap0, cap1, timeoutms, flags,
1576                                 fo, rc, ast_channel_tech_pvt(c0), ast_channel_tech_pvt(c1));
1577         }
1578
1579         instance0->glue = NULL;
1580         instance1->glue = NULL;
1581         instance0->chan = NULL;
1582         instance1->chan = NULL;
1583
1584         unlock_chans = 0;
1585
1586 done:
1587         if (unlock_chans) {
1588                 ast_channel_unlock(c0);
1589                 ast_channel_unlock(c1);
1590         }
1591         ast_format_cap_destroy(cap1);
1592         ast_format_cap_destroy(cap0);
1593
1594         unref_instance_cond(&instance0);
1595         unref_instance_cond(&instance1);
1596         unref_instance_cond(&vinstance0);
1597         unref_instance_cond(&vinstance1);
1598         unref_instance_cond(&tinstance0);
1599         unref_instance_cond(&tinstance1);
1600
1601         return res;
1602 }
1603
1604 struct ast_rtp_instance *ast_rtp_instance_get_bridged(struct ast_rtp_instance *instance)
1605 {
1606         return instance->bridged;
1607 }
1608
1609 void ast_rtp_instance_early_bridge_make_compatible(struct ast_channel *c0, struct ast_channel *c1)
1610 {
1611         struct ast_rtp_instance *instance0 = NULL, *instance1 = NULL,
1612                 *vinstance0 = NULL, *vinstance1 = NULL,
1613                 *tinstance0 = NULL, *tinstance1 = NULL;
1614         struct ast_rtp_glue *glue0, *glue1;
1615         enum ast_rtp_glue_result audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID, video_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1616         enum ast_rtp_glue_result audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID, video_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1617         struct ast_format_cap *cap0 = ast_format_cap_alloc_nolock();
1618         struct ast_format_cap *cap1 = ast_format_cap_alloc_nolock();
1619
1620         /* Lock both channels so we can look for the glue that binds them together */
1621         ast_channel_lock_both(c0, c1);
1622
1623         if (!cap1 || !cap0) {
1624                 goto done;
1625         }
1626
1627         /* Grab glue that binds each channel to something using the RTP engine */
1628         if (!(glue0 = ast_rtp_instance_get_glue(ast_channel_tech(c0)->type)) || !(glue1 = ast_rtp_instance_get_glue(ast_channel_tech(c1)->type))) {
1629                 ast_debug(1, "Can't find native functions for channel '%s'\n", glue0 ? ast_channel_name(c1) : ast_channel_name(c0));
1630                 goto done;
1631         }
1632
1633         audio_glue0_res = glue0->get_rtp_info(c0, &instance0);
1634         video_glue0_res = glue0->get_vrtp_info ? glue0->get_vrtp_info(c0, &vinstance0) : AST_RTP_GLUE_RESULT_FORBID;
1635
1636         audio_glue1_res = glue1->get_rtp_info(c1, &instance1);
1637         video_glue1_res = glue1->get_vrtp_info ? glue1->get_vrtp_info(c1, &vinstance1) : AST_RTP_GLUE_RESULT_FORBID;
1638
1639         /* If we are carrying video, and both sides are not going to remotely bridge... fail the native bridge */
1640         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)) {
1641                 audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1642         }
1643         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)) {
1644                 audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1645         }
1646         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) {
1647                 glue0->get_codec(c0, cap0);
1648         }
1649         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) {
1650                 glue1->get_codec(c1, cap1);
1651         }
1652
1653         /* If any sort of bridge is forbidden just completely bail out and go back to generic bridging */
1654         if (audio_glue0_res != AST_RTP_GLUE_RESULT_REMOTE || audio_glue1_res != AST_RTP_GLUE_RESULT_REMOTE) {
1655                 goto done;
1656         }
1657
1658         /* Make sure we have matching codecs */
1659         if (!ast_format_cap_has_joint(cap0, cap1)) {
1660                 goto done;
1661         }
1662
1663         ast_rtp_codecs_payloads_copy(&instance0->codecs, &instance1->codecs, instance1);
1664
1665         if (vinstance0 && vinstance1) {
1666                 ast_rtp_codecs_payloads_copy(&vinstance0->codecs, &vinstance1->codecs, vinstance1);
1667         }
1668         if (tinstance0 && tinstance1) {
1669                 ast_rtp_codecs_payloads_copy(&tinstance0->codecs, &tinstance1->codecs, tinstance1);
1670         }
1671
1672         if (glue0->update_peer(c0, instance1, vinstance1, tinstance1, cap1, 0)) {
1673                 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n",
1674                         ast_channel_name(c0), ast_channel_name(c1));
1675         } else {
1676                 ast_debug(1, "Seeded SDP of '%s' with that of '%s'\n",
1677                         ast_channel_name(c0), ast_channel_name(c1));
1678         }
1679
1680 done:
1681         ast_channel_unlock(c0);
1682         ast_channel_unlock(c1);
1683
1684         ast_format_cap_destroy(cap0);
1685         ast_format_cap_destroy(cap1);
1686
1687         unref_instance_cond(&instance0);
1688         unref_instance_cond(&instance1);
1689         unref_instance_cond(&vinstance0);
1690         unref_instance_cond(&vinstance1);
1691         unref_instance_cond(&tinstance0);
1692         unref_instance_cond(&tinstance1);
1693 }
1694
1695 int ast_rtp_instance_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
1696 {
1697         struct ast_rtp_instance *instance0 = NULL, *instance1 = NULL,
1698                         *vinstance0 = NULL, *vinstance1 = NULL,
1699                         *tinstance0 = NULL, *tinstance1 = NULL;
1700         struct ast_rtp_glue *glue0, *glue1;
1701         enum ast_rtp_glue_result audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID, video_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1702         enum ast_rtp_glue_result audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID, video_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1703         struct ast_format_cap *cap0 = ast_format_cap_alloc_nolock();
1704         struct ast_format_cap *cap1 = ast_format_cap_alloc_nolock();
1705         int res = 0;
1706
1707         /* If there is no second channel just immediately bail out, we are of no use in that scenario */
1708         if (!c1) {
1709                 ast_format_cap_destroy(cap0);
1710                 ast_format_cap_destroy(cap1);
1711                 return -1;
1712         }
1713
1714         /* Lock both channels so we can look for the glue that binds them together */
1715         ast_channel_lock(c0);
1716         while (ast_channel_trylock(c1)) {
1717                 ast_channel_unlock(c0);
1718                 usleep(1);
1719                 ast_channel_lock(c0);
1720         }
1721
1722         if (!cap1 || !cap0) {
1723                 goto done;
1724         }
1725
1726         /* Grab glue that binds each channel to something using the RTP engine */
1727         if (!(glue0 = ast_rtp_instance_get_glue(ast_channel_tech(c0)->type)) || !(glue1 = ast_rtp_instance_get_glue(ast_channel_tech(c1)->type))) {
1728                 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", glue0 ? ast_channel_name(c1) : ast_channel_name(c0));
1729                 goto done;
1730         }
1731
1732         audio_glue0_res = glue0->get_rtp_info(c0, &instance0);
1733         video_glue0_res = glue0->get_vrtp_info ? glue0->get_vrtp_info(c0, &vinstance0) : AST_RTP_GLUE_RESULT_FORBID;
1734
1735         audio_glue1_res = glue1->get_rtp_info(c1, &instance1);
1736         video_glue1_res = glue1->get_vrtp_info ? glue1->get_vrtp_info(c1, &vinstance1) : AST_RTP_GLUE_RESULT_FORBID;
1737
1738         /* If we are carrying video, and both sides are not going to remotely bridge... fail the native bridge */
1739         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)) {
1740                 audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1741         }
1742         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)) {
1743                 audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1744         }
1745         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) {
1746                 glue0->get_codec(c0, cap0);
1747         }
1748         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) {
1749                 glue1->get_codec(c1, cap1);
1750         }
1751
1752         /* If any sort of bridge is forbidden just completely bail out and go back to generic bridging */
1753         if (audio_glue0_res != AST_RTP_GLUE_RESULT_REMOTE || audio_glue1_res != AST_RTP_GLUE_RESULT_REMOTE) {
1754                 goto done;
1755         }
1756
1757         /* Make sure we have matching codecs */
1758         if (!ast_format_cap_has_joint(cap0, cap1)) {
1759                 goto done;
1760         }
1761
1762         /* Bridge media early */
1763         if (glue0->update_peer(c0, instance1, vinstance1, tinstance1, cap1, 0)) {
1764                 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", ast_channel_name(c0), c1 ? ast_channel_name(c1) : "<unspecified>");
1765         }
1766
1767         res = 0;
1768
1769 done:
1770         ast_channel_unlock(c0);
1771         ast_channel_unlock(c1);
1772
1773         ast_format_cap_destroy(cap0);
1774         ast_format_cap_destroy(cap1);
1775
1776         unref_instance_cond(&instance0);
1777         unref_instance_cond(&instance1);
1778         unref_instance_cond(&vinstance0);
1779         unref_instance_cond(&vinstance1);
1780         unref_instance_cond(&tinstance0);
1781         unref_instance_cond(&tinstance1);
1782
1783         if (!res) {
1784                 ast_debug(1, "Setting early bridge SDP of '%s' with that of '%s'\n", ast_channel_name(c0), c1 ? ast_channel_name(c1) : "<unspecified>");
1785         }
1786
1787         return res;
1788 }
1789
1790 int ast_rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations)
1791 {
1792         return instance->engine->red_init ? instance->engine->red_init(instance, buffer_time, payloads, generations) : -1;
1793 }
1794
1795 int ast_rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame)
1796 {
1797         return instance->engine->red_buffer ? instance->engine->red_buffer(instance, frame) : -1;
1798 }
1799
1800 int ast_rtp_instance_get_stats(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat)
1801 {
1802         return instance->engine->get_stat ? instance->engine->get_stat(instance, stats, stat) : -1;
1803 }
1804
1805 char *ast_rtp_instance_get_quality(struct ast_rtp_instance *instance, enum ast_rtp_instance_stat_field field, char *buf, size_t size)
1806 {
1807         struct ast_rtp_instance_stats stats = { 0, };
1808         enum ast_rtp_instance_stat stat;
1809
1810         /* Determine what statistics we will need to retrieve based on field passed in */
1811         if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY) {
1812                 stat = AST_RTP_INSTANCE_STAT_ALL;
1813         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER) {
1814                 stat = AST_RTP_INSTANCE_STAT_COMBINED_JITTER;
1815         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS) {
1816                 stat = AST_RTP_INSTANCE_STAT_COMBINED_LOSS;
1817         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT) {
1818                 stat = AST_RTP_INSTANCE_STAT_COMBINED_RTT;
1819         } else {
1820                 return NULL;
1821         }
1822
1823         /* Attempt to actually retrieve the statistics we need to generate the quality string */
1824         if (ast_rtp_instance_get_stats(instance, &stats, stat)) {
1825                 return NULL;
1826         }
1827
1828         /* Now actually fill the buffer with the good information */
1829         if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY) {
1830                 snprintf(buf, size, "ssrc=%i;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f",
1831                          stats.local_ssrc, stats.remote_ssrc, stats.rxploss, stats.txjitter, stats.rxcount, stats.rxjitter, stats.txcount, stats.txploss, stats.rtt);
1832         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER) {
1833                 snprintf(buf, size, "minrxjitter=%f;maxrxjitter=%f;avgrxjitter=%f;stdevrxjitter=%f;reported_minjitter=%f;reported_maxjitter=%f;reported_avgjitter=%f;reported_stdevjitter=%f;",
1834                          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));
1835         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS) {
1836                 snprintf(buf, size, "minrxlost=%f;maxrxlost=%f;avgrxlost=%f;stdevrxlost=%f;reported_minlost=%f;reported_maxlost=%f;reported_avglost=%f;reported_stdevlost=%f;",
1837                          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));
1838         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT) {
1839                 snprintf(buf, size, "minrtt=%f;maxrtt=%f;avgrtt=%f;stdevrtt=%f;", stats.minrtt, stats.maxrtt, stats.normdevrtt, stats.stdevrtt);
1840         }
1841
1842         return buf;
1843 }
1844
1845 void ast_rtp_instance_set_stats_vars(struct ast_channel *chan, struct ast_rtp_instance *instance)
1846 {
1847         char quality_buf[AST_MAX_USER_FIELD], *quality;
1848         struct ast_channel *bridge = ast_bridged_channel(chan);
1849
1850         if ((quality = ast_rtp_instance_get_quality(instance, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
1851                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOS", quality);
1852                 if (bridge) {
1853                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSBRIDGED", quality);
1854                 }
1855         }
1856
1857         if ((quality = ast_rtp_instance_get_quality(instance, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf)))) {
1858                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSJITTER", quality);
1859                 if (bridge) {
1860                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSJITTERBRIDGED", quality);
1861                 }
1862         }
1863
1864         if ((quality = ast_rtp_instance_get_quality(instance, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf)))) {
1865                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSLOSS", quality);
1866                 if (bridge) {
1867                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSLOSSBRIDGED", quality);
1868                 }
1869         }
1870
1871         if ((quality = ast_rtp_instance_get_quality(instance, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf)))) {
1872                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSRTT", quality);
1873                 if (bridge) {
1874                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSRTTBRIDGED", quality);
1875                 }
1876         }
1877 }
1878
1879 int ast_rtp_instance_set_read_format(struct ast_rtp_instance *instance, struct ast_format *format)
1880 {
1881         return instance->engine->set_read_format ? instance->engine->set_read_format(instance, format) : -1;
1882 }
1883
1884 int ast_rtp_instance_set_write_format(struct ast_rtp_instance *instance, struct ast_format *format)
1885 {
1886         return instance->engine->set_write_format ? instance->engine->set_write_format(instance, format) : -1;
1887 }
1888
1889 int ast_rtp_instance_make_compatible(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_channel *peer)
1890 {
1891         struct ast_rtp_glue *glue;
1892         struct ast_rtp_instance *peer_instance = NULL;
1893         int res = -1;
1894
1895         if (!instance->engine->make_compatible) {
1896                 return -1;
1897         }
1898
1899         ast_channel_lock(peer);
1900
1901         if (!(glue = ast_rtp_instance_get_glue(ast_channel_tech(peer)->type))) {
1902                 ast_channel_unlock(peer);
1903                 return -1;
1904         }
1905
1906         glue->get_rtp_info(peer, &peer_instance);
1907
1908         if (!peer_instance || peer_instance->engine != instance->engine) {
1909                 ast_channel_unlock(peer);
1910                 ao2_ref(peer_instance, -1);
1911                 peer_instance = NULL;
1912                 return -1;
1913         }
1914
1915         res = instance->engine->make_compatible(chan, instance, peer, peer_instance);
1916
1917         ast_channel_unlock(peer);
1918
1919         ao2_ref(peer_instance, -1);
1920         peer_instance = NULL;
1921
1922         return res;
1923 }
1924
1925 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)
1926 {
1927         if (instance->engine->available_formats) {
1928                 instance->engine->available_formats(instance, to_endpoint, to_asterisk, result);
1929                 if (!ast_format_cap_is_empty(result)) {
1930                         return;
1931                 }
1932         }
1933
1934         ast_translate_available_formats(to_endpoint, to_asterisk, result);
1935 }
1936
1937 int ast_rtp_instance_activate(struct ast_rtp_instance *instance)
1938 {
1939         return instance->engine->activate ? instance->engine->activate(instance) : 0;
1940 }
1941
1942 void ast_rtp_instance_stun_request(struct ast_rtp_instance *instance,
1943                                    struct ast_sockaddr *suggestion,
1944                                    const char *username)
1945 {
1946         if (instance->engine->stun_request) {
1947                 instance->engine->stun_request(instance, suggestion, username);
1948         }
1949 }
1950
1951 void ast_rtp_instance_set_timeout(struct ast_rtp_instance *instance, int timeout)
1952 {
1953         instance->timeout = timeout;
1954 }
1955
1956 void ast_rtp_instance_set_hold_timeout(struct ast_rtp_instance *instance, int timeout)
1957 {
1958         instance->holdtimeout = timeout;
1959 }
1960
1961 void ast_rtp_instance_set_keepalive(struct ast_rtp_instance *instance, int interval)
1962 {
1963         instance->keepalive = interval;
1964 }
1965
1966 int ast_rtp_instance_get_timeout(struct ast_rtp_instance *instance)
1967 {
1968         return instance->timeout;
1969 }
1970
1971 int ast_rtp_instance_get_hold_timeout(struct ast_rtp_instance *instance)
1972 {
1973         return instance->holdtimeout;
1974 }
1975
1976 int ast_rtp_instance_get_keepalive(struct ast_rtp_instance *instance)
1977 {
1978         return instance->keepalive;
1979 }
1980
1981 struct ast_rtp_engine *ast_rtp_instance_get_engine(struct ast_rtp_instance *instance)
1982 {
1983         return instance->engine;
1984 }
1985
1986 struct ast_rtp_glue *ast_rtp_instance_get_active_glue(struct ast_rtp_instance *instance)
1987 {
1988         return instance->glue;
1989 }
1990
1991 struct ast_channel *ast_rtp_instance_get_chan(struct ast_rtp_instance *instance)
1992 {
1993         return instance->chan;
1994 }
1995
1996 int ast_rtp_engine_register_srtp(struct ast_srtp_res *srtp_res, struct ast_srtp_policy_res *policy_res)
1997 {
1998         if (res_srtp || res_srtp_policy) {
1999                 return -1;
2000         }
2001         if (!srtp_res || !policy_res) {
2002                 return -1;
2003         }
2004
2005         res_srtp = srtp_res;
2006         res_srtp_policy = policy_res;
2007
2008         return 0;
2009 }
2010
2011 void ast_rtp_engine_unregister_srtp(void)
2012 {
2013         res_srtp = NULL;
2014         res_srtp_policy = NULL;
2015 }
2016
2017 int ast_rtp_engine_srtp_is_registered(void)
2018 {
2019         return res_srtp && res_srtp_policy;
2020 }
2021
2022 int ast_rtp_instance_add_srtp_policy(struct ast_rtp_instance *instance, struct ast_srtp_policy *remote_policy, struct ast_srtp_policy *local_policy)
2023 {
2024         int res = 0;
2025
2026         if (!res_srtp) {
2027                 return -1;
2028         }
2029
2030         if (!instance->srtp) {
2031                 res = res_srtp->create(&instance->srtp, instance, remote_policy);
2032         } else {
2033                 res = res_srtp->replace(&instance->srtp, instance, remote_policy);
2034         }
2035         if (!res) {
2036                 res = res_srtp->add_stream(instance->srtp, local_policy);
2037         }
2038
2039         return res;
2040 }
2041
2042 struct ast_srtp *ast_rtp_instance_get_srtp(struct ast_rtp_instance *instance)
2043 {
2044         return instance->srtp;
2045 }
2046
2047 int ast_rtp_instance_sendcng(struct ast_rtp_instance *instance, int level)
2048 {
2049         if (instance->engine->sendcng) {
2050                 return instance->engine->sendcng(instance, level);
2051         }
2052
2053         return -1;
2054 }
2055
2056 struct ast_rtp_engine_ice *ast_rtp_instance_get_ice(struct ast_rtp_instance *instance)
2057 {
2058         return instance->engine->ice;
2059 }
2060
2061 static void set_next_mime_type(const struct ast_format *format, int rtp_code, char *type, char *subtype, unsigned int sample_rate)
2062 {
2063         int x = mime_types_len;
2064         if (ARRAY_LEN(ast_rtp_mime_types) == mime_types_len) {
2065                 return;
2066         }
2067
2068         ast_rwlock_wrlock(&mime_types_lock);
2069         if (format) {
2070                 ast_rtp_mime_types[x].payload_type.asterisk_format = 1;
2071                 ast_format_copy(&ast_rtp_mime_types[x].payload_type.format, format);
2072         } else {
2073                 ast_rtp_mime_types[x].payload_type.rtp_code = rtp_code;
2074         }
2075         ast_rtp_mime_types[x].type = type;
2076         ast_rtp_mime_types[x].subtype = subtype;
2077         ast_rtp_mime_types[x].sample_rate = sample_rate;
2078         mime_types_len++;
2079         ast_rwlock_unlock(&mime_types_lock);
2080 }
2081
2082 static void add_static_payload(int map, const struct ast_format *format, int rtp_code)
2083 {
2084         int x;
2085         ast_rwlock_wrlock(&static_RTP_PT_lock);
2086         if (map < 0) {
2087                 /* find next available dynamic payload slot */
2088                 for (x = 96; x < 127; x++) {
2089                         if (!static_RTP_PT[x].asterisk_format && !static_RTP_PT[x].rtp_code) {
2090                                 map = x;
2091                                 break;
2092                         }
2093                 }
2094         }
2095
2096         if (map < 0) {
2097                 ast_log(LOG_WARNING, "No Dynamic RTP mapping avaliable for format %s\n" ,ast_getformatname(format));
2098                 ast_rwlock_unlock(&static_RTP_PT_lock);
2099                 return;
2100         }
2101
2102         if (format) {
2103                 static_RTP_PT[map].asterisk_format = 1;
2104                 ast_format_copy(&static_RTP_PT[map].format, format);
2105         } else {
2106                 static_RTP_PT[map].rtp_code = rtp_code;
2107         }
2108         ast_rwlock_unlock(&static_RTP_PT_lock);
2109 }
2110
2111 int ast_rtp_engine_load_format(const struct ast_format *format)
2112 {
2113         switch (format->id) {
2114         case AST_FORMAT_SILK:
2115                 set_next_mime_type(format, 0, "audio", "SILK", ast_format_rate(format));
2116                 add_static_payload(-1, format, 0);
2117                 break;
2118         case AST_FORMAT_CELT:
2119                 set_next_mime_type(format, 0, "audio", "CELT", ast_format_rate(format));
2120                 add_static_payload(-1, format, 0);
2121                 break;
2122         default:
2123                 break;
2124         }
2125
2126         return 0;
2127 }
2128
2129 int ast_rtp_engine_unload_format(const struct ast_format *format)
2130 {
2131         int x;
2132         int y = 0;
2133
2134         ast_rwlock_wrlock(&static_RTP_PT_lock);
2135         /* remove everything pertaining to this format id from the lists */
2136         for (x = 0; x < AST_RTP_MAX_PT; x++) {
2137                 if (ast_format_cmp(&static_RTP_PT[x].format, format) == AST_FORMAT_CMP_EQUAL) {
2138                         memset(&static_RTP_PT[x], 0, sizeof(struct ast_rtp_payload_type));
2139                 }
2140         }
2141         ast_rwlock_unlock(&static_RTP_PT_lock);
2142
2143
2144         ast_rwlock_wrlock(&mime_types_lock);
2145         /* rebuild the list skipping the items matching this id */
2146         for (x = 0; x < mime_types_len; x++) {
2147                 if (ast_format_cmp(&ast_rtp_mime_types[x].payload_type.format, format) == AST_FORMAT_CMP_EQUAL) {
2148                         continue;
2149                 }
2150                 ast_rtp_mime_types[y] = ast_rtp_mime_types[x];
2151                 y++;
2152         }
2153         mime_types_len = y;
2154         ast_rwlock_unlock(&mime_types_lock);
2155         return 0;
2156 }
2157
2158 int ast_rtp_engine_init()
2159 {
2160         struct ast_format tmpfmt;
2161
2162         ast_rwlock_init(&mime_types_lock);
2163         ast_rwlock_init(&static_RTP_PT_lock);
2164
2165         /* Define all the RTP mime types available */
2166         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G723_1, 0), 0, "audio", "G723", 8000);
2167         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_GSM, 0), 0, "audio", "GSM", 8000);
2168         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0), 0, "audio", "PCMU", 8000);
2169         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0), 0, "audio", "G711U", 8000);
2170         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ALAW, 0), 0, "audio", "PCMA", 8000);
2171         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ALAW, 0), 0, "audio", "G711A", 8000);
2172         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G726, 0), 0, "audio", "G726-32", 8000);
2173         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0, "audio", "DVI4", 8000);
2174         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR, 0), 0, "audio", "L16", 8000);
2175         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR16, 0), 0, "audio", "L16", 16000);
2176         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR16, 0), 0, "audio", "L16-256", 16000);
2177         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_LPC10, 0), 0, "audio", "LPC", 8000);
2178         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G729A, 0), 0, "audio", "G729", 8000);
2179         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G729A, 0), 0, "audio", "G729A", 8000);
2180         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G729A, 0), 0, "audio", "G.729", 8000);
2181         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SPEEX, 0), 0, "audio", "speex", 8000);
2182         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SPEEX16, 0), 0,  "audio", "speex", 16000);
2183         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SPEEX32, 0), 0,  "audio", "speex", 32000);
2184         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ILBC, 0), 0, "audio", "iLBC", 8000);
2185         /* this is the sample rate listed in the RTP profile for the G.722 codec, *NOT* the actual sample rate of the media stream */
2186         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G722, 0), 0, "audio", "G722", 8000);
2187         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G726_AAL2, 0), 0, "audio", "AAL2-G726-32", 8000);
2188         set_next_mime_type(NULL, AST_RTP_DTMF, "audio", "telephone-event", 8000);
2189         set_next_mime_type(NULL, AST_RTP_CISCO_DTMF, "audio", "cisco-telephone-event", 8000);
2190         set_next_mime_type(NULL, AST_RTP_CN, "audio", "CN", 8000);
2191         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_JPEG, 0), 0, "video", "JPEG", 90000);
2192         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_PNG, 0), 0, "video", "PNG", 90000);
2193         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_H261, 0), 0, "video", "H261", 90000);
2194         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_H263, 0), 0, "video", "H263", 90000);
2195         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_H263_PLUS, 0), 0, "video", "h263-1998", 90000);
2196         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_H264, 0), 0, "video", "H264", 90000);
2197         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_MP4_VIDEO, 0), 0, "video", "MP4V-ES", 90000);
2198         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_T140RED, 0), 0, "text", "RED", 1000);
2199         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_T140, 0), 0, "text", "T140", 1000);
2200         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SIREN7, 0), 0, "audio", "G7221", 16000);
2201         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SIREN14, 0), 0, "audio", "G7221", 32000);
2202         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G719, 0), 0, "audio", "G719", 48000);
2203
2204         /* Define the static rtp payload mappings */
2205         add_static_payload(0, ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0), 0);
2206         #ifdef USE_DEPRECATED_G726
2207         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... */
2208         #endif
2209         add_static_payload(3, ast_format_set(&tmpfmt, AST_FORMAT_GSM, 0), 0);
2210         add_static_payload(4, ast_format_set(&tmpfmt, AST_FORMAT_G723_1, 0), 0);
2211         add_static_payload(5, ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0);/* 8 kHz */
2212         add_static_payload(6, ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0); /* 16 kHz */
2213         add_static_payload(7, ast_format_set(&tmpfmt, AST_FORMAT_LPC10, 0), 0);
2214         add_static_payload(8, ast_format_set(&tmpfmt, AST_FORMAT_ALAW, 0), 0);
2215         add_static_payload(9, ast_format_set(&tmpfmt, AST_FORMAT_G722, 0), 0);
2216         add_static_payload(10, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR, 0), 0); /* 2 channels */
2217         add_static_payload(11, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR, 0), 0); /* 1 channel */
2218         add_static_payload(13, NULL, AST_RTP_CN);
2219         add_static_payload(16, ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0); /* 11.025 kHz */
2220         add_static_payload(17, ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0); /* 22.050 kHz */
2221         add_static_payload(18, ast_format_set(&tmpfmt, AST_FORMAT_G729A, 0), 0);
2222         add_static_payload(19, NULL, AST_RTP_CN);         /* Also used for CN */
2223         add_static_payload(26, ast_format_set(&tmpfmt, AST_FORMAT_JPEG, 0), 0);
2224         add_static_payload(31, ast_format_set(&tmpfmt, AST_FORMAT_H261, 0), 0);
2225         add_static_payload(34, ast_format_set(&tmpfmt, AST_FORMAT_H263, 0), 0);
2226         add_static_payload(97, ast_format_set(&tmpfmt, AST_FORMAT_ILBC, 0), 0);
2227         add_static_payload(98, ast_format_set(&tmpfmt, AST_FORMAT_H263_PLUS, 0), 0);
2228         add_static_payload(99, ast_format_set(&tmpfmt, AST_FORMAT_H264, 0), 0);
2229         add_static_payload(101, NULL, AST_RTP_DTMF);
2230         add_static_payload(102, ast_format_set(&tmpfmt, AST_FORMAT_SIREN7, 0), 0);
2231         add_static_payload(103, ast_format_set(&tmpfmt, AST_FORMAT_H263_PLUS, 0), 0);
2232         add_static_payload(104, ast_format_set(&tmpfmt, AST_FORMAT_MP4_VIDEO, 0), 0);
2233         add_static_payload(105, ast_format_set(&tmpfmt, AST_FORMAT_T140RED, 0), 0);   /* Real time text chat (with redundancy encoding) */
2234         add_static_payload(106, ast_format_set(&tmpfmt, AST_FORMAT_T140, 0), 0);     /* Real time text chat */
2235         add_static_payload(110, ast_format_set(&tmpfmt, AST_FORMAT_SPEEX, 0), 0);
2236         add_static_payload(111, ast_format_set(&tmpfmt, AST_FORMAT_G726, 0), 0);
2237         add_static_payload(112, ast_format_set(&tmpfmt, AST_FORMAT_G726_AAL2, 0), 0);
2238         add_static_payload(115, ast_format_set(&tmpfmt, AST_FORMAT_SIREN14, 0), 0);
2239         add_static_payload(116, ast_format_set(&tmpfmt, AST_FORMAT_G719, 0), 0);
2240         add_static_payload(117, ast_format_set(&tmpfmt, AST_FORMAT_SPEEX16, 0), 0);
2241         add_static_payload(118, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR16, 0), 0); /* 16 Khz signed linear */
2242         add_static_payload(119, ast_format_set(&tmpfmt, AST_FORMAT_SPEEX32, 0), 0);
2243         add_static_payload(121, NULL, AST_RTP_CISCO_DTMF);   /* Must be type 121 */
2244
2245         return 0;
2246 }