Merged revisions 344493 via svnmerge from
[asterisk/asterisk.git] / main / bridging.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2007 - 2009, 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 Channel Bridging API
22  *
23  * \author Joshua Colp <jcolp@digium.com>
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include <signal.h>
31
32 #include "asterisk/logger.h"
33 #include "asterisk/channel.h"
34 #include "asterisk/options.h"
35 #include "asterisk/utils.h"
36 #include "asterisk/lock.h"
37 #include "asterisk/linkedlists.h"
38 #include "asterisk/bridging.h"
39 #include "asterisk/bridging_technology.h"
40 #include "asterisk/app.h"
41 #include "asterisk/file.h"
42 #include "asterisk/module.h"
43 #include "asterisk/astobj2.h"
44
45 static AST_RWLIST_HEAD_STATIC(bridge_technologies, ast_bridge_technology);
46
47 /* Initial starting point for the bridge array of channels */
48 #define BRIDGE_ARRAY_START 128
49
50 /* Grow rate of bridge array of channels */
51 #define BRIDGE_ARRAY_GROW 32
52
53 static void cleanup_video_mode(struct ast_bridge *bridge);
54
55 /*! Default DTMF keys for built in features */
56 static char builtin_features_dtmf[AST_BRIDGE_BUILTIN_END][MAXIMUM_DTMF_FEATURE_STRING];
57
58 /*! Function handlers for the built in features */
59 static void *builtin_features_handlers[AST_BRIDGE_BUILTIN_END];
60
61 int __ast_bridge_technology_register(struct ast_bridge_technology *technology, struct ast_module *module)
62 {
63         struct ast_bridge_technology *current = NULL;
64
65         /* Perform a sanity check to make sure the bridge technology conforms to our needed requirements */
66         if (ast_strlen_zero(technology->name) || !technology->capabilities || !technology->write) {
67                 ast_log(LOG_WARNING, "Bridge technology %s failed registration sanity check.\n", technology->name);
68                 return -1;
69         }
70
71         AST_RWLIST_WRLOCK(&bridge_technologies);
72
73         /* Look for duplicate bridge technology already using this name, or already registered */
74         AST_RWLIST_TRAVERSE(&bridge_technologies, current, entry) {
75                 if ((!strcasecmp(current->name, technology->name)) || (current == technology)) {
76                         ast_log(LOG_WARNING, "A bridge technology of %s already claims to exist in our world.\n", technology->name);
77                         AST_RWLIST_UNLOCK(&bridge_technologies);
78                         return -1;
79                 }
80         }
81
82         /* Copy module pointer so reference counting can keep the module from unloading */
83         technology->mod = module;
84
85         /* Insert our new bridge technology into the list and print out a pretty message */
86         AST_RWLIST_INSERT_TAIL(&bridge_technologies, technology, entry);
87
88         AST_RWLIST_UNLOCK(&bridge_technologies);
89
90         if (option_verbose > 1) {
91                 ast_verbose(VERBOSE_PREFIX_2 "Registered bridge technology %s\n", technology->name);
92         }
93
94         return 0;
95 }
96
97 int ast_bridge_technology_unregister(struct ast_bridge_technology *technology)
98 {
99         struct ast_bridge_technology *current = NULL;
100
101         AST_RWLIST_WRLOCK(&bridge_technologies);
102
103         /* Ensure the bridge technology is registered before removing it */
104         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&bridge_technologies, current, entry) {
105                 if (current == technology) {
106                         AST_RWLIST_REMOVE_CURRENT(entry);
107                         if (option_verbose > 1) {
108                                 ast_verbose(VERBOSE_PREFIX_2 "Unregistered bridge technology %s\n", technology->name);
109                         }
110                         break;
111                 }
112         }
113         AST_RWLIST_TRAVERSE_SAFE_END;
114
115         AST_RWLIST_UNLOCK(&bridge_technologies);
116
117         return current ? 0 : -1;
118 }
119
120 void ast_bridge_change_state(struct ast_bridge_channel *bridge_channel, enum ast_bridge_channel_state new_state)
121 {
122         /* Change the state on the bridge channel */
123         bridge_channel->state = new_state;
124
125         /* Only poke the channel's thread if it is not us */
126         if (!pthread_equal(pthread_self(), bridge_channel->thread)) {
127                 pthread_kill(bridge_channel->thread, SIGURG);
128                 ao2_lock(bridge_channel);
129                 ast_cond_signal(&bridge_channel->cond);
130                 ao2_unlock(bridge_channel);
131         }
132
133         return;
134 }
135
136 /*! \brief Helper function to poke the bridge thread */
137 static void bridge_poke(struct ast_bridge *bridge)
138 {
139         /* Poke the thread just in case */
140         if (bridge->thread != AST_PTHREADT_NULL && bridge->thread != AST_PTHREADT_STOP) {
141                 pthread_kill(bridge->thread, SIGURG);
142         }
143
144         return;
145 }
146
147 /*! \brief Helper function to add a channel to the bridge array
148  *
149  * \note This function assumes the bridge is locked.
150  */
151 static void bridge_array_add(struct ast_bridge *bridge, struct ast_channel *chan)
152 {
153         /* We have to make sure the bridge thread is not using the bridge array before messing with it */
154         while (bridge->waiting) {
155                 bridge_poke(bridge);
156                 sched_yield();
157         }
158
159         bridge->array[bridge->array_num++] = chan;
160
161         ast_debug(1, "Added channel %s(%p) to bridge array on %p, new count is %d\n", chan->name, chan, bridge, (int)bridge->array_num);
162
163         /* If the next addition of a channel will exceed our array size grow it out */
164         if (bridge->array_num == bridge->array_size) {
165                 struct ast_channel **tmp;
166                 ast_debug(1, "Growing bridge array on %p from %d to %d\n", bridge, (int)bridge->array_size, (int)bridge->array_size + BRIDGE_ARRAY_GROW);
167                 if (!(tmp = ast_realloc(bridge->array, (bridge->array_size + BRIDGE_ARRAY_GROW) * sizeof(struct ast_channel *)))) {
168                         ast_log(LOG_ERROR, "Failed to allocate more space for another channel on bridge '%p', this is not going to end well\n", bridge);
169                         return;
170                 }
171                 bridge->array = tmp;
172                 bridge->array_size += BRIDGE_ARRAY_GROW;
173         }
174
175         return;
176 }
177
178 /*! \brief Helper function to remove a channel from the bridge array
179  *
180  * \note This function assumes the bridge is locked.
181  */
182 static void bridge_array_remove(struct ast_bridge *bridge, struct ast_channel *chan)
183 {
184         int i;
185
186         /* We have to make sure the bridge thread is not using the bridge array before messing with it */
187         while (bridge->waiting) {
188                 bridge_poke(bridge);
189                 sched_yield();
190         }
191
192         for (i = 0; i < bridge->array_num; i++) {
193                 if (bridge->array[i] == chan) {
194                         bridge->array[i] = (bridge->array[(bridge->array_num - 1)] != chan ? bridge->array[(bridge->array_num - 1)] : NULL);
195                         bridge->array[(bridge->array_num - 1)] = NULL;
196                         bridge->array_num--;
197                         ast_debug(1, "Removed channel %p from bridge array on %p, new count is %d\n", chan, bridge, (int)bridge->array_num);
198                         break;
199                 }
200         }
201
202         return;
203 }
204
205 /*! \brief Helper function to find a bridge channel given a channel */
206 static struct ast_bridge_channel *find_bridge_channel(struct ast_bridge *bridge, struct ast_channel *chan)
207 {
208         struct ast_bridge_channel *bridge_channel = NULL;
209
210         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
211                 if (bridge_channel->chan == chan) {
212                         break;
213                 }
214         }
215
216         return bridge_channel;
217 }
218
219 /*! \brief Internal function to see whether a bridge should dissolve, and if so do it */
220 static void bridge_check_dissolve(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
221 {
222         struct ast_bridge_channel *bridge_channel2 = NULL;
223
224         if (!ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE) && (!bridge_channel->features || !bridge_channel->features->usable || !ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_FLAG_DISSOLVE))) {
225                 return;
226         }
227
228         ast_debug(1, "Dissolving bridge %p\n", bridge);
229
230         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel2, entry) {
231                 if (bridge_channel2->state != AST_BRIDGE_CHANNEL_STATE_END && bridge_channel2->state != AST_BRIDGE_CHANNEL_STATE_DEPART) {
232                         ast_bridge_change_state(bridge_channel2, AST_BRIDGE_CHANNEL_STATE_HANGUP);
233                 }
234         }
235
236         /* Since all the channels are going away let's go ahead and stop our on thread */
237         bridge->stop = 1;
238
239         return;
240 }
241
242 /*! \brief Internal function to handle DTMF from a channel */
243 static struct ast_frame *bridge_handle_dtmf(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
244 {
245         struct ast_bridge_features *features = (bridge_channel->features ? bridge_channel->features : &bridge->features);
246         struct ast_bridge_features_hook *hook = NULL;
247
248         /* If the features structure we grabbed is not usable immediately return the frame */
249         if (!features->usable) {
250                 return frame;
251         }
252
253         /* See if this DTMF matches the beginnings of any feature hooks, if so we switch to the feature state to either execute the feature or collect more DTMF */
254         AST_LIST_TRAVERSE(&features->hooks, hook, entry) {
255                 if (hook->dtmf[0] == frame->subclass.integer) {
256                         ast_frfree(frame);
257                         frame = NULL;
258                         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_FEATURE);
259                         break;
260                 }
261         }
262
263         return frame;
264 }
265
266 /*! \brief Internal function used to determine whether a control frame should be dropped or not */
267 static int bridge_drop_control_frame(int subclass)
268 {
269         switch (subclass) {
270         case AST_CONTROL_ANSWER:
271         case -1:
272                 return 1;
273         default:
274                 return 0;
275         }
276 }
277
278 void ast_bridge_notify_talking(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, int started_talking)
279 {
280         if (started_talking) {
281                 ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_START_TALKING);
282         } else {
283                 ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_STOP_TALKING);
284         }
285 }
286
287 void ast_bridge_handle_trip(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_channel *chan, int outfd)
288 {
289         /* If no bridge channel has been provided and the actual channel has been provided find it */
290         if (chan && !bridge_channel) {
291                 bridge_channel = find_bridge_channel(bridge, chan);
292         }
293
294         /* If a bridge channel with actual channel is present read a frame and handle it */
295         if (chan && bridge_channel) {
296                 struct ast_frame *frame = (((bridge->features.mute) || (bridge_channel->features && bridge_channel->features->mute)) ? ast_read_noaudio(chan) : ast_read(chan));
297
298                 /* This is pretty simple... see if they hung up */
299                 if (!frame || (frame->frametype == AST_FRAME_CONTROL && frame->subclass.integer == AST_CONTROL_HANGUP)) {
300                         /* Signal the thread that is handling the bridged channel that it should be ended */
301                         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_END);
302                 } else if (frame->frametype == AST_FRAME_CONTROL && bridge_drop_control_frame(frame->subclass.integer)) {
303                         ast_debug(1, "Dropping control frame from bridge channel %p\n", bridge_channel);
304                 } else if (frame->frametype == AST_FRAME_DTMF_BEGIN || frame->frametype == AST_FRAME_DTMF_END) {
305                         int dtmf_passthrough = bridge_channel->features ?
306                                 bridge_channel->features->dtmf_passthrough :
307                                 bridge->features.dtmf_passthrough;
308
309                         if (frame->frametype == AST_FRAME_DTMF_BEGIN) {
310                                 frame = bridge_handle_dtmf(bridge, bridge_channel, frame);
311                         }
312
313                         if (frame && dtmf_passthrough) {
314                                 bridge->technology->write(bridge, bridge_channel, frame);
315                         }
316                 } else {
317                         /* Simply write the frame out to the bridge technology if it still exists */
318                         bridge->technology->write(bridge, bridge_channel, frame);
319                 }
320
321                 if (frame) {
322                         ast_frfree(frame);
323                 }
324                 return;
325         }
326
327         /* If a file descriptor actually tripped pass it off to the bridge technology */
328         if (outfd > -1 && bridge->technology->fd) {
329                 bridge->technology->fd(bridge, bridge_channel, outfd);
330                 return;
331         }
332
333         /* If all else fails just poke the bridge */
334         if (bridge->technology->poke && bridge_channel) {
335                 bridge->technology->poke(bridge, bridge_channel);
336                 return;
337         }
338
339         return;
340 }
341
342 /*! \brief Generic thread loop, TODO: Rethink this/improve it */
343 static int generic_thread_loop(struct ast_bridge *bridge)
344 {
345         while (!bridge->stop && !bridge->refresh && bridge->array_num) {
346                 struct ast_channel *winner = NULL;
347                 int to = -1;
348
349                 /* Move channels around for priority reasons if we have more than one channel in our array */
350                 if (bridge->array_num > 1) {
351                         struct ast_channel *first = bridge->array[0];
352                         memmove(bridge->array, bridge->array + 1, sizeof(struct ast_channel *) * (bridge->array_num - 1));
353                         bridge->array[(bridge->array_num - 1)] = first;
354                 }
355
356                 /* Wait on the channels */
357                 bridge->waiting = 1;
358                 ao2_unlock(bridge);
359                 winner = ast_waitfor_n(bridge->array, (int)bridge->array_num, &to);
360                 bridge->waiting = 0;
361                 ao2_lock(bridge);
362
363                 /* Process whatever they did */
364                 ast_bridge_handle_trip(bridge, NULL, winner, -1);
365         }
366
367         return 0;
368 }
369
370 /*! \brief Bridge thread function */
371 static void *bridge_thread(void *data)
372 {
373         struct ast_bridge *bridge = data;
374         int res = 0;
375
376         ao2_lock(bridge);
377
378         ast_debug(1, "Started bridge thread for %p\n", bridge);
379
380         /* Loop around until we are told to stop */
381         while (!bridge->stop && bridge->array_num && !res) {
382                 /* In case the refresh bit was set simply set it back to off */
383                 bridge->refresh = 0;
384
385                 ast_debug(1, "Launching bridge thread function %p for bridge %p\n", (bridge->technology->thread ? bridge->technology->thread : &generic_thread_loop), bridge);
386
387                 /* Execute the appropriate thread function. If the technology does not provide one we use the generic one */
388                 res = (bridge->technology->thread ? bridge->technology->thread(bridge) : generic_thread_loop(bridge));
389         }
390
391         ast_debug(1, "Ending bridge thread for %p\n", bridge);
392
393         /* Indicate the bridge thread is no longer active */
394         bridge->thread = AST_PTHREADT_NULL;
395         ao2_unlock(bridge);
396
397         ao2_ref(bridge, -1);
398
399         return NULL;
400 }
401
402 /*! \brief Helper function used to find the "best" bridge technology given a specified capabilities */
403 static struct ast_bridge_technology *find_best_technology(uint32_t capabilities)
404 {
405         struct ast_bridge_technology *current = NULL, *best = NULL;
406
407         AST_RWLIST_RDLOCK(&bridge_technologies);
408         AST_RWLIST_TRAVERSE(&bridge_technologies, current, entry) {
409                 if (current->suspended) {
410                         ast_debug(1, "Bridge technology %s is suspended. Skipping.\n", current->name);
411                         continue;
412                 }
413                 if (!(current->capabilities & capabilities)) {
414                         ast_debug(1, "Bridge technology %s does not have the capabilities we need.\n", current->name);
415                         continue;
416                 }
417                 if (best && best->preference < current->preference) {
418                         ast_debug(1, "Bridge technology %s has preference %d while %s has preference %d. Skipping.\n", current->name, current->preference, best->name, best->preference);
419                         continue;
420                 }
421                 best = current;
422         }
423
424         if (best) {
425                 /* Increment it's module reference count if present so it does not get unloaded while in use */
426                 if (best->mod) {
427                         ast_module_ref(best->mod);
428                 }
429                 ast_debug(1, "Chose bridge technology %s\n", best->name);
430         }
431
432         AST_RWLIST_UNLOCK(&bridge_technologies);
433
434         return best;
435 }
436
437 static void destroy_bridge(void *obj)
438 {
439         struct ast_bridge *bridge = obj;
440
441         ast_debug(1, "Actually destroying bridge %p, nobody wants it anymore\n", bridge);
442
443         /* Pass off the bridge to the technology to destroy if needed */
444         if (bridge->technology->destroy) {
445                 ast_debug(1, "Giving bridge technology %s the bridge structure %p to destroy\n", bridge->technology->name, bridge);
446                 if (bridge->technology->destroy(bridge)) {
447                         ast_debug(1, "Bridge technology %s failed to destroy bridge structure %p... trying our best\n", bridge->technology->name, bridge);
448                 }
449         }
450
451         /* We are no longer using the bridge technology so decrement the module reference count on it */
452         if (bridge->technology->mod) {
453                 ast_module_unref(bridge->technology->mod);
454         }
455
456         /* Last but not least clean up the features configuration */
457         ast_bridge_features_cleanup(&bridge->features);
458
459         /* Drop the array of channels */
460         ast_free(bridge->array);
461
462         cleanup_video_mode(bridge);
463
464         return;
465 }
466
467 struct ast_bridge *ast_bridge_new(uint32_t capabilities, int flags)
468 {
469         struct ast_bridge *bridge = NULL;
470         struct ast_bridge_technology *bridge_technology = NULL;
471
472         /* If we need to be a smart bridge see if we can move between 1to1 and multimix bridges */
473         if (flags & AST_BRIDGE_FLAG_SMART) {
474                 struct ast_bridge *other_bridge;
475
476                 if (!(other_bridge = ast_bridge_new((capabilities & AST_BRIDGE_CAPABILITY_1TO1MIX) ? AST_BRIDGE_CAPABILITY_MULTIMIX : AST_BRIDGE_CAPABILITY_1TO1MIX, 0))) {
477                         return NULL;
478                 }
479
480                 ast_bridge_destroy(other_bridge);
481         }
482
483         /* If capabilities were provided use our helper function to find the "best" bridge technology, otherwise we can
484          * just look for the most basic capability needed, single 1to1 mixing. */
485         bridge_technology = (capabilities ? find_best_technology(capabilities) : find_best_technology(AST_BRIDGE_CAPABILITY_1TO1MIX));
486
487         /* If no bridge technology was found we can't possibly do bridging so fail creation of the bridge */
488         if (!bridge_technology) {
489                 return NULL;
490         }
491
492         /* We have everything we need to create this bridge... so allocate the memory, link things together, and fire her up! */
493         if (!(bridge = ao2_alloc(sizeof(*bridge), destroy_bridge))) {
494                 return NULL;
495         }
496
497         bridge->technology = bridge_technology;
498         bridge->thread = AST_PTHREADT_NULL;
499
500         /* Create an array of pointers for the channels that will be joining us */
501         bridge->array = ast_calloc(BRIDGE_ARRAY_START, sizeof(struct ast_channel*));
502         bridge->array_size = BRIDGE_ARRAY_START;
503
504         ast_set_flag(&bridge->feature_flags, flags);
505
506         /* Pass off the bridge to the technology to manipulate if needed */
507         if (bridge->technology->create) {
508                 ast_debug(1, "Giving bridge technology %s the bridge structure %p to setup\n", bridge->technology->name, bridge);
509                 if (bridge->technology->create(bridge)) {
510                         ast_debug(1, "Bridge technology %s failed to setup bridge structure %p\n", bridge->technology->name, bridge);
511                         ao2_ref(bridge, -1);
512                         bridge = NULL;
513                 }
514         }
515
516         return bridge;
517 }
518
519 int ast_bridge_check(uint32_t capabilities)
520 {
521         struct ast_bridge_technology *bridge_technology = NULL;
522
523         if (!(bridge_technology = find_best_technology(capabilities))) {
524                 return 0;
525         }
526
527         ast_module_unref(bridge_technology->mod);
528
529         return 1;
530 }
531
532 int ast_bridge_destroy(struct ast_bridge *bridge)
533 {
534         struct ast_bridge_channel *bridge_channel = NULL;
535
536         ao2_lock(bridge);
537
538         bridge->stop = 1;
539
540         bridge_poke(bridge);
541
542         ast_debug(1, "Telling all channels in bridge %p to end and leave the party\n", bridge);
543
544         /* Drop every bridged channel, the last one will cause the bridge thread (if it exists) to exit */
545         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
546                 ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_END);
547         }
548
549         ao2_unlock(bridge);
550
551         ao2_ref(bridge, -1);
552
553         return 0;
554 }
555
556 static int bridge_make_compatible(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
557 {
558         struct ast_format formats[2];
559         ast_format_copy(&formats[0], &bridge_channel->chan->readformat);
560         ast_format_copy(&formats[1], &bridge_channel->chan->writeformat);
561
562         /* Are the formats currently in use something ths bridge can handle? */
563         if (!ast_format_cap_iscompatible(bridge->technology->format_capabilities, &bridge_channel->chan->readformat)) {
564                 struct ast_format best_format;
565                 ast_best_codec(bridge->technology->format_capabilities, &best_format);
566
567                 /* Read format is a no go... */
568                 if (option_debug) {
569                         char codec_buf[512];
570                         ast_debug(1, "Bridge technology %s wants to read any of formats %s but channel has %s\n", bridge->technology->name,
571                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf), bridge->technology->format_capabilities),
572                                 ast_getformatname(&formats[0]));
573                 }
574                 /* Switch read format to the best one chosen */
575                 if (ast_set_read_format(bridge_channel->chan, &best_format)) {
576                         ast_log(LOG_WARNING, "Failed to set channel %s to read format %s\n", bridge_channel->chan->name, ast_getformatname(&best_format));
577                         return -1;
578                 }
579                 ast_debug(1, "Bridge %p put channel %s into read format %s\n", bridge, bridge_channel->chan->name, ast_getformatname(&best_format));
580         } else {
581                 ast_debug(1, "Bridge %p is happy that channel %s already has read format %s\n", bridge, bridge_channel->chan->name, ast_getformatname(&formats[0]));
582         }
583
584         if (!ast_format_cap_iscompatible(bridge->technology->format_capabilities, &formats[1])) {
585                 struct ast_format best_format;
586                 ast_best_codec(bridge->technology->format_capabilities, &best_format);
587
588                 /* Write format is a no go... */
589                 if (option_debug) {
590                         char codec_buf[512];
591                         ast_debug(1, "Bridge technology %s wants to write any of formats %s but channel has %s\n", bridge->technology->name,
592                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf), bridge->technology->format_capabilities),
593                                 ast_getformatname(&formats[1]));
594                 }
595                 /* Switch write format to the best one chosen */
596                 if (ast_set_write_format(bridge_channel->chan, &best_format)) {
597                         ast_log(LOG_WARNING, "Failed to set channel %s to write format %s\n", bridge_channel->chan->name, ast_getformatname(&best_format));
598                         return -1;
599                 }
600                 ast_debug(1, "Bridge %p put channel %s into write format %s\n", bridge, bridge_channel->chan->name, ast_getformatname(&best_format));
601         } else {
602                 ast_debug(1, "Bridge %p is happy that channel %s already has write format %s\n", bridge, bridge_channel->chan->name, ast_getformatname(&formats[1]));
603         }
604
605         return 0;
606 }
607
608 /*! \brief Perform the smart bridge operation. Basically sees if a new bridge technology should be used instead of the current one. */
609 static int smart_bridge_operation(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, int count)
610 {
611         uint32_t new_capabilities = 0;
612         struct ast_bridge_technology *new_technology = NULL, *old_technology = bridge->technology;
613         struct ast_bridge temp_bridge = {
614                 .technology = bridge->technology,
615                 .bridge_pvt = bridge->bridge_pvt,
616         };
617         struct ast_bridge_channel *bridge_channel2 = NULL;
618
619         /* Based on current feature determine whether we want to change bridge technologies or not */
620         if (bridge->technology->capabilities & AST_BRIDGE_CAPABILITY_1TO1MIX) {
621                 if (count <= 2) {
622                         ast_debug(1, "Bridge %p channel count (%d) is within limits for bridge technology %s, not performing smart bridge operation.\n", bridge, count, bridge->technology->name);
623                         return 0;
624                 }
625                 new_capabilities = AST_BRIDGE_CAPABILITY_MULTIMIX;
626         } else if (bridge->technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX) {
627                 if (count > 2) {
628                         ast_debug(1, "Bridge %p channel count (%d) is within limits for bridge technology %s, not performing smart bridge operation.\n", bridge, count, bridge->technology->name);
629                         return 0;
630                 }
631                 new_capabilities = AST_BRIDGE_CAPABILITY_1TO1MIX;
632         }
633
634         if (!new_capabilities) {
635                 ast_debug(1, "Bridge '%p' has no new capabilities, not performing smart bridge operation.\n", bridge);
636                 return 0;
637         }
638
639         /* Attempt to find a new bridge technology to satisfy the capabilities */
640         if (!(new_technology = find_best_technology(new_capabilities))) {
641                 return -1;
642         }
643
644         ast_debug(1, "Performing smart bridge operation on bridge %p, moving from bridge technology %s to %s\n", bridge, old_technology->name, new_technology->name);
645
646         /* If a thread is currently executing for the current technology tell it to stop */
647         if (bridge->thread != AST_PTHREADT_NULL) {
648                 /* If the new bridge technology also needs a thread simply tell the bridge thread to refresh itself. This has the benefit of not incurring the cost/time of tearing down and bringing up a new thread. */
649                 if (new_technology->capabilities & AST_BRIDGE_CAPABILITY_THREAD) {
650                         ast_debug(1, "Telling current bridge thread for bridge %p to refresh\n", bridge);
651                         bridge->refresh = 1;
652                         bridge_poke(bridge);
653                 } else {
654                         pthread_t bridge_thread = bridge->thread;
655                         ast_debug(1, "Telling current bridge thread for bridge %p to stop\n", bridge);
656                         bridge->stop = 1;
657                         bridge_poke(bridge);
658                         ao2_unlock(bridge);
659                         pthread_join(bridge_thread, NULL);
660                         ao2_lock(bridge);
661                 }
662         }
663
664         /* Since we are soon going to pass this bridge to a new technology we need to NULL out the bridge_pvt pointer but don't worry as it still exists in temp_bridge, ditto for the old technology */
665         bridge->bridge_pvt = NULL;
666         bridge->technology = new_technology;
667
668         /* Pass the bridge to the new bridge technology so it can set it up */
669         if (new_technology->create) {
670                 ast_debug(1, "Giving bridge technology %s the bridge structure %p to setup\n", new_technology->name, bridge);
671                 if (new_technology->create(bridge)) {
672                         ast_debug(1, "Bridge technology %s failed to setup bridge structure %p\n", new_technology->name, bridge);
673                 }
674         }
675
676         /* Move existing channels over to the new technology, while taking them away from the old one */
677         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel2, entry) {
678                 /* Skip over channel that initiated the smart bridge operation */
679                 if (bridge_channel == bridge_channel2) {
680                         continue;
681                 }
682
683                 /* First we part them from the old technology */
684                 if (old_technology->leave) {
685                         ast_debug(1, "Giving bridge technology %s notification that %p is leaving bridge %p (really %p)\n", old_technology->name, bridge_channel2, &temp_bridge, bridge);
686                         if (old_technology->leave(&temp_bridge, bridge_channel2)) {
687                                 ast_debug(1, "Bridge technology %s failed to allow %p (really %p) to leave bridge %p\n", old_technology->name, bridge_channel2, &temp_bridge, bridge);
688                         }
689                 }
690
691                 /* Second we make them compatible again with the bridge */
692                 bridge_make_compatible(bridge, bridge_channel2);
693
694                 /* Third we join them to the new technology */
695                 if (new_technology->join) {
696                         ast_debug(1, "Giving bridge technology %s notification that %p is joining bridge %p\n", new_technology->name, bridge_channel2, bridge);
697                         if (new_technology->join(bridge, bridge_channel2)) {
698                                 ast_debug(1, "Bridge technology %s failed to join %p to bridge %p\n", new_technology->name, bridge_channel2, bridge);
699                         }
700                 }
701
702                 /* Fourth we tell them to wake up so they become aware that they above has happened */
703                 pthread_kill(bridge_channel2->thread, SIGURG);
704                 ao2_lock(bridge_channel2);
705                 ast_cond_signal(&bridge_channel2->cond);
706                 ao2_unlock(bridge_channel2);
707         }
708
709         /* Now that all the channels have been moved over we need to get rid of all the information the old technology may have left around */
710         if (old_technology->destroy) {
711                 ast_debug(1, "Giving bridge technology %s the bridge structure %p (really %p) to destroy\n", old_technology->name, &temp_bridge, bridge);
712                 if (old_technology->destroy(&temp_bridge)) {
713                         ast_debug(1, "Bridge technology %s failed to destroy bridge structure %p (really %p)... some memory may have leaked\n", old_technology->name, &temp_bridge, bridge);
714                 }
715         }
716
717         /* Finally if the old technology has module referencing remove our reference, we are no longer going to use it */
718         if (old_technology->mod) {
719                 ast_module_unref(old_technology->mod);
720         }
721
722         return 0;
723 }
724
725 /*! \brief Run in a multithreaded model. Each joined channel does writing/reading in their own thread. TODO: Improve */
726 static enum ast_bridge_channel_state bridge_channel_join_multithreaded(struct ast_bridge_channel *bridge_channel)
727 {
728         int fds[4] = { -1, }, nfds = 0, i = 0, outfd = -1, ms = -1;
729         struct ast_channel *chan = NULL;
730
731         /* Add any file descriptors we may want to monitor */
732         if (bridge_channel->bridge->technology->fd) {
733                 for (i = 0; i < 4; i ++) {
734                         if (bridge_channel->fds[i] >= 0) {
735                                 fds[nfds++] = bridge_channel->fds[i];
736                         }
737                 }
738         }
739
740         ao2_unlock(bridge_channel->bridge);
741
742         ao2_lock(bridge_channel);
743         /* Wait for data to either come from the channel or us to be signalled */
744         if (!bridge_channel->suspended) {
745                 ao2_unlock(bridge_channel);
746                 ast_debug(10, "Going into a multithreaded waitfor for bridge channel %p of bridge %p\n", bridge_channel, bridge_channel->bridge);
747                 chan = ast_waitfor_nandfds(&bridge_channel->chan, 1, fds, nfds, NULL, &outfd, &ms);
748         } else {
749                 ast_debug(10, "Going into a multithreaded signal wait for bridge channel %p of bridge %p\n", bridge_channel, bridge_channel->bridge);
750                 ast_cond_wait(&bridge_channel->cond, ao2_object_get_lockaddr(bridge_channel));
751                 ao2_unlock(bridge_channel);
752         }
753
754         ao2_lock(bridge_channel->bridge);
755
756         if (!bridge_channel->suspended) {
757                 ast_bridge_handle_trip(bridge_channel->bridge, bridge_channel, chan, outfd);
758         }
759
760         return bridge_channel->state;
761 }
762
763 /*! \brief Run in a singlethreaded model. Each joined channel yields itself to the main bridge thread. TODO: Improve */
764 static enum ast_bridge_channel_state bridge_channel_join_singlethreaded(struct ast_bridge_channel *bridge_channel)
765 {
766         ao2_unlock(bridge_channel->bridge);
767         ao2_lock(bridge_channel);
768         if (bridge_channel->state == AST_BRIDGE_CHANNEL_STATE_WAIT) {
769                 ast_debug(1, "Going into a single threaded signal wait for bridge channel %p of bridge %p\n", bridge_channel, bridge_channel->bridge);
770                 ast_cond_wait(&bridge_channel->cond, ao2_object_get_lockaddr(bridge_channel));
771         }
772         ao2_unlock(bridge_channel);
773         ao2_lock(bridge_channel->bridge);
774
775         return bridge_channel->state;
776 }
777
778 /*! \brief Internal function that suspends a channel from a bridge */
779 static void bridge_channel_suspend(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
780 {
781         ao2_lock(bridge_channel);
782         bridge_channel->suspended = 1;
783         bridge_array_remove(bridge, bridge_channel->chan);
784         ao2_unlock(bridge_channel);
785
786         if (bridge->technology->suspend) {
787                 bridge->technology->suspend(bridge, bridge_channel);
788         }
789
790         return;
791 }
792
793 /*! \brief Internal function that unsuspends a channel from a bridge */
794 static void bridge_channel_unsuspend(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
795 {
796         ao2_lock(bridge_channel);
797         bridge_channel->suspended = 0;
798         bridge_array_add(bridge, bridge_channel->chan);
799         ast_cond_signal(&bridge_channel->cond);
800         ao2_unlock(bridge_channel);
801
802         if (bridge->technology->unsuspend) {
803                 bridge->technology->unsuspend(bridge, bridge_channel);
804         }
805
806
807
808         return;
809 }
810
811 /*!
812  * \brief Internal function that executes a feature on a bridge channel
813  * \note Neither the bridge nor the bridge_channel locks should be held when entering
814  * this function.
815  */
816 static void bridge_channel_feature(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
817 {
818         struct ast_bridge_features *features = (bridge_channel->features ? bridge_channel->features : &bridge->features);
819         struct ast_bridge_features_hook *hook = NULL;
820         char dtmf[MAXIMUM_DTMF_FEATURE_STRING] = "";
821         int look_for_dtmf = 1, dtmf_len = 0;
822
823         /* The channel is now under our control and we don't really want any begin frames to do our DTMF matching so disable 'em at the core level */
824         ast_set_flag(bridge_channel->chan, AST_FLAG_END_DTMF_ONLY);
825
826         /* Wait for DTMF on the channel and put it into a buffer. If the buffer matches any feature hook execute the hook. */
827         while (look_for_dtmf) {
828                 int res = ast_waitfordigit(bridge_channel->chan, 3000);
829
830                 /* If the above timed out simply exit */
831                 if (!res) {
832                         ast_debug(1, "DTMF feature string collection on bridge channel %p timed out\n", bridge_channel);
833                         break;
834                 } else if (res < 0) {
835                         ast_debug(1, "DTMF feature string collection failed on bridge channel %p for some reason\n", bridge_channel);
836                         break;
837                 }
838
839                 /* Add the above DTMF into the DTMF string so we can do our matching */
840                 dtmf[dtmf_len++] = res;
841
842                 ast_debug(1, "DTMF feature string on bridge channel %p is now '%s'\n", bridge_channel, dtmf);
843
844                 /* Assume that we do not want to look for DTMF any longer */
845                 look_for_dtmf = 0;
846
847                 /* See if a DTMF feature hook matches or can match */
848                 AST_LIST_TRAVERSE(&features->hooks, hook, entry) {
849                         /* If this hook matches just break out now */
850                         if (!strcmp(hook->dtmf, dtmf)) {
851                                 ast_debug(1, "DTMF feature hook %p matched DTMF string '%s' on bridge channel %p\n", hook, dtmf, bridge_channel);
852                                 look_for_dtmf = 0;
853                                 break;
854                         } else if (!strncmp(hook->dtmf, dtmf, dtmf_len)) {
855                                 ast_debug(1, "DTMF feature hook %p can match DTMF string '%s', it wants '%s', on bridge channel %p\n", hook, dtmf, hook->dtmf, bridge_channel);
856                                 look_for_dtmf = 1;
857                         } else {
858                                 ast_debug(1, "DTMF feature hook %p does not match DTMF string '%s', it wants '%s', on bridge channel %p\n", hook, dtmf, hook->dtmf, bridge_channel);
859                         }
860                 }
861
862                 /* If we have reached the maximum length of a DTMF feature string bail out */
863                 if (dtmf_len == MAXIMUM_DTMF_FEATURE_STRING) {
864                         break;
865                 }
866         }
867
868         /* Since we are done bringing DTMF in return to using both begin and end frames */
869         ast_clear_flag(bridge_channel->chan, AST_FLAG_END_DTMF_ONLY);
870
871         /* If a hook was actually matched execute it on this channel, otherwise stream up the DTMF to the other channels */
872         if (hook) {
873                 hook->callback(bridge, bridge_channel, hook->hook_pvt);
874                 /* If we are handing the channel off to an external hook for ownership,
875                  * we are not guaranteed what kind of state it will come back in.  If
876                  * the channel hungup, we need to detect that here. */
877                 if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
878                         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_END);
879                 }
880         } else {
881                 ast_bridge_dtmf_stream(bridge, dtmf, bridge_channel->chan);
882         }
883
884         /* if the channel is still in feature state, revert it back to wait state */
885         if (bridge_channel->state == AST_BRIDGE_CHANNEL_STATE_FEATURE) {
886                 ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_WAIT);
887         }
888
889         return;
890 }
891
892 static void bridge_channel_talking(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
893 {
894         struct ast_bridge_features *features = (bridge_channel->features ? bridge_channel->features : &bridge->features);
895
896         if (features && features->talker_cb) {
897                 features->talker_cb(bridge, bridge_channel, features->talker_pvt_data);
898         }
899         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_WAIT);
900 }
901
902 /*! \brief Internal function that plays back DTMF on a bridge channel */
903 static void bridge_channel_dtmf_stream(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
904 {
905         char dtmf_q[8] = "";
906
907         ast_copy_string(dtmf_q, bridge_channel->dtmf_stream_q, sizeof(dtmf_q));
908         bridge_channel->dtmf_stream_q[0] = '\0';
909
910         ast_debug(1, "Playing DTMF stream '%s' out to bridge channel %p\n", dtmf_q, bridge_channel);
911         ast_dtmf_stream(bridge_channel->chan, NULL, dtmf_q, 250, 0);
912
913         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_WAIT);
914
915         return;
916 }
917
918 /*! \brief Join a channel to a bridge and handle anything the bridge may want us to do */
919 static enum ast_bridge_channel_state bridge_channel_join(struct ast_bridge_channel *bridge_channel)
920 {
921         struct ast_format formats[2];
922         enum ast_bridge_channel_state state;
923         ast_format_copy(&formats[0], &bridge_channel->chan->readformat);
924         ast_format_copy(&formats[1], &bridge_channel->chan->writeformat);
925
926         /* Record the thread that will be the owner of us */
927         bridge_channel->thread = pthread_self();
928
929         ast_debug(1, "Joining bridge channel %p to bridge %p\n", bridge_channel, bridge_channel->bridge);
930
931         ao2_lock(bridge_channel->bridge);
932
933         state = bridge_channel->state;
934
935         /* Add channel into the bridge */
936         AST_LIST_INSERT_TAIL(&bridge_channel->bridge->channels, bridge_channel, entry);
937         bridge_channel->bridge->num++;
938
939         bridge_array_add(bridge_channel->bridge, bridge_channel->chan);
940
941         if (bridge_channel->swap) {
942                 struct ast_bridge_channel *bridge_channel2 = NULL;
943
944                 /* If we are performing a swap operation we do not need
945                  * to execute the smart bridge operation as the actual number
946                  * of channels involved will not have changed, we just need to
947                  * tell the other channel to leave */
948                 if ((bridge_channel2 = find_bridge_channel(bridge_channel->bridge, bridge_channel->swap))) {
949                         ast_debug(1, "Swapping bridge channel %p out from bridge %p so bridge channel %p can slip in\n", bridge_channel2, bridge_channel->bridge, bridge_channel);
950                         ast_bridge_change_state(bridge_channel2, AST_BRIDGE_CHANNEL_STATE_HANGUP);
951                 }
952
953                 bridge_channel->swap = NULL;
954         } else if (ast_test_flag(&bridge_channel->bridge->feature_flags, AST_BRIDGE_FLAG_SMART)) {
955                 /* Perform the smart bridge operation, basically see if we need to move around between technologies */
956                 smart_bridge_operation(bridge_channel->bridge, bridge_channel, bridge_channel->bridge->num);
957         }
958
959         /* Make the channel compatible with the bridge */
960         bridge_make_compatible(bridge_channel->bridge, bridge_channel);
961
962         /* Tell the bridge technology we are joining so they set us up */
963         if (bridge_channel->bridge->technology->join) {
964                 ast_debug(1, "Giving bridge technology %s notification that %p is joining bridge %p\n", bridge_channel->bridge->technology->name, bridge_channel, bridge_channel->bridge);
965                 if (bridge_channel->bridge->technology->join(bridge_channel->bridge, bridge_channel)) {
966                         ast_debug(1, "Bridge technology %s failed to join %p to bridge %p\n", bridge_channel->bridge->technology->name, bridge_channel, bridge_channel->bridge);
967                 }
968         }
969
970         /* Actually execute the respective threading model, and keep our bridge thread alive */
971         while (bridge_channel->state == AST_BRIDGE_CHANNEL_STATE_WAIT) {
972                 /* Update bridge pointer on channel */
973                 bridge_channel->chan->bridge = bridge_channel->bridge;
974                 /* If the technology requires a thread and one is not running, start it up */
975                 if (bridge_channel->bridge->thread == AST_PTHREADT_NULL && (bridge_channel->bridge->technology->capabilities & AST_BRIDGE_CAPABILITY_THREAD)) {
976                         bridge_channel->bridge->stop = 0;
977                         ast_debug(1, "Starting a bridge thread for bridge %p\n", bridge_channel->bridge);
978                         ao2_ref(bridge_channel->bridge, +1);
979                         if (ast_pthread_create(&bridge_channel->bridge->thread, NULL, bridge_thread, bridge_channel->bridge)) {
980                                 ast_debug(1, "Failed to create a bridge thread for bridge %p, giving it another go.\n", bridge_channel->bridge);
981                                 ao2_ref(bridge_channel->bridge, -1);
982                                 continue;
983                         }
984                 }
985                 /* Execute the threading model */
986                 state = (bridge_channel->bridge->technology->capabilities & AST_BRIDGE_CAPABILITY_MULTITHREADED ? bridge_channel_join_multithreaded(bridge_channel) : bridge_channel_join_singlethreaded(bridge_channel));
987                 /* Depending on the above state see what we need to do */
988                 switch (state) {
989                 case AST_BRIDGE_CHANNEL_STATE_FEATURE:
990                         bridge_channel_suspend(bridge_channel->bridge, bridge_channel);
991                         ao2_unlock(bridge_channel->bridge);
992                         bridge_channel_feature(bridge_channel->bridge, bridge_channel);
993                         ao2_lock(bridge_channel->bridge);
994                         bridge_channel_unsuspend(bridge_channel->bridge, bridge_channel);
995                         break;
996                 case AST_BRIDGE_CHANNEL_STATE_DTMF:
997                         bridge_channel_suspend(bridge_channel->bridge, bridge_channel);
998                         bridge_channel_dtmf_stream(bridge_channel->bridge, bridge_channel);
999                         bridge_channel_unsuspend(bridge_channel->bridge, bridge_channel);
1000                         break;
1001                 case AST_BRIDGE_CHANNEL_STATE_START_TALKING:
1002                 case AST_BRIDGE_CHANNEL_STATE_STOP_TALKING:
1003                         ao2_unlock(bridge_channel->bridge);
1004                         bridge_channel_talking(bridge_channel->bridge, bridge_channel);
1005                         ao2_lock(bridge_channel->bridge);
1006                         break;
1007                 default:
1008                         break;
1009                 }
1010         }
1011
1012         bridge_channel->chan->bridge = NULL;
1013
1014         /* See if we need to dissolve the bridge itself if they hung up */
1015         if (bridge_channel->state == AST_BRIDGE_CHANNEL_STATE_END) {
1016                 bridge_check_dissolve(bridge_channel->bridge, bridge_channel);
1017         }
1018
1019         /* Tell the bridge technology we are leaving so they tear us down */
1020         if (bridge_channel->bridge->technology->leave) {
1021                 ast_debug(1, "Giving bridge technology %s notification that %p is leaving bridge %p\n", bridge_channel->bridge->technology->name, bridge_channel, bridge_channel->bridge);
1022                 if (bridge_channel->bridge->technology->leave(bridge_channel->bridge, bridge_channel)) {
1023                         ast_debug(1, "Bridge technology %s failed to leave %p from bridge %p\n", bridge_channel->bridge->technology->name, bridge_channel, bridge_channel->bridge);
1024                 }
1025         }
1026
1027         /* Remove channel from the bridge */
1028         bridge_channel->bridge->num--;
1029         AST_LIST_REMOVE(&bridge_channel->bridge->channels, bridge_channel, entry);
1030
1031         bridge_array_remove(bridge_channel->bridge, bridge_channel->chan);
1032
1033         /* Perform the smart bridge operation if needed since a channel has left */
1034         if (ast_test_flag(&bridge_channel->bridge->feature_flags, AST_BRIDGE_FLAG_SMART)) {
1035                 smart_bridge_operation(bridge_channel->bridge, NULL, bridge_channel->bridge->num);
1036         }
1037
1038         ao2_unlock(bridge_channel->bridge);
1039
1040         /* Restore original formats of the channel as they came in */
1041         if (ast_format_cmp(&bridge_channel->chan->readformat, &formats[0]) == AST_FORMAT_CMP_NOT_EQUAL) {
1042                 ast_debug(1, "Bridge is returning %p to read format %s(%d)\n", bridge_channel, ast_getformatname(&formats[0]), formats[0].id);
1043                 if (ast_set_read_format(bridge_channel->chan, &formats[0])) {
1044                         ast_debug(1, "Bridge failed to return channel %p to read format %s(%d)\n", bridge_channel, ast_getformatname(&formats[0]), formats[0].id);
1045                 }
1046         }
1047         if (ast_format_cmp(&bridge_channel->chan->writeformat, &formats[1]) == AST_FORMAT_CMP_NOT_EQUAL) {
1048                 ast_debug(1, "Bridge is returning %p to write format %s(%d)\n", bridge_channel, ast_getformatname(&formats[1]), formats[1].id);
1049                 if (ast_set_write_format(bridge_channel->chan, &formats[1])) {
1050                         ast_debug(1, "Bridge failed to return channel %p to write format %s(%d)\n", bridge_channel, ast_getformatname(&formats[1]), formats[1].id);
1051                 }
1052         }
1053
1054         return bridge_channel->state;
1055 }
1056
1057 static void bridge_channel_destroy(void *obj)
1058 {
1059         struct ast_bridge_channel *bridge_channel = obj;
1060
1061         if (bridge_channel->bridge) {
1062                 ao2_ref(bridge_channel->bridge, -1);
1063                 bridge_channel->bridge = NULL;
1064         }
1065         /* Destroy elements of the bridge channel structure and the bridge channel structure itself */
1066         ast_cond_destroy(&bridge_channel->cond);
1067 }
1068
1069 static struct ast_bridge_channel *bridge_channel_alloc(struct ast_bridge *bridge)
1070 {
1071         struct ast_bridge_channel *bridge_channel = ao2_alloc(sizeof(struct ast_bridge_channel), bridge_channel_destroy);
1072         if (!(bridge_channel)) {
1073                 return NULL;
1074         }
1075         ast_cond_init(&bridge_channel->cond, NULL);
1076         if (bridge) {
1077                 bridge_channel->bridge = bridge;
1078                 ao2_ref(bridge_channel->bridge, +1);
1079         }
1080         return bridge_channel;
1081 }
1082
1083 enum ast_bridge_channel_state ast_bridge_join(struct ast_bridge *bridge,
1084         struct ast_channel *chan,
1085         struct ast_channel *swap,
1086         struct ast_bridge_features *features,
1087         struct ast_bridge_tech_optimizations *tech_args)
1088 {
1089         struct ast_bridge_channel *bridge_channel = bridge_channel_alloc(bridge);
1090         enum ast_bridge_channel_state state = AST_BRIDGE_CHANNEL_STATE_HANGUP;
1091
1092         if (!bridge_channel) {
1093                 return state;
1094         }
1095         if (tech_args) {
1096                 memcpy(&bridge_channel->tech_args, tech_args, sizeof(bridge_channel->tech_args));
1097         }
1098
1099         /* Initialize various other elements of the bridge channel structure that we can't do above */
1100         bridge_channel->chan = chan;
1101         bridge_channel->swap = swap;
1102         bridge_channel->features = features;
1103
1104         state = bridge_channel_join(bridge_channel);
1105
1106         /* Cleanup all the data in the bridge channel after it leaves the bridge. */
1107         ao2_lock(bridge_channel);
1108         bridge_channel->chan = NULL;
1109         bridge_channel->swap = NULL;
1110         bridge_channel->features = NULL;
1111         ao2_unlock(bridge_channel);
1112
1113         ao2_ref(bridge_channel, -1);
1114
1115         return state;
1116 }
1117
1118 /*! \brief Thread responsible for imparted bridged channels */
1119 static void *bridge_channel_thread(void *data)
1120 {
1121         struct ast_bridge_channel *bridge_channel = data;
1122         enum ast_bridge_channel_state state;
1123
1124         state = bridge_channel_join(bridge_channel);
1125
1126         /* If no other thread is going to take the channel then hang it up, or else we would have to service it until something else came along */
1127         if (state == AST_BRIDGE_CHANNEL_STATE_END || state == AST_BRIDGE_CHANNEL_STATE_HANGUP) {
1128                 ast_hangup(bridge_channel->chan);
1129         }
1130
1131         /* cleanup */
1132         ao2_lock(bridge_channel);
1133         bridge_channel->chan = NULL;
1134         bridge_channel->swap = NULL;
1135         bridge_channel->features = NULL;
1136         ao2_unlock(bridge_channel);
1137
1138         ao2_ref(bridge_channel, -1);
1139
1140         return NULL;
1141 }
1142
1143 int ast_bridge_impart(struct ast_bridge *bridge, struct ast_channel *chan, struct ast_channel *swap, struct ast_bridge_features *features)
1144 {
1145         struct ast_bridge_channel *bridge_channel = bridge_channel_alloc(bridge);
1146         /* Try to allocate a structure for the bridge channel */
1147         if (!(bridge_channel)) {
1148                 return -1;
1149         }
1150
1151         /* Setup various parameters */
1152         bridge_channel->chan = chan;
1153         bridge_channel->swap = swap;
1154         bridge_channel->features = features;
1155
1156         /* Actually create the thread that will handle the channel */
1157         if (ast_pthread_create(&bridge_channel->thread, NULL, bridge_channel_thread, bridge_channel)) {
1158                 ao2_ref(bridge_channel, -1);
1159                 return -1;
1160         }
1161
1162         return 0;
1163 }
1164
1165 int ast_bridge_depart(struct ast_bridge *bridge, struct ast_channel *chan)
1166 {
1167         struct ast_bridge_channel *bridge_channel = NULL;
1168         pthread_t thread;
1169
1170         ao2_lock(bridge);
1171
1172         /* Try to find the channel that we want to depart */
1173         if (!(bridge_channel = find_bridge_channel(bridge, chan))) {
1174                 ao2_unlock(bridge);
1175                 return -1;
1176         }
1177
1178         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_DEPART);
1179         thread = bridge_channel->thread;
1180
1181         ao2_unlock(bridge);
1182
1183         pthread_join(thread, NULL);
1184
1185         return 0;
1186 }
1187
1188 int ast_bridge_remove(struct ast_bridge *bridge, struct ast_channel *chan)
1189 {
1190         struct ast_bridge_channel *bridge_channel = NULL;
1191
1192         ao2_lock(bridge);
1193
1194         /* Try to find the channel that we want to remove */
1195         if (!(bridge_channel = find_bridge_channel(bridge, chan))) {
1196                 ao2_unlock(bridge);
1197                 return -1;
1198         }
1199
1200         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
1201
1202         ao2_unlock(bridge);
1203
1204         return 0;
1205 }
1206
1207 int ast_bridge_merge(struct ast_bridge *bridge0, struct ast_bridge *bridge1)
1208 {
1209         struct ast_bridge_channel *bridge_channel = NULL;
1210
1211         ao2_lock(bridge0);
1212         ao2_lock(bridge1);
1213
1214         /* If the first bridge currently has 2 channels and is not capable of becoming a multimixing bridge we can not merge */
1215         if ((bridge0->num + bridge1->num) > 2 && (!(bridge0->technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX) && !ast_test_flag(&bridge0->feature_flags, AST_BRIDGE_FLAG_SMART))) {
1216                 ao2_unlock(bridge1);
1217                 ao2_unlock(bridge0);
1218                 ast_debug(1, "Can't merge bridge %p into bridge %p, multimix is needed and it could not be acquired.\n", bridge1, bridge0);
1219                 return -1;
1220         }
1221
1222         ast_debug(1, "Merging channels from bridge %p into bridge %p\n", bridge1, bridge0);
1223
1224         /* Perform smart bridge operation on bridge we are merging into so it can change bridge technology if needed */
1225         if (smart_bridge_operation(bridge0, NULL, bridge0->num + bridge1->num)) {
1226                 ao2_unlock(bridge1);
1227                 ao2_unlock(bridge0);
1228                 ast_debug(1, "Can't merge bridge %p into bridge %p, tried to perform smart bridge operation and failed.\n", bridge1, bridge0);
1229                 return -1;
1230         }
1231
1232         /* If a thread is currently executing on bridge1 tell it to stop */
1233         if (bridge1->thread) {
1234                 ast_debug(1, "Telling bridge thread on bridge %p to stop as it is being merged into %p\n", bridge1, bridge0);
1235                 bridge1->thread = AST_PTHREADT_STOP;
1236         }
1237
1238         /* Move channels from bridge1 over to bridge0 */
1239         while ((bridge_channel = AST_LIST_REMOVE_HEAD(&bridge1->channels, entry))) {
1240                 /* Tell the technology handling bridge1 that the bridge channel is leaving */
1241                 if (bridge1->technology->leave) {
1242                         ast_debug(1, "Giving bridge technology %s notification that %p is leaving bridge %p\n", bridge1->technology->name, bridge_channel, bridge1);
1243                         if (bridge1->technology->leave(bridge1, bridge_channel)) {
1244                                 ast_debug(1, "Bridge technology %s failed to allow %p to leave bridge %p\n", bridge1->technology->name, bridge_channel, bridge1);
1245                         }
1246                 }
1247
1248                 /* Drop channel count and reference count on the bridge they are leaving */
1249                 bridge1->num--;
1250                 ao2_ref(bridge1, -1);
1251
1252                 bridge_array_remove(bridge1, bridge_channel->chan);
1253
1254                 /* Now add them into the bridge they are joining, increase channel count, and bump up reference count */
1255                 bridge_channel->bridge = bridge0;
1256                 AST_LIST_INSERT_TAIL(&bridge0->channels, bridge_channel, entry);
1257                 bridge0->num++;
1258                 ao2_ref(bridge0, +1);
1259
1260                 bridge_array_add(bridge0, bridge_channel->chan);
1261
1262                 /* Make the channel compatible with the new bridge it is joining or else formats would go amuck */
1263                 bridge_make_compatible(bridge0, bridge_channel);
1264
1265                 /* Tell the technology handling bridge0 that the bridge channel is joining */
1266                 if (bridge0->technology->join) {
1267                         ast_debug(1, "Giving bridge technology %s notification that %p is joining bridge %p\n", bridge0->technology->name, bridge_channel, bridge0);
1268                         if (bridge0->technology->join(bridge0, bridge_channel)) {
1269                                 ast_debug(1, "Bridge technology %s failed to join %p to bridge %p\n", bridge0->technology->name, bridge_channel, bridge0);
1270                         }
1271                 }
1272
1273                 /* Poke the bridge channel, this will cause it to wake up and execute the proper threading model for the new bridge it is in */
1274                 pthread_kill(bridge_channel->thread, SIGURG);
1275                 ao2_lock(bridge_channel);
1276                 ast_cond_signal(&bridge_channel->cond);
1277                 ao2_unlock(bridge_channel);
1278         }
1279
1280         ast_debug(1, "Merged channels from bridge %p into bridge %p\n", bridge1, bridge0);
1281
1282         ao2_unlock(bridge1);
1283         ao2_unlock(bridge0);
1284
1285         return 0;
1286 }
1287
1288 int ast_bridge_suspend(struct ast_bridge *bridge, struct ast_channel *chan)
1289 {
1290         struct ast_bridge_channel *bridge_channel;
1291
1292         ao2_lock(bridge);
1293
1294         if (!(bridge_channel = find_bridge_channel(bridge, chan))) {
1295                 ao2_unlock(bridge);
1296                 return -1;
1297         }
1298
1299         bridge_channel_suspend(bridge, bridge_channel);
1300
1301         ao2_unlock(bridge);
1302
1303         return 0;
1304 }
1305
1306 int ast_bridge_unsuspend(struct ast_bridge *bridge, struct ast_channel *chan)
1307 {
1308         struct ast_bridge_channel *bridge_channel;
1309
1310         ao2_lock(bridge);
1311
1312         if (!(bridge_channel = find_bridge_channel(bridge, chan))) {
1313                 ao2_unlock(bridge);
1314                 return -1;
1315         }
1316
1317         bridge_channel_unsuspend(bridge, bridge_channel);
1318
1319         ao2_unlock(bridge);
1320
1321         return 0;
1322 }
1323
1324 void ast_bridge_technology_suspend(struct ast_bridge_technology *technology)
1325 {
1326         technology->suspended = 1;
1327         return;
1328 }
1329
1330 void ast_bridge_technology_unsuspend(struct ast_bridge_technology *technology)
1331 {
1332         technology->suspended = 0;
1333         return;
1334 }
1335
1336 int ast_bridge_features_register(enum ast_bridge_builtin_feature feature, ast_bridge_features_hook_callback callback, const char *dtmf)
1337 {
1338         if (builtin_features_handlers[feature]) {
1339                 return -1;
1340         }
1341
1342         if (!ast_strlen_zero(dtmf)) {
1343                 ast_copy_string(builtin_features_dtmf[feature], dtmf, sizeof(builtin_features_dtmf[feature]));
1344         }
1345
1346         builtin_features_handlers[feature] = callback;
1347
1348         return 0;
1349 }
1350
1351 int ast_bridge_features_unregister(enum ast_bridge_builtin_feature feature)
1352 {
1353         if (!builtin_features_handlers[feature]) {
1354                 return -1;
1355         }
1356
1357         builtin_features_handlers[feature] = NULL;
1358
1359         return 0;
1360 }
1361
1362 int ast_bridge_features_hook(struct ast_bridge_features *features,
1363         const char *dtmf,
1364         ast_bridge_features_hook_callback callback,
1365         void *hook_pvt,
1366         ast_bridge_features_hook_pvt_destructor destructor)
1367 {
1368         struct ast_bridge_features_hook *hook = NULL;
1369
1370         /* Allocate new memory and setup it's various variables */
1371         if (!(hook = ast_calloc(1, sizeof(*hook)))) {
1372                 return -1;
1373         }
1374
1375         ast_copy_string(hook->dtmf, dtmf, sizeof(hook->dtmf));
1376         hook->callback = callback;
1377         hook->destructor = destructor;
1378         hook->hook_pvt = hook_pvt;
1379
1380         /* Once done we add it onto the list. Now it will be picked up when DTMF is used */
1381         AST_LIST_INSERT_TAIL(&features->hooks, hook, entry);
1382
1383         features->usable = 1;
1384
1385         return 0;
1386 }
1387
1388 int ast_bridge_features_set_talk_detector(struct ast_bridge_features *features,
1389         ast_bridge_talking_indicate_callback talker_cb,
1390         ast_bridge_talking_indicate_destructor talker_destructor,
1391         void *pvt_data)
1392 {
1393         features->talker_cb = talker_cb;
1394         features->talker_destructor_cb = talker_destructor;
1395         features->talker_pvt_data = pvt_data;
1396         return 0;
1397 }
1398
1399 int ast_bridge_features_enable(struct ast_bridge_features *features, enum ast_bridge_builtin_feature feature, const char *dtmf, void *config)
1400 {
1401         /* If no alternate DTMF stream was provided use the default one */
1402         if (ast_strlen_zero(dtmf)) {
1403                 dtmf = builtin_features_dtmf[feature];
1404                 /* If no DTMF is still available (ie: it has been disabled) then error out now */
1405                 if (ast_strlen_zero(dtmf)) {
1406                         ast_debug(1, "Failed to enable built in feature %d on %p, no DTMF string is available for it.\n", feature, features);
1407                         return -1;
1408                 }
1409         }
1410
1411         if (!builtin_features_handlers[feature]) {
1412                 return -1;
1413         }
1414
1415         /* The rest is basically pretty easy. We create another hook using the built in feature's callback and DTMF, easy as pie. */
1416         return ast_bridge_features_hook(features, dtmf, builtin_features_handlers[feature], config, NULL);
1417 }
1418
1419 int ast_bridge_features_set_flag(struct ast_bridge_features *features, enum ast_bridge_feature_flags flag)
1420 {
1421         ast_set_flag(&features->feature_flags, flag);
1422         features->usable = 1;
1423         return 0;
1424 }
1425
1426 int ast_bridge_features_init(struct ast_bridge_features *features)
1427 {
1428         /* Zero out the structure */
1429         memset(features, 0, sizeof(*features));
1430
1431         /* Initialize the hooks list, just in case */
1432         AST_LIST_HEAD_INIT_NOLOCK(&features->hooks);
1433
1434         return 0;
1435 }
1436
1437 int ast_bridge_features_cleanup(struct ast_bridge_features *features)
1438 {
1439         struct ast_bridge_features_hook *hook = NULL;
1440
1441         /* This is relatively simple, hooks are kept as a list on the features structure so we just pop them off and free them */
1442         while ((hook = AST_LIST_REMOVE_HEAD(&features->hooks, entry))) {
1443                 if (hook->destructor) {
1444                         hook->destructor(hook->hook_pvt);
1445                 }
1446                 ast_free(hook);
1447         }
1448         if (features->talker_destructor_cb && features->talker_pvt_data) {
1449                 features->talker_destructor_cb(features->talker_pvt_data);
1450                 features->talker_pvt_data = NULL;
1451         }
1452
1453         return 0;
1454 }
1455
1456 int ast_bridge_dtmf_stream(struct ast_bridge *bridge, const char *dtmf, struct ast_channel *chan)
1457 {
1458         struct ast_bridge_channel *bridge_channel = NULL;
1459
1460         ao2_lock(bridge);
1461
1462         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1463                 if (bridge_channel->chan == chan) {
1464                         continue;
1465                 }
1466                 ast_copy_string(bridge_channel->dtmf_stream_q, dtmf, sizeof(bridge_channel->dtmf_stream_q));
1467                 ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_DTMF);
1468         }
1469
1470         ao2_unlock(bridge);
1471
1472         return 0;
1473 }
1474
1475 void ast_bridge_set_mixing_interval(struct ast_bridge *bridge, unsigned int mixing_interval)
1476 {
1477         ao2_lock(bridge);
1478         bridge->internal_mixing_interval = mixing_interval;
1479         ao2_unlock(bridge);
1480 }
1481
1482 void ast_bridge_set_internal_sample_rate(struct ast_bridge *bridge, unsigned int sample_rate)
1483 {
1484
1485         ao2_lock(bridge);
1486         bridge->internal_sample_rate = sample_rate;
1487         ao2_unlock(bridge);
1488 }
1489
1490 static void cleanup_video_mode(struct ast_bridge *bridge)
1491 {
1492         switch (bridge->video_mode.mode) {
1493         case AST_BRIDGE_VIDEO_MODE_NONE:
1494                 break;
1495         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
1496                 if (bridge->video_mode.mode_data.single_src_data.chan_vsrc) {
1497                         ast_channel_unref(bridge->video_mode.mode_data.single_src_data.chan_vsrc);
1498                 }
1499                 break;
1500         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
1501                 if (bridge->video_mode.mode_data.talker_src_data.chan_vsrc) {
1502                         ast_channel_unref(bridge->video_mode.mode_data.talker_src_data.chan_vsrc);
1503                 }
1504                 if (bridge->video_mode.mode_data.talker_src_data.chan_old_vsrc) {
1505                         ast_channel_unref(bridge->video_mode.mode_data.talker_src_data.chan_old_vsrc);
1506                 }
1507         }
1508         memset(&bridge->video_mode, 0, sizeof(bridge->video_mode));
1509 }
1510
1511 void ast_bridge_set_single_src_video_mode(struct ast_bridge *bridge, struct ast_channel *video_src_chan)
1512 {
1513         ao2_lock(bridge);
1514         cleanup_video_mode(bridge);
1515         bridge->video_mode.mode = AST_BRIDGE_VIDEO_MODE_SINGLE_SRC;
1516         bridge->video_mode.mode_data.single_src_data.chan_vsrc = ast_channel_ref(video_src_chan);
1517         ast_indicate(video_src_chan, AST_CONTROL_VIDUPDATE);
1518         ao2_unlock(bridge);
1519 }
1520
1521 void ast_bridge_set_talker_src_video_mode(struct ast_bridge *bridge)
1522 {
1523         ao2_lock(bridge);
1524         cleanup_video_mode(bridge);
1525         bridge->video_mode.mode = AST_BRIDGE_VIDEO_MODE_TALKER_SRC;
1526         ao2_unlock(bridge);
1527 }
1528
1529 void ast_bridge_update_talker_src_video_mode(struct ast_bridge *bridge, struct ast_channel *chan, int talker_energy, int is_keyframe)
1530 {
1531         struct ast_bridge_video_talker_src_data *data;
1532         /* If the channel doesn't support video, we don't care about it */
1533         if (!ast_format_cap_has_type(chan->nativeformats, AST_FORMAT_TYPE_VIDEO)) {
1534                 return;
1535         }
1536
1537         ao2_lock(bridge);
1538         data = &bridge->video_mode.mode_data.talker_src_data;
1539
1540         if (data->chan_vsrc == chan) {
1541                 data->average_talking_energy = talker_energy;
1542         } else if ((data->average_talking_energy < talker_energy) && is_keyframe) {
1543                 if (data->chan_old_vsrc) {
1544                         ast_channel_unref(data->chan_old_vsrc);
1545                 }
1546                 if (data->chan_vsrc) {
1547                         data->chan_old_vsrc = data->chan_vsrc;
1548                         ast_indicate(data->chan_old_vsrc, AST_CONTROL_VIDUPDATE);
1549                 }
1550                 data->chan_vsrc = ast_channel_ref(chan);
1551                 data->average_talking_energy = talker_energy;
1552                 ast_indicate(data->chan_vsrc, AST_CONTROL_VIDUPDATE);
1553         } else if ((data->average_talking_energy < talker_energy) && !is_keyframe) {
1554                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
1555         } else if (!data->chan_vsrc && is_keyframe) {
1556                 data->chan_vsrc = ast_channel_ref(chan);
1557                 data->average_talking_energy = talker_energy;
1558                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
1559         } else if (!data->chan_old_vsrc && is_keyframe) {
1560                 data->chan_old_vsrc = ast_channel_ref(chan);
1561                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
1562         }
1563         ao2_unlock(bridge);
1564 }
1565
1566 int ast_bridge_number_video_src(struct ast_bridge *bridge)
1567 {
1568         int res = 0;
1569
1570         ao2_lock(bridge);
1571         switch (bridge->video_mode.mode) {
1572         case AST_BRIDGE_VIDEO_MODE_NONE:
1573                 break;
1574         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
1575                 if (bridge->video_mode.mode_data.single_src_data.chan_vsrc) {
1576                         res = 1;
1577                 }
1578                 break;
1579         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
1580                 if (bridge->video_mode.mode_data.talker_src_data.chan_vsrc) {
1581                         res++;
1582                 }
1583                 if (bridge->video_mode.mode_data.talker_src_data.chan_old_vsrc) {
1584                         res++;
1585                 }
1586         }
1587         ao2_unlock(bridge);
1588         return res;
1589 }
1590
1591 int ast_bridge_is_video_src(struct ast_bridge *bridge, struct ast_channel *chan)
1592 {
1593         int res = 0;
1594
1595         ao2_lock(bridge);
1596         switch (bridge->video_mode.mode) {
1597         case AST_BRIDGE_VIDEO_MODE_NONE:
1598                 break;
1599         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
1600                 if (bridge->video_mode.mode_data.single_src_data.chan_vsrc == chan) {
1601                         res = 1;
1602                 }
1603                 break;
1604         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
1605                 if (bridge->video_mode.mode_data.talker_src_data.chan_vsrc == chan) {
1606                         res = 1;
1607                 } else if (bridge->video_mode.mode_data.talker_src_data.chan_old_vsrc == chan) {
1608                         res = 2;
1609                 }
1610
1611         }
1612         ao2_unlock(bridge);
1613         return res;
1614 }
1615
1616 void ast_bridge_remove_video_src(struct ast_bridge *bridge, struct ast_channel *chan)
1617 {
1618         ao2_lock(bridge);
1619         switch (bridge->video_mode.mode) {
1620         case AST_BRIDGE_VIDEO_MODE_NONE:
1621                 break;
1622         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
1623                 if (bridge->video_mode.mode_data.single_src_data.chan_vsrc == chan) {
1624                         if (bridge->video_mode.mode_data.single_src_data.chan_vsrc) {
1625                                 ast_channel_unref(bridge->video_mode.mode_data.single_src_data.chan_vsrc);
1626                         }
1627                         bridge->video_mode.mode_data.single_src_data.chan_vsrc = NULL;
1628                 }
1629                 break;
1630         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
1631                 if (bridge->video_mode.mode_data.talker_src_data.chan_vsrc == chan) {
1632                         if (bridge->video_mode.mode_data.talker_src_data.chan_vsrc) {
1633                                 ast_channel_unref(bridge->video_mode.mode_data.talker_src_data.chan_vsrc);
1634                         }
1635                         bridge->video_mode.mode_data.talker_src_data.chan_vsrc = NULL;
1636                         bridge->video_mode.mode_data.talker_src_data.average_talking_energy = 0;
1637                 }
1638                 if (bridge->video_mode.mode_data.talker_src_data.chan_old_vsrc == chan) {
1639                         if (bridge->video_mode.mode_data.talker_src_data.chan_old_vsrc) {
1640                                 ast_channel_unref(bridge->video_mode.mode_data.talker_src_data.chan_old_vsrc);
1641                         }
1642                         bridge->video_mode.mode_data.talker_src_data.chan_old_vsrc = NULL;
1643                 }
1644         }
1645         ao2_unlock(bridge);
1646 }