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