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