Remove the unsafe bridge parameter from ast_bridge_hook_callback's.
[asterisk/asterisk.git] / main / bridge.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 Bridging API
22  *
23  * \author Joshua Colp <jcolp@digium.com>
24  */
25
26 /*** MODULEINFO
27         <support_level>core</support_level>
28  ***/
29
30 #include "asterisk.h"
31
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
33
34 #include "asterisk/logger.h"
35 #include "asterisk/channel.h"
36 #include "asterisk/options.h"
37 #include "asterisk/utils.h"
38 #include "asterisk/lock.h"
39 #include "asterisk/linkedlists.h"
40 #include "asterisk/bridge.h"
41 #include "asterisk/bridge_internal.h"
42 #include "asterisk/bridge_channel_internal.h"
43 #include "asterisk/bridge_basic.h"
44 #include "asterisk/bridge_technology.h"
45 #include "asterisk/bridge_channel.h"
46 #include "asterisk/bridge_after.h"
47 #include "asterisk/stasis_bridges.h"
48 #include "asterisk/stasis_channels.h"
49 #include "asterisk/app.h"
50 #include "asterisk/file.h"
51 #include "asterisk/module.h"
52 #include "asterisk/astobj2.h"
53 #include "asterisk/pbx.h"
54 #include "asterisk/test.h"
55 #include "asterisk/_private.h"
56
57 #include "asterisk/heap.h"
58 #include "asterisk/say.h"
59 #include "asterisk/timing.h"
60 #include "asterisk/stringfields.h"
61 #include "asterisk/musiconhold.h"
62 #include "asterisk/features.h"
63 #include "asterisk/cli.h"
64 #include "asterisk/parking.h"
65 #include "asterisk/core_local.h"
66 #include "asterisk/core_unreal.h"
67
68 /*! All bridges container. */
69 static struct ao2_container *bridges;
70
71 static AST_RWLIST_HEAD_STATIC(bridge_technologies, ast_bridge_technology);
72
73 /* Initial starting point for the bridge array of channels */
74 #define BRIDGE_ARRAY_START 128
75
76 /* Grow rate of bridge array of channels */
77 #define BRIDGE_ARRAY_GROW 32
78
79 static void cleanup_video_mode(struct ast_bridge *bridge);
80 static int bridge_make_compatible(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel);
81
82 /*! Default DTMF keys for built in features */
83 static char builtin_features_dtmf[AST_BRIDGE_BUILTIN_END][MAXIMUM_DTMF_FEATURE_STRING];
84
85 /*! Function handlers for the built in features */
86 static ast_bridge_hook_callback builtin_features_handlers[AST_BRIDGE_BUILTIN_END];
87
88 /*! Function handlers for built in interval features */
89 static ast_bridge_builtin_set_limits_fn builtin_interval_handlers[AST_BRIDGE_BUILTIN_INTERVAL_END];
90
91 /*! Bridge manager service request */
92 struct bridge_manager_request {
93         /*! List of bridge service requests. */
94         AST_LIST_ENTRY(bridge_manager_request) node;
95         /*! Refed bridge requesting service. */
96         struct ast_bridge *bridge;
97 };
98
99 struct bridge_manager_controller {
100         /*! Condition, used to wake up the bridge manager thread. */
101         ast_cond_t cond;
102         /*! Queue of bridge service requests. */
103         AST_LIST_HEAD_NOLOCK(, bridge_manager_request) service_requests;
104         /*! Manager thread */
105         pthread_t thread;
106         /*! TRUE if the manager needs to stop. */
107         unsigned int stop:1;
108 };
109
110 /*! Bridge manager controller. */
111 static struct bridge_manager_controller *bridge_manager;
112
113 /*!
114  * \internal
115  * \brief Request service for a bridge from the bridge manager.
116  * \since 12.0.0
117  *
118  * \param bridge Requesting service.
119  *
120  * \return Nothing
121  */
122 static void bridge_manager_service_req(struct ast_bridge *bridge)
123 {
124         struct bridge_manager_request *request;
125
126         ao2_lock(bridge_manager);
127         if (bridge_manager->stop) {
128                 ao2_unlock(bridge_manager);
129                 return;
130         }
131
132         /* Create the service request. */
133         request = ast_calloc(1, sizeof(*request));
134         if (!request) {
135                 /* Well. This isn't good. */
136                 ao2_unlock(bridge_manager);
137                 return;
138         }
139         ao2_ref(bridge, +1);
140         request->bridge = bridge;
141
142         /* Put request into the queue and wake the bridge manager. */
143         AST_LIST_INSERT_TAIL(&bridge_manager->service_requests, request, node);
144         ast_cond_signal(&bridge_manager->cond);
145         ao2_unlock(bridge_manager);
146 }
147
148 int __ast_bridge_technology_register(struct ast_bridge_technology *technology, struct ast_module *module)
149 {
150         struct ast_bridge_technology *current;
151
152         /* Perform a sanity check to make sure the bridge technology conforms to our needed requirements */
153         if (ast_strlen_zero(technology->name)
154                 || !technology->capabilities
155                 || !technology->write) {
156                 ast_log(LOG_WARNING, "Bridge technology %s failed registration sanity check.\n",
157                         technology->name);
158                 return -1;
159         }
160
161         AST_RWLIST_WRLOCK(&bridge_technologies);
162
163         /* Look for duplicate bridge technology already using this name, or already registered */
164         AST_RWLIST_TRAVERSE(&bridge_technologies, current, entry) {
165                 if ((!strcasecmp(current->name, technology->name)) || (current == technology)) {
166                         ast_log(LOG_WARNING, "A bridge technology of %s already claims to exist in our world.\n",
167                                 technology->name);
168                         AST_RWLIST_UNLOCK(&bridge_technologies);
169                         return -1;
170                 }
171         }
172
173         /* Copy module pointer so reference counting can keep the module from unloading */
174         technology->mod = module;
175
176         /* Insert our new bridge technology into the list and print out a pretty message */
177         AST_RWLIST_INSERT_TAIL(&bridge_technologies, technology, entry);
178
179         AST_RWLIST_UNLOCK(&bridge_technologies);
180
181         ast_verb(2, "Registered bridge technology %s\n", technology->name);
182
183         return 0;
184 }
185
186 int ast_bridge_technology_unregister(struct ast_bridge_technology *technology)
187 {
188         struct ast_bridge_technology *current;
189
190         AST_RWLIST_WRLOCK(&bridge_technologies);
191
192         /* Ensure the bridge technology is registered before removing it */
193         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&bridge_technologies, current, entry) {
194                 if (current == technology) {
195                         AST_RWLIST_REMOVE_CURRENT(entry);
196                         ast_verb(2, "Unregistered bridge technology %s\n", technology->name);
197                         break;
198                 }
199         }
200         AST_RWLIST_TRAVERSE_SAFE_END;
201
202         AST_RWLIST_UNLOCK(&bridge_technologies);
203
204         return current ? 0 : -1;
205 }
206
207 /*!
208  * \internal
209  * \brief Put an action onto the specified bridge. Don't dup the action frame.
210  * \since 12.0.0
211  *
212  * \param bridge What to queue the action on.
213  * \param action What to do.
214  *
215  * \return Nothing
216  */
217 static void bridge_queue_action_nodup(struct ast_bridge *bridge, struct ast_frame *action)
218 {
219         ast_debug(1, "Bridge %s: queueing action type:%d sub:%d\n",
220                 bridge->uniqueid, action->frametype, action->subclass.integer);
221
222         ast_bridge_lock(bridge);
223         AST_LIST_INSERT_TAIL(&bridge->action_queue, action, frame_list);
224         ast_bridge_unlock(bridge);
225         bridge_manager_service_req(bridge);
226 }
227
228 int ast_bridge_queue_action(struct ast_bridge *bridge, struct ast_frame *action)
229 {
230         struct ast_frame *dup;
231
232         dup = ast_frdup(action);
233         if (!dup) {
234                 return -1;
235         }
236         bridge_queue_action_nodup(bridge, dup);
237         return 0;
238 }
239
240 /*!
241  * \internal
242  * \brief Dissolve the bridge.
243  * \since 12.0.0
244  *
245  * \param bridge Bridge to eject all channels
246  *
247  * \details
248  * Force out all channels that are not already going out of the
249  * bridge.  Any new channels joining will leave immediately.
250  *
251  * \note On entry, bridge is already locked.
252  *
253  * \return Nothing
254  */
255 void bridge_dissolve(struct ast_bridge *bridge)
256 {
257         struct ast_bridge_channel *bridge_channel;
258         struct ast_frame action = {
259                 .frametype = AST_FRAME_BRIDGE_ACTION,
260                 .subclass.integer = BRIDGE_CHANNEL_ACTION_DEFERRED_DISSOLVING,
261         };
262
263         if (bridge->dissolved) {
264                 return;
265         }
266         bridge->dissolved = 1;
267
268         ast_debug(1, "Bridge %s: dissolving bridge\n", bridge->uniqueid);
269
270 /* BUGBUG need a cause code on the bridge for the later ejected channels. */
271         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
272                 ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
273         }
274
275         /* Must defer dissolving bridge because it is already locked. */
276         ast_bridge_queue_action(bridge, &action);
277 }
278
279 /*!
280  * \internal
281  * \brief Check if a bridge should dissolve because of a stolen channel and do it.
282  * \since 12.0.0
283  *
284  * \param bridge Bridge to check.
285  * \param bridge_channel Stolen channel causing the check.  It is not in the bridge to check and may be in another bridge.
286  *
287  * \note On entry, bridge and bridge_channel->bridge are already locked.
288  *
289  * \return Nothing
290  */
291 static void bridge_dissolve_check_stolen(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
292 {
293         if (bridge->dissolved) {
294                 return;
295         }
296
297         if (bridge_channel->features->usable
298                 && ast_test_flag(&bridge_channel->features->feature_flags,
299                         AST_BRIDGE_CHANNEL_FLAG_DISSOLVE_HANGUP)) {
300                 /* The stolen channel controlled the bridge it was stolen from. */
301                 bridge_dissolve(bridge);
302                 return;
303         }
304         if (bridge->num_channels < 2
305                 && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_HANGUP)) {
306                 /*
307                  * The stolen channel has not left enough channels to keep the
308                  * bridge alive.  Assume the stolen channel hung up.
309                  */
310                 bridge_dissolve(bridge);
311                 return;
312         }
313 }
314
315 /*!
316  * \internal
317  * \brief Update connected line information after a bridge has been reconfigured.
318  *
319  * \param bridge The bridge itself.
320  *
321  * \return Nothing
322  */
323 static void bridge_reconfigured_connected_line_update(struct ast_bridge *bridge)
324 {
325         struct ast_party_connected_line connected;
326         struct ast_bridge_channel *bridge_channel = AST_LIST_FIRST(&bridge->channels), *peer;
327         unsigned char data[1024];
328         size_t datalen;
329
330         if (!bridge_channel ||
331                 !(bridge->technology->capabilities & (AST_BRIDGE_CAPABILITY_1TO1MIX | AST_BRIDGE_CAPABILITY_NATIVE)) ||
332                 !(peer = ast_bridge_channel_peer(bridge_channel)) ||
333                 ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_ZOMBIE) ||
334                 ast_test_flag(ast_channel_flags(peer->chan), AST_FLAG_ZOMBIE) ||
335                 ast_check_hangup_locked(bridge_channel->chan) ||
336                 ast_check_hangup_locked(peer->chan)) {
337                 return;
338         }
339
340         ast_party_connected_line_init(&connected);
341
342         ast_channel_lock(bridge_channel->chan);
343         ast_connected_line_copy_from_caller(&connected, ast_channel_caller(bridge_channel->chan));
344         ast_channel_unlock(bridge_channel->chan);
345
346         if ((datalen = ast_connected_line_build_data(data, sizeof(data), &connected, NULL)) != (size_t) -1) {
347                 ast_bridge_channel_queue_control_data(peer, AST_CONTROL_CONNECTED_LINE, data, datalen);
348         }
349
350         ast_channel_lock(peer->chan);
351         ast_connected_line_copy_from_caller(&connected, ast_channel_caller(peer->chan));
352         ast_channel_unlock(peer->chan);
353
354         if ((datalen = ast_connected_line_build_data(data, sizeof(data), &connected, NULL)) != (size_t) -1) {
355                 ast_bridge_channel_queue_control_data(bridge_channel, AST_CONTROL_CONNECTED_LINE, data, datalen);
356         }
357
358         ast_party_connected_line_free(&connected);
359 }
360
361 /*!
362  * \internal
363  * \brief Complete joining a channel to the bridge.
364  * \since 12.0.0
365  *
366  * \param bridge What to operate upon.
367  * \param bridge_channel What is joining the bridge technology.
368  *
369  * \note On entry, bridge is already locked.
370  *
371  * \return Nothing
372  */
373 static void bridge_channel_complete_join(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
374 {
375         /* Make the channel compatible with the bridge */
376         bridge_make_compatible(bridge, bridge_channel);
377
378         /* Tell the bridge technology we are joining so they set us up */
379         ast_debug(1, "Bridge %s: %p(%s) is joining %s technology\n",
380                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
381                 bridge->technology->name);
382         if (bridge->technology->join
383                 && bridge->technology->join(bridge, bridge_channel)) {
384                 ast_debug(1, "Bridge %s: %p(%s) failed to join %s technology\n",
385                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
386                         bridge->technology->name);
387                 bridge_channel->just_joined = 1;
388                 return;
389         }
390
391         bridge_channel->just_joined = 0;
392 }
393
394 /*!
395  * \internal
396  * \brief Complete joining new channels to the bridge.
397  * \since 12.0.0
398  *
399  * \param bridge Check for new channels on this bridge.
400  *
401  * \note On entry, bridge is already locked.
402  *
403  * \return Nothing
404  */
405 static void bridge_complete_join(struct ast_bridge *bridge)
406 {
407         struct ast_bridge_channel *bridge_channel;
408
409         if (bridge->dissolved) {
410                 /*
411                  * No sense in completing the join on channels for a dissolved
412                  * bridge.  They are just going to be removed soon anyway.
413                  * However, we do have reason to abort here because the bridge
414                  * technology may not be able to handle the number of channels
415                  * still in the bridge.
416                  */
417                 return;
418         }
419
420         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
421                 if (!bridge_channel->just_joined) {
422                         continue;
423                 }
424                 bridge_channel_complete_join(bridge, bridge_channel);
425         }
426 }
427
428 /*! \brief Helper function used to find the "best" bridge technology given specified capabilities */
429 static struct ast_bridge_technology *find_best_technology(uint32_t capabilities, struct ast_bridge *bridge)
430 {
431         struct ast_bridge_technology *current;
432         struct ast_bridge_technology *best = NULL;
433
434         AST_RWLIST_RDLOCK(&bridge_technologies);
435         AST_RWLIST_TRAVERSE(&bridge_technologies, current, entry) {
436                 if (current->suspended) {
437                         ast_debug(1, "Bridge technology %s is suspended. Skipping.\n",
438                                 current->name);
439                         continue;
440                 }
441                 if (!(current->capabilities & capabilities)) {
442                         ast_debug(1, "Bridge technology %s does not have any capabilities we want.\n",
443                                 current->name);
444                         continue;
445                 }
446                 if (best && current->preference <= best->preference) {
447                         ast_debug(1, "Bridge technology %s has less preference than %s (%d <= %d). Skipping.\n",
448                                 current->name, best->name, current->preference, best->preference);
449                         continue;
450                 }
451                 if (current->compatible && !current->compatible(bridge)) {
452                         ast_debug(1, "Bridge technology %s is not compatible with properties of existing bridge.\n",
453                                 current->name);
454                         continue;
455                 }
456                 best = current;
457         }
458
459         if (best) {
460                 /* Increment it's module reference count if present so it does not get unloaded while in use */
461                 ast_module_ref(best->mod);
462                 ast_debug(1, "Chose bridge technology %s\n", best->name);
463         }
464
465         AST_RWLIST_UNLOCK(&bridge_technologies);
466
467         return best;
468 }
469
470 struct tech_deferred_destroy {
471         struct ast_bridge_technology *tech;
472         void *tech_pvt;
473 };
474
475 /*!
476  * \internal
477  * \brief Deferred destruction of bridge tech private structure.
478  * \since 12.0.0
479  *
480  * \param bridge What to execute the action on.
481  * \param action Deferred bridge tech destruction.
482  *
483  * \note On entry, bridge must not be locked.
484  *
485  * \return Nothing
486  */
487 static void bridge_tech_deferred_destroy(struct ast_bridge *bridge, struct ast_frame *action)
488 {
489         struct tech_deferred_destroy *deferred = action->data.ptr;
490         struct ast_bridge dummy_bridge = {
491                 .technology = deferred->tech,
492                 .tech_pvt = deferred->tech_pvt,
493                 };
494
495         ast_copy_string(dummy_bridge.uniqueid, bridge->uniqueid, sizeof(dummy_bridge.uniqueid));
496         ast_debug(1, "Bridge %s: calling %s technology destructor (deferred, dummy)\n",
497                 dummy_bridge.uniqueid, dummy_bridge.technology->name);
498         dummy_bridge.technology->destroy(&dummy_bridge);
499         ast_module_unref(dummy_bridge.technology->mod);
500 }
501
502 /*!
503  * \internal
504  * \brief Handle bridge action frame.
505  * \since 12.0.0
506  *
507  * \param bridge What to execute the action on.
508  * \param action What to do.
509  *
510  * \note On entry, bridge is already locked.
511  * \note Can be called by the bridge destructor.
512  *
513  * \return Nothing
514  */
515 static void bridge_action_bridge(struct ast_bridge *bridge, struct ast_frame *action)
516 {
517 #if 0   /* In case we need to know when the destructor is calling us. */
518         int in_destructor = !ao2_ref(bridge, 0);
519 #endif
520
521         switch (action->subclass.integer) {
522         case BRIDGE_CHANNEL_ACTION_DEFERRED_TECH_DESTROY:
523                 ast_bridge_unlock(bridge);
524                 bridge_tech_deferred_destroy(bridge, action);
525                 ast_bridge_lock(bridge);
526                 break;
527         case BRIDGE_CHANNEL_ACTION_DEFERRED_DISSOLVING:
528                 ast_bridge_unlock(bridge);
529                 bridge->v_table->dissolving(bridge);
530                 ast_bridge_lock(bridge);
531                 break;
532         default:
533                 /* Unexpected deferred action type.  Should never happen. */
534                 ast_assert(0);
535                 break;
536         }
537 }
538
539 /*!
540  * \internal
541  * \brief Do any pending bridge actions.
542  * \since 12.0.0
543  *
544  * \param bridge What to do actions on.
545  *
546  * \note On entry, bridge is already locked.
547  * \note Can be called by the bridge destructor.
548  *
549  * \return Nothing
550  */
551 static void bridge_handle_actions(struct ast_bridge *bridge)
552 {
553         struct ast_frame *action;
554
555         while ((action = AST_LIST_REMOVE_HEAD(&bridge->action_queue, frame_list))) {
556                 switch (action->frametype) {
557                 case AST_FRAME_BRIDGE_ACTION:
558                         bridge_action_bridge(bridge, action);
559                         break;
560                 default:
561                         /* Unexpected deferred frame type.  Should never happen. */
562                         ast_assert(0);
563                         break;
564                 }
565                 ast_frfree(action);
566         }
567 }
568
569 static struct stasis_message *create_bridge_snapshot_message(struct ast_bridge *bridge)
570 {
571         RAII_VAR(struct ast_bridge_snapshot *, snapshot, NULL, ao2_cleanup);
572
573         snapshot = ast_bridge_snapshot_create(bridge);
574         if (!snapshot) {
575                 return NULL;
576         }
577
578         return stasis_message_create(ast_bridge_snapshot_type(), snapshot);
579 }
580
581 static void destroy_bridge(void *obj)
582 {
583         struct ast_bridge *bridge = obj;
584
585         ast_debug(1, "Bridge %s: actually destroying %s bridge, nobody wants it anymore\n",
586                 bridge->uniqueid, bridge->v_table->name);
587
588         if (bridge->construction_completed) {
589                 RAII_VAR(struct stasis_message *, clear_msg, NULL, ao2_cleanup);
590
591                 clear_msg = create_bridge_snapshot_message(bridge);
592                 if (clear_msg) {
593                         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
594
595                         msg = stasis_cache_clear_create(clear_msg);
596                         if (msg) {
597                                 stasis_publish(ast_bridge_topic(bridge), msg);
598                         }
599                 }
600         }
601
602         /* Do any pending actions in the context of destruction. */
603         ast_bridge_lock(bridge);
604         bridge_handle_actions(bridge);
605         ast_bridge_unlock(bridge);
606
607         /* There should not be any channels left in the bridge. */
608         ast_assert(AST_LIST_EMPTY(&bridge->channels));
609
610         ast_debug(1, "Bridge %s: calling %s bridge destructor\n",
611                 bridge->uniqueid, bridge->v_table->name);
612         bridge->v_table->destroy(bridge);
613
614         /* Pass off the bridge to the technology to destroy if needed */
615         if (bridge->technology) {
616                 ast_debug(1, "Bridge %s: calling %s technology stop\n",
617                         bridge->uniqueid, bridge->technology->name);
618                 if (bridge->technology->stop) {
619                         ast_bridge_lock(bridge);
620                         bridge->technology->stop(bridge);
621                         ast_bridge_unlock(bridge);
622                 }
623                 ast_debug(1, "Bridge %s: calling %s technology destructor\n",
624                         bridge->uniqueid, bridge->technology->name);
625                 if (bridge->technology->destroy) {
626                         bridge->technology->destroy(bridge);
627                 }
628                 ast_module_unref(bridge->technology->mod);
629                 bridge->technology = NULL;
630         }
631
632         if (bridge->callid) {
633                 bridge->callid = ast_callid_unref(bridge->callid);
634         }
635
636         cleanup_video_mode(bridge);
637 }
638
639 struct ast_bridge *bridge_register(struct ast_bridge *bridge)
640 {
641         if (bridge) {
642                 bridge->construction_completed = 1;
643                 ast_bridge_publish_state(bridge);
644                 if (!ao2_link(bridges, bridge)) {
645                         ast_bridge_destroy(bridge);
646                         bridge = NULL;
647                 }
648         }
649         return bridge;
650 }
651
652 struct ast_bridge *bridge_alloc(size_t size, const struct ast_bridge_methods *v_table)
653 {
654         struct ast_bridge *bridge;
655
656         /* Check v_table that all methods are present. */
657         if (!v_table
658                 || !v_table->name
659                 || !v_table->destroy
660                 || !v_table->dissolving
661                 || !v_table->push
662                 || !v_table->pull
663                 || !v_table->notify_masquerade
664                 || !v_table->get_merge_priority) {
665                 ast_log(LOG_ERROR, "Virtual method table for bridge class %s not complete.\n",
666                         v_table && v_table->name ? v_table->name : "<unknown>");
667                 ast_assert(0);
668                 return NULL;
669         }
670
671         bridge = ao2_alloc(size, destroy_bridge);
672         if (bridge) {
673                 bridge->v_table = v_table;
674         }
675         return bridge;
676 }
677
678 struct ast_bridge *bridge_base_init(struct ast_bridge *self, uint32_t capabilities, unsigned int flags)
679 {
680         if (!self) {
681                 return NULL;
682         }
683
684         ast_uuid_generate_str(self->uniqueid, sizeof(self->uniqueid));
685         ast_set_flag(&self->feature_flags, flags);
686         self->allowed_capabilities = capabilities;
687
688         /* Use our helper function to find the "best" bridge technology. */
689         self->technology = find_best_technology(capabilities, self);
690         if (!self->technology) {
691                 ast_log(LOG_WARNING, "Bridge %s: Could not create class %s.  No technology to support it.\n",
692                         self->uniqueid, self->v_table->name);
693                 ao2_ref(self, -1);
694                 return NULL;
695         }
696
697         /* Pass off the bridge to the technology to manipulate if needed */
698         ast_debug(1, "Bridge %s: calling %s technology constructor\n",
699                 self->uniqueid, self->technology->name);
700         if (self->technology->create && self->technology->create(self)) {
701                 ast_log(LOG_WARNING, "Bridge %s: failed to setup bridge technology %s\n",
702                         self->uniqueid, self->technology->name);
703                 ao2_ref(self, -1);
704                 return NULL;
705         }
706         ast_debug(1, "Bridge %s: calling %s technology start\n",
707                 self->uniqueid, self->technology->name);
708         if (self->technology->start && self->technology->start(self)) {
709                 ast_log(LOG_WARNING, "Bridge %s: failed to start bridge technology %s\n",
710                         self->uniqueid, self->technology->name);
711                 ao2_ref(self, -1);
712                 return NULL;
713         }
714
715         if (!ast_bridge_topic(self)) {
716                 ao2_ref(self, -1);
717                 return NULL;
718         }
719
720         return self;
721 }
722
723 /*!
724  * \internal
725  * \brief ast_bridge base class destructor.
726  * \since 12.0.0
727  *
728  * \param self Bridge to operate upon.
729  *
730  * \note Stub because of nothing to do.
731  *
732  * \return Nothing
733  */
734 static void bridge_base_destroy(struct ast_bridge *self)
735 {
736 }
737
738 /*!
739  * \internal
740  * \brief The bridge is being dissolved.
741  * \since 12.0.0
742  *
743  * \param self Bridge to operate upon.
744  *
745  * \return Nothing
746  */
747 static void bridge_base_dissolving(struct ast_bridge *self)
748 {
749         ao2_unlink(bridges, self);
750 }
751
752 /*!
753  * \internal
754  * \brief ast_bridge base push method.
755  * \since 12.0.0
756  *
757  * \param self Bridge to operate upon.
758  * \param bridge_channel Bridge channel to push.
759  * \param swap Bridge channel to swap places with if not NULL.
760  *
761  * \note On entry, self is already locked.
762  * \note Stub because of nothing to do.
763  *
764  * \retval 0 on success
765  * \retval -1 on failure
766  */
767 static int bridge_base_push(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
768 {
769         return 0;
770 }
771
772 /*!
773  * \internal
774  * \brief ast_bridge base pull method.
775  * \since 12.0.0
776  *
777  * \param self Bridge to operate upon.
778  * \param bridge_channel Bridge channel to pull.
779  *
780  * \note On entry, self is already locked.
781  *
782  * \return Nothing
783  */
784 static void bridge_base_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
785 {
786         ast_bridge_features_remove(bridge_channel->features, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
787 }
788
789 /*!
790  * \internal
791  * \brief ast_bridge base notify_masquerade method.
792  * \since 12.0.0
793  *
794  * \param self Bridge to operate upon.
795  * \param bridge_channel Bridge channel that was masqueraded.
796  *
797  * \note On entry, self is already locked.
798  *
799  * \return Nothing
800  */
801 static void bridge_base_notify_masquerade(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
802 {
803         self->reconfigured = 1;
804 }
805
806 /*!
807  * \internal
808  * \brief Get the merge priority of this bridge.
809  * \since 12.0.0
810  *
811  * \param self Bridge to operate upon.
812  *
813  * \note On entry, self is already locked.
814  *
815  * \return Merge priority
816  */
817 static int bridge_base_get_merge_priority(struct ast_bridge *self)
818 {
819         return 0;
820 }
821
822 struct ast_bridge_methods ast_bridge_base_v_table = {
823         .name = "base",
824         .destroy = bridge_base_destroy,
825         .dissolving = bridge_base_dissolving,
826         .push = bridge_base_push,
827         .pull = bridge_base_pull,
828         .notify_masquerade = bridge_base_notify_masquerade,
829         .get_merge_priority = bridge_base_get_merge_priority,
830 };
831
832 struct ast_bridge *ast_bridge_base_new(uint32_t capabilities, unsigned int flags)
833 {
834         void *bridge;
835
836         bridge = bridge_alloc(sizeof(struct ast_bridge), &ast_bridge_base_v_table);
837         bridge = bridge_base_init(bridge, capabilities, flags);
838         bridge = bridge_register(bridge);
839         return bridge;
840 }
841
842 int ast_bridge_destroy(struct ast_bridge *bridge)
843 {
844         ast_debug(1, "Bridge %s: telling all channels to leave the party\n", bridge->uniqueid);
845         ast_bridge_lock(bridge);
846         bridge_dissolve(bridge);
847         ast_bridge_unlock(bridge);
848
849         ao2_ref(bridge, -1);
850
851         return 0;
852 }
853
854 static int bridge_make_compatible(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
855 {
856         struct ast_format read_format;
857         struct ast_format write_format;
858         struct ast_format best_format;
859         char codec_buf[512];
860
861         ast_format_copy(&read_format, ast_channel_readformat(bridge_channel->chan));
862         ast_format_copy(&write_format, ast_channel_writeformat(bridge_channel->chan));
863
864         /* Are the formats currently in use something this bridge can handle? */
865         if (!ast_format_cap_iscompatible(bridge->technology->format_capabilities, ast_channel_readformat(bridge_channel->chan))) {
866                 ast_best_codec(bridge->technology->format_capabilities, &best_format);
867
868                 /* Read format is a no go... */
869                 ast_debug(1, "Bridge technology %s wants to read any of formats %s but channel has %s\n",
870                         bridge->technology->name,
871                         ast_getformatname_multiple(codec_buf, sizeof(codec_buf), bridge->technology->format_capabilities),
872                         ast_getformatname(&read_format));
873
874                 /* Switch read format to the best one chosen */
875                 if (ast_set_read_format(bridge_channel->chan, &best_format)) {
876                         ast_log(LOG_WARNING, "Failed to set channel %s to read format %s\n",
877                                 ast_channel_name(bridge_channel->chan), ast_getformatname(&best_format));
878                         return -1;
879                 }
880                 ast_debug(1, "Bridge %s put channel %s into read format %s\n",
881                         bridge->uniqueid, ast_channel_name(bridge_channel->chan),
882                         ast_getformatname(&best_format));
883         } else {
884                 ast_debug(1, "Bridge %s is happy that channel %s already has read format %s\n",
885                         bridge->uniqueid, ast_channel_name(bridge_channel->chan),
886                         ast_getformatname(&read_format));
887         }
888
889         if (!ast_format_cap_iscompatible(bridge->technology->format_capabilities, &write_format)) {
890                 ast_best_codec(bridge->technology->format_capabilities, &best_format);
891
892                 /* Write format is a no go... */
893                 ast_debug(1, "Bridge technology %s wants to write any of formats %s but channel has %s\n",
894                         bridge->technology->name,
895                         ast_getformatname_multiple(codec_buf, sizeof(codec_buf), bridge->technology->format_capabilities),
896                         ast_getformatname(&write_format));
897
898                 /* Switch write format to the best one chosen */
899                 if (ast_set_write_format(bridge_channel->chan, &best_format)) {
900                         ast_log(LOG_WARNING, "Failed to set channel %s to write format %s\n",
901                                 ast_channel_name(bridge_channel->chan), ast_getformatname(&best_format));
902                         return -1;
903                 }
904                 ast_debug(1, "Bridge %s put channel %s into write format %s\n",
905                         bridge->uniqueid, ast_channel_name(bridge_channel->chan),
906                         ast_getformatname(&best_format));
907         } else {
908                 ast_debug(1, "Bridge %s is happy that channel %s already has write format %s\n",
909                         bridge->uniqueid, ast_channel_name(bridge_channel->chan),
910                         ast_getformatname(&write_format));
911         }
912
913         return 0;
914 }
915
916 /*!
917  * \internal
918  * \brief Perform the smart bridge operation.
919  * \since 12.0.0
920  *
921  * \param bridge Work on this bridge.
922  *
923  * \details
924  * Basically see if a new bridge technology should be used instead
925  * of the current one.
926  *
927  * \note On entry, bridge is already locked.
928  *
929  * \retval 0 on success.
930  * \retval -1 on error.
931  */
932 static int smart_bridge_operation(struct ast_bridge *bridge)
933 {
934         uint32_t new_capabilities;
935         struct ast_bridge_technology *new_technology;
936         struct ast_bridge_technology *old_technology = bridge->technology;
937         struct ast_bridge_channel *bridge_channel;
938         struct ast_frame *deferred_action;
939         struct ast_bridge dummy_bridge = {
940                 .technology = bridge->technology,
941                 .tech_pvt = bridge->tech_pvt,
942         };
943
944         if (bridge->dissolved) {
945                 ast_debug(1, "Bridge %s is dissolved, not performing smart bridge operation.\n",
946                         bridge->uniqueid);
947                 return 0;
948         }
949
950         /* Determine new bridge technology capabilities needed. */
951         if (2 < bridge->num_channels) {
952                 new_capabilities = AST_BRIDGE_CAPABILITY_MULTIMIX;
953                 new_capabilities &= bridge->allowed_capabilities;
954         } else {
955                 new_capabilities = AST_BRIDGE_CAPABILITY_NATIVE | AST_BRIDGE_CAPABILITY_1TO1MIX;
956                 new_capabilities &= bridge->allowed_capabilities;
957                 if (!new_capabilities
958                         && (bridge->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
959                         /* Allow switching between different multimix bridge technologies. */
960                         new_capabilities = AST_BRIDGE_CAPABILITY_MULTIMIX;
961                 }
962         }
963
964         /* Find a bridge technology to satisfy the new capabilities. */
965         new_technology = find_best_technology(new_capabilities, bridge);
966         if (!new_technology) {
967                 int is_compatible = 0;
968
969                 if (old_technology->compatible) {
970                         is_compatible = old_technology->compatible(bridge);
971                 } else if (old_technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX) {
972                         is_compatible = 1;
973                 } else if (bridge->num_channels <= 2
974                         && (old_technology->capabilities & AST_BRIDGE_CAPABILITY_1TO1MIX)) {
975                         is_compatible = 1;
976                 }
977
978                 if (is_compatible) {
979                         ast_debug(1, "Bridge %s could not get a new technology, staying with old technology.\n",
980                                 bridge->uniqueid);
981                         return 0;
982                 }
983                 ast_log(LOG_WARNING, "Bridge %s has no technology available to support it.\n",
984                         bridge->uniqueid);
985                 return -1;
986         }
987         if (new_technology == old_technology) {
988                 ast_debug(1, "Bridge %s is already using the new technology.\n",
989                         bridge->uniqueid);
990                 ast_module_unref(old_technology->mod);
991                 return 0;
992         }
993
994         ast_copy_string(dummy_bridge.uniqueid, bridge->uniqueid, sizeof(dummy_bridge.uniqueid));
995
996         if (old_technology->destroy) {
997                 struct tech_deferred_destroy deferred_tech_destroy = {
998                         .tech = dummy_bridge.technology,
999                         .tech_pvt = dummy_bridge.tech_pvt,
1000                 };
1001                 struct ast_frame action = {
1002                         .frametype = AST_FRAME_BRIDGE_ACTION,
1003                         .subclass.integer = BRIDGE_CHANNEL_ACTION_DEFERRED_TECH_DESTROY,
1004                         .data.ptr = &deferred_tech_destroy,
1005                         .datalen = sizeof(deferred_tech_destroy),
1006                 };
1007
1008                 /*
1009                  * We need to defer the bridge technology destroy callback
1010                  * because we have the bridge locked.
1011                  */
1012                 deferred_action = ast_frdup(&action);
1013                 if (!deferred_action) {
1014                         ast_module_unref(new_technology->mod);
1015                         return -1;
1016                 }
1017         } else {
1018                 deferred_action = NULL;
1019         }
1020
1021         /*
1022          * We are now committed to changing the bridge technology.  We
1023          * must not release the bridge lock until we have installed the
1024          * new bridge technology.
1025          */
1026         ast_verb(4, "Bridge %s: switching from %s technology to %s\n",
1027                 bridge->uniqueid, old_technology->name, new_technology->name);
1028
1029         /*
1030          * Since we are soon going to pass this bridge to a new
1031          * technology we need to NULL out the tech_pvt pointer but
1032          * don't worry as it still exists in dummy_bridge, ditto for the
1033          * old technology.
1034          */
1035         bridge->tech_pvt = NULL;
1036         bridge->technology = new_technology;
1037
1038         /* Setup the new bridge technology. */
1039         ast_debug(1, "Bridge %s: calling %s technology constructor\n",
1040                 bridge->uniqueid, new_technology->name);
1041         if (new_technology->create && new_technology->create(bridge)) {
1042                 ast_log(LOG_WARNING, "Bridge %s: failed to setup bridge technology %s\n",
1043                         bridge->uniqueid, new_technology->name);
1044                 bridge->tech_pvt = dummy_bridge.tech_pvt;
1045                 bridge->technology = dummy_bridge.technology;
1046                 ast_module_unref(new_technology->mod);
1047                 return -1;
1048         }
1049
1050         ast_debug(1, "Bridge %s: calling %s technology stop\n",
1051                 dummy_bridge.uniqueid, old_technology->name);
1052         if (old_technology->stop) {
1053                 old_technology->stop(&dummy_bridge);
1054         }
1055
1056         /*
1057          * Move existing channels over to the new technology and
1058          * complete joining any new channels to the bridge.
1059          */
1060         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1061                 if (!bridge_channel->just_joined) {
1062                         /* Take existing channel from the old technology. */
1063                         ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology (dummy)\n",
1064                                 dummy_bridge.uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1065                                 old_technology->name);
1066                         if (old_technology->leave) {
1067                                 old_technology->leave(&dummy_bridge, bridge_channel);
1068                         }
1069                 }
1070
1071                 /* Add any new channels or re-add an existing channel to the bridge. */
1072                 bridge_channel_complete_join(bridge, bridge_channel);
1073         }
1074
1075         ast_debug(1, "Bridge %s: calling %s technology start\n",
1076                 bridge->uniqueid, new_technology->name);
1077         if (new_technology->start && new_technology->start(bridge)) {
1078                 ast_log(LOG_WARNING, "Bridge %s: failed to start bridge technology %s\n",
1079                         bridge->uniqueid, new_technology->name);
1080         }
1081
1082         /*
1083          * Now that all the channels have been moved over we need to get
1084          * rid of all the information the old technology may have left
1085          * around.
1086          */
1087         if (old_technology->destroy) {
1088                 ast_debug(1, "Bridge %s: deferring %s technology destructor\n",
1089                         dummy_bridge.uniqueid, old_technology->name);
1090                 bridge_queue_action_nodup(bridge, deferred_action);
1091         } else {
1092                 ast_debug(1, "Bridge %s: calling %s technology destructor\n",
1093                         dummy_bridge.uniqueid, old_technology->name);
1094                 ast_module_unref(old_technology->mod);
1095         }
1096
1097         return 0;
1098 }
1099
1100 /*!
1101  * \internal
1102  * \brief Bridge channel to check if a BRIDGE_PLAY_SOUND needs to be played.
1103  * \since 12.0.0
1104  *
1105  * \param bridge_channel What to check.
1106  *
1107  * \return Nothing
1108  */
1109 static void check_bridge_play_sound(struct ast_bridge_channel *bridge_channel)
1110 {
1111         const char *play_file;
1112
1113         ast_channel_lock(bridge_channel->chan);
1114         play_file = pbx_builtin_getvar_helper(bridge_channel->chan, "BRIDGE_PLAY_SOUND");
1115         if (!ast_strlen_zero(play_file)) {
1116                 play_file = ast_strdupa(play_file);
1117                 pbx_builtin_setvar_helper(bridge_channel->chan, "BRIDGE_PLAY_SOUND", NULL);
1118         } else {
1119                 play_file = NULL;
1120         }
1121         ast_channel_unlock(bridge_channel->chan);
1122
1123         if (play_file) {
1124                 ast_bridge_channel_queue_playfile(bridge_channel, NULL, play_file, NULL);
1125         }
1126 }
1127
1128 /*!
1129  * \internal
1130  * \brief Check for any BRIDGE_PLAY_SOUND channel variables in the bridge.
1131  * \since 12.0.0
1132  *
1133  * \param bridge What to operate on.
1134  *
1135  * \note On entry, the bridge is already locked.
1136  *
1137  * \return Nothing
1138  */
1139 static void check_bridge_play_sounds(struct ast_bridge *bridge)
1140 {
1141         struct ast_bridge_channel *bridge_channel;
1142
1143         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1144                 check_bridge_play_sound(bridge_channel);
1145         }
1146 }
1147
1148 static void update_bridge_vars_set(struct ast_channel *chan, const char *name, const char *pvtid)
1149 {
1150         pbx_builtin_setvar_helper(chan, "BRIDGEPEER", name);
1151         pbx_builtin_setvar_helper(chan, "BRIDGEPVTCALLID", pvtid);
1152 }
1153
1154 /*!
1155  * \internal
1156  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a 2 party bridge.
1157  * \since 12.0.0
1158  *
1159  * \param c0 Party of the first part.
1160  * \param c1 Party of the second part.
1161  *
1162  * \note On entry, the bridge is already locked.
1163  * \note The bridge is expected to have exactly two parties.
1164  *
1165  * \return Nothing
1166  */
1167 static void set_bridge_peer_vars_2party(struct ast_channel *c0, struct ast_channel *c1)
1168 {
1169         const char *c0_name;
1170         const char *c1_name;
1171         const char *c0_pvtid = NULL;
1172         const char *c1_pvtid = NULL;
1173 #define UPDATE_BRIDGE_VARS_GET(chan, name, pvtid)                                                                       \
1174         do {                                                                                                                                                    \
1175                 name = ast_strdupa(ast_channel_name(chan));                                                                     \
1176                 if (ast_channel_tech(chan)->get_pvt_uniqueid) {                                                         \
1177                         pvtid = ast_strdupa(ast_channel_tech(chan)->get_pvt_uniqueid(chan));    \
1178                 }                                                                                                                                                       \
1179         } while (0)
1180
1181         ast_channel_lock(c1);
1182         UPDATE_BRIDGE_VARS_GET(c1, c1_name, c1_pvtid);
1183         ast_channel_unlock(c1);
1184
1185         ast_channel_lock(c0);
1186         update_bridge_vars_set(c0, c1_name, c1_pvtid);
1187         UPDATE_BRIDGE_VARS_GET(c0, c0_name, c0_pvtid);
1188         ast_channel_unlock(c0);
1189
1190         ast_channel_lock(c1);
1191         update_bridge_vars_set(c1, c0_name, c0_pvtid);
1192         ast_channel_unlock(c1);
1193 }
1194
1195 /*!
1196  * \internal
1197  * \brief Fill the BRIDGEPEER value buffer with a comma separated list of channel names.
1198  * \since 12.0.0
1199  *
1200  * \param buf Buffer to fill.  The caller must guarantee the buffer is large enough.
1201  * \param cur_idx Which index into names[] to skip.
1202  * \param names Channel names to put in the buffer.
1203  * \param num_names Number of names in the array.
1204  *
1205  * \return Nothing
1206  */
1207 static void fill_bridgepeer_buf(char *buf, unsigned int cur_idx, const char *names[], unsigned int num_names)
1208 {
1209         int need_separator = 0;
1210         unsigned int idx;
1211         const char *src;
1212         char *pos;
1213
1214         pos = buf;
1215         for (idx = 0; idx < num_names; ++idx) {
1216                 if (idx == cur_idx) {
1217                         continue;
1218                 }
1219
1220                 if (need_separator) {
1221                         *pos++ = ',';
1222                 }
1223                 need_separator = 1;
1224
1225                 /* Copy name into buffer. */
1226                 src = names[idx];
1227                 while (*src) {
1228                         *pos++ = *src++;
1229                 }
1230         }
1231         *pos = '\0';
1232 }
1233
1234 /*!
1235  * \internal
1236  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a multi-party bridge.
1237  * \since 12.0.0
1238  *
1239  * \param bridge What to operate on.
1240  *
1241  * \note On entry, the bridge is already locked.
1242  * \note The bridge is expected to have more than two parties.
1243  *
1244  * \return Nothing
1245  */
1246 static void set_bridge_peer_vars_multiparty(struct ast_bridge *bridge)
1247 {
1248 /*
1249  * Set a maximum number of channel names for the BRIDGEPEER
1250  * list.  The plus one is for the current channel which is not
1251  * put in the list.
1252  */
1253 #define MAX_BRIDGEPEER_CHANS    (10 + 1)
1254
1255         unsigned int idx;
1256         unsigned int num_names;
1257         unsigned int len;
1258         const char **names;
1259         char *buf;
1260         struct ast_bridge_channel *bridge_channel;
1261
1262         /* Get first MAX_BRIDGEPEER_CHANS channel names. */
1263         num_names = MIN(bridge->num_channels, MAX_BRIDGEPEER_CHANS);
1264         names = ast_alloca(num_names * sizeof(*names));
1265         idx = 0;
1266         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1267                 if (num_names <= idx) {
1268                         break;
1269                 }
1270                 ast_channel_lock(bridge_channel->chan);
1271                 names[idx++] = ast_strdupa(ast_channel_name(bridge_channel->chan));
1272                 ast_channel_unlock(bridge_channel->chan);
1273         }
1274
1275         /* Determine maximum buf size needed. */
1276         len = num_names;
1277         for (idx = 0; idx < num_names; ++idx) {
1278                 len += strlen(names[idx]);
1279         }
1280         buf = ast_alloca(len);
1281
1282         /* Set the bridge channel variables. */
1283         idx = 0;
1284         buf[0] = '\0';
1285         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1286                 if (idx < num_names) {
1287                         fill_bridgepeer_buf(buf, idx, names, num_names);
1288                 }
1289                 ++idx;
1290
1291                 ast_channel_lock(bridge_channel->chan);
1292                 update_bridge_vars_set(bridge_channel->chan, buf, NULL);
1293                 ast_channel_unlock(bridge_channel->chan);
1294         }
1295 }
1296
1297 /*!
1298  * \internal
1299  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a holding bridge.
1300  * \since 12.0.0
1301  *
1302  * \param bridge What to operate on.
1303  *
1304  * \note On entry, the bridge is already locked.
1305  *
1306  * \return Nothing
1307  */
1308 static void set_bridge_peer_vars_holding(struct ast_bridge *bridge)
1309 {
1310         struct ast_bridge_channel *bridge_channel;
1311
1312         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1313                 ast_channel_lock(bridge_channel->chan);
1314                 update_bridge_vars_set(bridge_channel->chan, NULL, NULL);
1315                 ast_channel_unlock(bridge_channel->chan);
1316         }
1317 }
1318
1319 /*!
1320  * \internal
1321  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in the bridge.
1322  * \since 12.0.0
1323  *
1324  * \param bridge What to operate on.
1325  *
1326  * \note On entry, the bridge is already locked.
1327  *
1328  * \return Nothing
1329  */
1330 static void set_bridge_peer_vars(struct ast_bridge *bridge)
1331 {
1332         if (bridge->technology->capabilities & AST_BRIDGE_CAPABILITY_HOLDING) {
1333                 set_bridge_peer_vars_holding(bridge);
1334                 return;
1335         }
1336         if (bridge->num_channels < 2) {
1337                 return;
1338         }
1339         if (bridge->num_channels == 2) {
1340                 set_bridge_peer_vars_2party(AST_LIST_FIRST(&bridge->channels)->chan,
1341                         AST_LIST_LAST(&bridge->channels)->chan);
1342         } else {
1343                 set_bridge_peer_vars_multiparty(bridge);
1344         }
1345 }
1346
1347 void bridge_reconfigured(struct ast_bridge *bridge, unsigned int colp_update)
1348 {
1349         if (!bridge->reconfigured) {
1350                 return;
1351         }
1352         bridge->reconfigured = 0;
1353         if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_SMART)
1354                 && smart_bridge_operation(bridge)) {
1355                 /* Smart bridge failed. */
1356                 bridge_dissolve(bridge);
1357                 return;
1358         }
1359         bridge_complete_join(bridge);
1360
1361         if (bridge->dissolved) {
1362                 return;
1363         }
1364         check_bridge_play_sounds(bridge);
1365         set_bridge_peer_vars(bridge);
1366         ast_bridge_publish_state(bridge);
1367
1368         if (colp_update) {
1369                 bridge_reconfigured_connected_line_update(bridge);
1370         }
1371 }
1372
1373 struct ast_bridge_channel *bridge_find_channel(struct ast_bridge *bridge, struct ast_channel *chan)
1374 {
1375         struct ast_bridge_channel *bridge_channel;
1376
1377         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1378                 if (bridge_channel->chan == chan) {
1379                         break;
1380                 }
1381         }
1382
1383         return bridge_channel;
1384 }
1385
1386 void ast_bridge_notify_masquerade(struct ast_channel *chan)
1387 {
1388         struct ast_bridge_channel *bridge_channel;
1389         struct ast_bridge *bridge;
1390
1391         /* Safely get the bridge_channel pointer for the chan. */
1392         ast_channel_lock(chan);
1393         bridge_channel = ast_channel_get_bridge_channel(chan);
1394         ast_channel_unlock(chan);
1395         if (!bridge_channel) {
1396                 /* Not in a bridge */
1397                 return;
1398         }
1399
1400         ast_bridge_channel_lock_bridge(bridge_channel);
1401         bridge = bridge_channel->bridge;
1402         if (bridge_channel == bridge_find_channel(bridge, chan)) {
1403 /* BUGBUG this needs more work.  The channels need to be made compatible again if the formats change. The bridge_channel thread needs to monitor for this case. */
1404                 /* The channel we want to notify is still in a bridge. */
1405                 bridge->v_table->notify_masquerade(bridge, bridge_channel);
1406                 bridge_reconfigured(bridge, 1);
1407         }
1408         ast_bridge_unlock(bridge);
1409         ao2_ref(bridge_channel, -1);
1410 }
1411
1412 /*
1413  * BUGBUG make ast_bridge_join() require features to be allocated just like ast_bridge_impart() and not expect the struct back.
1414  *
1415  * This change is really going to break ConfBridge.  All other
1416  * users are easily changed.  However, it is needed so the
1417  * bridging code can manipulate features on all channels
1418  * consistently no matter how they joined.
1419  *
1420  * Need to update the features parameter doxygen when this
1421  * change is made to be like ast_bridge_impart().
1422  */
1423 int ast_bridge_join(struct ast_bridge *bridge,
1424         struct ast_channel *chan,
1425         struct ast_channel *swap,
1426         struct ast_bridge_features *features,
1427         struct ast_bridge_tech_optimizations *tech_args,
1428         int pass_reference)
1429 {
1430         struct ast_bridge_channel *bridge_channel;
1431         int res;
1432
1433         bridge_channel = bridge_channel_internal_alloc(bridge);
1434         if (pass_reference) {
1435                 ao2_ref(bridge, -1);
1436         }
1437         if (!bridge_channel) {
1438                 res = -1;
1439                 goto join_exit;
1440         }
1441 /* BUGBUG features cannot be NULL when passed in. When it is changed to allocated we can do like ast_bridge_impart() and allocate one. */
1442         ast_assert(features != NULL);
1443         if (!features) {
1444                 ao2_ref(bridge_channel, -1);
1445                 res = -1;
1446                 goto join_exit;
1447         }
1448         if (tech_args) {
1449                 bridge_channel->tech_args = *tech_args;
1450         }
1451
1452         /* Initialize various other elements of the bridge channel structure that we can't do above */
1453         ast_channel_lock(chan);
1454         ast_channel_internal_bridge_channel_set(chan, bridge_channel);
1455         ast_channel_unlock(chan);
1456         bridge_channel->thread = pthread_self();
1457         bridge_channel->chan = chan;
1458         bridge_channel->swap = swap;
1459         bridge_channel->features = features;
1460
1461         res = bridge_channel_internal_join(bridge_channel);
1462
1463         /* Cleanup all the data in the bridge channel after it leaves the bridge. */
1464         ast_channel_lock(chan);
1465         ast_channel_internal_bridge_channel_set(chan, NULL);
1466         ast_channel_unlock(chan);
1467         bridge_channel->chan = NULL;
1468         bridge_channel->swap = NULL;
1469         bridge_channel->features = NULL;
1470
1471         ao2_ref(bridge_channel, -1);
1472
1473 join_exit:;
1474 /* BUGBUG this is going to cause problems for DTMF atxfer attended bridge between B & C.  Maybe an ast_bridge_join_internal() that does not do the after bridge goto for this case. */
1475         ast_bridge_run_after_callback(chan);
1476         if (!(ast_channel_softhangup_internal_flag(chan) & AST_SOFTHANGUP_ASYNCGOTO)
1477                 && !ast_bridge_setup_after_goto(chan)) {
1478                 /* Claim the after bridge goto is an async goto destination. */
1479                 ast_channel_lock(chan);
1480                 ast_softhangup_nolock(chan, AST_SOFTHANGUP_ASYNCGOTO);
1481                 ast_channel_unlock(chan);
1482         }
1483         return res;
1484 }
1485
1486 /*! \brief Thread responsible for imparted bridged channels to be departed */
1487 static void *bridge_channel_depart_thread(void *data)
1488 {
1489         struct ast_bridge_channel *bridge_channel = data;
1490
1491         if (bridge_channel->callid) {
1492                 ast_callid_threadassoc_add(bridge_channel->callid);
1493         }
1494
1495         bridge_channel_internal_join(bridge_channel);
1496
1497         /* cleanup */
1498         bridge_channel->swap = NULL;
1499         ast_bridge_features_destroy(bridge_channel->features);
1500         bridge_channel->features = NULL;
1501
1502         ast_bridge_discard_after_callback(bridge_channel->chan, AST_BRIDGE_AFTER_CB_REASON_DEPART);
1503         ast_bridge_discard_after_goto(bridge_channel->chan);
1504
1505         return NULL;
1506 }
1507
1508 /*! \brief Thread responsible for independent imparted bridged channels */
1509 static void *bridge_channel_ind_thread(void *data)
1510 {
1511         struct ast_bridge_channel *bridge_channel = data;
1512         struct ast_channel *chan;
1513
1514         if (bridge_channel->callid) {
1515                 ast_callid_threadassoc_add(bridge_channel->callid);
1516         }
1517
1518         bridge_channel_internal_join(bridge_channel);
1519         chan = bridge_channel->chan;
1520
1521         /* cleanup */
1522         ast_channel_lock(chan);
1523         ast_channel_internal_bridge_channel_set(chan, NULL);
1524         ast_channel_unlock(chan);
1525         bridge_channel->chan = NULL;
1526         bridge_channel->swap = NULL;
1527         ast_bridge_features_destroy(bridge_channel->features);
1528         bridge_channel->features = NULL;
1529
1530         ao2_ref(bridge_channel, -1);
1531
1532         ast_bridge_run_after_callback(chan);
1533         ast_bridge_run_after_goto(chan);
1534         return NULL;
1535 }
1536
1537 int ast_bridge_impart(struct ast_bridge *bridge, struct ast_channel *chan, struct ast_channel *swap, struct ast_bridge_features *features, int independent)
1538 {
1539         int res;
1540         struct ast_bridge_channel *bridge_channel;
1541
1542         /* Supply an empty features structure if the caller did not. */
1543         if (!features) {
1544                 features = ast_bridge_features_new();
1545                 if (!features) {
1546                         return -1;
1547                 }
1548         }
1549
1550         /* Try to allocate a structure for the bridge channel */
1551         bridge_channel = bridge_channel_internal_alloc(bridge);
1552         if (!bridge_channel) {
1553                 ast_bridge_features_destroy(features);
1554                 return -1;
1555         }
1556
1557         /* Setup various parameters */
1558         ast_channel_lock(chan);
1559         ast_channel_internal_bridge_channel_set(chan, bridge_channel);
1560         ast_channel_unlock(chan);
1561         bridge_channel->chan = chan;
1562         bridge_channel->swap = swap;
1563         bridge_channel->features = features;
1564         bridge_channel->depart_wait = independent ? 0 : 1;
1565         bridge_channel->callid = ast_read_threadstorage_callid();
1566
1567         /* Actually create the thread that will handle the channel */
1568         if (independent) {
1569                 /* Independently imparted channels cannot have a PBX. */
1570                 ast_assert(!ast_channel_pbx(chan));
1571
1572                 res = ast_pthread_create_detached(&bridge_channel->thread, NULL,
1573                         bridge_channel_ind_thread, bridge_channel);
1574         } else {
1575                 /* Imparted channels to be departed should not have a PBX either. */
1576                 ast_assert(!ast_channel_pbx(chan));
1577
1578                 res = ast_pthread_create(&bridge_channel->thread, NULL,
1579                         bridge_channel_depart_thread, bridge_channel);
1580         }
1581
1582         if (res) {
1583                 /* cleanup */
1584                 ast_channel_lock(chan);
1585                 ast_channel_internal_bridge_channel_set(chan, NULL);
1586                 ast_channel_unlock(chan);
1587                 bridge_channel->chan = NULL;
1588                 bridge_channel->swap = NULL;
1589                 ast_bridge_features_destroy(bridge_channel->features);
1590                 bridge_channel->features = NULL;
1591
1592                 ao2_ref(bridge_channel, -1);
1593                 return -1;
1594         }
1595
1596         return 0;
1597 }
1598
1599 int ast_bridge_depart(struct ast_channel *chan)
1600 {
1601         struct ast_bridge_channel *bridge_channel;
1602         int departable;
1603
1604         ast_channel_lock(chan);
1605         bridge_channel = ast_channel_internal_bridge_channel(chan);
1606         departable = bridge_channel && bridge_channel->depart_wait;
1607         ast_channel_unlock(chan);
1608         if (!departable) {
1609                 ast_log(LOG_ERROR, "Channel %s cannot be departed.\n",
1610                         ast_channel_name(chan));
1611                 /*
1612                  * Should never happen.  It likely means that
1613                  * ast_bridge_depart() is called by two threads for the same
1614                  * channel, the channel was never imparted to be departed, or it
1615                  * has already been departed.
1616                  */
1617                 ast_assert(0);
1618                 return -1;
1619         }
1620
1621         /*
1622          * We are claiming the reference held by the depart bridge
1623          * channel thread.
1624          */
1625
1626         ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
1627
1628         /* Wait for the depart thread to die */
1629         ast_debug(1, "Waiting for %p(%s) bridge thread to die.\n",
1630                 bridge_channel, ast_channel_name(bridge_channel->chan));
1631         pthread_join(bridge_channel->thread, NULL);
1632
1633         ast_channel_lock(chan);
1634         ast_channel_internal_bridge_channel_set(chan, NULL);
1635         ast_channel_unlock(chan);
1636
1637         /* We can get rid of the bridge_channel after the depart thread has died. */
1638         ao2_ref(bridge_channel, -1);
1639         return 0;
1640 }
1641
1642 int ast_bridge_remove(struct ast_bridge *bridge, struct ast_channel *chan)
1643 {
1644         struct ast_bridge_channel *bridge_channel;
1645
1646         ast_bridge_lock(bridge);
1647
1648         /* Try to find the channel that we want to remove */
1649         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
1650                 ast_bridge_unlock(bridge);
1651                 return -1;
1652         }
1653
1654         ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
1655
1656         ast_bridge_unlock(bridge);
1657
1658         return 0;
1659 }
1660
1661 /*!
1662  * \internal
1663  * \brief Point the bridge_channel to a new bridge.
1664  * \since 12.0.0
1665  *
1666  * \param bridge_channel What is to point to a new bridge.
1667  * \param new_bridge Where the bridge channel should point.
1668  *
1669  * \return Nothing
1670  */
1671 static void bridge_channel_change_bridge(struct ast_bridge_channel *bridge_channel, struct ast_bridge *new_bridge)
1672 {
1673         struct ast_bridge *old_bridge;
1674
1675         ao2_ref(new_bridge, +1);
1676         ast_bridge_channel_lock(bridge_channel);
1677         ast_channel_lock(bridge_channel->chan);
1678         old_bridge = bridge_channel->bridge;
1679         bridge_channel->bridge = new_bridge;
1680         ast_channel_internal_bridge_set(bridge_channel->chan, new_bridge);
1681         ast_channel_unlock(bridge_channel->chan);
1682         ast_bridge_channel_unlock(bridge_channel);
1683         ao2_ref(old_bridge, -1);
1684 }
1685
1686 void bridge_do_merge(struct ast_bridge *dst_bridge, struct ast_bridge *src_bridge, struct ast_bridge_channel **kick_me, unsigned int num_kick,
1687         unsigned int optimized)
1688 {
1689         struct ast_bridge_channel *bridge_channel;
1690         unsigned int idx;
1691
1692         ast_debug(1, "Merging bridge %s into bridge %s\n",
1693                 src_bridge->uniqueid, dst_bridge->uniqueid);
1694
1695         ast_bridge_publish_merge(dst_bridge, src_bridge);
1696
1697         /*
1698          * Move channels from src_bridge over to dst_bridge.
1699          *
1700          * We must use AST_LIST_TRAVERSE_SAFE_BEGIN() because
1701          * bridge_channel_internal_pull() alters the list we are traversing.
1702          */
1703         AST_LIST_TRAVERSE_SAFE_BEGIN(&src_bridge->channels, bridge_channel, entry) {
1704                 if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
1705                         /*
1706                          * The channel is already leaving let it leave normally because
1707                          * pulling it may delete hooks that should run for this channel.
1708                          */
1709                         continue;
1710                 }
1711                 if (ast_test_flag(&bridge_channel->features->feature_flags,
1712                         AST_BRIDGE_CHANNEL_FLAG_IMMOVABLE)) {
1713                         continue;
1714                 }
1715
1716                 if (kick_me) {
1717                         for (idx = 0; idx < num_kick; ++idx) {
1718                                 if (bridge_channel == kick_me[idx]) {
1719                                         ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
1720                                         break;
1721                                 }
1722                         }
1723                 }
1724                 bridge_channel_internal_pull(bridge_channel);
1725                 if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
1726                         /*
1727                          * The channel died as a result of being pulled or it was
1728                          * kicked.  Leave it pointing to the original bridge.
1729                          */
1730                         continue;
1731                 }
1732
1733                 /* Point to new bridge.*/
1734                 bridge_channel_change_bridge(bridge_channel, dst_bridge);
1735
1736                 if (bridge_channel_internal_push(bridge_channel)) {
1737                         ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
1738                 }
1739         }
1740         AST_LIST_TRAVERSE_SAFE_END;
1741
1742         if (kick_me) {
1743                 /*
1744                  * Now we can kick any channels in the dst_bridge without
1745                  * potentially dissolving the bridge.
1746                  */
1747                 for (idx = 0; idx < num_kick; ++idx) {
1748                         bridge_channel = kick_me[idx];
1749                         ast_bridge_channel_lock(bridge_channel);
1750                         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
1751                                 ast_bridge_channel_leave_bridge_nolock(bridge_channel, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
1752                                 bridge_channel_internal_pull(bridge_channel);
1753                         }
1754                         ast_bridge_channel_unlock(bridge_channel);
1755                 }
1756         }
1757
1758         bridge_reconfigured(dst_bridge, !optimized);
1759         bridge_reconfigured(src_bridge, !optimized);
1760
1761         ast_debug(1, "Merged bridge %s into bridge %s\n",
1762                 src_bridge->uniqueid, dst_bridge->uniqueid);
1763 }
1764
1765 struct merge_direction {
1766         /*! Destination merge bridge. */
1767         struct ast_bridge *dest;
1768         /*! Source merge bridge. */
1769         struct ast_bridge *src;
1770 };
1771
1772 /*!
1773  * \internal
1774  * \brief Determine which bridge should merge into the other.
1775  * \since 12.0.0
1776  *
1777  * \param bridge1 A bridge for merging
1778  * \param bridge2 A bridge for merging
1779  *
1780  * \note The two bridges are assumed already locked.
1781  *
1782  * \return Which bridge merges into which or NULL bridges if cannot merge.
1783  */
1784 static struct merge_direction bridge_merge_determine_direction(struct ast_bridge *bridge1, struct ast_bridge *bridge2)
1785 {
1786         struct merge_direction merge = { NULL, NULL };
1787         int bridge1_priority;
1788         int bridge2_priority;
1789
1790         if (!ast_test_flag(&bridge1->feature_flags,
1791                         AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)
1792                 && !ast_test_flag(&bridge2->feature_flags,
1793                         AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
1794                 /*
1795                  * Can merge either way.  Merge to the higher priority merge
1796                  * bridge.  Otherwise merge to the larger bridge.
1797                  */
1798                 bridge1_priority = bridge1->v_table->get_merge_priority(bridge1);
1799                 bridge2_priority = bridge2->v_table->get_merge_priority(bridge2);
1800                 if (bridge2_priority < bridge1_priority) {
1801                         merge.dest = bridge1;
1802                         merge.src = bridge2;
1803                 } else if (bridge1_priority < bridge2_priority) {
1804                         merge.dest = bridge2;
1805                         merge.src = bridge1;
1806                 } else {
1807                         /* Merge to the larger bridge. */
1808                         if (bridge2->num_channels <= bridge1->num_channels) {
1809                                 merge.dest = bridge1;
1810                                 merge.src = bridge2;
1811                         } else {
1812                                 merge.dest = bridge2;
1813                                 merge.src = bridge1;
1814                         }
1815                 }
1816         } else if (!ast_test_flag(&bridge1->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
1817                 && !ast_test_flag(&bridge2->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
1818                 /* Can merge only one way. */
1819                 merge.dest = bridge1;
1820                 merge.src = bridge2;
1821         } else if (!ast_test_flag(&bridge2->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
1822                 && !ast_test_flag(&bridge1->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
1823                 /* Can merge only one way. */
1824                 merge.dest = bridge2;
1825                 merge.src = bridge1;
1826         }
1827
1828         return merge;
1829 }
1830
1831 /*!
1832  * \internal
1833  * \brief Merge two bridges together
1834  * \since 12.0.0
1835  *
1836  * \param dst_bridge Destination bridge of merge.
1837  * \param src_bridge Source bridge of merge.
1838  * \param merge_best_direction TRUE if don't care about which bridge merges into the other.
1839  * \param kick_me Array of channels to kick from the bridges.
1840  * \param num_kick Number of channels in the kick_me array.
1841  *
1842  * \note The dst_bridge and src_bridge are assumed already locked.
1843  *
1844  * \retval 0 on success
1845  * \retval -1 on failure
1846  */
1847 static int bridge_merge_locked(struct ast_bridge *dst_bridge, struct ast_bridge *src_bridge, int merge_best_direction, struct ast_channel **kick_me, unsigned int num_kick)
1848 {
1849         struct merge_direction merge;
1850         struct ast_bridge_channel **kick_them = NULL;
1851
1852         /* Sanity check. */
1853         ast_assert(dst_bridge && src_bridge && dst_bridge != src_bridge && (!num_kick || kick_me));
1854
1855         if (dst_bridge->dissolved || src_bridge->dissolved) {
1856                 ast_debug(1, "Can't merge bridges %s and %s, at least one bridge is dissolved.\n",
1857                         src_bridge->uniqueid, dst_bridge->uniqueid);
1858                 return -1;
1859         }
1860         if (ast_test_flag(&dst_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)
1861                 || ast_test_flag(&src_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)) {
1862                 ast_debug(1, "Can't merge bridges %s and %s, masquerade only.\n",
1863                         src_bridge->uniqueid, dst_bridge->uniqueid);
1864                 return -1;
1865         }
1866         if (dst_bridge->inhibit_merge || src_bridge->inhibit_merge) {
1867                 ast_debug(1, "Can't merge bridges %s and %s, merging temporarily inhibited.\n",
1868                         src_bridge->uniqueid, dst_bridge->uniqueid);
1869                 return -1;
1870         }
1871
1872         if (merge_best_direction) {
1873                 merge = bridge_merge_determine_direction(dst_bridge, src_bridge);
1874         } else {
1875                 merge.dest = dst_bridge;
1876                 merge.src = src_bridge;
1877         }
1878
1879         if (!merge.dest
1880                 || ast_test_flag(&merge.dest->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
1881                 || ast_test_flag(&merge.src->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
1882                 ast_debug(1, "Can't merge bridges %s and %s, merging inhibited.\n",
1883                         src_bridge->uniqueid, dst_bridge->uniqueid);
1884                 return -1;
1885         }
1886         if (merge.src->num_channels < 2) {
1887                 /*
1888                  * For a two party bridge, a channel may be temporarily removed
1889                  * from the source bridge or the initial bridge members have not
1890                  * joined yet.
1891                  */
1892                 ast_debug(1, "Can't merge bridge %s into bridge %s, not enough channels in source bridge.\n",
1893                         merge.src->uniqueid, merge.dest->uniqueid);
1894                 return -1;
1895         }
1896         if (2 + num_kick < merge.dest->num_channels + merge.src->num_channels
1897                 && !(merge.dest->technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)
1898                 && (!ast_test_flag(&merge.dest->feature_flags, AST_BRIDGE_FLAG_SMART)
1899                         || !(merge.dest->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX))) {
1900                 ast_debug(1, "Can't merge bridge %s into bridge %s, multimix is needed and it cannot be acquired.\n",
1901                         merge.src->uniqueid, merge.dest->uniqueid);
1902                 return -1;
1903         }
1904
1905         if (num_kick) {
1906                 unsigned int num_to_kick = 0;
1907                 unsigned int idx;
1908
1909                 kick_them = ast_alloca(num_kick * sizeof(*kick_them));
1910                 for (idx = 0; idx < num_kick; ++idx) {
1911                         kick_them[num_to_kick] = bridge_find_channel(merge.src, kick_me[idx]);
1912                         if (!kick_them[num_to_kick]) {
1913                                 kick_them[num_to_kick] = bridge_find_channel(merge.dest, kick_me[idx]);
1914                         }
1915                         if (kick_them[num_to_kick]) {
1916                                 ++num_to_kick;
1917                         }
1918                 }
1919
1920                 if (num_to_kick != num_kick) {
1921                         ast_debug(1, "Can't merge bridge %s into bridge %s, at least one kicked channel is not in either bridge.\n",
1922                                 merge.src->uniqueid, merge.dest->uniqueid);
1923                         return -1;
1924                 }
1925         }
1926
1927         bridge_do_merge(merge.dest, merge.src, kick_them, num_kick, 0);
1928         return 0;
1929 }
1930
1931 int ast_bridge_merge(struct ast_bridge *dst_bridge, struct ast_bridge *src_bridge, int merge_best_direction, struct ast_channel **kick_me, unsigned int num_kick)
1932 {
1933         int res;
1934
1935         /* Sanity check. */
1936         ast_assert(dst_bridge && src_bridge);
1937
1938         ast_bridge_lock_both(dst_bridge, src_bridge);
1939         res = bridge_merge_locked(dst_bridge, src_bridge, merge_best_direction, kick_me, num_kick);
1940         ast_bridge_unlock(src_bridge);
1941         ast_bridge_unlock(dst_bridge);
1942         return res;
1943 }
1944
1945 int bridge_do_move(struct ast_bridge *dst_bridge, struct ast_bridge_channel *bridge_channel, int attempt_recovery,
1946         unsigned int optimized)
1947 {
1948         struct ast_bridge *orig_bridge;
1949         int was_in_bridge;
1950         int res = 0;
1951
1952 /* BUGBUG need bridge move stasis event and a success/fail event. */
1953         if (bridge_channel->swap) {
1954                 ast_debug(1, "Moving %p(%s) into bridge %s swapping with %s\n",
1955                         bridge_channel, ast_channel_name(bridge_channel->chan), dst_bridge->uniqueid,
1956                         ast_channel_name(bridge_channel->swap));
1957         } else {
1958                 ast_debug(1, "Moving %p(%s) into bridge %s\n",
1959                         bridge_channel, ast_channel_name(bridge_channel->chan), dst_bridge->uniqueid);
1960         }
1961
1962         orig_bridge = bridge_channel->bridge;
1963         was_in_bridge = bridge_channel->in_bridge;
1964
1965         bridge_channel_internal_pull(bridge_channel);
1966         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
1967                 /*
1968                  * The channel died as a result of being pulled.  Leave it
1969                  * pointing to the original bridge.
1970                  */
1971                 bridge_reconfigured(orig_bridge, 0);
1972                 return -1;
1973         }
1974
1975         /* Point to new bridge.*/
1976         ao2_ref(orig_bridge, +1);/* Keep a ref in case the push fails. */
1977         bridge_channel_change_bridge(bridge_channel, dst_bridge);
1978
1979         if (bridge_channel_internal_push(bridge_channel)) {
1980                 /* Try to put the channel back into the original bridge. */
1981                 if (attempt_recovery && was_in_bridge) {
1982                         /* Point back to original bridge. */
1983                         bridge_channel_change_bridge(bridge_channel, orig_bridge);
1984
1985                         if (bridge_channel_internal_push(bridge_channel)) {
1986                                 ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
1987                         }
1988                 } else {
1989                         ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
1990                 }
1991                 res = -1;
1992         }
1993
1994         bridge_reconfigured(dst_bridge, !optimized);
1995         bridge_reconfigured(orig_bridge, !optimized);
1996         ao2_ref(orig_bridge, -1);
1997         return res;
1998 }
1999
2000 /*!
2001  * \internal
2002  * \brief Move a channel from one bridge to another.
2003  * \since 12.0.0
2004  *
2005  * \param dst_bridge Destination bridge of bridge channel move.
2006  * \param src_bridge Source bridge of bridge channel move.
2007  * \param chan Channel to move.
2008  * \param swap Channel to replace in dst_bridge.
2009  * \param attempt_recovery TRUE if failure attempts to push channel back into original bridge.
2010  *
2011  * \note The dst_bridge and src_bridge are assumed already locked.
2012  *
2013  * \retval 0 on success.
2014  * \retval -1 on failure.
2015  */
2016 static int bridge_move_locked(struct ast_bridge *dst_bridge, struct ast_bridge *src_bridge, struct ast_channel *chan, struct ast_channel *swap, int attempt_recovery)
2017 {
2018         struct ast_bridge_channel *bridge_channel;
2019
2020         if (dst_bridge->dissolved || src_bridge->dissolved) {
2021                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, at least one bridge is dissolved.\n",
2022                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2023                 return -1;
2024         }
2025         if (ast_test_flag(&dst_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)
2026                 || ast_test_flag(&src_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)) {
2027                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, masquerade only.\n",
2028                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2029                 return -1;
2030         }
2031         if (dst_bridge->inhibit_merge || src_bridge->inhibit_merge) {
2032                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, temporarily inhibited.\n",
2033                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2034                 return -1;
2035         }
2036
2037         bridge_channel = bridge_find_channel(src_bridge, chan);
2038         if (!bridge_channel) {
2039                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel not in bridge.\n",
2040                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2041                 return -1;
2042         }
2043         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2044                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel leaving bridge.\n",
2045                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2046                 return -1;
2047         }
2048         if (ast_test_flag(&bridge_channel->features->feature_flags,
2049                 AST_BRIDGE_CHANNEL_FLAG_IMMOVABLE)) {
2050                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel immovable.\n",
2051                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2052                 return -1;
2053         }
2054
2055         if (swap) {
2056                 struct ast_bridge_channel *bridge_channel_swap;
2057
2058                 bridge_channel_swap = bridge_find_channel(dst_bridge, swap);
2059                 if (!bridge_channel_swap) {
2060                         ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, swap channel %s not in bridge.\n",
2061                                 ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid,
2062                                 ast_channel_name(swap));
2063                         return -1;
2064                 }
2065                 if (bridge_channel_swap->state != BRIDGE_CHANNEL_STATE_WAIT) {
2066                         ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, swap channel %s leaving bridge.\n",
2067                                 ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid,
2068                                 ast_channel_name(swap));
2069                         return -1;
2070                 }
2071         }
2072
2073         bridge_channel->swap = swap;
2074         return bridge_do_move(dst_bridge, bridge_channel, attempt_recovery, 0);
2075 }
2076
2077 int ast_bridge_move(struct ast_bridge *dst_bridge, struct ast_bridge *src_bridge, struct ast_channel *chan, struct ast_channel *swap, int attempt_recovery)
2078 {
2079         int res;
2080
2081         ast_bridge_lock_both(dst_bridge, src_bridge);
2082         res = bridge_move_locked(dst_bridge, src_bridge, chan, swap, attempt_recovery);
2083         ast_bridge_unlock(src_bridge);
2084         ast_bridge_unlock(dst_bridge);
2085         return res;
2086 }
2087
2088 int ast_bridge_add_channel(struct ast_bridge *bridge, struct ast_channel *chan,
2089         struct ast_bridge_features *features, int play_tone, const char *xfersound)
2090 {
2091         RAII_VAR(struct ast_bridge *, chan_bridge, NULL, ao2_cleanup);
2092         RAII_VAR(struct ast_channel *, yanked_chan, NULL, ao2_cleanup);
2093
2094         ast_channel_lock(chan);
2095         chan_bridge = ast_channel_get_bridge(chan);
2096         ast_channel_unlock(chan);
2097
2098         if (chan_bridge) {
2099                 RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
2100
2101                 ast_bridge_lock_both(bridge, chan_bridge);
2102                 bridge_channel = bridge_find_channel(chan_bridge, chan);
2103                 if (bridge_move_locked(bridge, chan_bridge, chan, NULL, 1)) {
2104                         ast_bridge_unlock(chan_bridge);
2105                         ast_bridge_unlock(bridge);
2106                         return -1;
2107                 }
2108
2109                 /*
2110                  * bridge_move_locked() will implicitly ensure that
2111                  * bridge_channel is not NULL.
2112                  */
2113                 ast_assert(bridge_channel != NULL);
2114
2115                 /*
2116                  * Additional checks if the channel we just stole dissolves the
2117                  * original bridge.
2118                  */
2119                 bridge_dissolve_check_stolen(chan_bridge, bridge_channel);
2120                 ast_bridge_unlock(chan_bridge);
2121                 ast_bridge_unlock(bridge);
2122
2123                 /* The channel was in a bridge so it is not getting any new features. */
2124                 ast_bridge_features_destroy(features);
2125         } else {
2126                 /* Slightly less easy case. We need to yank channel A from
2127                  * where he currently is and impart him into our bridge.
2128                  */
2129                 yanked_chan = ast_channel_yank(chan);
2130                 if (!yanked_chan) {
2131                         ast_log(LOG_WARNING, "Could not gain control of channel %s\n", ast_channel_name(chan));
2132                         return -1;
2133                 }
2134                 if (ast_channel_state(yanked_chan) != AST_STATE_UP) {
2135                         ast_answer(yanked_chan);
2136                 }
2137                 ast_channel_ref(yanked_chan);
2138                 if (ast_bridge_impart(bridge, yanked_chan, NULL, features, 1)) {
2139                         ast_log(LOG_WARNING, "Could not add %s to the bridge\n", ast_channel_name(chan));
2140                         ast_hangup(yanked_chan);
2141                         return -1;
2142                 }
2143         }
2144
2145         if (play_tone && !ast_strlen_zero(xfersound)) {
2146                 struct ast_channel *play_chan = yanked_chan ?: chan;
2147                 RAII_VAR(struct ast_bridge_channel *, play_bridge_channel, NULL, ao2_cleanup);
2148
2149                 ast_channel_lock(play_chan);
2150                 play_bridge_channel = ast_channel_get_bridge_channel(play_chan);
2151                 ast_channel_unlock(play_chan);
2152
2153                 if (!play_bridge_channel) {
2154                         ast_log(LOG_WARNING, "Unable to play tone for channel %s. No longer in a bridge.\n",
2155                                 ast_channel_name(play_chan));
2156                 } else {
2157                         ast_bridge_channel_queue_playfile(play_bridge_channel, NULL, xfersound, NULL);
2158                 }
2159         }
2160         return 0;
2161 }
2162
2163 static int bridge_allows_optimization(struct ast_bridge *bridge)
2164 {
2165         return !(bridge->inhibit_merge
2166                 || bridge->dissolved
2167                 || ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY));
2168 }
2169
2170 /*!
2171  * \internal
2172  * \brief Lock the unreal channel stack for chan and prequalify it.
2173  * \since 12.0.0
2174  *
2175  * \param chan Unreal channel writing a frame into the channel driver.
2176  *
2177  * \note It is assumed that chan is already locked.
2178  *
2179  * \retval bridge on success with bridge and bridge_channel locked.
2180  * \retval NULL if cannot do optimization now.
2181  */
2182 static struct ast_bridge *optimize_lock_chan_stack(struct ast_channel *chan)
2183 {
2184         struct ast_bridge *bridge;
2185         struct ast_bridge_channel *bridge_channel;
2186
2187         if (!AST_LIST_EMPTY(ast_channel_readq(chan))) {
2188                 return NULL;
2189         }
2190         if (ast_channel_has_audio_frame_or_monitor(chan)) {
2191                 /* Channel has an active monitor, audiohook, or framehook. */
2192                 return NULL;
2193         }
2194         bridge_channel = ast_channel_internal_bridge_channel(chan);
2195         if (!bridge_channel || ast_bridge_channel_trylock(bridge_channel)) {
2196                 return NULL;
2197         }
2198         bridge = bridge_channel->bridge;
2199         if (bridge_channel->activity != BRIDGE_CHANNEL_THREAD_SIMPLE
2200                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
2201                 || ast_bridge_trylock(bridge)) {
2202                 ast_bridge_channel_unlock(bridge_channel);
2203                 return NULL;
2204         }
2205         if (!bridge_channel_internal_allows_optimization(bridge_channel) ||
2206                         !bridge_allows_optimization(bridge)) {
2207                 ast_bridge_unlock(bridge);
2208                 ast_bridge_channel_unlock(bridge_channel);
2209                 return NULL;
2210         }
2211         return bridge;
2212 }
2213
2214 /*!
2215  * \internal
2216  * \brief Lock the unreal channel stack for peer and prequalify it.
2217  * \since 12.0.0
2218  *
2219  * \param peer Other unreal channel in the pair.
2220  *
2221  * \retval bridge on success with bridge, bridge_channel, and peer locked.
2222  * \retval NULL if cannot do optimization now.
2223  */
2224 static struct ast_bridge *optimize_lock_peer_stack(struct ast_channel *peer)
2225 {
2226         struct ast_bridge *bridge;
2227         struct ast_bridge_channel *bridge_channel;
2228
2229         if (ast_channel_trylock(peer)) {
2230                 return NULL;
2231         }
2232         if (!AST_LIST_EMPTY(ast_channel_readq(peer))) {
2233                 ast_channel_unlock(peer);
2234                 return NULL;
2235         }
2236         if (ast_channel_has_audio_frame_or_monitor(peer)) {
2237                 /* Peer has an active monitor, audiohook, or framehook. */
2238                 ast_channel_unlock(peer);
2239                 return NULL;
2240         }
2241         bridge_channel = ast_channel_internal_bridge_channel(peer);
2242         if (!bridge_channel || ast_bridge_channel_trylock(bridge_channel)) {
2243                 ast_channel_unlock(peer);
2244                 return NULL;
2245         }
2246         bridge = bridge_channel->bridge;
2247         if (bridge_channel->activity != BRIDGE_CHANNEL_THREAD_IDLE
2248                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
2249                 || ast_bridge_trylock(bridge)) {
2250                 ast_bridge_channel_unlock(bridge_channel);
2251                 ast_channel_unlock(peer);
2252                 return NULL;
2253         }
2254         if (!bridge_allows_optimization(bridge) ||
2255                         !bridge_channel_internal_allows_optimization(bridge_channel)) {
2256                 ast_bridge_unlock(bridge);
2257                 ast_bridge_channel_unlock(bridge_channel);
2258                 ast_channel_unlock(peer);
2259                 return NULL;
2260         }
2261         return bridge;
2262 }
2263
2264 /*!
2265  * \internal
2266  * \brief Indicates allowability of a swap optimization
2267  */
2268 enum bridge_allow_swap {
2269         /*! Bridges cannot allow for a swap optimization to occur */
2270         SWAP_PROHIBITED,
2271         /*! Bridge swap optimization can occur into the chan_bridge */
2272         SWAP_TO_CHAN_BRIDGE,
2273         /*! Bridge swap optimization can occur into the peer_bridge */
2274         SWAP_TO_PEER_BRIDGE,
2275 };
2276
2277 /*!
2278  * \internal
2279  * \brief Determine if two bridges allow for swap optimization to occur
2280  *
2281  * \param chan_bridge First bridge being tested
2282  * \param peer_bridge Second bridge being tested
2283  * \return Allowability of swap optimization
2284  */
2285 static enum bridge_allow_swap bridges_allow_swap_optimization(struct ast_bridge *chan_bridge,
2286                 struct ast_bridge *peer_bridge)
2287 {
2288         int chan_priority;
2289         int peer_priority;
2290
2291         if (!ast_test_flag(&chan_bridge->feature_flags,
2292                         AST_BRIDGE_FLAG_SWAP_INHIBIT_TO | AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM |
2293                         AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
2294                 && !ast_test_flag(&peer_bridge->feature_flags,
2295                         AST_BRIDGE_FLAG_SWAP_INHIBIT_TO | AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM |
2296                         AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)) {
2297                 /*
2298                  * Can swap either way.  Swap to the higher priority merge
2299                  * bridge.
2300                  */
2301                 chan_priority = chan_bridge->v_table->get_merge_priority(chan_bridge);
2302                 peer_priority = peer_bridge->v_table->get_merge_priority(peer_bridge);
2303                 if (chan_bridge->num_channels == 2
2304                         && chan_priority <= peer_priority) {
2305                         return SWAP_TO_PEER_BRIDGE;
2306                 } else if (peer_bridge->num_channels == 2
2307                         && peer_priority <= chan_priority) {
2308                         return SWAP_TO_CHAN_BRIDGE;
2309                 }
2310         } else if (chan_bridge->num_channels == 2
2311                 && !ast_test_flag(&chan_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM | AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
2312                 && !ast_test_flag(&peer_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_TO)) {
2313                 /* Can swap optimize only one way. */
2314                 return SWAP_TO_PEER_BRIDGE;
2315         } else if (peer_bridge->num_channels == 2
2316                 && !ast_test_flag(&peer_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM | AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
2317                 && !ast_test_flag(&chan_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_TO)) {
2318                 /* Can swap optimize only one way. */
2319                 return SWAP_TO_CHAN_BRIDGE;
2320         }
2321
2322         return SWAP_PROHIBITED;
2323 }
2324
2325 /*!
2326  * \internal
2327  * \brief Check and attempt to swap optimize out the unreal channels.
2328  * \since 12.0.0
2329  *
2330  * \param chan_bridge
2331  * \param chan_bridge_channel
2332  * \param peer_bridge
2333  * \param peer_bridge_channel
2334  * \param pvt Unreal data containing callbacks to call if the optimization actually
2335  * happens
2336  *
2337  * \retval 1 if unreal channels failed to optimize out.
2338  * \retval 0 if unreal channels were not optimized out.
2339  * \retval -1 if unreal channels were optimized out.
2340  */
2341 static int try_swap_optimize_out(struct ast_bridge *chan_bridge,
2342         struct ast_bridge_channel *chan_bridge_channel, struct ast_bridge *peer_bridge,
2343         struct ast_bridge_channel *peer_bridge_channel,
2344         struct ast_unreal_pvt *pvt)
2345 {
2346         struct ast_bridge *dst_bridge;
2347         struct ast_bridge_channel *dst_bridge_channel;
2348         struct ast_bridge_channel *src_bridge_channel;
2349         struct ast_bridge_channel *other;
2350         int res = 1;
2351
2352         switch (bridges_allow_swap_optimization(chan_bridge, peer_bridge)) {
2353         case SWAP_TO_CHAN_BRIDGE:
2354                 dst_bridge = chan_bridge;
2355                 dst_bridge_channel = chan_bridge_channel;
2356                 src_bridge_channel = peer_bridge_channel;
2357                 break;
2358         case SWAP_TO_PEER_BRIDGE:
2359                 dst_bridge = peer_bridge;
2360                 dst_bridge_channel = peer_bridge_channel;
2361                 src_bridge_channel = chan_bridge_channel;
2362                 break;
2363         case SWAP_PROHIBITED:
2364         default:
2365                 return 0;
2366         }
2367
2368         other = ast_bridge_channel_peer(src_bridge_channel);
2369         if (other && other->state == BRIDGE_CHANNEL_STATE_WAIT) {
2370                 ast_verb(3, "Move-swap optimizing %s <-- %s.\n",
2371                         ast_channel_name(dst_bridge_channel->chan),
2372                         ast_channel_name(other->chan));
2373
2374                 if (pvt && !ast_test_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN) && pvt->callbacks
2375                                 && pvt->callbacks->optimization_started) {
2376                         pvt->callbacks->optimization_started(pvt);
2377                         ast_set_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN);
2378                 }
2379                 other->swap = dst_bridge_channel->chan;
2380                 if (!bridge_do_move(dst_bridge, other, 1, 1)) {
2381                         ast_bridge_channel_leave_bridge(src_bridge_channel, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
2382                         res = -1;
2383                         if (pvt && pvt->callbacks && pvt->callbacks->optimization_finished) {
2384                                 pvt->callbacks->optimization_finished(pvt);
2385                         }
2386                 }
2387         }
2388         return res;
2389 }
2390
2391 /*!
2392  * \internal
2393  * \brief Indicates allowability of a merge optimization
2394  */
2395 enum bridge_allow_merge {
2396         /*! Bridge properties prohibit merge optimization */
2397         MERGE_PROHIBITED,
2398         /*! Merge optimization cannot occur because the source bridge has too few channels */
2399         MERGE_NOT_ENOUGH_CHANNELS,
2400         /*! Merge optimization cannot occur because multimix capability could not be requested */
2401         MERGE_NO_MULTIMIX,
2402         /*! Merge optimization allowed between bridges */
2403         MERGE_ALLOWED,
2404 };
2405
2406 /*!
2407  * \internal
2408  * \brief Determines allowability of a merge optimization
2409  *
2410  * \note The merge output parameter is undefined if MERGE_PROHIBITED is returned. For success
2411  * and other failure returns, a merge direction was determined, and the parameter is safe to
2412  * access.
2413  *
2414  * \param chan_bridge First bridge being tested
2415  * \param peer_bridge Second bridge being tested
2416  * \param num_kick_channels The number of channels to remove from the bridges during merging
2417  * \param[out] merge Indicates the recommended direction for the bridge merge
2418  */
2419 static enum bridge_allow_merge bridges_allow_merge_optimization(struct ast_bridge *chan_bridge,
2420                 struct ast_bridge *peer_bridge, int num_kick_channels, struct merge_direction *merge)
2421 {
2422         *merge = bridge_merge_determine_direction(chan_bridge, peer_bridge);
2423         if (!merge->dest) {
2424                 return MERGE_PROHIBITED;
2425         }
2426         if (merge->src->num_channels < 2) {
2427                 return MERGE_NOT_ENOUGH_CHANNELS;
2428         } else if ((2 + num_kick_channels) < merge->dest->num_channels + merge->src->num_channels
2429                 && !(merge->dest->technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)
2430                 && (!ast_test_flag(&merge->dest->feature_flags, AST_BRIDGE_FLAG_SMART)
2431                         || !(merge->dest->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX))) {
2432                 return MERGE_NO_MULTIMIX;
2433         }
2434
2435         return MERGE_ALLOWED;
2436 }
2437
2438 /*!
2439  * \internal
2440  * \brief Check and attempt to merge optimize out the unreal channels.
2441  * \since 12.0.0
2442  *
2443  * \param chan_bridge
2444  * \param chan_bridge_channel
2445  * \param peer_bridge
2446  * \param peer_bridge_channel
2447  * \param pvt Unreal data containing callbacks to call if the optimization actually
2448  * happens
2449  *
2450  * \retval 0 if unreal channels were not optimized out.
2451  * \retval -1 if unreal channels were optimized out.
2452  */
2453 static int try_merge_optimize_out(struct ast_bridge *chan_bridge,
2454         struct ast_bridge_channel *chan_bridge_channel, struct ast_bridge *peer_bridge,
2455         struct ast_bridge_channel *peer_bridge_channel,
2456         struct ast_unreal_pvt *pvt)
2457 {
2458         struct merge_direction merge;
2459         struct ast_bridge_channel *kick_me[] = {
2460                 chan_bridge_channel,
2461                 peer_bridge_channel,
2462         };
2463
2464         switch (bridges_allow_merge_optimization(chan_bridge, peer_bridge, ARRAY_LEN(kick_me), &merge)) {
2465         case MERGE_ALLOWED:
2466                 break;
2467         case MERGE_PROHIBITED:
2468                 return 0;
2469         case MERGE_NOT_ENOUGH_CHANNELS:
2470                 ast_debug(4, "Can't optimize %s -- %s out, not enough channels in bridge %s.\n",
2471                         ast_channel_name(chan_bridge_channel->chan),
2472                         ast_channel_name(peer_bridge_channel->chan),
2473                         merge.src->uniqueid);
2474                 return 0;
2475         case MERGE_NO_MULTIMIX:
2476                 ast_debug(4, "Can't optimize %s -- %s out, multimix is needed and it cannot be acquired.\n",
2477                         ast_channel_name(chan_bridge_channel->chan),
2478                         ast_channel_name(peer_bridge_channel->chan));
2479                 return 0;
2480         }
2481
2482         ast_verb(3, "Merge optimizing %s -- %s out.\n",
2483                 ast_channel_name(chan_bridge_channel->chan),
2484                 ast_channel_name(peer_bridge_channel->chan));
2485
2486         if (pvt && !ast_test_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN) && pvt->callbacks
2487                         && pvt->callbacks->optimization_started) {
2488                 pvt->callbacks->optimization_started(pvt);
2489                 ast_set_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN);
2490         }
2491         bridge_do_merge(merge.dest, merge.src, kick_me, ARRAY_LEN(kick_me), 1);
2492         if (pvt && pvt->callbacks && pvt->callbacks->optimization_finished) {
2493                 pvt->callbacks->optimization_finished(pvt);
2494         }
2495
2496         return -1;
2497 }
2498
2499 int ast_bridge_unreal_optimize_out(struct ast_channel *chan, struct ast_channel *peer, struct ast_unreal_pvt *pvt)
2500 {
2501         struct ast_bridge *chan_bridge;
2502         struct ast_bridge *peer_bridge;
2503         struct ast_bridge_channel *chan_bridge_channel;
2504         struct ast_bridge_channel *peer_bridge_channel;
2505         int res = 0;
2506
2507         chan_bridge = optimize_lock_chan_stack(chan);
2508         if (!chan_bridge) {
2509                 return res;
2510         }
2511         chan_bridge_channel = ast_channel_internal_bridge_channel(chan);
2512
2513         peer_bridge = optimize_lock_peer_stack(peer);
2514         if (peer_bridge) {
2515                 peer_bridge_channel = ast_channel_internal_bridge_channel(peer);
2516
2517                 res = try_swap_optimize_out(chan_bridge, chan_bridge_channel,
2518                         peer_bridge, peer_bridge_channel, pvt);
2519                 if (!res) {
2520                         res = try_merge_optimize_out(chan_bridge, chan_bridge_channel,
2521                                 peer_bridge, peer_bridge_channel, pvt);
2522                 } else if (0 < res) {
2523                         res = 0;
2524                 }
2525
2526                 /* Release peer locks. */
2527                 ast_bridge_unlock(peer_bridge);
2528                 ast_bridge_channel_unlock(peer_bridge_channel);
2529                 ast_channel_unlock(peer);
2530         }
2531
2532         /* Release chan locks. */
2533         ast_bridge_unlock(chan_bridge);
2534         ast_bridge_channel_unlock(chan_bridge_channel);
2535
2536         return res;
2537 }
2538
2539 enum ast_bridge_optimization ast_bridges_allow_optimization(struct ast_bridge *chan_bridge,
2540                 struct ast_bridge *peer_bridge)
2541 {
2542         struct merge_direction merge;
2543
2544         if (!bridge_allows_optimization(chan_bridge) || !bridge_allows_optimization(peer_bridge)) {
2545                 return AST_BRIDGE_OPTIMIZE_PROHIBITED;
2546         }
2547
2548         switch (bridges_allow_swap_optimization(chan_bridge, peer_bridge)) {
2549         case SWAP_TO_CHAN_BRIDGE:
2550                 return AST_BRIDGE_OPTIMIZE_SWAP_TO_CHAN_BRIDGE;
2551         case SWAP_TO_PEER_BRIDGE:
2552                 return AST_BRIDGE_OPTIMIZE_SWAP_TO_PEER_BRIDGE;
2553         case SWAP_PROHIBITED:
2554         default:
2555                 break;
2556         }
2557
2558         /* Two channels will be kicked from the bridges, the unreal;1 and unreal;2 channels */
2559         if (bridges_allow_merge_optimization(chan_bridge, peer_bridge, 2, &merge) != MERGE_ALLOWED) {
2560                 return AST_BRIDGE_OPTIMIZE_PROHIBITED;
2561         }
2562
2563         if (merge.dest == chan_bridge) {
2564                 return AST_BRIDGE_OPTIMIZE_MERGE_TO_CHAN_BRIDGE;
2565         } else {
2566                 return AST_BRIDGE_OPTIMIZE_MERGE_TO_PEER_BRIDGE;
2567         }
2568 }
2569
2570 /*!
2571  * \internal
2572  * \brief Adjust the bridge merge inhibit request count.
2573  * \since 12.0.0
2574  *
2575  * \param bridge What to operate on.
2576  * \param request Inhibit request increment.
2577  *     (Positive to add requests.  Negative to remove requests.)
2578  *
2579  * \note This function assumes bridge is locked.
2580  *
2581  * \return Nothing
2582  */
2583 void bridge_merge_inhibit_nolock(struct ast_bridge *bridge, int request)
2584 {
2585         int new_request;
2586
2587         new_request = bridge->inhibit_merge + request;
2588         ast_assert(0 <= new_request);
2589         bridge->inhibit_merge = new_request;
2590 }
2591
2592 void ast_bridge_merge_inhibit(struct ast_bridge *bridge, int request)
2593 {
2594         ast_bridge_lock(bridge);
2595         bridge_merge_inhibit_nolock(bridge, request);
2596         ast_bridge_unlock(bridge);
2597 }
2598
2599 int ast_bridge_suspend(struct ast_bridge *bridge, struct ast_channel *chan)
2600 {
2601         struct ast_bridge_channel *bridge_channel;
2602 /* BUGBUG the case of a disolved bridge while channel is suspended is not handled. */
2603 /* BUGBUG suspend/unsuspend needs to be rethought. The caller must block until it has successfully suspended the channel for temporary control. */
2604 /* BUGBUG external suspend/unsuspend needs to be eliminated. The channel may be playing a file at the time and stealing it then is not good. */
2605
2606         ast_bridge_lock(bridge);
2607
2608         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
2609                 ast_bridge_unlock(bridge);
2610                 return -1;
2611         }
2612
2613         bridge_channel_internal_suspend_nolock(bridge_channel);
2614
2615         ast_bridge_unlock(bridge);
2616
2617         return 0;
2618 }
2619
2620 int ast_bridge_unsuspend(struct ast_bridge *bridge, struct ast_channel *chan)
2621 {
2622         struct ast_bridge_channel *bridge_channel;
2623 /* BUGBUG the case of a disolved bridge while channel is suspended is not handled. */
2624
2625         ast_bridge_lock(bridge);
2626
2627         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
2628                 ast_bridge_unlock(bridge);
2629                 return -1;
2630         }
2631
2632         bridge_channel_internal_unsuspend_nolock(bridge_channel);
2633
2634         ast_bridge_unlock(bridge);
2635
2636         return 0;
2637 }
2638
2639 void ast_bridge_technology_suspend(struct ast_bridge_technology *technology)
2640 {
2641         technology->suspended = 1;
2642 }
2643
2644 void ast_bridge_technology_unsuspend(struct ast_bridge_technology *technology)
2645 {
2646 /* BUGBUG unsuspending a bridge technology probably needs to prod all existing bridges to see if they should start using it. */
2647         technology->suspended = 0;
2648 }
2649
2650 int ast_bridge_features_register(enum ast_bridge_builtin_feature feature, ast_bridge_hook_callback callback, const char *dtmf)
2651 {
2652         if (ARRAY_LEN(builtin_features_handlers) <= feature
2653                 || builtin_features_handlers[feature]) {
2654                 return -1;
2655         }
2656
2657         if (!ast_strlen_zero(dtmf)) {
2658                 ast_copy_string(builtin_features_dtmf[feature], dtmf, sizeof(builtin_features_dtmf[feature]));
2659         }
2660
2661         builtin_features_handlers[feature] = callback;
2662
2663         return 0;
2664 }
2665
2666 int ast_bridge_features_unregister(enum ast_bridge_builtin_feature feature)
2667 {
2668         if (ARRAY_LEN(builtin_features_handlers) <= feature
2669                 || !builtin_features_handlers[feature]) {
2670                 return -1;
2671         }
2672
2673         builtin_features_handlers[feature] = NULL;
2674
2675         return 0;
2676 }
2677
2678 int ast_bridge_features_do(enum ast_bridge_builtin_feature feature, struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2679 {
2680         ast_bridge_hook_callback callback;
2681
2682         if (ARRAY_LEN(builtin_features_handlers) <= feature) {
2683                 return -1;
2684         }
2685
2686         callback = builtin_features_handlers[feature];
2687         if (!callback) {
2688                 return -1;
2689         }
2690         callback(bridge_channel, hook_pvt);
2691
2692         return 0;
2693 }
2694
2695 int ast_bridge_interval_register(enum ast_bridge_builtin_interval interval, ast_bridge_builtin_set_limits_fn callback)
2696 {
2697         if (ARRAY_LEN(builtin_interval_handlers) <= interval
2698                 || builtin_interval_handlers[interval]) {
2699                 return -1;
2700         }
2701
2702         builtin_interval_handlers[interval] = callback;
2703
2704         return 0;
2705 }
2706
2707 int ast_bridge_interval_unregister(enum ast_bridge_builtin_interval interval)
2708 {
2709         if (ARRAY_LEN(builtin_interval_handlers) <= interval
2710                 || !builtin_interval_handlers[interval]) {
2711                 return -1;
2712         }
2713
2714         builtin_interval_handlers[interval] = NULL;
2715
2716         return 0;
2717
2718 }
2719
2720 /*!
2721  * \internal
2722  * \brief Bridge hook destructor.
2723  * \since 12.0.0
2724  *
2725  * \param vhook Object to destroy.
2726  *
2727  * \return Nothing
2728  */
2729 static void bridge_hook_destroy(void *vhook)
2730 {
2731         struct ast_bridge_hook *hook = vhook;
2732
2733         if (hook->destructor) {
2734                 hook->destructor(hook->hook_pvt);
2735         }
2736 }
2737
2738 /*!
2739  * \internal
2740  * \brief Allocate and setup a generic bridge hook.
2741  * \since 12.0.0
2742  *
2743  * \param size How big an object to allocate.
2744  * \param callback Function to execute upon activation
2745  * \param hook_pvt Unique data
2746  * \param destructor Optional destructor callback for hook_pvt data
2747  * \param remove_flags Dictates what situations the hook should be removed.
2748  *
2749  * \retval hook on success.
2750  * \retval NULL on error.
2751  */
2752 static struct ast_bridge_hook *bridge_hook_generic(size_t size,
2753         ast_bridge_hook_callback callback,
2754         void *hook_pvt,
2755         ast_bridge_hook_pvt_destructor destructor,
2756         enum ast_bridge_hook_remove_flags remove_flags)
2757 {
2758         struct ast_bridge_hook *hook;
2759
2760         /* Allocate new hook and setup it's basic variables */
2761         hook = ao2_alloc_options(size, bridge_hook_destroy, AO2_ALLOC_OPT_LOCK_NOLOCK);
2762         if (hook) {
2763                 hook->callback = callback;
2764                 hook->destructor = destructor;
2765                 hook->hook_pvt = hook_pvt;
2766                 ast_set_flag(&hook->remove_flags, remove_flags);
2767         }
2768
2769         return hook;
2770 }
2771
2772 int ast_bridge_dtmf_hook(struct ast_bridge_features *features,
2773         const char *dtmf,
2774         ast_bridge_hook_callback callback,
2775         void *hook_pvt,
2776         ast_bridge_hook_pvt_destructor destructor,
2777         enum ast_bridge_hook_remove_flags remove_flags)
2778 {
2779         struct ast_bridge_hook_dtmf *hook;
2780         int res;
2781
2782         /* Allocate new hook and setup it's various variables */
2783         hook = (struct ast_bridge_hook_dtmf *) bridge_hook_generic(sizeof(*hook), callback,
2784                 hook_pvt, destructor, remove_flags);
2785         if (!hook) {
2786                 return -1;
2787         }
2788         hook->generic.type = AST_BRIDGE_HOOK_TYPE_DTMF;
2789         ast_copy_string(hook->dtmf.code, dtmf, sizeof(hook->dtmf.code));
2790
2791         /* Once done we put it in the container. */
2792         res = ao2_link(features->dtmf_hooks, hook) ? 0 : -1;
2793         if (res) {
2794                 /*
2795                  * Could not link the hook into the container.
2796                  *
2797                  * Remove the hook_pvt destructor call from the hook since we
2798                  * are returning failure to install the hook.
2799                  */
2800                 hook->generic.destructor = NULL;
2801         }
2802         ao2_ref(hook, -1);
2803
2804         return res;
2805 }
2806
2807 /*!
2808  * \internal
2809  * \brief Attach an other hook to a bridge features structure
2810  *
2811  * \param features Bridge features structure
2812  * \param callback Function to execute upon activation
2813  * \param hook_pvt Unique data
2814  * \param destructor Optional destructor callback for hook_pvt data
2815  * \param remove_flags Dictates what situations the hook should be removed.
2816  * \param type What type of hook is being attached.
2817  *
2818  * \retval 0 on success
2819  * \retval -1 on failure (The caller must cleanup any hook_pvt resources.)
2820  */
2821 static int bridge_other_hook(struct ast_bridge_features *features,
2822         ast_bridge_hook_callback callback,
2823         void *hook_pvt,
2824         ast_bridge_hook_pvt_destructor destructor,
2825         enum ast_bridge_hook_remove_flags remove_flags,
2826         enum ast_bridge_hook_type type)
2827 {
2828         struct ast_bridge_hook *hook;
2829         int res;
2830
2831         /* Allocate new hook and setup it's various variables */
2832         hook = bridge_hook_generic(sizeof(*hook), callback, hook_pvt, destructor,
2833                 remove_flags);
2834         if (!hook) {
2835                 return -1;
2836         }
2837         hook->type = type;
2838
2839         /* Once done we put it in the container. */
2840         res = ao2_link(features->other_hooks, hook) ? 0 : -1;
2841         if (res) {
2842                 /*
2843                  * Could not link the hook into the container.
2844                  *
2845                  * Remove the hook_pvt destructor call from the hook since we
2846                  * are returning failure to install the hook.
2847                  */
2848                 hook->destructor = NULL;
2849         }
2850         ao2_ref(hook, -1);
2851
2852         return res;
2853 }
2854
2855 int ast_bridge_hangup_hook(struct ast_bridge_features *features,
2856         ast_bridge_hook_callback callback,
2857         void *hook_pvt,
2858         ast_bridge_hook_pvt_destructor destructor,
2859         enum ast_bridge_hook_remove_flags remove_flags)
2860 {
2861         return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
2862                 AST_BRIDGE_HOOK_TYPE_HANGUP);
2863 }
2864
2865 int ast_bridge_join_hook(struct ast_bridge_features *features,
2866         ast_bridge_hook_callback callback,
2867         void *hook_pvt,
2868         ast_bridge_hook_pvt_destructor destructor,
2869         enum ast_bridge_hook_remove_flags remove_flags)
2870 {
2871         return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
2872                 AST_BRIDGE_HOOK_TYPE_JOIN);
2873 }
2874
2875 int ast_bridge_leave_hook(struct ast_bridge_features *features,
2876         ast_bridge_hook_callback callback,
2877         void *hook_pvt,
2878         ast_bridge_hook_pvt_destructor destructor,
2879         enum ast_bridge_hook_remove_flags remove_flags)
2880 {
2881         return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
2882                 AST_BRIDGE_HOOK_TYPE_LEAVE);
2883 }
2884
2885 int ast_bridge_talk_detector_hook(struct ast_bridge_features *features,
2886         ast_bridge_talking_indicate_callback callback,
2887         void *hook_pvt,
2888         ast_bridge_hook_pvt_destructor destructor,
2889         enum ast_bridge_hook_remove_flags remove_flags)
2890 {
2891         ast_bridge_hook_callback hook_cb = (ast_bridge_hook_callback) callback;
2892
2893         return bridge_other_hook(features, hook_cb, hook_pvt, destructor, remove_flags,
2894                 AST_BRIDGE_HOOK_TYPE_TALK);
2895 }
2896
2897 int ast_bridge_interval_hook(struct ast_bridge_features *features,
2898         unsigned int interval,
2899         ast_bridge_hook_callback callback,
2900         void *hook_pvt,
2901         ast_bridge_hook_pvt_destructor destructor,
2902         enum ast_bridge_hook_remove_flags remove_flags)
2903 {
2904         struct ast_bridge_hook_timer *hook;
2905         int res;
2906
2907         if (!features ||!interval || !callback) {
2908                 return -1;
2909         }
2910
2911         /* Allocate new hook and setup it's various variables */
2912         hook = (struct ast_bridge_hook_timer *) bridge_hook_generic(sizeof(*hook), callback,
2913                 hook_pvt, destructor, remove_flags);
2914         if (!hook) {
2915                 return -1;
2916         }
2917         hook->generic.type = AST_BRIDGE_HOOK_TYPE_TIMER;
2918         hook->timer.interval = interval;
2919         hook->timer.trip_time = ast_tvadd(ast_tvnow(), ast_samp2tv(hook->timer.interval, 1000));
2920         hook->timer.seqno = ast_atomic_fetchadd_int((int *) &features->interval_sequence, +1);
2921
2922         ast_debug(1, "Putting interval hook %p with interval %u in the heap on features %p\n",
2923                 hook, hook->timer.interval, features);
2924         ast_heap_wrlock(features->interval_hooks);
2925         res = ast_heap_push(features->interval_hooks, hook);
2926         ast_heap_unlock(features->interval_hooks);
2927         if (res) {
2928                 /*
2929                  * Could not push the hook into the heap
2930                  *
2931                  * Remove the hook_pvt destructor call from the hook since we
2932                  * are returning failure to install the hook.
2933                  */
2934                 hook->generic.destructor = NULL;
2935                 ao2_ref(hook, -1);
2936         }
2937
2938         return res ? -1 : 0;
2939 }
2940
2941 int ast_bridge_features_enable(struct ast_bridge_features *features,
2942         enum ast_bridge_builtin_feature feature,
2943         const char *dtmf,
2944         void *config,
2945         ast_bridge_hook_pvt_destructor destructor,
2946         enum ast_bridge_hook_remove_flags remove_flags)
2947 {
2948         if (ARRAY_LEN(builtin_features_handlers) <= feature
2949                 || !builtin_features_handlers[feature]) {
2950                 return -1;
2951         }
2952
2953         /* If no alternate DTMF stream was provided use the default one */
2954         if (ast_strlen_zero(dtmf)) {
2955                 dtmf = builtin_features_dtmf[feature];
2956                 /* If no DTMF is still available (ie: it has been disabled) then error out now */
2957                 if (ast_strlen_zero(dtmf)) {
2958                         ast_debug(1, "Failed to enable built in feature %d on %p, no DTMF string is available for it.\n",
2959                                 feature, features);
2960                         return -1;
2961                 }
2962         }
2963
2964         /*
2965          * The rest is basically pretty easy.  We create another hook
2966          * using the built in feature's DTMF callback.  Easy as pie.
2967          */
2968         return ast_bridge_dtmf_hook(features, dtmf, builtin_features_handlers[feature],
2969                 config, destructor, remove_flags);
2970 }
2971
2972 int ast_bridge_features_limits_construct(struct ast_bridge_features_limits *limits)
2973 {
2974         memset(limits, 0, sizeof(*limits));
2975
2976         if (ast_string_field_init(limits, 256)) {
2977                 return -1;
2978         }
2979
2980         return 0;
2981 }
2982
2983 void ast_bridge_features_limits_destroy(struct ast_bridge_features_limits *limits)
2984 {
2985         ast_string_field_free_memory(limits);
2986 }
2987
2988 int ast_bridge_features_set_limits(struct ast_bridge_features *features,
2989         struct ast_bridge_features_limits *limits,
2990         enum ast_bridge_hook_remove_flags remove_flags)
2991 {
2992         if (builtin_interval_handlers[AST_BRIDGE_BUILTIN_INTERVAL_LIMITS]) {
2993                 ast_bridge_builtin_set_limits_fn callback;
2994
2995                 callback = builtin_interval_handlers[AST_BRIDGE_BUILTIN_INTERVAL_LIMITS];
2996                 return callback(features, limits, remove_flags);
2997         }
2998
2999         ast_log(LOG_ERROR, "Attempted to set limits without an AST_BRIDGE_BUILTIN_INTERVAL_LIMITS callback registered.\n");
3000         return -1;
3001 }
3002
3003 void ast_bridge_features_set_flag(struct ast_bridge_features *features, unsigned int flag)
3004 {
3005         ast_set_flag(&features->feature_flags, flag);
3006         features->usable = 1;
3007 }
3008
3009 /*!
3010  * \internal
3011  * \brief ao2 object match hooks with appropriate remove_flags.
3012  * \since 12.0.0
3013  *
3014  * \param obj Feature hook object.
3015  * \param arg Removal flags
3016  * \param flags Not used
3017  *
3018  * \retval CMP_MATCH if hook's remove_flags match the removal flags set.
3019  * \retval 0 if not match.
3020  */
3021 static int hook_remove_match(void *obj, void *arg, int flags)
3022 {
3023         struct ast_bridge_hook *hook = obj;
3024         enum ast_bridge_hook_remove_flags *remove_flags = arg;
3025
3026         if (ast_test_flag(&hook->remove_flags, *remove_flags)) {
3027                 return CMP_MATCH;
3028         } else {
3029                 return 0;
3030         }
3031 }
3032
3033 /*!
3034  * \internal
3035  * \brief Remove all hooks with appropriate remove_flags in the container.
3036  * \since 12.0.0
3037  *
3038  * \param hooks Hooks container to work on.
3039  * \param remove_flags Determinator for whether hook is removed
3040  *
3041  * \return Nothing
3042  */
3043 static void hooks_remove_container(struct ao2_container *hooks, enum ast_bridge_hook_remove_flags remove_flags)
3044 {
3045         ao2_callback(hooks, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
3046                 hook_remove_match, &remove_flags);
3047 }
3048
3049 /*!
3050  * \internal
3051  * \brief Remove all hooks in the heap with appropriate remove_flags set.
3052  * \since 12.0.0
3053  *
3054  * \param hooks Hooks heap to work on.
3055  * \param remove_flags Determinator for whether hook is removed
3056  *
3057  * \return Nothing
3058  */
3059 static void hooks_remove_heap(struct ast_heap *hooks, enum ast_bridge_hook_remove_flags remove_flags)
3060 {
3061         struct ast_bridge_hook *hook;
3062         int changed;
3063
3064         ast_heap_wrlock(hooks);
3065         do {
3066                 int idx;
3067
3068                 changed = 0;
3069                 for (idx = ast_heap_size(hooks); idx; --idx) {
3070                         hook = ast_heap_peek(hooks, idx);
3071                         if (ast_test_flag(&hook->remove_flags, remove_flags)) {
3072                                 ast_heap_remove(hooks, hook);
3073                                 ao2_ref(hook, -1);
3074                                 changed = 1;
3075                         }
3076                 }
3077         } while (changed);
3078         ast_heap_unlock(hooks);
3079 }
3080
3081 void ast_bridge_features_remove(struct ast_bridge_features *features, enum ast_bridge_hook_remove_flags remove_flags)
3082 {
3083         hooks_remove_container(features->dtmf_hooks, remove_flags);
3084         hooks_remove_container(features->other_hooks, remove_flags);
3085         hooks_remove_heap(features->interval_hooks, remove_flags);
3086 }
3087
3088 static int interval_hook_time_cmp(void *a, void *b)
3089 {
3090         struct ast_bridge_hook_timer *hook_a = a;
3091         struct ast_bridge_hook_timer *hook_b = b;
3092         int cmp;
3093
3094         cmp = ast_tvcmp(hook_b->timer.trip_time, hook_a->timer.trip_time);
3095         if (cmp) {
3096                 return cmp;
3097         }
3098
3099         cmp = hook_b->timer.seqno - hook_a->timer.seqno;
3100         return cmp;
3101 }
3102
3103 /*!
3104  * \internal
3105  * \brief DTMF hook container sort comparison function.
3106  * \since 12.0.0
3107  *
3108  * \param obj_left pointer to the (user-defined part) of an object.
3109  * \param obj_right pointer to the (user-defined part) of an object.
3110  * \param flags flags from ao2_callback()
3111  *   OBJ_POINTER - if set, 'obj_right', is an object.
3112  *   OBJ_KEY - if set, 'obj_right', is a search key item that is not an object.
3113  *   OBJ_PARTIAL_KEY - if set, 'obj_right', is a partial search key item that is not an object.
3114  *
3115  * \retval <0 if obj_left < obj_right
3116  * \retval =0 if obj_left == obj_right
3117  * \retval >0 if obj_left > obj_right
3118  */
3119 static int bridge_dtmf_hook_sort(const void *obj_left, const void *obj_right, int flags)
3120 {
3121         const struct ast_bridge_hook_dtmf *hook_left = obj_left;
3122         const struct ast_bridge_hook_dtmf *hook_right = obj_right;
3123         const char *right_key = obj_right;
3124         int cmp;
3125
3126         switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
3127         default:
3128         case OBJ_POINTER:
3129                 right_key = hook_right->dtmf.code;
3130                 /* Fall through */
3131         case OBJ_KEY:
3132                 cmp = strcasecmp(hook_left->dtmf.code, right_key);
3133                 break;
3134         case OBJ_PARTIAL_KEY:
3135                 cmp = strncasecmp(hook_left->dtmf.code, right_key, strlen(right_key));
3136                 break;
3137         }
3138         return cmp;
3139 }
3140
3141 /* BUGBUG make ast_bridge_features_init() static when make ast_bridge_join() requires features to be allocated. */
3142 int ast_bridge_features_init(struct ast_bridge_features *features)
3143 {
3144         /* Zero out the structure */
3145         memset(features, 0, sizeof(*features));
3146
3147         /* Initialize the DTMF hooks container */
3148         features->dtmf_hooks = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX,
3149                 AO2_CONTAINER_ALLOC_OPT_DUPS_REPLACE, bridge_dtmf_hook_sort, NULL);
3150         if (!features->dtmf_hooks) {
3151                 return -1;
3152         }
3153
3154         /* Initialize the miscellaneous other hooks container */
3155         features->other_hooks = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL,
3156                 NULL);
3157         if (!features->other_hooks) {
3158                 return -1;
3159         }
3160
3161         /* Initialize the interval hooks heap */
3162         features->interval_hooks = ast_heap_create(8, interval_hook_time_cmp,
3163                 offsetof(struct ast_bridge_hook_timer, timer.heap_index));
3164         if (!features->interval_hooks) {
3165                 return -1;
3166         }
3167
3168         return 0;
3169 }
3170
3171 /* BUGBUG make ast_bridge_features_cleanup() static when make ast_bridge_join() requires features to be allocated. */
3172 void ast_bridge_features_cleanup(struct ast_bridge_features *features)
3173 {
3174         struct ast_bridge_hook_timer *hook;
3175
3176         /* Destroy the interval hooks heap. */
3177         if (features->interval_hooks) {
3178                 while ((hook = ast_heap_pop(features->interval_hooks))) {
3179                         ao2_ref(hook, -1);
3180                 }
3181                 features->interval_hooks = ast_heap_destroy(features->interval_hooks);
3182         }
3183
3184         /* Destroy the miscellaneous other hooks container. */
3185         ao2_cleanup(features->other_hooks);
3186         features->other_hooks = NULL;
3187
3188         /* Destroy the DTMF hooks container. */
3189         ao2_cleanup(features->dtmf_hooks);
3190         features->dtmf_hooks = NULL;
3191 }
3192
3193 void ast_bridge_features_destroy(struct ast_bridge_features *features)
3194 {
3195         if (!features) {
3196                 return;
3197         }
3198         ast_bridge_features_cleanup(features);
3199         ast_free(features);
3200 }
3201
3202 struct ast_bridge_features *ast_bridge_features_new(void)
3203 {
3204         struct ast_bridge_features *features;
3205
3206         features = ast_malloc(sizeof(*features));
3207         if (features) {
3208                 if (ast_bridge_features_init(features)) {
3209                         ast_bridge_features_destroy(features);
3210                         features = NULL;
3211                 }
3212         }
3213
3214         return features;
3215 }
3216
3217 void ast_bridge_set_mixing_interval(struct ast_bridge *bridge, unsigned int mixing_interval)
3218 {
3219         ast_bridge_lock(bridge);
3220         bridge->softmix.internal_mixing_interval = mixing_interval;
3221         ast_bridge_unlock(bridge);
3222 }
3223
3224 void ast_bridge_set_internal_sample_rate(struct ast_bridge *bridge, unsigned int sample_rate)
3225 {
3226         ast_bridge_lock(bridge);
3227         bridge->softmix.internal_sample_rate = sample_rate;
3228         ast_bridge_unlock(bridge);
3229 }
3230
3231 static void cleanup_video_mode(struct ast_bridge *bridge)
3232 {
3233         switch (bridge->softmix.video_mode.mode) {
3234         case AST_BRIDGE_VIDEO_MODE_NONE:
3235                 break;
3236         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
3237                 if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc) {
3238                         ast_channel_unref(bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc);
3239                 }
3240                 break;
3241         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
3242                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc) {
3243                         ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc);
3244                 }
3245                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc) {
3246                         ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc);
3247                 }
3248         }
3249         memset(&bridge->softmix.video_mode, 0, sizeof(bridge->softmix.video_mode));
3250 }
3251
3252 void ast_bridge_set_single_src_video_mode(struct ast_bridge *bridge, struct ast_channel *video_src_chan)
3253 {
3254         ast_bridge_lock(bridge);
3255         cleanup_video_mode(bridge);
3256         bridge->softmix.video_mode.mode = AST_BRIDGE_VIDEO_MODE_SINGLE_SRC;
3257         bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc = ast_channel_ref(video_src_chan);
3258         ast_test_suite_event_notify("BRIDGE_VIDEO_MODE", "Message: video mode set to single source\r\nVideo Mode: %d\r\nVideo Channel: %s",
3259                 bridge->softmix.video_mode.mode, ast_channel_name(video_src_chan));
3260         ast_indicate(video_src_chan, AST_CONTROL_VIDUPDATE);
3261         ast_bridge_unlock(bridge);
3262 }
3263
3264 void ast_bridge_set_talker_src_video_mode(struct ast_bridge *bridge)
3265 {
3266         ast_bridge_lock(bridge);
3267         cleanup_video_mode(bridge);
3268         bridge->softmix.video_mode.mode = AST_BRIDGE_VIDEO_MODE_TALKER_SRC;
3269         ast_test_suite_event_notify("BRIDGE_VIDEO_MODE", "Message: video mode set to talker source\r\nVideo Mode: %d",
3270                 bridge->softmix.video_mode.mode);
3271         ast_bridge_unlock(bridge);
3272 }
3273
3274 void ast_bridge_update_talker_src_video_mode(struct ast_bridge *bridge, struct ast_channel *chan, int talker_energy, int is_keyframe)
3275 {
3276         struct ast_bridge_video_talker_src_data *data;
3277
3278         /* If the channel doesn't support video, we don't care about it */
3279         if (!ast_format_cap_has_type(ast_channel_nativeformats(chan), AST_FORMAT_TYPE_VIDEO)) {
3280                 return;
3281         }
3282
3283         ast_bridge_lock(bridge);
3284         data = &bridge->softmix.video_mode.mode_data.talker_src_data;
3285
3286         if (data->chan_vsrc == chan) {
3287                 data->average_talking_energy = talker_energy;
3288         } else if ((data->average_talking_energy < talker_energy) && is_keyframe) {
3289                 if (data->chan_old_vsrc) {
3290                         ast_channel_unref(data->chan_old_vsrc);
3291                 }
3292                 if (data->chan_vsrc) {
3293                         data->chan_old_vsrc = data->chan_vsrc;
3294                         ast_indicate(data->chan_old_vsrc, AST_CONTROL_VIDUPDATE);
3295                 }
3296                 data->chan_vsrc = ast_channel_ref(chan);
3297                 data->average_talking_energy = talker_energy;
3298                 ast_test_suite_event_notify("BRIDGE_VIDEO_SRC", "Message: video source updated\r\nVideo Channel: %s", ast_channel_name(data->chan_vsrc));
3299                 ast_indicate(data->chan_vsrc, AST_CONTROL_VIDUPDATE);
3300         } else if ((data->average_talking_energy < talker_energy) && !is_keyframe) {
3301                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
3302         } else if (!data->chan_vsrc && is_keyframe) {
3303                 data->chan_vsrc = ast_channel_ref(chan);
3304                 data->average_talking_energy = talker_energy;
3305                 ast_test_suite_event_notify("BRIDGE_VIDEO_SRC", "Message: video source updated\r\nVideo Channel: %s", ast_channel_name(data->chan_vsrc));
3306                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
3307         } else if (!data->chan_old_vsrc && is_keyframe) {
3308                 data->chan_old_vsrc = ast_channel_ref(chan);
3309                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
3310         }
3311         ast_bridge_unlock(bridge);
3312 }
3313
3314 int ast_bridge_number_video_src(struct ast_bridge *bridge)
3315 {
3316         int res = 0;
3317
3318         ast_bridge_lock(bridge);
3319         switch (bridge->softmix.video_mode.mode) {
3320         case AST_BRIDGE_VIDEO_MODE_NONE:
3321                 break;
3322         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
3323                 if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc) {
3324                         res = 1;
3325                 }
3326                 break;
3327         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
3328                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc) {
3329                         res++;
3330                 }
3331                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc) {
3332                         res++;
3333                 }
3334         }
3335         ast_bridge_unlock(bridge);
3336         return res;
3337 }
3338
3339 int ast_bridge_is_video_src(struct ast_bridge *bridge, struct ast_channel *chan)
3340 {
3341         int res = 0;
3342
3343         ast_bridge_lock(bridge);
3344         switch (bridge->softmix.video_mode.mode) {
3345         case AST_BRIDGE_VIDEO_MODE_NONE:
3346                 break;
3347         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
3348                 if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc == chan) {
3349                         res = 1;
3350                 }
3351                 break;
3352         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
3353                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc == chan) {
3354                         res = 1;
3355                 } else if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc == chan) {
3356                         res = 2;
3357                 }
3358
3359         }
3360         ast_bridge_unlock(bridge);
3361         return res;
3362 }
3363
3364 void ast_bridge_remove_video_src(struct ast_bridge *bridge, struct ast_channel *chan)
3365 {
3366         ast_bridge_lock(bridge);
3367         switch (bridge->softmix.video_mode.mode) {
3368         case AST_BRIDGE_VIDEO_MODE_NONE:
3369                 break;
3370         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
3371                 if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc == chan) {
3372                         if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc) {
3373                                 ast_channel_unref(bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc);
3374                         }
3375                         bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc = NULL;
3376                 }
3377                 break;
3378         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
3379                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc == chan) {
3380                         if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc) {
3381                                 ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc);
3382                         }
3383                         bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc = NULL;
3384                         bridge->softmix.video_mode.mode_data.talker_src_data.average_talking_energy = 0;
3385                 }
3386                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc == chan) {
3387                         if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc) {
3388                                 ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc);
3389                         }
3390                         bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc = NULL;
3391                 }
3392         }
3393         ast_bridge_unlock(bridge);
3394 }
3395
3396 static int channel_hash(const void *obj, int flags)
3397 {
3398         const struct ast_channel *chan = obj;
3399         const char *name = obj;
3400         int hash;
3401
3402         switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
3403         default:
3404         case OBJ_POINTER:
3405                 name = ast_channel_name(chan);
3406                 /* Fall through */
3407         case OBJ_KEY:
3408                 hash&nb