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