Payload and RTP code are must remain separate since in non-Asterisk format cases...
[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         if (payload < 0 || payload >= AST_RTP_MAX_PT || !(type = ao2_find(codecs->payloads, &payload, OBJ_KEY | OBJ_NOLOCK))) {
538                 ast_rwlock_unlock(&static_RTP_PT_lock);
539                 return;
540         }
541
542         type->asterisk_format = static_RTP_PT[payload].asterisk_format;
543         type->rtp_code = static_RTP_PT[payload].rtp_code;
544         type->payload = payload;
545         ast_format_copy(&type->format, &static_RTP_PT[payload].format);
546
547         ast_debug(1, "Setting payload %d based on m type on %p\n", payload, codecs);
548
549         if (instance && instance->engine && instance->engine->payload_set) {
550                 instance->engine->payload_set(instance, payload, type->asterisk_format, &type->format, type->rtp_code);
551         }
552
553         ao2_ref(type, -1);
554
555         ast_rwlock_unlock(&static_RTP_PT_lock);
556 }
557
558 int ast_rtp_codecs_payloads_set_rtpmap_type_rate(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, int pt,
559                                  char *mimetype, char *mimesubtype,
560                                  enum ast_rtp_options options,
561                                  unsigned int sample_rate)
562 {
563         unsigned int i;
564         int found = 0;
565
566         if (pt < 0 || pt >= AST_RTP_MAX_PT)
567                 return -1; /* bogus payload type */
568
569         ast_rwlock_rdlock(&mime_types_lock);
570         for (i = 0; i < mime_types_len; ++i) {
571                 const struct ast_rtp_mime_type *t = &ast_rtp_mime_types[i];
572                 struct ast_rtp_payload_type *type;
573
574                 if (strcasecmp(mimesubtype, t->subtype)) {
575                         continue;
576                 }
577
578                 if (strcasecmp(mimetype, t->type)) {
579                         continue;
580                 }
581
582                 /* if both sample rates have been supplied, and they don't match,
583                  * then this not a match; if one has not been supplied, then the
584                  * rates are not compared */
585                 if (sample_rate && t->sample_rate &&
586                     (sample_rate != t->sample_rate)) {
587                         continue;
588                 }
589
590                 found = 1;
591
592                 if (!(type = ao2_find(codecs->payloads, &pt, OBJ_KEY | OBJ_NOLOCK))) {
593                         if (!(type = ao2_alloc(sizeof(*type), NULL))) {
594                                 continue;
595                         }
596                         type->payload = pt;
597                         ao2_link_flags(codecs->payloads, type, OBJ_NOLOCK);
598                 }
599
600                 *type = t->payload_type;
601                 type->payload = pt;
602
603                 if ((t->payload_type.format.id == AST_FORMAT_G726) && t->payload_type.asterisk_format && (options & AST_RTP_OPT_G726_NONSTANDARD)) {
604                         ast_format_set(&type->format, AST_FORMAT_G726_AAL2, 0);
605                 }
606
607                 if (instance && instance->engine && instance->engine->payload_set) {
608                         instance->engine->payload_set(instance, pt, type->asterisk_format, &type->format, type->rtp_code);
609                 }
610
611                 ao2_ref(type, -1);
612
613                 break;
614         }
615         ast_rwlock_unlock(&mime_types_lock);
616
617         return (found ? 0 : -2);
618 }
619
620 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)
621 {
622         return ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, instance, payload, mimetype, mimesubtype, options, 0);
623 }
624
625 void ast_rtp_codecs_payloads_unset(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, int payload)
626 {
627         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
628                 return;
629         }
630
631         ast_debug(2, "Unsetting payload %d on %p\n", payload, codecs);
632
633         ao2_find(codecs->payloads, &payload, OBJ_KEY | OBJ_NOLOCK | OBJ_NODATA | OBJ_UNLINK);
634
635         if (instance && instance->engine && instance->engine->payload_set) {
636                 instance->engine->payload_set(instance, payload, 0, NULL, 0);
637         }
638 }
639
640 struct ast_rtp_payload_type ast_rtp_codecs_payload_lookup(struct ast_rtp_codecs *codecs, int payload)
641 {
642         struct ast_rtp_payload_type result = { .asterisk_format = 0, }, *type;
643
644         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
645                 return result;
646         }
647
648         if ((type = ao2_find(codecs->payloads, &payload, OBJ_KEY | OBJ_NOLOCK))) {
649                 result = *type;
650                 ao2_ref(type, -1);
651         }
652
653         if (!result.rtp_code && !result.asterisk_format) {
654                 ast_rwlock_rdlock(&static_RTP_PT_lock);
655                 result = static_RTP_PT[payload];
656                 ast_rwlock_unlock(&static_RTP_PT_lock);
657         }
658
659         return result;
660 }
661
662
663 struct ast_format *ast_rtp_codecs_get_payload_format(struct ast_rtp_codecs *codecs, int payload)
664 {
665         struct ast_rtp_payload_type *type;
666         struct ast_format *format;
667
668         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
669                 return NULL;
670         }
671
672         if (!(type = ao2_find(codecs->payloads, &payload, OBJ_KEY | OBJ_NOLOCK))) {
673                 return NULL;
674         }
675
676         format = type->asterisk_format ? &type->format : NULL;
677
678         ao2_ref(type, -1);
679
680         return format;
681 }
682
683 static int rtp_payload_type_add_ast(void *obj, void *arg, int flags)
684 {
685         struct ast_rtp_payload_type *type = obj;
686         struct ast_format_cap *astformats = arg;
687
688         if (type->asterisk_format) {
689                 ast_format_cap_add(astformats, &type->format);
690         }
691
692         return 0;
693 }
694
695 static int rtp_payload_type_add_nonast(void *obj, void *arg, int flags)
696 {
697         struct ast_rtp_payload_type *type = obj;
698         int *nonastformats = arg;
699
700         if (!type->asterisk_format) {
701                 *nonastformats |= type->rtp_code;
702         }
703
704         return 0;
705 }
706
707 void ast_rtp_codecs_payload_formats(struct ast_rtp_codecs *codecs, struct ast_format_cap *astformats, int *nonastformats)
708 {
709         ast_format_cap_remove_all(astformats);
710         *nonastformats = 0;
711
712         ao2_callback(codecs->payloads, OBJ_NODATA | OBJ_MULTIPLE | OBJ_NOLOCK, rtp_payload_type_add_ast, astformats);
713         ao2_callback(codecs->payloads, OBJ_NODATA | OBJ_MULTIPLE | OBJ_NOLOCK, rtp_payload_type_add_nonast, nonastformats);
714 }
715
716 static int rtp_payload_type_find_format(void *obj, void *arg, int flags)
717 {
718         struct ast_rtp_payload_type *type = obj;
719         struct ast_format *format = arg;
720
721         return (type->asterisk_format && (ast_format_cmp(&type->format, format) != AST_FORMAT_CMP_NOT_EQUAL)) ? CMP_MATCH | CMP_STOP : 0;
722 }
723
724 int ast_rtp_codecs_payload_code(struct ast_rtp_codecs *codecs, int asterisk_format, const struct ast_format *format, int code)
725 {
726         struct ast_rtp_payload_type *type;
727         int i, res = -1;
728
729         if (asterisk_format && format && (type = ao2_callback(codecs->payloads, OBJ_NOLOCK, rtp_payload_type_find_format, (void*)format))) {
730                 res = type->payload;
731                 ao2_ref(type, -1);
732                 return res;
733         } else if (!asterisk_format && (type = ao2_find(codecs->payloads, &code, OBJ_NOLOCK | OBJ_KEY))) {
734                 res = type->payload;
735                 ao2_ref(type, -1);
736                 return res;
737         }
738
739         ast_rwlock_rdlock(&static_RTP_PT_lock);
740         for (i = 0; i < AST_RTP_MAX_PT; i++) {
741                 if (static_RTP_PT[i].asterisk_format && asterisk_format && format &&
742                         (ast_format_cmp(format, &static_RTP_PT[i].format) != AST_FORMAT_CMP_NOT_EQUAL)) {
743                         res = i;
744                         break;
745                 } else if (!static_RTP_PT[i].asterisk_format && !asterisk_format &&
746                         (static_RTP_PT[i].rtp_code == code)) {
747                         res = i;
748                         break;
749                 }
750         }
751         ast_rwlock_unlock(&static_RTP_PT_lock);
752
753         return res;
754 }
755
756 const char *ast_rtp_lookup_mime_subtype2(const int asterisk_format, struct ast_format *format, int code, enum ast_rtp_options options)
757 {
758         int i;
759         const char *res = "";
760
761         ast_rwlock_rdlock(&mime_types_lock);
762         for (i = 0; i < mime_types_len; i++) {
763                 if (ast_rtp_mime_types[i].payload_type.asterisk_format && asterisk_format && format &&
764                         (ast_format_cmp(format, &ast_rtp_mime_types[i].payload_type.format) != AST_FORMAT_CMP_NOT_EQUAL)) {
765                         if ((format->id == AST_FORMAT_G726_AAL2) && (options & AST_RTP_OPT_G726_NONSTANDARD)) {
766                                 res = "G726-32";
767                                 break;
768                         } else {
769                                 res = ast_rtp_mime_types[i].subtype;
770                                 break;
771                         }
772                 } else if (!ast_rtp_mime_types[i].payload_type.asterisk_format && !asterisk_format &&
773                         ast_rtp_mime_types[i].payload_type.rtp_code == code) {
774
775                         res = ast_rtp_mime_types[i].subtype;
776                         break;
777                 }
778         }
779         ast_rwlock_unlock(&mime_types_lock);
780
781         return res;
782 }
783
784 unsigned int ast_rtp_lookup_sample_rate2(int asterisk_format, struct ast_format *format, int code)
785 {
786         unsigned int i;
787         unsigned int res = 0;
788
789         ast_rwlock_rdlock(&mime_types_lock);
790         for (i = 0; i < mime_types_len; ++i) {
791                 if (ast_rtp_mime_types[i].payload_type.asterisk_format && asterisk_format && format &&
792                         (ast_format_cmp(format, &ast_rtp_mime_types[i].payload_type.format) != AST_FORMAT_CMP_NOT_EQUAL)) {
793                         res = ast_rtp_mime_types[i].sample_rate;
794                         break;
795                 } else if (!ast_rtp_mime_types[i].payload_type.asterisk_format && !asterisk_format &&
796                         ast_rtp_mime_types[i].payload_type.rtp_code == code) {
797                         res = ast_rtp_mime_types[i].sample_rate;
798                         break;
799                 }
800         }
801         ast_rwlock_unlock(&mime_types_lock);
802
803         return res;
804 }
805
806 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)
807 {
808         int found = 0;
809         const char *name;
810         if (!buf) {
811                 return NULL;
812         }
813
814
815         if (asterisk_format) {
816                 struct ast_format tmp_fmt;
817                 ast_format_cap_iter_start(ast_format_capability);
818                 while (!ast_format_cap_iter_next(ast_format_capability, &tmp_fmt)) {
819                         name = ast_rtp_lookup_mime_subtype2(asterisk_format, &tmp_fmt, 0, options);
820                         ast_str_append(&buf, 0, "%s|", name);
821                         found = 1;
822                 }
823                 ast_format_cap_iter_end(ast_format_capability);
824
825         } else {
826                 int x;
827                 ast_str_append(&buf, 0, "0x%x (", (unsigned int) rtp_capability);
828                 for (x = 1; x < AST_RTP_MAX; x <<= 1) {
829                         if (rtp_capability & x) {
830                                 name = ast_rtp_lookup_mime_subtype2(asterisk_format, NULL, x, options);
831                                 ast_str_append(&buf, 0, "%s|", name);
832                                 found = 1;
833                         }
834                 }
835         }
836
837         ast_str_append(&buf, 0, "%s", found ? ")" : "nothing)");
838
839         return ast_str_buffer(buf);
840 }
841
842 void ast_rtp_codecs_packetization_set(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, struct ast_codec_pref *prefs)
843 {
844         codecs->pref = *prefs;
845
846         if (instance && instance->engine->packetization_set) {
847                 instance->engine->packetization_set(instance, &instance->codecs.pref);
848         }
849 }
850
851 int ast_rtp_instance_dtmf_begin(struct ast_rtp_instance *instance, char digit)
852 {
853         return instance->engine->dtmf_begin ? instance->engine->dtmf_begin(instance, digit) : -1;
854 }
855
856 int ast_rtp_instance_dtmf_end(struct ast_rtp_instance *instance, char digit)
857 {
858         return instance->engine->dtmf_end ? instance->engine->dtmf_end(instance, digit) : -1;
859 }
860 int ast_rtp_instance_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
861 {
862         return instance->engine->dtmf_end_with_duration ? instance->engine->dtmf_end_with_duration(instance, digit, duration) : -1;
863 }
864
865 int ast_rtp_instance_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
866 {
867         return (!instance->engine->dtmf_mode_set || instance->engine->dtmf_mode_set(instance, dtmf_mode)) ? -1 : 0;
868 }
869
870 enum ast_rtp_dtmf_mode ast_rtp_instance_dtmf_mode_get(struct ast_rtp_instance *instance)
871 {
872         return instance->engine->dtmf_mode_get ? instance->engine->dtmf_mode_get(instance) : 0;
873 }
874
875 void ast_rtp_instance_update_source(struct ast_rtp_instance *instance)
876 {
877         if (instance->engine->update_source) {
878                 instance->engine->update_source(instance);
879         }
880 }
881
882 void ast_rtp_instance_change_source(struct ast_rtp_instance *instance)
883 {
884         if (instance->engine->change_source) {
885                 instance->engine->change_source(instance);
886         }
887 }
888
889 int ast_rtp_instance_set_qos(struct ast_rtp_instance *instance, int tos, int cos, const char *desc)
890 {
891         return instance->engine->qos ? instance->engine->qos(instance, tos, cos, desc) : -1;
892 }
893
894 void ast_rtp_instance_stop(struct ast_rtp_instance *instance)
895 {
896         if (instance->engine->stop) {
897                 instance->engine->stop(instance);
898         }
899 }
900
901 int ast_rtp_instance_fd(struct ast_rtp_instance *instance, int rtcp)
902 {
903         return instance->engine->fd ? instance->engine->fd(instance, rtcp) : -1;
904 }
905
906 struct ast_rtp_glue *ast_rtp_instance_get_glue(const char *type)
907 {
908         struct ast_rtp_glue *glue = NULL;
909
910         AST_RWLIST_RDLOCK(&glues);
911
912         AST_RWLIST_TRAVERSE(&glues, glue, entry) {
913                 if (!strcasecmp(glue->type, type)) {
914                         break;
915                 }
916         }
917
918         AST_RWLIST_UNLOCK(&glues);
919
920         return glue;
921 }
922
923 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)
924 {
925         enum ast_bridge_result res = AST_BRIDGE_FAILED;
926         struct ast_channel *who = NULL, *other = NULL, *cs[3] = { NULL, };
927         struct ast_frame *fr = NULL;
928
929         /* Start locally bridging both instances */
930         if (instance0->engine->local_bridge && instance0->engine->local_bridge(instance0, instance1)) {
931                 ast_debug(1, "Failed to locally bridge %s to %s, backing out.\n", ast_channel_name(c0), ast_channel_name(c1));
932                 ast_channel_unlock(c0);
933                 ast_channel_unlock(c1);
934                 return AST_BRIDGE_FAILED_NOWARN;
935         }
936         if (instance1->engine->local_bridge && instance1->engine->local_bridge(instance1, instance0)) {
937                 ast_debug(1, "Failed to locally bridge %s to %s, backing out.\n", ast_channel_name(c1), ast_channel_name(c0));
938                 if (instance0->engine->local_bridge) {
939                         instance0->engine->local_bridge(instance0, NULL);
940                 }
941                 ast_channel_unlock(c0);
942                 ast_channel_unlock(c1);
943                 return AST_BRIDGE_FAILED_NOWARN;
944         }
945
946         ast_channel_unlock(c0);
947         ast_channel_unlock(c1);
948
949         instance0->bridged = instance1;
950         instance1->bridged = instance0;
951
952         ast_poll_channel_add(c0, c1);
953
954         /* Hop into a loop waiting for a frame from either channel */
955         cs[0] = c0;
956         cs[1] = c1;
957         cs[2] = NULL;
958         for (;;) {
959                 /* If the underlying formats have changed force this bridge to break */
960                 if ((ast_format_cmp(ast_channel_rawreadformat(c0), ast_channel_rawwriteformat(c1)) == AST_FORMAT_CMP_NOT_EQUAL) ||
961                         (ast_format_cmp(ast_channel_rawreadformat(c1), ast_channel_rawwriteformat(c0)) == AST_FORMAT_CMP_NOT_EQUAL)) {
962                         ast_debug(1, "rtp-engine-local-bridge: Oooh, formats changed, backing out\n");
963                         res = AST_BRIDGE_FAILED_NOWARN;
964                         break;
965                 }
966                 /* Check if anything changed */
967                 if ((ast_channel_tech_pvt(c0) != pvt0) ||
968                     (ast_channel_tech_pvt(c1) != pvt1) ||
969                     (ast_channel_masq(c0) || ast_channel_masqr(c0) || ast_channel_masq(c1) || ast_channel_masqr(c1)) ||
970                     (ast_channel_monitor(c0) || ast_channel_audiohooks(c0) || ast_channel_monitor(c1) || ast_channel_audiohooks(c1)) ||
971                     (!ast_framehook_list_is_empty(ast_channel_framehooks(c0)) || !ast_framehook_list_is_empty(ast_channel_framehooks(c1)))) {
972                         ast_debug(1, "rtp-engine-local-bridge: Oooh, something is weird, backing out\n");
973                         /* 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 */
974                         if ((ast_channel_masq(c0) || ast_channel_masqr(c0)) && (fr = ast_read(c0))) {
975                                 ast_frfree(fr);
976                         }
977                         if ((ast_channel_masq(c1) || ast_channel_masqr(c1)) && (fr = ast_read(c1))) {
978                                 ast_frfree(fr);
979                         }
980                         res = AST_BRIDGE_RETRY;
981                         break;
982                 }
983                 /* Wait on a channel to feed us a frame */
984                 if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
985                         if (!timeoutms) {
986                                 res = AST_BRIDGE_RETRY;
987                                 break;
988                         }
989                         ast_debug(2, "rtp-engine-local-bridge: Ooh, empty read...\n");
990                         if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
991                                 break;
992                         }
993                         continue;
994                 }
995                 /* Read in frame from channel */
996                 fr = ast_read(who);
997                 other = (who == c0) ? c1 : c0;
998                 /* Depending on the frame we may need to break out of our bridge */
999                 if (!fr || ((fr->frametype == AST_FRAME_DTMF_BEGIN || fr->frametype == AST_FRAME_DTMF_END) &&
1000                             ((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) |
1001                             ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)))) {
1002                         /* Record received frame and who */
1003                         *fo = fr;
1004                         *rc = who;
1005                         ast_debug(1, "rtp-engine-local-bridge: Ooh, got a %s\n", fr ? "digit" : "hangup");
1006                         res = AST_BRIDGE_COMPLETE;
1007                         break;
1008                 } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1009                         if ((fr->subclass.integer == AST_CONTROL_HOLD) ||
1010                             (fr->subclass.integer == AST_CONTROL_UNHOLD) ||
1011                             (fr->subclass.integer == AST_CONTROL_VIDUPDATE) ||
1012                             (fr->subclass.integer == AST_CONTROL_SRCUPDATE) ||
1013                             (fr->subclass.integer == AST_CONTROL_T38_PARAMETERS) ||
1014                             (fr->subclass.integer == AST_CONTROL_UPDATE_RTP_PEER)) {
1015                                 /* If we are going on hold, then break callback mode and P2P bridging */
1016                                 if (fr->subclass.integer == AST_CONTROL_HOLD) {
1017                                         if (instance0->engine->local_bridge) {
1018                                                 instance0->engine->local_bridge(instance0, NULL);
1019                                         }
1020                                         if (instance1->engine->local_bridge) {
1021                                                 instance1->engine->local_bridge(instance1, NULL);
1022                                         }
1023                                         instance0->bridged = NULL;
1024                                         instance1->bridged = NULL;
1025                                 } else if (fr->subclass.integer == AST_CONTROL_UNHOLD) {
1026                                         if (instance0->engine->local_bridge) {
1027                                                 instance0->engine->local_bridge(instance0, instance1);
1028                                         }
1029                                         if (instance1->engine->local_bridge) {
1030                                                 instance1->engine->local_bridge(instance1, instance0);
1031                                         }
1032                                         instance0->bridged = instance1;
1033                                         instance1->bridged = instance0;
1034                                 }
1035                                 /* Since UPDATE_BRIDGE_PEER is only used by the bridging code, don't forward it */
1036                                 if (fr->subclass.integer != AST_CONTROL_UPDATE_RTP_PEER) {
1037                                         ast_indicate_data(other, fr->subclass.integer, fr->data.ptr, fr->datalen);
1038                                 }
1039                                 ast_frfree(fr);
1040                         } else if (fr->subclass.integer == AST_CONTROL_CONNECTED_LINE) {
1041                                 if (ast_channel_connected_line_sub(who, other, fr, 1) &&
1042                                         ast_channel_connected_line_macro(who, other, fr, other == c0, 1)) {
1043                                         ast_indicate_data(other, fr->subclass.integer, fr->data.ptr, fr->datalen);
1044                                 }
1045                                 ast_frfree(fr);
1046                         } else if (fr->subclass.integer == AST_CONTROL_REDIRECTING) {
1047                                 if (ast_channel_redirecting_sub(who, other, fr, 1) &&
1048                                         ast_channel_redirecting_macro(who, other, fr, other == c0, 1)) {
1049                                         ast_indicate_data(other, fr->subclass.integer, fr->data.ptr, fr->datalen);
1050                                 }
1051                                 ast_frfree(fr);
1052                         } else if (fr->subclass.integer == AST_CONTROL_PVT_CAUSE_CODE) {
1053                                 ast_channel_hangupcause_hash_set(other, fr->data.ptr, fr->datalen);
1054                                 ast_frfree(fr);
1055                         } else {
1056                                 *fo = fr;
1057                                 *rc = who;
1058                                 ast_debug(1, "rtp-engine-local-bridge: Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass.integer, ast_channel_name(who));
1059                                 res = AST_BRIDGE_COMPLETE;
1060                                 break;
1061                         }
1062                 } else {
1063                         if ((fr->frametype == AST_FRAME_DTMF_BEGIN) ||
1064                             (fr->frametype == AST_FRAME_DTMF_END) ||
1065                             (fr->frametype == AST_FRAME_VOICE) ||
1066                             (fr->frametype == AST_FRAME_VIDEO) ||
1067                             (fr->frametype == AST_FRAME_IMAGE) ||
1068                             (fr->frametype == AST_FRAME_HTML) ||
1069                             (fr->frametype == AST_FRAME_MODEM) ||
1070                             (fr->frametype == AST_FRAME_TEXT)) {
1071                                 ast_write(other, fr);
1072                         }
1073
1074                         ast_frfree(fr);
1075                 }
1076                 /* Swap priority */
1077                 cs[2] = cs[0];
1078                 cs[0] = cs[1];
1079                 cs[1] = cs[2];
1080         }
1081
1082         /* Stop locally bridging both instances */
1083         if (instance0->engine->local_bridge) {
1084                 instance0->engine->local_bridge(instance0, NULL);
1085         }
1086         if (instance1->engine->local_bridge) {
1087                 instance1->engine->local_bridge(instance1, NULL);
1088         }
1089
1090         instance0->bridged = NULL;
1091         instance1->bridged = NULL;
1092
1093         ast_poll_channel_del(c0, c1);
1094
1095         return res;
1096 }
1097
1098 static enum ast_bridge_result remote_bridge_loop(struct ast_channel *c0,
1099         struct ast_channel *c1,
1100         struct ast_rtp_instance *instance0,
1101         struct ast_rtp_instance *instance1,
1102         struct ast_rtp_instance *vinstance0,
1103         struct ast_rtp_instance *vinstance1,
1104         struct ast_rtp_instance *tinstance0,
1105         struct ast_rtp_instance *tinstance1,
1106         struct ast_rtp_glue *glue0,
1107         struct ast_rtp_glue *glue1,
1108         struct ast_format_cap *cap0,
1109         struct ast_format_cap *cap1,
1110         int timeoutms,
1111         int flags,
1112         struct ast_frame **fo,
1113         struct ast_channel **rc,
1114         void *pvt0,
1115         void *pvt1)
1116 {
1117         enum ast_bridge_result res = AST_BRIDGE_FAILED;
1118         struct ast_channel *who = NULL, *other = NULL, *cs[3] = { NULL, };
1119         struct ast_format_cap *oldcap0 = ast_format_cap_dup(cap0);
1120         struct ast_format_cap *oldcap1 = ast_format_cap_dup(cap1);
1121         struct ast_sockaddr ac1 = {{0,}}, vac1 = {{0,}}, tac1 = {{0,}}, ac0 = {{0,}}, vac0 = {{0,}}, tac0 = {{0,}};
1122         struct ast_sockaddr t1 = {{0,}}, vt1 = {{0,}}, tt1 = {{0,}}, t0 = {{0,}}, vt0 = {{0,}}, tt0 = {{0,}};
1123         struct ast_frame *fr = NULL;
1124
1125         if (!oldcap0 || !oldcap1) {
1126                 ast_channel_unlock(c0);
1127                 ast_channel_unlock(c1);
1128                 goto remote_bridge_cleanup;
1129         }
1130         /* Test the first channel */
1131         if (!(glue0->update_peer(c0, instance1, vinstance1, tinstance1, cap1, 0))) {
1132                 ast_rtp_instance_get_remote_address(instance1, &ac1);
1133                 if (vinstance1) {
1134                         ast_rtp_instance_get_remote_address(vinstance1, &vac1);
1135                 }
1136                 if (tinstance1) {
1137                         ast_rtp_instance_get_remote_address(tinstance1, &tac1);
1138                 }
1139         } else {
1140                 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", ast_channel_name(c0), ast_channel_name(c1));
1141         }
1142
1143         /* Test the second channel */
1144         if (!(glue1->update_peer(c1, instance0, vinstance0, tinstance0, cap0, 0))) {
1145                 ast_rtp_instance_get_remote_address(instance0, &ac0);
1146                 if (vinstance0) {
1147                         ast_rtp_instance_get_remote_address(instance0, &vac0);
1148                 }
1149                 if (tinstance0) {
1150                         ast_rtp_instance_get_remote_address(instance0, &tac0);
1151                 }
1152         } else {
1153                 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", ast_channel_name(c1), ast_channel_name(c0));
1154         }
1155
1156         ast_channel_unlock(c0);
1157         ast_channel_unlock(c1);
1158
1159         instance0->bridged = instance1;
1160         instance1->bridged = instance0;
1161
1162         ast_poll_channel_add(c0, c1);
1163
1164         /* Go into a loop handling any stray frames that may come in */
1165         cs[0] = c0;
1166         cs[1] = c1;
1167         cs[2] = NULL;
1168         for (;;) {
1169                 /* Check if anything changed */
1170                 if ((ast_channel_tech_pvt(c0) != pvt0) ||
1171                     (ast_channel_tech_pvt(c1) != pvt1) ||
1172                     (ast_channel_masq(c0) || ast_channel_masqr(c0) || ast_channel_masq(c1) || ast_channel_masqr(c1)) ||
1173                     (ast_channel_monitor(c0) || ast_channel_audiohooks(c0) || ast_channel_monitor(c1) || ast_channel_audiohooks(c1)) ||
1174                     (!ast_framehook_list_is_empty(ast_channel_framehooks(c0)) || !ast_framehook_list_is_empty(ast_channel_framehooks(c1)))) {
1175                         ast_debug(1, "Oooh, something is weird, backing out\n");
1176                         res = AST_BRIDGE_RETRY;
1177                         break;
1178                 }
1179
1180                 /* Check if they have changed their address */
1181                 ast_rtp_instance_get_remote_address(instance1, &t1);
1182                 if (vinstance1) {
1183                         ast_rtp_instance_get_remote_address(vinstance1, &vt1);
1184                 }
1185                 if (tinstance1) {
1186                         ast_rtp_instance_get_remote_address(tinstance1, &tt1);
1187                 }
1188                 if (glue1->get_codec) {
1189                         ast_format_cap_remove_all(cap1);
1190                         glue1->get_codec(c1, cap1);
1191                 }
1192
1193                 ast_rtp_instance_get_remote_address(instance0, &t0);
1194                 if (vinstance0) {
1195                         ast_rtp_instance_get_remote_address(vinstance0, &vt0);
1196                 }
1197                 if (tinstance0) {
1198                         ast_rtp_instance_get_remote_address(tinstance0, &tt0);
1199                 }
1200                 if (glue0->get_codec) {
1201                         ast_format_cap_remove_all(cap0);
1202                         glue0->get_codec(c0, cap0);
1203                 }
1204
1205                 if ((ast_sockaddr_cmp(&t1, &ac1)) ||
1206                     (vinstance1 && ast_sockaddr_cmp(&vt1, &vac1)) ||
1207                     (tinstance1 && ast_sockaddr_cmp(&tt1, &tac1)) ||
1208                     (!ast_format_cap_identical(cap1, oldcap1))) {
1209                         char tmp_buf[512] = { 0, };
1210                         ast_debug(1, "Oooh, '%s' changed end address to %s (format %s)\n",
1211                                   ast_channel_name(c1), ast_sockaddr_stringify(&t1),
1212                                   ast_getformatname_multiple(tmp_buf, sizeof(tmp_buf), cap1));
1213                         ast_debug(1, "Oooh, '%s' changed end vaddress to %s (format %s)\n",
1214                                   ast_channel_name(c1), ast_sockaddr_stringify(&vt1),
1215                                   ast_getformatname_multiple(tmp_buf, sizeof(tmp_buf), cap1));
1216                         ast_debug(1, "Oooh, '%s' changed end taddress to %s (format %s)\n",
1217                                   ast_channel_name(c1), ast_sockaddr_stringify(&tt1),
1218                                   ast_getformatname_multiple(tmp_buf, sizeof(tmp_buf), cap1));
1219                         ast_debug(1, "Oooh, '%s' was %s/(format %s)\n",
1220                                   ast_channel_name(c1), ast_sockaddr_stringify(&ac1),
1221                                   ast_getformatname_multiple(tmp_buf, sizeof(tmp_buf), oldcap1));
1222                         ast_debug(1, "Oooh, '%s' was %s/(format %s)\n",
1223                                   ast_channel_name(c1), ast_sockaddr_stringify(&vac1),
1224                                   ast_getformatname_multiple(tmp_buf, sizeof(tmp_buf), oldcap1));
1225                         ast_debug(1, "Oooh, '%s' was %s/(format %s)\n",
1226                                   ast_channel_name(c1), ast_sockaddr_stringify(&tac1),
1227                                   ast_getformatname_multiple(tmp_buf, sizeof(tmp_buf), oldcap1));
1228                         if (glue0->update_peer(c0,
1229                                                ast_sockaddr_isnull(&t1)  ? NULL : instance1,
1230                                                ast_sockaddr_isnull(&vt1) ? NULL : vinstance1,
1231                                                ast_sockaddr_isnull(&tt1) ? NULL : tinstance1,
1232                                                cap1, 0)) {
1233                                 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", ast_channel_name(c0), ast_channel_name(c1));
1234                         }
1235                         ast_sockaddr_copy(&ac1, &t1);
1236                         ast_sockaddr_copy(&vac1, &vt1);
1237                         ast_sockaddr_copy(&tac1, &tt1);
1238                         ast_format_cap_copy(oldcap1, cap1);
1239                 }
1240                 if ((ast_sockaddr_cmp(&t0, &ac0)) ||
1241                     (vinstance0 && ast_sockaddr_cmp(&vt0, &vac0)) ||
1242                     (tinstance0 && ast_sockaddr_cmp(&tt0, &tac0)) ||
1243                     (!ast_format_cap_identical(cap0, oldcap0))) {
1244                         char tmp_buf[512] = { 0, };
1245                         ast_debug(1, "Oooh, '%s' changed end address to %s (format %s)\n",
1246                                   ast_channel_name(c0), ast_sockaddr_stringify(&t0),
1247                                   ast_getformatname_multiple(tmp_buf, sizeof(tmp_buf), cap0));
1248                         ast_debug(1, "Oooh, '%s' was %s/(format %s)\n",
1249                                   ast_channel_name(c0), ast_sockaddr_stringify(&ac0),
1250                                   ast_getformatname_multiple(tmp_buf, sizeof(tmp_buf), oldcap0));
1251                         if (glue1->update_peer(c1, t0.len ? instance0 : NULL,
1252                                                 vt0.len ? vinstance0 : NULL,
1253                                                 tt0.len ? tinstance0 : NULL,
1254                                                 cap0, 0)) {
1255                                 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", ast_channel_name(c1), ast_channel_name(c0));
1256                         }
1257                         ast_sockaddr_copy(&ac0, &t0);
1258                         ast_sockaddr_copy(&vac0, &vt0);
1259                         ast_sockaddr_copy(&tac0, &tt0);
1260                         ast_format_cap_copy(oldcap0, cap0);
1261                 }
1262
1263                 /* Wait for frame to come in on the channels */
1264                 if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
1265                         if (!timeoutms) {
1266                                 res = AST_BRIDGE_RETRY;
1267                                 break;
1268                         }
1269                         ast_debug(1, "Ooh, empty read...\n");
1270                         if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
1271                                 break;
1272                         }
1273                         continue;
1274                 }
1275                 fr = ast_read(who);
1276                 other = (who == c0) ? c1 : c0;
1277                 if (!fr || ((fr->frametype == AST_FRAME_DTMF_BEGIN || fr->frametype == AST_FRAME_DTMF_END) &&
1278                             (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
1279                              ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
1280                         /* Break out of bridge */
1281                         *fo = fr;
1282                         *rc = who;
1283                         ast_debug(1, "Oooh, got a %s\n", fr ? "digit" : "hangup");
1284                         res = AST_BRIDGE_COMPLETE;
1285                         break;
1286                 } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1287                         if ((fr->subclass.integer == AST_CONTROL_HOLD) ||
1288                             (fr->subclass.integer == AST_CONTROL_UNHOLD) ||
1289                             (fr->subclass.integer == AST_CONTROL_VIDUPDATE) ||
1290                             (fr->subclass.integer == AST_CONTROL_SRCUPDATE) ||
1291                             (fr->subclass.integer == AST_CONTROL_T38_PARAMETERS) ||
1292                                 (fr->subclass.integer == AST_CONTROL_UPDATE_RTP_PEER)) {
1293                                 if (fr->subclass.integer == AST_CONTROL_HOLD) {
1294                                         /* If we someone went on hold we want the other side to reinvite back to us */
1295                                         if (who == c0) {
1296                                                 glue1->update_peer(c1, NULL, NULL, NULL, 0, 0);
1297                                         } else {
1298                                                 glue0->update_peer(c0, NULL, NULL, NULL, 0, 0);
1299                                         }
1300                                 } else if (fr->subclass.integer == AST_CONTROL_UNHOLD ||
1301                                         fr->subclass.integer == AST_CONTROL_UPDATE_RTP_PEER) {
1302                                         /* If they went off hold they should go back to being direct, or if we have
1303                                          * been told to force a peer update, go ahead and do it. */
1304                                         if (who == c0) {
1305                                                 glue1->update_peer(c1, instance0, vinstance0, tinstance0, cap0, 0);
1306                                         } else {
1307                                                 glue0->update_peer(c0, instance1, vinstance1, tinstance1, cap1, 0);
1308                                         }
1309                                 }
1310                                 /* Update local address information */
1311                                 ast_rtp_instance_get_remote_address(instance0, &t0);
1312                                 ast_sockaddr_copy(&ac0, &t0);
1313                                 ast_rtp_instance_get_remote_address(instance1, &t1);
1314                                 ast_sockaddr_copy(&ac1, &t1);
1315                                 /* Update codec information */
1316                                 if (glue0->get_codec && ast_channel_tech_pvt(c0)) {
1317                                         ast_format_cap_remove_all(cap0);
1318                                         ast_format_cap_remove_all(oldcap0);
1319                                         glue0->get_codec(c0, cap0);
1320                                         ast_format_cap_append(oldcap0, cap0);
1321
1322                                 }
1323                                 if (glue1->get_codec && ast_channel_tech_pvt(c1)) {
1324                                         ast_format_cap_remove_all(cap1);
1325                                         ast_format_cap_remove_all(oldcap1);
1326                                         glue1->get_codec(c1, cap1);
1327                                         ast_format_cap_append(oldcap1, cap1);
1328                                 }
1329                                 /* Since UPDATE_BRIDGE_PEER is only used by the bridging code, don't forward it */
1330                                 if (fr->subclass.integer != AST_CONTROL_UPDATE_RTP_PEER) {
1331                                         ast_indicate_data(other, fr->subclass.integer, fr->data.ptr, fr->datalen);
1332                                 }
1333                                 ast_frfree(fr);
1334                         } else if (fr->subclass.integer == AST_CONTROL_CONNECTED_LINE) {
1335                                 if (ast_channel_connected_line_sub(who, other, fr, 1) &&
1336                                         ast_channel_connected_line_macro(who, other, fr, other == c0, 1)) {
1337                                         ast_indicate_data(other, fr->subclass.integer, fr->data.ptr, fr->datalen);
1338                                 }
1339                                 ast_frfree(fr);
1340                         } else if (fr->subclass.integer == AST_CONTROL_REDIRECTING) {
1341                                 if (ast_channel_redirecting_sub(who, other, fr, 1) &&
1342                                         ast_channel_redirecting_macro(who, other, fr, other == c0, 1)) {
1343                                         ast_indicate_data(other, fr->subclass.integer, fr->data.ptr, fr->datalen);
1344                                 }
1345                                 ast_frfree(fr);
1346                         } else if (fr->subclass.integer == AST_CONTROL_PVT_CAUSE_CODE) {
1347                                 ast_channel_hangupcause_hash_set(other, fr->data.ptr, fr->datalen);
1348                                 ast_frfree(fr);
1349                         } else {
1350                                 *fo = fr;
1351                                 *rc = who;
1352                                 ast_debug(1, "Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass.integer, ast_channel_name(who));
1353                                 res = AST_BRIDGE_COMPLETE;
1354                                 goto remote_bridge_cleanup;
1355                         }
1356                 } else {
1357                         if ((fr->frametype == AST_FRAME_DTMF_BEGIN) ||
1358                             (fr->frametype == AST_FRAME_DTMF_END) ||
1359                             (fr->frametype == AST_FRAME_VOICE) ||
1360                             (fr->frametype == AST_FRAME_VIDEO) ||
1361                             (fr->frametype == AST_FRAME_IMAGE) ||
1362                             (fr->frametype == AST_FRAME_HTML) ||
1363                             (fr->frametype == AST_FRAME_MODEM) ||
1364                             (fr->frametype == AST_FRAME_TEXT)) {
1365                                 ast_write(other, fr);
1366                         }
1367                         ast_frfree(fr);
1368                 }
1369                 /* Swap priority */
1370                 cs[2] = cs[0];
1371                 cs[0] = cs[1];
1372                 cs[1] = cs[2];
1373         }
1374
1375         if (ast_test_flag(ast_channel_flags(c0), AST_FLAG_ZOMBIE)) {
1376                 ast_debug(1, "Channel '%s' Zombie cleardown from bridge\n", ast_channel_name(c0));
1377         } else if (ast_channel_tech_pvt(c0) != pvt0) {
1378                 ast_debug(1, "Channel c0->'%s' pvt changed, in bridge with c1->'%s'\n", ast_channel_name(c0), ast_channel_name(c1));
1379         } else if (glue0 != ast_rtp_instance_get_glue(ast_channel_tech(c0)->type)) {
1380                 ast_debug(1, "Channel c0->'%s' technology changed, in bridge with c1->'%s'\n", ast_channel_name(c0), ast_channel_name(c1));
1381         } else if (glue0->update_peer(c0, NULL, NULL, NULL, 0, 0)) {
1382                 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", ast_channel_name(c0));
1383         }
1384         if (ast_test_flag(ast_channel_flags(c1), AST_FLAG_ZOMBIE)) {
1385                 ast_debug(1, "Channel '%s' Zombie cleardown from bridge\n", ast_channel_name(c1));
1386         } else if (ast_channel_tech_pvt(c1) != pvt1) {
1387                 ast_debug(1, "Channel c1->'%s' pvt changed, in bridge with c0->'%s'\n", ast_channel_name(c1), ast_channel_name(c0));
1388         } else if (glue1 != ast_rtp_instance_get_glue(ast_channel_tech(c1)->type)) {
1389                 ast_debug(1, "Channel c1->'%s' technology changed, in bridge with c0->'%s'\n", ast_channel_name(c1), ast_channel_name(c0));
1390         } else if (glue1->update_peer(c1, NULL, NULL, NULL, 0, 0)) {
1391                 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", ast_channel_name(c1));
1392         }
1393
1394         instance0->bridged = NULL;
1395         instance1->bridged = NULL;
1396
1397         ast_poll_channel_del(c0, c1);
1398
1399 remote_bridge_cleanup:
1400         ast_format_cap_destroy(oldcap0);
1401         ast_format_cap_destroy(oldcap1);
1402
1403         return res;
1404 }
1405
1406 /*!
1407  * \brief Conditionally unref an rtp instance
1408  */
1409 static void unref_instance_cond(struct ast_rtp_instance **instance)
1410 {
1411         if (*instance) {
1412                 ao2_ref(*instance, -1);
1413                 *instance = NULL;
1414         }
1415 }
1416
1417 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)
1418 {
1419         struct ast_rtp_instance *instance0 = NULL, *instance1 = NULL,
1420                         *vinstance0 = NULL, *vinstance1 = NULL,
1421                         *tinstance0 = NULL, *tinstance1 = NULL;
1422         struct ast_rtp_glue *glue0, *glue1;
1423         struct ast_sockaddr addr1 = { {0, }, }, addr2 = { {0, }, };
1424         enum ast_rtp_glue_result audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID, video_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1425         enum ast_rtp_glue_result audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID, video_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1426         enum ast_bridge_result res = AST_BRIDGE_FAILED;
1427         enum ast_rtp_dtmf_mode dmode;
1428         struct ast_format_cap *cap0 = ast_format_cap_alloc_nolock();
1429         struct ast_format_cap *cap1 = ast_format_cap_alloc_nolock();
1430         int unlock_chans = 1;
1431
1432         if (!cap0 || !cap1) {
1433                 unlock_chans = 0;
1434                 goto done;
1435         }
1436
1437         /* Lock both channels so we can look for the glue that binds them together */
1438         ast_channel_lock(c0);
1439         while (ast_channel_trylock(c1)) {
1440                 ast_channel_unlock(c0);
1441                 usleep(1);
1442                 ast_channel_lock(c0);
1443         }
1444
1445         /* Ensure neither channel got hungup during lock avoidance */
1446         if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
1447                 ast_log(LOG_WARNING, "Got hangup while attempting to bridge '%s' and '%s'\n", ast_channel_name(c0), ast_channel_name(c1));
1448                 goto done;
1449         }
1450
1451         /* Grab glue that binds each channel to something using the RTP engine */
1452         if (!(glue0 = ast_rtp_instance_get_glue(ast_channel_tech(c0)->type)) || !(glue1 = ast_rtp_instance_get_glue(ast_channel_tech(c1)->type))) {
1453                 ast_debug(1, "Can't find native functions for channel '%s'\n", glue0 ? ast_channel_name(c1) : ast_channel_name(c0));
1454                 goto done;
1455         }
1456
1457         audio_glue0_res = glue0->get_rtp_info(c0, &instance0);
1458         video_glue0_res = glue0->get_vrtp_info ? glue0->get_vrtp_info(c0, &vinstance0) : AST_RTP_GLUE_RESULT_FORBID;
1459
1460         audio_glue1_res = glue1->get_rtp_info(c1, &instance1);
1461         video_glue1_res = glue1->get_vrtp_info ? glue1->get_vrtp_info(c1, &vinstance1) : AST_RTP_GLUE_RESULT_FORBID;
1462
1463         /* If the channels are of the same technology, they might have limitations on remote bridging */
1464         if (ast_channel_tech(c0) == ast_channel_tech(c1)) {
1465                 if (audio_glue0_res == audio_glue1_res && audio_glue1_res == AST_RTP_GLUE_RESULT_REMOTE) {
1466                         if (glue0->allow_rtp_remote && !(glue0->allow_rtp_remote(c0, c1))) {
1467                                 /* If the allow_rtp_remote indicates that remote isn't allowed, revert to local bridge */
1468                                 audio_glue0_res = audio_glue1_res = AST_RTP_GLUE_RESULT_LOCAL;
1469                         }
1470                 }
1471                 if (video_glue0_res == video_glue1_res && video_glue1_res == AST_RTP_GLUE_RESULT_REMOTE) {
1472                         if (glue0->allow_vrtp_remote && !(glue0->allow_vrtp_remote(c0, c1))) {
1473                                 /* if the allow_vrtp_remote indicates that remote isn't allowed, revert to local bridge */
1474                                 video_glue0_res = video_glue1_res = AST_RTP_GLUE_RESULT_LOCAL;
1475                         }
1476                 }
1477         }
1478
1479         /* If we are carrying video, and both sides are not going to remotely bridge... fail the native bridge */
1480         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)) {
1481                 audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1482         }
1483         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)) {
1484                 audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1485         }
1486
1487         /* If any sort of bridge is forbidden just completely bail out and go back to generic bridging */
1488         if (audio_glue0_res == AST_RTP_GLUE_RESULT_FORBID || audio_glue1_res == AST_RTP_GLUE_RESULT_FORBID) {
1489                 res = AST_BRIDGE_FAILED_NOWARN;
1490                 goto done;
1491         }
1492
1493
1494         /* If address families differ, force a local bridge */
1495         ast_rtp_instance_get_remote_address(instance0, &addr1);
1496         ast_rtp_instance_get_remote_address(instance1, &addr2);
1497
1498         if (addr1.ss.ss_family != addr2.ss.ss_family ||
1499            (ast_sockaddr_is_ipv4_mapped(&addr1) != ast_sockaddr_is_ipv4_mapped(&addr2))) {
1500                 audio_glue0_res = AST_RTP_GLUE_RESULT_LOCAL;
1501                 audio_glue1_res = AST_RTP_GLUE_RESULT_LOCAL;
1502         }
1503
1504         /* If we need to get DTMF see if we can do it outside of the RTP stream itself */
1505         dmode = ast_rtp_instance_dtmf_mode_get(instance0);
1506         if ((flags & AST_BRIDGE_DTMF_CHANNEL_0) && dmode) {
1507                 res = AST_BRIDGE_FAILED_NOWARN;
1508                 goto done;
1509         }
1510         dmode = ast_rtp_instance_dtmf_mode_get(instance1);
1511         if ((flags & AST_BRIDGE_DTMF_CHANNEL_1) && dmode) {
1512                 res = AST_BRIDGE_FAILED_NOWARN;
1513                 goto done;
1514         }
1515
1516         /* 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 */
1517         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)))) {
1518                 res = AST_BRIDGE_FAILED_NOWARN;
1519                 goto done;
1520         }
1521
1522         /* Make sure that codecs match */
1523         if (glue0->get_codec){
1524                 glue0->get_codec(c0, cap0);
1525         }
1526         if (glue1->get_codec) {
1527                 glue1->get_codec(c1, cap1);
1528         }
1529         if (!ast_format_cap_is_empty(cap0) && !ast_format_cap_is_empty(cap1) && !ast_format_cap_has_joint(cap0, cap1)) {
1530                 char tmp0[256] = { 0, };
1531                 char tmp1[256] = { 0, };
1532                 ast_debug(1, "Channel codec0 = %s is not codec1 = %s, cannot native bridge in RTP.\n",
1533                         ast_getformatname_multiple(tmp0, sizeof(tmp0), cap0),
1534                         ast_getformatname_multiple(tmp1, sizeof(tmp1), cap1));
1535                 res = AST_BRIDGE_FAILED_NOWARN;
1536                 goto done;
1537         }
1538
1539         instance0->glue = glue0;
1540         instance1->glue = glue1;
1541         instance0->chan = c0;
1542         instance1->chan = c1;
1543
1544         /* Depending on the end result for bridging either do a local bridge or remote bridge */
1545         if (audio_glue0_res == AST_RTP_GLUE_RESULT_LOCAL || audio_glue1_res == AST_RTP_GLUE_RESULT_LOCAL) {
1546                 ast_verb(3, "Locally bridging %s and %s\n", ast_channel_name(c0), ast_channel_name(c1));
1547                 res = local_bridge_loop(c0, c1, instance0, instance1, timeoutms, flags, fo, rc, ast_channel_tech_pvt(c0), ast_channel_tech_pvt(c1));
1548         } else {
1549                 ast_verb(3, "Remotely bridging %s and %s\n", ast_channel_name(c0), ast_channel_name(c1));
1550                 res = remote_bridge_loop(c0, c1, instance0, instance1, vinstance0, vinstance1,
1551                                 tinstance0, tinstance1, glue0, glue1, cap0, cap1, timeoutms, flags,
1552                                 fo, rc, ast_channel_tech_pvt(c0), ast_channel_tech_pvt(c1));
1553         }
1554
1555         instance0->glue = NULL;
1556         instance1->glue = NULL;
1557         instance0->chan = NULL;
1558         instance1->chan = NULL;
1559
1560         unlock_chans = 0;
1561
1562 done:
1563         if (unlock_chans) {
1564                 ast_channel_unlock(c0);
1565                 ast_channel_unlock(c1);
1566         }
1567         ast_format_cap_destroy(cap1);
1568         ast_format_cap_destroy(cap0);
1569
1570         unref_instance_cond(&instance0);
1571         unref_instance_cond(&instance1);
1572         unref_instance_cond(&vinstance0);
1573         unref_instance_cond(&vinstance1);
1574         unref_instance_cond(&tinstance0);
1575         unref_instance_cond(&tinstance1);
1576
1577         return res;
1578 }
1579
1580 struct ast_rtp_instance *ast_rtp_instance_get_bridged(struct ast_rtp_instance *instance)
1581 {
1582         return instance->bridged;
1583 }
1584
1585 void ast_rtp_instance_early_bridge_make_compatible(struct ast_channel *c0, struct ast_channel *c1)
1586 {
1587         struct ast_rtp_instance *instance0 = NULL, *instance1 = NULL,
1588                 *vinstance0 = NULL, *vinstance1 = NULL,
1589                 *tinstance0 = NULL, *tinstance1 = NULL;
1590         struct ast_rtp_glue *glue0, *glue1;
1591         enum ast_rtp_glue_result audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID, video_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1592         enum ast_rtp_glue_result audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID, video_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1593         struct ast_format_cap *cap0 = ast_format_cap_alloc_nolock();
1594         struct ast_format_cap *cap1 = ast_format_cap_alloc_nolock();
1595
1596         /* Lock both channels so we can look for the glue that binds them together */
1597         ast_channel_lock_both(c0, c1);
1598
1599         if (!cap1 || !cap0) {
1600                 goto done;
1601         }
1602
1603         /* Grab glue that binds each channel to something using the RTP engine */
1604         if (!(glue0 = ast_rtp_instance_get_glue(ast_channel_tech(c0)->type)) || !(glue1 = ast_rtp_instance_get_glue(ast_channel_tech(c1)->type))) {
1605                 ast_debug(1, "Can't find native functions for channel '%s'\n", glue0 ? ast_channel_name(c1) : ast_channel_name(c0));
1606                 goto done;
1607         }
1608
1609         audio_glue0_res = glue0->get_rtp_info(c0, &instance0);
1610         video_glue0_res = glue0->get_vrtp_info ? glue0->get_vrtp_info(c0, &vinstance0) : AST_RTP_GLUE_RESULT_FORBID;
1611
1612         audio_glue1_res = glue1->get_rtp_info(c1, &instance1);
1613         video_glue1_res = glue1->get_vrtp_info ? glue1->get_vrtp_info(c1, &vinstance1) : AST_RTP_GLUE_RESULT_FORBID;
1614
1615         /* If we are carrying video, and both sides are not going to remotely bridge... fail the native bridge */
1616         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)) {
1617                 audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1618         }
1619         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)) {
1620                 audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1621         }
1622         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) {
1623                 glue0->get_codec(c0, cap0);
1624         }
1625         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) {
1626                 glue1->get_codec(c1, cap1);
1627         }
1628
1629         /* If any sort of bridge is forbidden just completely bail out and go back to generic bridging */
1630         if (audio_glue0_res != AST_RTP_GLUE_RESULT_REMOTE || audio_glue1_res != AST_RTP_GLUE_RESULT_REMOTE) {
1631                 goto done;
1632         }
1633
1634         /* Make sure we have matching codecs */
1635         if (!ast_format_cap_has_joint(cap0, cap1)) {
1636                 goto done;
1637         }
1638
1639         ast_rtp_codecs_payloads_copy(&instance0->codecs, &instance1->codecs, instance1);
1640
1641         if (vinstance0 && vinstance1) {
1642                 ast_rtp_codecs_payloads_copy(&vinstance0->codecs, &vinstance1->codecs, vinstance1);
1643         }
1644         if (tinstance0 && tinstance1) {
1645                 ast_rtp_codecs_payloads_copy(&tinstance0->codecs, &tinstance1->codecs, tinstance1);
1646         }
1647
1648         if (glue0->update_peer(c0, instance1, vinstance1, tinstance1, cap1, 0)) {
1649                 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n",
1650                         ast_channel_name(c0), ast_channel_name(c1));
1651         } else {
1652                 ast_debug(1, "Seeded SDP of '%s' with that of '%s'\n",
1653                         ast_channel_name(c0), ast_channel_name(c1));
1654         }
1655
1656 done:
1657         ast_channel_unlock(c0);
1658         ast_channel_unlock(c1);
1659
1660         ast_format_cap_destroy(cap0);
1661         ast_format_cap_destroy(cap1);
1662
1663         unref_instance_cond(&instance0);
1664         unref_instance_cond(&instance1);
1665         unref_instance_cond(&vinstance0);
1666         unref_instance_cond(&vinstance1);
1667         unref_instance_cond(&tinstance0);
1668         unref_instance_cond(&tinstance1);
1669 }
1670
1671 int ast_rtp_instance_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
1672 {
1673         struct ast_rtp_instance *instance0 = NULL, *instance1 = NULL,
1674                         *vinstance0 = NULL, *vinstance1 = NULL,
1675                         *tinstance0 = NULL, *tinstance1 = NULL;
1676         struct ast_rtp_glue *glue0, *glue1;
1677         enum ast_rtp_glue_result audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID, video_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1678         enum ast_rtp_glue_result audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID, video_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1679         struct ast_format_cap *cap0 = ast_format_cap_alloc_nolock();
1680         struct ast_format_cap *cap1 = ast_format_cap_alloc_nolock();
1681         int res = 0;
1682
1683         /* If there is no second channel just immediately bail out, we are of no use in that scenario */
1684         if (!c1) {
1685                 ast_format_cap_destroy(cap0);
1686                 ast_format_cap_destroy(cap1);
1687                 return -1;
1688         }
1689
1690         /* Lock both channels so we can look for the glue that binds them together */
1691         ast_channel_lock(c0);
1692         while (ast_channel_trylock(c1)) {
1693                 ast_channel_unlock(c0);
1694                 usleep(1);
1695                 ast_channel_lock(c0);
1696         }
1697
1698         if (!cap1 || !cap0) {
1699                 goto done;
1700         }
1701
1702         /* Grab glue that binds each channel to something using the RTP engine */
1703         if (!(glue0 = ast_rtp_instance_get_glue(ast_channel_tech(c0)->type)) || !(glue1 = ast_rtp_instance_get_glue(ast_channel_tech(c1)->type))) {
1704                 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", glue0 ? ast_channel_name(c1) : ast_channel_name(c0));
1705                 goto done;
1706         }
1707
1708         audio_glue0_res = glue0->get_rtp_info(c0, &instance0);
1709         video_glue0_res = glue0->get_vrtp_info ? glue0->get_vrtp_info(c0, &vinstance0) : AST_RTP_GLUE_RESULT_FORBID;
1710
1711         audio_glue1_res = glue1->get_rtp_info(c1, &instance1);
1712         video_glue1_res = glue1->get_vrtp_info ? glue1->get_vrtp_info(c1, &vinstance1) : AST_RTP_GLUE_RESULT_FORBID;
1713
1714         /* If we are carrying video, and both sides are not going to remotely bridge... fail the native bridge */
1715         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)) {
1716                 audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
1717         }
1718         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)) {
1719                 audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
1720         }
1721         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) {
1722                 glue0->get_codec(c0, cap0);
1723         }
1724         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) {
1725                 glue1->get_codec(c1, cap1);
1726         }
1727
1728         /* If any sort of bridge is forbidden just completely bail out and go back to generic bridging */
1729         if (audio_glue0_res != AST_RTP_GLUE_RESULT_REMOTE || audio_glue1_res != AST_RTP_GLUE_RESULT_REMOTE) {
1730                 goto done;
1731         }
1732
1733         /* Make sure we have matching codecs */
1734         if (!ast_format_cap_has_joint(cap0, cap1)) {
1735                 goto done;
1736         }
1737
1738         /* Bridge media early */
1739         if (glue0->update_peer(c0, instance1, vinstance1, tinstance1, cap1, 0)) {
1740                 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", ast_channel_name(c0), c1 ? ast_channel_name(c1) : "<unspecified>");
1741         }
1742
1743         res = 0;
1744
1745 done:
1746         ast_channel_unlock(c0);
1747         ast_channel_unlock(c1);
1748
1749         ast_format_cap_destroy(cap0);
1750         ast_format_cap_destroy(cap1);
1751
1752         unref_instance_cond(&instance0);
1753         unref_instance_cond(&instance1);
1754         unref_instance_cond(&vinstance0);
1755         unref_instance_cond(&vinstance1);
1756         unref_instance_cond(&tinstance0);
1757         unref_instance_cond(&tinstance1);
1758
1759         if (!res) {
1760                 ast_debug(1, "Setting early bridge SDP of '%s' with that of '%s'\n", ast_channel_name(c0), c1 ? ast_channel_name(c1) : "<unspecified>");
1761         }
1762
1763         return res;
1764 }
1765
1766 int ast_rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations)
1767 {
1768         return instance->engine->red_init ? instance->engine->red_init(instance, buffer_time, payloads, generations) : -1;
1769 }
1770
1771 int ast_rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame)
1772 {
1773         return instance->engine->red_buffer ? instance->engine->red_buffer(instance, frame) : -1;
1774 }
1775
1776 int ast_rtp_instance_get_stats(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat)
1777 {
1778         return instance->engine->get_stat ? instance->engine->get_stat(instance, stats, stat) : -1;
1779 }
1780
1781 char *ast_rtp_instance_get_quality(struct ast_rtp_instance *instance, enum ast_rtp_instance_stat_field field, char *buf, size_t size)
1782 {
1783         struct ast_rtp_instance_stats stats = { 0, };
1784         enum ast_rtp_instance_stat stat;
1785
1786         /* Determine what statistics we will need to retrieve based on field passed in */
1787         if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY) {
1788                 stat = AST_RTP_INSTANCE_STAT_ALL;
1789         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER) {
1790                 stat = AST_RTP_INSTANCE_STAT_COMBINED_JITTER;
1791         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS) {
1792                 stat = AST_RTP_INSTANCE_STAT_COMBINED_LOSS;
1793         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT) {
1794                 stat = AST_RTP_INSTANCE_STAT_COMBINED_RTT;
1795         } else {
1796                 return NULL;
1797         }
1798
1799         /* Attempt to actually retrieve the statistics we need to generate the quality string */
1800         if (ast_rtp_instance_get_stats(instance, &stats, stat)) {
1801                 return NULL;
1802         }
1803
1804         /* Now actually fill the buffer with the good information */
1805         if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY) {
1806                 snprintf(buf, size, "ssrc=%i;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f",
1807                          stats.local_ssrc, stats.remote_ssrc, stats.rxploss, stats.txjitter, stats.rxcount, stats.rxjitter, stats.txcount, stats.txploss, stats.rtt);
1808         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER) {
1809                 snprintf(buf, size, "minrxjitter=%f;maxrxjitter=%f;avgrxjitter=%f;stdevrxjitter=%f;reported_minjitter=%f;reported_maxjitter=%f;reported_avgjitter=%f;reported_stdevjitter=%f;",
1810                          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));
1811         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS) {
1812                 snprintf(buf, size, "minrxlost=%f;maxrxlost=%f;avgrxlost=%f;stdevrxlost=%f;reported_minlost=%f;reported_maxlost=%f;reported_avglost=%f;reported_stdevlost=%f;",
1813                          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));
1814         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT) {
1815                 snprintf(buf, size, "minrtt=%f;maxrtt=%f;avgrtt=%f;stdevrtt=%f;", stats.minrtt, stats.maxrtt, stats.normdevrtt, stats.stdevrtt);
1816         }
1817
1818         return buf;
1819 }
1820
1821 void ast_rtp_instance_set_stats_vars(struct ast_channel *chan, struct ast_rtp_instance *instance)
1822 {
1823         char quality_buf[AST_MAX_USER_FIELD], *quality;
1824         struct ast_channel *bridge = ast_bridged_channel(chan);
1825
1826         if ((quality = ast_rtp_instance_get_quality(instance, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
1827                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOS", quality);
1828                 if (bridge) {
1829                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSBRIDGED", quality);
1830                 }
1831         }
1832
1833         if ((quality = ast_rtp_instance_get_quality(instance, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf)))) {
1834                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSJITTER", quality);
1835                 if (bridge) {
1836                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSJITTERBRIDGED", quality);
1837                 }
1838         }
1839
1840         if ((quality = ast_rtp_instance_get_quality(instance, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf)))) {
1841                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSLOSS", quality);
1842                 if (bridge) {
1843                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSLOSSBRIDGED", quality);
1844                 }
1845         }
1846
1847         if ((quality = ast_rtp_instance_get_quality(instance, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf)))) {
1848                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSRTT", quality);
1849                 if (bridge) {
1850                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSRTTBRIDGED", quality);
1851                 }
1852         }
1853 }
1854
1855 int ast_rtp_instance_set_read_format(struct ast_rtp_instance *instance, struct ast_format *format)
1856 {
1857         return instance->engine->set_read_format ? instance->engine->set_read_format(instance, format) : -1;
1858 }
1859
1860 int ast_rtp_instance_set_write_format(struct ast_rtp_instance *instance, struct ast_format *format)
1861 {
1862         return instance->engine->set_write_format ? instance->engine->set_write_format(instance, format) : -1;
1863 }
1864
1865 int ast_rtp_instance_make_compatible(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_channel *peer)
1866 {
1867         struct ast_rtp_glue *glue;
1868         struct ast_rtp_instance *peer_instance = NULL;
1869         int res = -1;
1870
1871         if (!instance->engine->make_compatible) {
1872                 return -1;
1873         }
1874
1875         ast_channel_lock(peer);
1876
1877         if (!(glue = ast_rtp_instance_get_glue(ast_channel_tech(peer)->type))) {
1878                 ast_channel_unlock(peer);
1879                 return -1;
1880         }
1881
1882         glue->get_rtp_info(peer, &peer_instance);
1883
1884         if (!peer_instance || peer_instance->engine != instance->engine) {
1885                 ast_channel_unlock(peer);
1886                 ao2_ref(peer_instance, -1);
1887                 peer_instance = NULL;
1888                 return -1;
1889         }
1890
1891         res = instance->engine->make_compatible(chan, instance, peer, peer_instance);
1892
1893         ast_channel_unlock(peer);
1894
1895         ao2_ref(peer_instance, -1);
1896         peer_instance = NULL;
1897
1898         return res;
1899 }
1900
1901 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)
1902 {
1903         if (instance->engine->available_formats) {
1904                 instance->engine->available_formats(instance, to_endpoint, to_asterisk, result);
1905                 if (!ast_format_cap_is_empty(result)) {
1906                         return;
1907                 }
1908         }
1909
1910         ast_translate_available_formats(to_endpoint, to_asterisk, result);
1911 }
1912
1913 int ast_rtp_instance_activate(struct ast_rtp_instance *instance)
1914 {
1915         return instance->engine->activate ? instance->engine->activate(instance) : 0;
1916 }
1917
1918 void ast_rtp_instance_stun_request(struct ast_rtp_instance *instance,
1919                                    struct ast_sockaddr *suggestion,
1920                                    const char *username)
1921 {
1922         if (instance->engine->stun_request) {
1923                 instance->engine->stun_request(instance, suggestion, username);
1924         }
1925 }
1926
1927 void ast_rtp_instance_set_timeout(struct ast_rtp_instance *instance, int timeout)
1928 {
1929         instance->timeout = timeout;
1930 }
1931
1932 void ast_rtp_instance_set_hold_timeout(struct ast_rtp_instance *instance, int timeout)
1933 {
1934         instance->holdtimeout = timeout;
1935 }
1936
1937 void ast_rtp_instance_set_keepalive(struct ast_rtp_instance *instance, int interval)
1938 {
1939         instance->keepalive = interval;
1940 }
1941
1942 int ast_rtp_instance_get_timeout(struct ast_rtp_instance *instance)
1943 {
1944         return instance->timeout;
1945 }
1946
1947 int ast_rtp_instance_get_hold_timeout(struct ast_rtp_instance *instance)
1948 {
1949         return instance->holdtimeout;
1950 }
1951
1952 int ast_rtp_instance_get_keepalive(struct ast_rtp_instance *instance)
1953 {
1954         return instance->keepalive;
1955 }
1956
1957 struct ast_rtp_engine *ast_rtp_instance_get_engine(struct ast_rtp_instance *instance)
1958 {
1959         return instance->engine;
1960 }
1961
1962 struct ast_rtp_glue *ast_rtp_instance_get_active_glue(struct ast_rtp_instance *instance)
1963 {
1964         return instance->glue;
1965 }
1966
1967 struct ast_channel *ast_rtp_instance_get_chan(struct ast_rtp_instance *instance)
1968 {
1969         return instance->chan;
1970 }
1971
1972 int ast_rtp_engine_register_srtp(struct ast_srtp_res *srtp_res, struct ast_srtp_policy_res *policy_res)
1973 {
1974         if (res_srtp || res_srtp_policy) {
1975                 return -1;
1976         }
1977         if (!srtp_res || !policy_res) {
1978                 return -1;
1979         }
1980
1981         res_srtp = srtp_res;
1982         res_srtp_policy = policy_res;
1983
1984         return 0;
1985 }
1986
1987 void ast_rtp_engine_unregister_srtp(void)
1988 {
1989         res_srtp = NULL;
1990         res_srtp_policy = NULL;
1991 }
1992
1993 int ast_rtp_engine_srtp_is_registered(void)
1994 {
1995         return res_srtp && res_srtp_policy;
1996 }
1997
1998 int ast_rtp_instance_add_srtp_policy(struct ast_rtp_instance *instance, struct ast_srtp_policy *remote_policy, struct ast_srtp_policy *local_policy)
1999 {
2000         int res = 0;
2001
2002         if (!res_srtp) {
2003                 return -1;
2004         }
2005
2006         if (!instance->srtp) {
2007                 res = res_srtp->create(&instance->srtp, instance, remote_policy);
2008         } else {
2009                 res = res_srtp->replace(&instance->srtp, instance, remote_policy);
2010         }
2011         if (!res) {
2012                 res = res_srtp->add_stream(instance->srtp, local_policy);
2013         }
2014
2015         return res;
2016 }
2017
2018 struct ast_srtp *ast_rtp_instance_get_srtp(struct ast_rtp_instance *instance)
2019 {
2020         return instance->srtp;
2021 }
2022
2023 int ast_rtp_instance_sendcng(struct ast_rtp_instance *instance, int level)
2024 {
2025         if (instance->engine->sendcng) {
2026                 return instance->engine->sendcng(instance, level);
2027         }
2028
2029         return -1;
2030 }
2031
2032 struct ast_rtp_engine_ice *ast_rtp_instance_get_ice(struct ast_rtp_instance *instance)
2033 {
2034         return instance->engine->ice;
2035 }
2036
2037 static void set_next_mime_type(const struct ast_format *format, int rtp_code, char *type, char *subtype, unsigned int sample_rate)
2038 {
2039         int x = mime_types_len;
2040         if (ARRAY_LEN(ast_rtp_mime_types) == mime_types_len) {
2041                 return;
2042         }
2043
2044         ast_rwlock_wrlock(&mime_types_lock);
2045         if (format) {
2046                 ast_rtp_mime_types[x].payload_type.asterisk_format = 1;
2047                 ast_format_copy(&ast_rtp_mime_types[x].payload_type.format, format);
2048         } else {
2049                 ast_rtp_mime_types[x].payload_type.rtp_code = rtp_code;
2050         }
2051         ast_rtp_mime_types[x].type = type;
2052         ast_rtp_mime_types[x].subtype = subtype;
2053         ast_rtp_mime_types[x].sample_rate = sample_rate;
2054         mime_types_len++;
2055         ast_rwlock_unlock(&mime_types_lock);
2056 }
2057
2058 static void add_static_payload(int map, const struct ast_format *format, int rtp_code)
2059 {
2060         int x;
2061         ast_rwlock_wrlock(&static_RTP_PT_lock);
2062         if (map < 0) {
2063                 /* find next available dynamic payload slot */
2064                 for (x = 96; x < 127; x++) {
2065                         if (!static_RTP_PT[x].asterisk_format && !static_RTP_PT[x].rtp_code) {
2066                                 map = x;
2067                                 break;
2068                         }
2069                 }
2070         }
2071
2072         if (map < 0) {
2073                 ast_log(LOG_WARNING, "No Dynamic RTP mapping avaliable for format %s\n" ,ast_getformatname(format));
2074                 ast_rwlock_unlock(&static_RTP_PT_lock);
2075                 return;
2076         }
2077
2078         if (format) {
2079                 static_RTP_PT[map].asterisk_format = 1;
2080                 ast_format_copy(&static_RTP_PT[map].format, format);
2081         } else {
2082                 static_RTP_PT[map].rtp_code = rtp_code;
2083         }
2084         ast_rwlock_unlock(&static_RTP_PT_lock);
2085 }
2086
2087 int ast_rtp_engine_load_format(const struct ast_format *format)
2088 {
2089         switch (format->id) {
2090         case AST_FORMAT_SILK:
2091                 set_next_mime_type(format, 0, "audio", "SILK", ast_format_rate(format));
2092                 add_static_payload(-1, format, 0);
2093                 break;
2094         case AST_FORMAT_CELT:
2095                 set_next_mime_type(format, 0, "audio", "CELT", ast_format_rate(format));
2096                 add_static_payload(-1, format, 0);
2097                 break;
2098         default:
2099                 break;
2100         }
2101
2102         return 0;
2103 }
2104
2105 int ast_rtp_engine_unload_format(const struct ast_format *format)
2106 {
2107         int x;
2108         int y = 0;
2109
2110         ast_rwlock_wrlock(&static_RTP_PT_lock);
2111         /* remove everything pertaining to this format id from the lists */
2112         for (x = 0; x < AST_RTP_MAX_PT; x++) {
2113                 if (ast_format_cmp(&static_RTP_PT[x].format, format) == AST_FORMAT_CMP_EQUAL) {
2114                         memset(&static_RTP_PT[x], 0, sizeof(struct ast_rtp_payload_type));
2115                 }
2116         }
2117         ast_rwlock_unlock(&static_RTP_PT_lock);
2118
2119
2120         ast_rwlock_wrlock(&mime_types_lock);
2121         /* rebuild the list skipping the items matching this id */
2122         for (x = 0; x < mime_types_len; x++) {
2123                 if (ast_format_cmp(&ast_rtp_mime_types[x].payload_type.format, format) == AST_FORMAT_CMP_EQUAL) {
2124                         continue;
2125                 }
2126                 ast_rtp_mime_types[y] = ast_rtp_mime_types[x];
2127                 y++;
2128         }
2129         mime_types_len = y;
2130         ast_rwlock_unlock(&mime_types_lock);
2131         return 0;
2132 }
2133
2134 int ast_rtp_engine_init()
2135 {
2136         struct ast_format tmpfmt;
2137
2138         ast_rwlock_init(&mime_types_lock);
2139         ast_rwlock_init(&static_RTP_PT_lock);
2140
2141         /* Define all the RTP mime types available */
2142         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G723_1, 0), 0, "audio", "G723", 8000);
2143         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_GSM, 0), 0, "audio", "GSM", 8000);
2144         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0), 0, "audio", "PCMU", 8000);
2145         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0), 0, "audio", "G711U", 8000);
2146         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ALAW, 0), 0, "audio", "PCMA", 8000);
2147         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ALAW, 0), 0, "audio", "G711A", 8000);
2148         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G726, 0), 0, "audio", "G726-32", 8000);
2149         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0, "audio", "DVI4", 8000);
2150         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR, 0), 0, "audio", "L16", 8000);
2151         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR16, 0), 0, "audio", "L16", 16000);
2152         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR16, 0), 0, "audio", "L16-256", 16000);
2153         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_LPC10, 0), 0, "audio", "LPC", 8000);
2154         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G729A, 0), 0, "audio", "G729", 8000);
2155         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G729A, 0), 0, "audio", "G729A", 8000);
2156         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G729A, 0), 0, "audio", "G.729", 8000);
2157         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SPEEX, 0), 0, "audio", "speex", 8000);
2158         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SPEEX16, 0), 0,  "audio", "speex", 16000);
2159         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SPEEX32, 0), 0,  "audio", "speex", 32000);
2160         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_ILBC, 0), 0, "audio", "iLBC", 8000);
2161         /* this is the sample rate listed in the RTP profile for the G.722 codec, *NOT* the actual sample rate of the media stream */
2162         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G722, 0), 0, "audio", "G722", 8000);
2163         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G726_AAL2, 0), 0, "audio", "AAL2-G726-32", 8000);
2164         set_next_mime_type(NULL, AST_RTP_DTMF, "audio", "telephone-event", 8000);
2165         set_next_mime_type(NULL, AST_RTP_CISCO_DTMF, "audio", "cisco-telephone-event", 8000);
2166         set_next_mime_type(NULL, AST_RTP_CN, "audio", "CN", 8000);
2167         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_JPEG, 0), 0, "video", "JPEG", 90000);
2168         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_PNG, 0), 0, "video", "PNG", 90000);
2169         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_H261, 0), 0, "video", "H261", 90000);
2170         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_H263, 0), 0, "video", "H263", 90000);
2171         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_H263_PLUS, 0), 0, "video", "h263-1998", 90000);
2172         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_H264, 0), 0, "video", "H264", 90000);
2173         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_MP4_VIDEO, 0), 0, "video", "MP4V-ES", 90000);
2174         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_T140RED, 0), 0, "text", "RED", 1000);
2175         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_T140, 0), 0, "text", "T140", 1000);
2176         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SIREN7, 0), 0, "audio", "G7221", 16000);
2177         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_SIREN14, 0), 0, "audio", "G7221", 32000);
2178         set_next_mime_type(ast_format_set(&tmpfmt, AST_FORMAT_G719, 0), 0, "audio", "G719", 48000);
2179
2180         /* Define the static rtp payload mappings */
2181         add_static_payload(0, ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0), 0);
2182         #ifdef USE_DEPRECATED_G726
2183         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... */
2184         #endif
2185         add_static_payload(3, ast_format_set(&tmpfmt, AST_FORMAT_GSM, 0), 0);
2186         add_static_payload(4, ast_format_set(&tmpfmt, AST_FORMAT_G723_1, 0), 0);
2187         add_static_payload(5, ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0);/* 8 kHz */
2188         add_static_payload(6, ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0); /* 16 kHz */
2189         add_static_payload(7, ast_format_set(&tmpfmt, AST_FORMAT_LPC10, 0), 0);
2190         add_static_payload(8, ast_format_set(&tmpfmt, AST_FORMAT_ALAW, 0), 0);
2191         add_static_payload(9, ast_format_set(&tmpfmt, AST_FORMAT_G722, 0), 0);
2192         add_static_payload(10, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR, 0), 0); /* 2 channels */
2193         add_static_payload(11, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR, 0), 0); /* 1 channel */
2194         add_static_payload(13, NULL, AST_RTP_CN);
2195         add_static_payload(16, ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0); /* 11.025 kHz */
2196         add_static_payload(17, ast_format_set(&tmpfmt, AST_FORMAT_ADPCM, 0), 0); /* 22.050 kHz */
2197         add_static_payload(18, ast_format_set(&tmpfmt, AST_FORMAT_G729A, 0), 0);
2198         add_static_payload(19, NULL, AST_RTP_CN);         /* Also used for CN */
2199         add_static_payload(26, ast_format_set(&tmpfmt, AST_FORMAT_JPEG, 0), 0);
2200         add_static_payload(31, ast_format_set(&tmpfmt, AST_FORMAT_H261, 0), 0);
2201         add_static_payload(34, ast_format_set(&tmpfmt, AST_FORMAT_H263, 0), 0);
2202         add_static_payload(97, ast_format_set(&tmpfmt, AST_FORMAT_ILBC, 0), 0);
2203         add_static_payload(98, ast_format_set(&tmpfmt, AST_FORMAT_H263_PLUS, 0), 0);
2204         add_static_payload(99, ast_format_set(&tmpfmt, AST_FORMAT_H264, 0), 0);
2205         add_static_payload(101, NULL, AST_RTP_DTMF);
2206         add_static_payload(102, ast_format_set(&tmpfmt, AST_FORMAT_SIREN7, 0), 0);
2207         add_static_payload(103, ast_format_set(&tmpfmt, AST_FORMAT_H263_PLUS, 0), 0);
2208         add_static_payload(104, ast_format_set(&tmpfmt, AST_FORMAT_MP4_VIDEO, 0), 0);
2209         add_static_payload(105, ast_format_set(&tmpfmt, AST_FORMAT_T140RED, 0), 0);   /* Real time text chat (with redundancy encoding) */
2210         add_static_payload(106, ast_format_set(&tmpfmt, AST_FORMAT_T140, 0), 0);     /* Real time text chat */
2211         add_static_payload(110, ast_format_set(&tmpfmt, AST_FORMAT_SPEEX, 0), 0);
2212         add_static_payload(111, ast_format_set(&tmpfmt, AST_FORMAT_G726, 0), 0);
2213         add_static_payload(112, ast_format_set(&tmpfmt, AST_FORMAT_G726_AAL2, 0), 0);
2214         add_static_payload(115, ast_format_set(&tmpfmt, AST_FORMAT_SIREN14, 0), 0);
2215         add_static_payload(116, ast_format_set(&tmpfmt, AST_FORMAT_G719, 0), 0);
2216         add_static_payload(117, ast_format_set(&tmpfmt, AST_FORMAT_SPEEX16, 0), 0);
2217         add_static_payload(118, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR16, 0), 0); /* 16 Khz signed linear */
2218         add_static_payload(119, ast_format_set(&tmpfmt, AST_FORMAT_SPEEX32, 0), 0);
2219         add_static_payload(121, NULL, AST_RTP_CISCO_DTMF);   /* Must be type 121 */
2220
2221         return 0;
2222 }