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