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