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