ab3bb17e62d785ebca883fafa7d2d4cee4c5213d
[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                 return -1;
1681         }
1682
1683         /* Supply an empty features structure if the caller did not. */
1684         if (!features) {
1685                 features = ast_bridge_features_new();
1686                 if (!features) {
1687                         return -1;
1688                 }
1689         }
1690
1691         /* Try to allocate a structure for the bridge channel */
1692         bridge_channel = bridge_channel_internal_alloc(bridge);
1693         if (!bridge_channel) {
1694                 ast_bridge_features_destroy(features);
1695                 return -1;
1696         }
1697
1698         ast_channel_lock(chan);
1699         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE)) {
1700                 ast_log(AST_LOG_NOTICE, "Channel %s is a zombie and cannot be imparted into bridge %s\n",
1701                         ast_channel_name(chan), bridge->uniqueid);
1702                 res = -1;
1703         } else {
1704                 ast_channel_internal_bridge_channel_set(chan, bridge_channel);
1705         }
1706         ast_channel_unlock(chan);
1707         bridge_channel->chan = chan;
1708         bridge_channel->swap = swap;
1709         bridge_channel->features = features;
1710         bridge_channel->inhibit_colp = !!(flags & AST_BRIDGE_IMPART_INHIBIT_JOIN_COLP);
1711         bridge_channel->depart_wait =
1712                 (flags & AST_BRIDGE_IMPART_CHAN_MASK) == AST_BRIDGE_IMPART_CHAN_DEPARTABLE;
1713         bridge_channel->callid = ast_read_threadstorage_callid();
1714
1715         /* Actually create the thread that will handle the channel */
1716         if (!res) {
1717                 if ((flags & AST_BRIDGE_IMPART_CHAN_MASK) == AST_BRIDGE_IMPART_CHAN_INDEPENDENT) {
1718                         res = ast_pthread_create_detached(&bridge_channel->thread, NULL,
1719                                 bridge_channel_ind_thread, bridge_channel);
1720                 } else {
1721                         res = ast_pthread_create(&bridge_channel->thread, NULL,
1722                                 bridge_channel_depart_thread, bridge_channel);
1723                 }
1724         }
1725
1726         if (res) {
1727                 /* cleanup */
1728                 ast_channel_lock(chan);
1729                 ast_channel_internal_bridge_channel_set(chan, NULL);
1730                 ast_channel_unlock(chan);
1731                 bridge_channel->chan = NULL;
1732                 bridge_channel->swap = NULL;
1733                 ast_bridge_features_destroy(bridge_channel->features);
1734                 bridge_channel->features = NULL;
1735
1736                 ao2_ref(bridge_channel, -1);
1737                 return -1;
1738         }
1739
1740         return 0;
1741 }
1742
1743 int ast_bridge_depart(struct ast_channel *chan)
1744 {
1745         struct ast_bridge_channel *bridge_channel;
1746         int departable;
1747
1748         ast_channel_lock(chan);
1749         bridge_channel = ast_channel_internal_bridge_channel(chan);
1750         departable = bridge_channel && bridge_channel->depart_wait;
1751         ast_channel_unlock(chan);
1752         if (!departable) {
1753                 ast_log(LOG_ERROR, "Channel %s cannot be departed.\n",
1754                         ast_channel_name(chan));
1755                 /*
1756                  * Should never happen.  It likely means that
1757                  * ast_bridge_depart() is called by two threads for the same
1758                  * channel, the channel was never imparted to be departed, or it
1759                  * has already been departed.
1760                  */
1761                 ast_assert(0);
1762                 return -1;
1763         }
1764
1765         /*
1766          * We are claiming the reference held by the depart bridge
1767          * channel thread.
1768          */
1769
1770         ast_bridge_channel_leave_bridge(bridge_channel,
1771                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
1772
1773         /* Wait for the depart thread to die */
1774         ast_debug(1, "Waiting for %p(%s) bridge thread to die.\n",
1775                 bridge_channel, ast_channel_name(bridge_channel->chan));
1776         pthread_join(bridge_channel->thread, NULL);
1777
1778         ast_channel_lock(chan);
1779         ast_channel_internal_bridge_channel_set(chan, NULL);
1780         ast_channel_unlock(chan);
1781
1782         /* We can get rid of the bridge_channel after the depart thread has died. */
1783         ao2_ref(bridge_channel, -1);
1784         return 0;
1785 }
1786
1787 int ast_bridge_remove(struct ast_bridge *bridge, struct ast_channel *chan)
1788 {
1789         struct ast_bridge_channel *bridge_channel;
1790
1791         ast_bridge_lock(bridge);
1792
1793         /* Try to find the channel that we want to remove */
1794         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
1795                 ast_bridge_unlock(bridge);
1796                 return -1;
1797         }
1798
1799         ast_bridge_channel_leave_bridge(bridge_channel,
1800                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
1801
1802         ast_bridge_unlock(bridge);
1803
1804         return 0;
1805 }
1806
1807 static void kick_it(struct ast_bridge_channel *bridge_channel, const void *payload, size_t payload_size)
1808 {
1809         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1810 }
1811
1812 int ast_bridge_kick(struct ast_bridge *bridge, struct ast_channel *chan)
1813 {
1814         struct ast_bridge_channel *bridge_channel;
1815         int res;
1816
1817         ast_bridge_lock(bridge);
1818
1819         /* Try to find the channel that we want to kick. */
1820         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
1821                 ast_bridge_unlock(bridge);
1822                 return -1;
1823         }
1824
1825         res = ast_bridge_channel_queue_callback(bridge_channel, 0, kick_it, NULL, 0);
1826
1827         ast_bridge_unlock(bridge);
1828
1829         return res;
1830 }
1831
1832 /*!
1833  * \internal
1834  * \brief Point the bridge_channel to a new bridge.
1835  * \since 12.0.0
1836  *
1837  * \param bridge_channel What is to point to a new bridge.
1838  * \param new_bridge Where the bridge channel should point.
1839  *
1840  * \return Nothing
1841  */
1842 static void bridge_channel_change_bridge(struct ast_bridge_channel *bridge_channel, struct ast_bridge *new_bridge)
1843 {
1844         struct ast_bridge *old_bridge;
1845
1846         ao2_ref(new_bridge, +1);
1847         ast_bridge_channel_lock(bridge_channel);
1848         ast_channel_lock(bridge_channel->chan);
1849         old_bridge = bridge_channel->bridge;
1850         bridge_channel->bridge = new_bridge;
1851         ast_channel_internal_bridge_set(bridge_channel->chan, new_bridge);
1852         ast_channel_unlock(bridge_channel->chan);
1853         ast_bridge_channel_unlock(bridge_channel);
1854         ao2_ref(old_bridge, -1);
1855 }
1856
1857 static void bridge_channel_moving(struct ast_bridge_channel *bridge_channel, struct ast_bridge *src, struct ast_bridge *dst)
1858 {
1859         struct ast_bridge_features *features = bridge_channel->features;
1860         struct ast_bridge_hook *hook;
1861         struct ao2_iterator iter;
1862
1863         /* Run any moving hooks. */
1864         iter = ao2_iterator_init(features->other_hooks, 0);
1865         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1866                 int remove_me;
1867                 ast_bridge_move_indicate_callback move_cb;
1868
1869                 if (hook->type != AST_BRIDGE_HOOK_TYPE_MOVE) {
1870                         continue;
1871                 }
1872                 move_cb = (ast_bridge_move_indicate_callback) hook->callback;
1873                 remove_me = move_cb(bridge_channel, hook->hook_pvt, src, dst);
1874                 if (remove_me) {
1875                         ast_debug(1, "Move detection hook %p is being removed from %p(%s)\n",
1876                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1877                         ao2_unlink(features->other_hooks, hook);
1878                 }
1879         }
1880         ao2_iterator_destroy(&iter);
1881 }
1882
1883 void bridge_do_merge(struct ast_bridge *dst_bridge, struct ast_bridge *src_bridge, struct ast_bridge_channel **kick_me, unsigned int num_kick,
1884         unsigned int optimized)
1885 {
1886         struct ast_bridge_channel *bridge_channel;
1887         unsigned int idx;
1888
1889         ast_debug(1, "Merging bridge %s into bridge %s\n",
1890                 src_bridge->uniqueid, dst_bridge->uniqueid);
1891
1892         ast_bridge_publish_merge(dst_bridge, src_bridge);
1893
1894         /*
1895          * Move channels from src_bridge over to dst_bridge.
1896          *
1897          * We must use AST_LIST_TRAVERSE_SAFE_BEGIN() because
1898          * bridge_channel_internal_pull() alters the list we are traversing.
1899          */
1900         AST_LIST_TRAVERSE_SAFE_BEGIN(&src_bridge->channels, bridge_channel, entry) {
1901                 if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
1902                         /*
1903                          * The channel is already leaving let it leave normally because
1904                          * pulling it may delete hooks that should run for this channel.
1905                          */
1906                         continue;
1907                 }
1908                 if (ast_test_flag(&bridge_channel->features->feature_flags,
1909                         AST_BRIDGE_CHANNEL_FLAG_IMMOVABLE)) {
1910                         continue;
1911                 }
1912
1913                 if (kick_me) {
1914                         for (idx = 0; idx < num_kick; ++idx) {
1915                                 if (bridge_channel == kick_me[idx]) {
1916                                         ast_bridge_channel_leave_bridge(bridge_channel,
1917                                                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
1918                                         break;
1919                                 }
1920                         }
1921                 }
1922                 bridge_channel_internal_pull(bridge_channel);
1923                 if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
1924                         /*
1925                          * The channel died as a result of being pulled or it was
1926                          * kicked.  Leave it pointing to the original bridge.
1927                          */
1928                         continue;
1929                 }
1930
1931                 bridge_channel_moving(bridge_channel, bridge_channel->bridge, dst_bridge);
1932
1933                 /* Point to new bridge.*/
1934                 bridge_channel_change_bridge(bridge_channel, dst_bridge);
1935
1936                 if (bridge_channel_internal_push(bridge_channel)) {
1937                         ast_bridge_features_remove(bridge_channel->features,
1938                                 AST_BRIDGE_HOOK_REMOVE_ON_PULL);
1939                         ast_bridge_channel_leave_bridge(bridge_channel,
1940                                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, bridge_channel->bridge->cause);
1941                 }
1942         }
1943         AST_LIST_TRAVERSE_SAFE_END;
1944
1945         if (kick_me) {
1946                 /*
1947                  * Now we can kick any channels in the dst_bridge without
1948                  * potentially dissolving the bridge.
1949                  */
1950                 for (idx = 0; idx < num_kick; ++idx) {
1951                         bridge_channel = kick_me[idx];
1952                         ast_bridge_channel_lock(bridge_channel);
1953                         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
1954                                 ast_bridge_channel_leave_bridge_nolock(bridge_channel,
1955                                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
1956                                 bridge_channel_internal_pull(bridge_channel);
1957                         }
1958                         ast_bridge_channel_unlock(bridge_channel);
1959                 }
1960         }
1961
1962         bridge_reconfigured(dst_bridge, !optimized);
1963         bridge_reconfigured(src_bridge, !optimized);
1964
1965         ast_debug(1, "Merged bridge %s into bridge %s\n",
1966                 src_bridge->uniqueid, dst_bridge->uniqueid);
1967 }
1968
1969 struct merge_direction {
1970         /*! Destination merge bridge. */
1971         struct ast_bridge *dest;
1972         /*! Source merge bridge. */
1973         struct ast_bridge *src;
1974 };
1975
1976 /*!
1977  * \internal
1978  * \brief Determine which bridge should merge into the other.
1979  * \since 12.0.0
1980  *
1981  * \param bridge1 A bridge for merging
1982  * \param bridge2 A bridge for merging
1983  *
1984  * \note The two bridges are assumed already locked.
1985  *
1986  * \return Which bridge merges into which or NULL bridges if cannot merge.
1987  */
1988 static struct merge_direction bridge_merge_determine_direction(struct ast_bridge *bridge1, struct ast_bridge *bridge2)
1989 {
1990         struct merge_direction merge = { NULL, NULL };
1991         int bridge1_priority;
1992         int bridge2_priority;
1993
1994         if (!ast_test_flag(&bridge1->feature_flags,
1995                         AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)
1996                 && !ast_test_flag(&bridge2->feature_flags,
1997                         AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
1998                 /*
1999                  * Can merge either way.  Merge to the higher priority merge
2000                  * bridge.  Otherwise merge to the larger bridge.
2001                  */
2002                 bridge1_priority = bridge1->v_table->get_merge_priority(bridge1);
2003                 bridge2_priority = bridge2->v_table->get_merge_priority(bridge2);
2004                 if (bridge2_priority < bridge1_priority) {
2005                         merge.dest = bridge1;
2006                         merge.src = bridge2;
2007                 } else if (bridge1_priority < bridge2_priority) {
2008                         merge.dest = bridge2;
2009                         merge.src = bridge1;
2010                 } else {
2011                         /* Merge to the larger bridge. */
2012                         if (bridge2->num_channels <= bridge1->num_channels) {
2013                                 merge.dest = bridge1;
2014                                 merge.src = bridge2;
2015                         } else {
2016                                 merge.dest = bridge2;
2017                                 merge.src = bridge1;
2018                         }
2019                 }
2020         } else if (!ast_test_flag(&bridge1->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
2021                 && !ast_test_flag(&bridge2->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
2022                 /* Can merge only one way. */
2023                 merge.dest = bridge1;
2024                 merge.src = bridge2;
2025         } else if (!ast_test_flag(&bridge2->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
2026                 && !ast_test_flag(&bridge1->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
2027                 /* Can merge only one way. */
2028                 merge.dest = bridge2;
2029                 merge.src = bridge1;
2030         }
2031
2032         return merge;
2033 }
2034
2035 /*!
2036  * \internal
2037  * \brief Merge two bridges together
2038  * \since 12.0.0
2039  *
2040  * \param dst_bridge Destination bridge of merge.
2041  * \param src_bridge Source bridge of merge.
2042  * \param merge_best_direction TRUE if don't care about which bridge merges into the other.
2043  * \param kick_me Array of channels to kick from the bridges.
2044  * \param num_kick Number of channels in the kick_me array.
2045  *
2046  * \note The dst_bridge and src_bridge are assumed already locked.
2047  *
2048  * \retval 0 on success
2049  * \retval -1 on failure
2050  */
2051 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)
2052 {
2053         struct merge_direction merge;
2054         struct ast_bridge_channel **kick_them = NULL;
2055
2056         /* Sanity check. */
2057         ast_assert(dst_bridge && src_bridge && dst_bridge != src_bridge && (!num_kick || kick_me));
2058
2059         if (dst_bridge->dissolved || src_bridge->dissolved) {
2060                 ast_debug(1, "Can't merge bridges %s and %s, at least one bridge is dissolved.\n",
2061                         src_bridge->uniqueid, dst_bridge->uniqueid);
2062                 return -1;
2063         }
2064         if (ast_test_flag(&dst_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)
2065                 || ast_test_flag(&src_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)) {
2066                 ast_debug(1, "Can't merge bridges %s and %s, masquerade only.\n",
2067                         src_bridge->uniqueid, dst_bridge->uniqueid);
2068                 return -1;
2069         }
2070         if (dst_bridge->inhibit_merge || src_bridge->inhibit_merge) {
2071                 ast_debug(1, "Can't merge bridges %s and %s, merging temporarily inhibited.\n",
2072                         src_bridge->uniqueid, dst_bridge->uniqueid);
2073                 return -1;
2074         }
2075
2076         if (merge_best_direction) {
2077                 merge = bridge_merge_determine_direction(dst_bridge, src_bridge);
2078         } else {
2079                 merge.dest = dst_bridge;
2080                 merge.src = src_bridge;
2081         }
2082
2083         if (!merge.dest
2084                 || ast_test_flag(&merge.dest->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
2085                 || ast_test_flag(&merge.src->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
2086                 ast_debug(1, "Can't merge bridges %s and %s, merging inhibited.\n",
2087                         src_bridge->uniqueid, dst_bridge->uniqueid);
2088                 return -1;
2089         }
2090         if (merge.src->num_channels < 2) {
2091                 /*
2092                  * For a two party bridge, a channel may be temporarily removed
2093                  * from the source bridge or the initial bridge members have not
2094                  * joined yet.
2095                  */
2096                 ast_debug(1, "Can't merge bridge %s into bridge %s, not enough channels in source bridge.\n",
2097                         merge.src->uniqueid, merge.dest->uniqueid);
2098                 return -1;
2099         }
2100         if (2 + num_kick < merge.dest->num_channels + merge.src->num_channels
2101                 && !(merge.dest->technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)
2102                 && (!ast_test_flag(&merge.dest->feature_flags, AST_BRIDGE_FLAG_SMART)
2103                         || !(merge.dest->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX))) {
2104                 ast_debug(1, "Can't merge bridge %s into bridge %s, multimix is needed and it cannot be acquired.\n",
2105                         merge.src->uniqueid, merge.dest->uniqueid);
2106                 return -1;
2107         }
2108
2109         if (num_kick) {
2110                 unsigned int num_to_kick = 0;
2111                 unsigned int idx;
2112
2113                 kick_them = ast_alloca(num_kick * sizeof(*kick_them));
2114                 for (idx = 0; idx < num_kick; ++idx) {
2115                         kick_them[num_to_kick] = bridge_find_channel(merge.src, kick_me[idx]);
2116                         if (!kick_them[num_to_kick]) {
2117                                 kick_them[num_to_kick] = bridge_find_channel(merge.dest, kick_me[idx]);
2118                         }
2119                         if (kick_them[num_to_kick]) {
2120                                 ++num_to_kick;
2121                         }
2122                 }
2123
2124                 if (num_to_kick != num_kick) {
2125                         ast_debug(1, "Can't merge bridge %s into bridge %s, at least one kicked channel is not in either bridge.\n",
2126                                 merge.src->uniqueid, merge.dest->uniqueid);
2127                         return -1;
2128                 }
2129         }
2130
2131         bridge_do_merge(merge.dest, merge.src, kick_them, num_kick, 0);
2132         return 0;
2133 }
2134
2135 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)
2136 {
2137         int res;
2138
2139         /* Sanity check. */
2140         ast_assert(dst_bridge && src_bridge);
2141
2142         ast_bridge_lock_both(dst_bridge, src_bridge);
2143         res = bridge_merge_locked(dst_bridge, src_bridge, merge_best_direction, kick_me, num_kick);
2144         ast_bridge_unlock(src_bridge);
2145         ast_bridge_unlock(dst_bridge);
2146         return res;
2147 }
2148
2149 int bridge_do_move(struct ast_bridge *dst_bridge, struct ast_bridge_channel *bridge_channel, int attempt_recovery,
2150         unsigned int optimized)
2151 {
2152         struct ast_bridge *orig_bridge;
2153         int was_in_bridge;
2154         int res = 0;
2155
2156         if (bridge_channel->swap) {
2157                 ast_debug(1, "Moving %p(%s) into bridge %s swapping with %s\n",
2158                         bridge_channel, ast_channel_name(bridge_channel->chan), dst_bridge->uniqueid,
2159                         ast_channel_name(bridge_channel->swap));
2160         } else {
2161                 ast_debug(1, "Moving %p(%s) into bridge %s\n",
2162                         bridge_channel, ast_channel_name(bridge_channel->chan), dst_bridge->uniqueid);
2163         }
2164
2165         orig_bridge = bridge_channel->bridge;
2166         was_in_bridge = bridge_channel->in_bridge;
2167
2168         bridge_channel_internal_pull(bridge_channel);
2169         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2170                 /*
2171                  * The channel died as a result of being pulled.  Leave it
2172                  * pointing to the original bridge.
2173                  */
2174                 bridge_reconfigured(orig_bridge, 0);
2175                 return -1;
2176         }
2177
2178         /* Point to new bridge.*/
2179         ao2_ref(orig_bridge, +1);/* Keep a ref in case the push fails. */
2180         bridge_channel_change_bridge(bridge_channel, dst_bridge);
2181
2182         bridge_channel_moving(bridge_channel, orig_bridge, dst_bridge);
2183
2184         if (bridge_channel_internal_push(bridge_channel)) {
2185                 /* Try to put the channel back into the original bridge. */
2186                 ast_bridge_features_remove(bridge_channel->features,
2187                         AST_BRIDGE_HOOK_REMOVE_ON_PULL);
2188                 if (attempt_recovery && was_in_bridge) {
2189                         /* Point back to original bridge. */
2190                         bridge_channel_change_bridge(bridge_channel, orig_bridge);
2191
2192                         if (bridge_channel_internal_push(bridge_channel)) {
2193                                 ast_bridge_features_remove(bridge_channel->features,
2194                                         AST_BRIDGE_HOOK_REMOVE_ON_PULL);
2195                                 ast_bridge_channel_leave_bridge(bridge_channel,
2196                                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, bridge_channel->bridge->cause);
2197                                 bridge_channel_settle_owed_events(orig_bridge, bridge_channel);
2198                         }
2199                 } else {
2200                         ast_bridge_channel_leave_bridge(bridge_channel,
2201                                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, bridge_channel->bridge->cause);
2202                         bridge_channel_settle_owed_events(orig_bridge, bridge_channel);
2203                 }
2204                 res = -1;
2205         } else {
2206                 bridge_channel_settle_owed_events(orig_bridge, bridge_channel);
2207         }
2208
2209         bridge_reconfigured(dst_bridge, !optimized);
2210         bridge_reconfigured(orig_bridge, !optimized);
2211         ao2_ref(orig_bridge, -1);
2212         return res;
2213 }
2214
2215 /*!
2216  * \internal
2217  * \brief Move a channel from one bridge to another.
2218  * \since 12.0.0
2219  *
2220  * \param dst_bridge Destination bridge of bridge channel move.
2221  * \param src_bridge Source bridge of bridge channel move.
2222  * \param chan Channel to move.
2223  * \param swap Channel to replace in dst_bridge.
2224  * \param attempt_recovery TRUE if failure attempts to push channel back into original bridge.
2225  *
2226  * \note The dst_bridge and src_bridge are assumed already locked.
2227  *
2228  * \retval 0 on success.
2229  * \retval -1 on failure.
2230  */
2231 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)
2232 {
2233         struct ast_bridge_channel *bridge_channel;
2234
2235         if (dst_bridge->dissolved || src_bridge->dissolved) {
2236                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, at least one bridge is dissolved.\n",
2237                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2238                 return -1;
2239         }
2240         if (ast_test_flag(&dst_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)
2241                 || ast_test_flag(&src_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)) {
2242                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, masquerade only.\n",
2243                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2244                 return -1;
2245         }
2246         if (dst_bridge->inhibit_merge || src_bridge->inhibit_merge) {
2247                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, temporarily inhibited.\n",
2248                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2249                 return -1;
2250         }
2251
2252         bridge_channel = bridge_find_channel(src_bridge, chan);
2253         if (!bridge_channel) {
2254                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel not in bridge.\n",
2255                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2256                 return -1;
2257         }
2258         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2259                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel leaving bridge.\n",
2260                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2261                 return -1;
2262         }
2263         if (ast_test_flag(&bridge_channel->features->feature_flags,
2264                 AST_BRIDGE_CHANNEL_FLAG_IMMOVABLE)) {
2265                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel immovable.\n",
2266                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2267                 return -1;
2268         }
2269
2270         if (swap) {
2271                 struct ast_bridge_channel *bridge_channel_swap;
2272
2273                 bridge_channel_swap = bridge_find_channel(dst_bridge, swap);
2274                 if (!bridge_channel_swap) {
2275                         ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, swap channel %s not in bridge.\n",
2276                                 ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid,
2277                                 ast_channel_name(swap));
2278                         return -1;
2279                 }
2280                 if (bridge_channel_swap->state != BRIDGE_CHANNEL_STATE_WAIT) {
2281                         ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, swap channel %s leaving bridge.\n",
2282                                 ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid,
2283                                 ast_channel_name(swap));
2284                         return -1;
2285                 }
2286         }
2287
2288         bridge_channel->swap = swap;
2289         return bridge_do_move(dst_bridge, bridge_channel, attempt_recovery, 0);
2290 }
2291
2292 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)
2293 {
2294         int res;
2295
2296         ast_bridge_lock_both(dst_bridge, src_bridge);
2297         res = bridge_move_locked(dst_bridge, src_bridge, chan, swap, attempt_recovery);
2298         ast_bridge_unlock(src_bridge);
2299         ast_bridge_unlock(dst_bridge);
2300         return res;
2301 }
2302
2303 int ast_bridge_add_channel(struct ast_bridge *bridge, struct ast_channel *chan,
2304         struct ast_bridge_features *features, int play_tone, const char *xfersound)
2305 {
2306         RAII_VAR(struct ast_bridge *, chan_bridge, NULL, ao2_cleanup);
2307         RAII_VAR(struct ast_channel *, yanked_chan, NULL, ao2_cleanup);
2308
2309         ast_channel_lock(chan);
2310         chan_bridge = ast_channel_get_bridge(chan);
2311         ast_channel_unlock(chan);
2312
2313         if (chan_bridge) {
2314                 struct ast_bridge_channel *bridge_channel;
2315
2316                 ast_bridge_lock_both(bridge, chan_bridge);
2317                 bridge_channel = bridge_find_channel(chan_bridge, chan);
2318
2319                 if (bridge_move_locked(bridge, chan_bridge, chan, NULL, 1)) {
2320                         ast_bridge_unlock(chan_bridge);
2321                         ast_bridge_unlock(bridge);
2322                         return -1;
2323                 }
2324
2325                 /*
2326                  * bridge_move_locked() will implicitly ensure that
2327                  * bridge_channel is not NULL.
2328                  */
2329                 ast_assert(bridge_channel != NULL);
2330
2331                 /*
2332                  * Additional checks if the channel we just stole dissolves the
2333                  * original bridge.
2334                  */
2335                 bridge_dissolve_check_stolen(chan_bridge, bridge_channel);
2336                 ast_bridge_unlock(chan_bridge);
2337                 ast_bridge_unlock(bridge);
2338
2339                 /* The channel was in a bridge so it is not getting any new features. */
2340                 ast_bridge_features_destroy(features);
2341         } else {
2342                 /* Slightly less easy case. We need to yank channel A from
2343                  * where he currently is and impart him into our bridge.
2344                  */
2345                 yanked_chan = ast_channel_yank(chan);
2346                 if (!yanked_chan) {
2347                         ast_log(LOG_WARNING, "Could not gain control of channel %s\n", ast_channel_name(chan));
2348                         return -1;
2349                 }
2350                 if (ast_channel_state(yanked_chan) != AST_STATE_UP) {
2351                         ast_answer(yanked_chan);
2352                 }
2353                 ast_channel_ref(yanked_chan);
2354                 if (ast_bridge_impart(bridge, yanked_chan, NULL, features,
2355                         AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
2356                         /* It is possible for us to yank a channel and have some other
2357                          * thread start a PBX on the channl after we yanked it. In particular,
2358                          * this can theoretically happen on the ;2 of a Local channel if we
2359                          * yank it prior to the ;1 being answered. Make sure that it isn't
2360                          * executing a PBX before hanging it up.
2361                          */
2362                         if (ast_channel_pbx(yanked_chan)) {
2363                                 ast_channel_unref(yanked_chan);
2364                         } else {
2365                                 ast_hangup(yanked_chan);
2366                         }
2367                         return -1;
2368                 }
2369         }
2370
2371         if (play_tone && !ast_strlen_zero(xfersound)) {
2372                 struct ast_channel *play_chan = yanked_chan ?: chan;
2373                 RAII_VAR(struct ast_bridge_channel *, play_bridge_channel, NULL, ao2_cleanup);
2374
2375                 ast_channel_lock(play_chan);
2376                 play_bridge_channel = ast_channel_get_bridge_channel(play_chan);
2377                 ast_channel_unlock(play_chan);
2378
2379                 if (!play_bridge_channel) {
2380                         ast_log(LOG_WARNING, "Unable to play tone for channel %s. No longer in a bridge.\n",
2381                                 ast_channel_name(play_chan));
2382                 } else {
2383                         ast_bridge_channel_queue_playfile(play_bridge_channel, NULL, xfersound, NULL);
2384                 }
2385         }
2386         return 0;
2387 }
2388
2389 static int bridge_allows_optimization(struct ast_bridge *bridge)
2390 {
2391         return !(bridge->inhibit_merge
2392                 || bridge->dissolved
2393                 || ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY));
2394 }
2395
2396 /*!
2397  * \internal
2398  * \brief Lock the unreal channel stack for chan and prequalify it.
2399  * \since 12.0.0
2400  *
2401  * \param chan Unreal channel writing a frame into the channel driver.
2402  *
2403  * \note It is assumed that chan is already locked.
2404  *
2405  * \retval bridge on success with bridge and bridge_channel locked.
2406  * \retval NULL if cannot do optimization now.
2407  */
2408 static struct ast_bridge *optimize_lock_chan_stack(struct ast_channel *chan)
2409 {
2410         struct ast_bridge *bridge;
2411         struct ast_bridge_channel *bridge_channel;
2412
2413         if (!AST_LIST_EMPTY(ast_channel_readq(chan))) {
2414                 return NULL;
2415         }
2416         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF)) {
2417                 return NULL;
2418         }
2419         if (ast_channel_has_audio_frame_or_monitor(chan)) {
2420                 /* Channel has an active monitor, audiohook, or framehook. */
2421                 return NULL;
2422         }
2423         bridge_channel = ast_channel_internal_bridge_channel(chan);
2424         if (!bridge_channel || ast_bridge_channel_trylock(bridge_channel)) {
2425                 return NULL;
2426         }
2427         bridge = bridge_channel->bridge;
2428         if (bridge_channel->activity != BRIDGE_CHANNEL_THREAD_SIMPLE
2429                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
2430                 || ast_bridge_trylock(bridge)) {
2431                 ast_bridge_channel_unlock(bridge_channel);
2432                 return NULL;
2433         }
2434         if (!bridge_channel_internal_allows_optimization(bridge_channel) ||
2435                         !bridge_allows_optimization(bridge)) {
2436                 ast_bridge_unlock(bridge);
2437                 ast_bridge_channel_unlock(bridge_channel);
2438                 return NULL;
2439         }
2440         return bridge;
2441 }
2442
2443 /*!
2444  * \internal
2445  * \brief Lock the unreal channel stack for peer and prequalify it.
2446  * \since 12.0.0
2447  *
2448  * \param peer Other unreal channel in the pair.
2449  *
2450  * \retval bridge on success with bridge, bridge_channel, and peer locked.
2451  * \retval NULL if cannot do optimization now.
2452  */
2453 static struct ast_bridge *optimize_lock_peer_stack(struct ast_channel *peer)
2454 {
2455         struct ast_bridge *bridge;
2456         struct ast_bridge_channel *bridge_channel;
2457
2458         if (ast_channel_trylock(peer)) {
2459                 return NULL;
2460         }
2461         if (!AST_LIST_EMPTY(ast_channel_readq(peer))) {
2462                 ast_channel_unlock(peer);
2463                 return NULL;
2464         }
2465         if (ast_test_flag(ast_channel_flags(peer), AST_FLAG_EMULATE_DTMF)) {
2466                 ast_channel_unlock(peer);
2467                 return NULL;
2468         }
2469         if (ast_channel_has_audio_frame_or_monitor(peer)) {
2470                 /* Peer has an active monitor, audiohook, or framehook. */
2471                 ast_channel_unlock(peer);
2472                 return NULL;
2473         }
2474         bridge_channel = ast_channel_internal_bridge_channel(peer);
2475         if (!bridge_channel || ast_bridge_channel_trylock(bridge_channel)) {
2476                 ast_channel_unlock(peer);
2477                 return NULL;
2478         }
2479         bridge = bridge_channel->bridge;
2480         if (bridge_channel->activity != BRIDGE_CHANNEL_THREAD_IDLE
2481                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
2482                 || ast_bridge_trylock(bridge)) {
2483                 ast_bridge_channel_unlock(bridge_channel);
2484                 ast_channel_unlock(peer);
2485                 return NULL;
2486         }
2487         if (!bridge_allows_optimization(bridge) ||
2488                         !bridge_channel_internal_allows_optimization(bridge_channel)) {
2489                 ast_bridge_unlock(bridge);
2490                 ast_bridge_channel_unlock(bridge_channel);
2491                 ast_channel_unlock(peer);
2492                 return NULL;
2493         }
2494         return bridge;
2495 }
2496
2497 /*!
2498  * \internal
2499  * \brief Indicates allowability of a swap optimization
2500  */
2501 enum bridge_allow_swap {
2502         /*! Bridges cannot allow for a swap optimization to occur */
2503         SWAP_PROHIBITED,
2504         /*! Bridge swap optimization can occur into the chan_bridge */
2505         SWAP_TO_CHAN_BRIDGE,
2506         /*! Bridge swap optimization can occur into the peer_bridge */
2507         SWAP_TO_PEER_BRIDGE,
2508 };
2509
2510 /*!
2511  * \internal
2512  * \brief Determine if two bridges allow for swap optimization to occur
2513  *
2514  * \param chan_bridge First bridge being tested
2515  * \param peer_bridge Second bridge being tested
2516  * \return Allowability of swap optimization
2517  */
2518 static enum bridge_allow_swap bridges_allow_swap_optimization(struct ast_bridge *chan_bridge,
2519                 struct ast_bridge *peer_bridge)
2520 {
2521         int chan_priority;
2522         int peer_priority;
2523
2524         if (!ast_test_flag(&chan_bridge->feature_flags,
2525                         AST_BRIDGE_FLAG_SWAP_INHIBIT_TO | AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM |
2526                         AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
2527                 && !ast_test_flag(&peer_bridge->feature_flags,
2528                         AST_BRIDGE_FLAG_SWAP_INHIBIT_TO | AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM |
2529                         AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)) {
2530                 /*
2531                  * Can swap either way.  Swap to the higher priority merge
2532                  * bridge.
2533                  */
2534                 chan_priority = chan_bridge->v_table->get_merge_priority(chan_bridge);
2535                 peer_priority = peer_bridge->v_table->get_merge_priority(peer_bridge);
2536                 if (chan_bridge->num_channels == 2
2537                         && chan_priority <= peer_priority) {
2538                         return SWAP_TO_PEER_BRIDGE;
2539                 } else if (peer_bridge->num_channels == 2
2540                         && peer_priority <= chan_priority) {
2541                         return SWAP_TO_CHAN_BRIDGE;
2542                 }
2543         } else if (chan_bridge->num_channels == 2
2544                 && !ast_test_flag(&chan_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM | AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
2545                 && !ast_test_flag(&peer_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_TO)) {
2546                 /* Can swap optimize only one way. */
2547                 return SWAP_TO_PEER_BRIDGE;
2548         } else if (peer_bridge->num_channels == 2
2549                 && !ast_test_flag(&peer_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM | AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
2550                 && !ast_test_flag(&chan_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_TO)) {
2551                 /* Can swap optimize only one way. */
2552                 return SWAP_TO_CHAN_BRIDGE;
2553         }
2554
2555         return SWAP_PROHIBITED;
2556 }
2557
2558 /*!
2559  * \internal
2560  * \brief Check and attempt to swap optimize out the unreal channels.
2561  * \since 12.0.0
2562  *
2563  * \param chan_bridge
2564  * \param chan_bridge_channel
2565  * \param peer_bridge
2566  * \param peer_bridge_channel
2567  * \param pvt Unreal data containing callbacks to call if the optimization actually
2568  * happens
2569  *
2570  * \retval 1 if unreal channels failed to optimize out.
2571  * \retval 0 if unreal channels were not optimized out.
2572  * \retval -1 if unreal channels were optimized out.
2573  */
2574 static int try_swap_optimize_out(struct ast_bridge *chan_bridge,
2575         struct ast_bridge_channel *chan_bridge_channel, struct ast_bridge *peer_bridge,
2576         struct ast_bridge_channel *peer_bridge_channel,
2577         struct ast_unreal_pvt *pvt)
2578 {
2579         struct ast_bridge *dst_bridge;
2580         struct ast_bridge_channel *dst_bridge_channel;
2581         struct ast_bridge_channel *src_bridge_channel;
2582         struct ast_bridge_channel *other;
2583         int res = 1;
2584
2585         switch (bridges_allow_swap_optimization(chan_bridge, peer_bridge)) {
2586         case SWAP_TO_CHAN_BRIDGE:
2587                 dst_bridge = chan_bridge;
2588                 dst_bridge_channel = chan_bridge_channel;
2589                 src_bridge_channel = peer_bridge_channel;
2590                 break;
2591         case SWAP_TO_PEER_BRIDGE:
2592                 dst_bridge = peer_bridge;
2593                 dst_bridge_channel = peer_bridge_channel;
2594                 src_bridge_channel = chan_bridge_channel;
2595                 break;
2596         case SWAP_PROHIBITED:
2597         default:
2598                 return 0;
2599         }
2600
2601         other = ast_bridge_channel_peer(src_bridge_channel);
2602         if (other && other->state == BRIDGE_CHANNEL_STATE_WAIT) {
2603                 unsigned int id;
2604
2605                 if (ast_channel_trylock(other->chan)) {
2606                         return 1;
2607                 }
2608
2609                 id = ast_atomic_fetchadd_int((int *) &optimization_id, +1);
2610
2611                 ast_verb(4, "Move-swap optimizing %s <-- %s.\n",
2612                         ast_channel_name(dst_bridge_channel->chan),
2613                         ast_channel_name(other->chan));
2614
2615                 if (pvt && !ast_test_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN) && pvt->callbacks
2616                                 && pvt->callbacks->optimization_started) {
2617                         pvt->callbacks->optimization_started(pvt, other->chan,
2618                                         dst_bridge_channel->chan == pvt->owner ? AST_UNREAL_OWNER : AST_UNREAL_CHAN,
2619                                         id);
2620                         ast_set_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN);
2621                 }
2622                 other->swap = dst_bridge_channel->chan;
2623                 if (!bridge_do_move(dst_bridge, other, 1, 1)) {
2624                         ast_bridge_channel_leave_bridge(src_bridge_channel,
2625                                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
2626                         res = -1;
2627                 }
2628                 if (pvt && pvt->callbacks && pvt->callbacks->optimization_finished) {
2629                         pvt->callbacks->optimization_finished(pvt, res == 1, id);
2630                 }
2631                 ast_channel_unlock(other->chan);
2632         }
2633         return res;
2634 }
2635
2636 /*!
2637  * \internal
2638  * \brief Indicates allowability of a merge optimization
2639  */
2640 enum bridge_allow_merge {
2641         /*! Bridge properties prohibit merge optimization */
2642         MERGE_PROHIBITED,
2643         /*! Merge optimization cannot occur because the source bridge has too few channels */
2644         MERGE_NOT_ENOUGH_CHANNELS,
2645         /*! Merge optimization cannot occur because multimix capability could not be requested */
2646         MERGE_NO_MULTIMIX,
2647         /*! Merge optimization allowed between bridges */
2648         MERGE_ALLOWED,
2649 };
2650
2651 /*!
2652  * \internal
2653  * \brief Determines allowability of a merge optimization
2654  *
2655  * \note The merge output parameter is undefined if MERGE_PROHIBITED is returned. For success
2656  * and other failure returns, a merge direction was determined, and the parameter is safe to
2657  * access.
2658  *
2659  * \param chan_bridge First bridge being tested
2660  * \param peer_bridge Second bridge being tested
2661  * \param num_kick_channels The number of channels to remove from the bridges during merging
2662  * \param[out] merge Indicates the recommended direction for the bridge merge
2663  */
2664 static enum bridge_allow_merge bridges_allow_merge_optimization(struct ast_bridge *chan_bridge,
2665                 struct ast_bridge *peer_bridge, int num_kick_channels, struct merge_direction *merge)
2666 {
2667         *merge = bridge_merge_determine_direction(chan_bridge, peer_bridge);
2668         if (!merge->dest) {
2669                 return MERGE_PROHIBITED;
2670         }
2671         if (merge->src->num_channels < 2) {
2672                 return MERGE_NOT_ENOUGH_CHANNELS;
2673         } else if ((2 + num_kick_channels) < merge->dest->num_channels + merge->src->num_channels
2674                 && !(merge->dest->technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)
2675                 && (!ast_test_flag(&merge->dest->feature_flags, AST_BRIDGE_FLAG_SMART)
2676                         || !(merge->dest->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX))) {
2677                 return MERGE_NO_MULTIMIX;
2678         }
2679
2680         return MERGE_ALLOWED;
2681 }
2682
2683 /*!
2684  * \internal
2685  * \brief Check and attempt to merge optimize out the unreal channels.
2686  * \since 12.0.0
2687  *
2688  * \param chan_bridge
2689  * \param chan_bridge_channel
2690  * \param peer_bridge
2691  * \param peer_bridge_channel
2692  * \param pvt Unreal data containing callbacks to call if the optimization actually
2693  * happens
2694  *
2695  * \retval 0 if unreal channels were not optimized out.
2696  * \retval -1 if unreal channels were optimized out.
2697  */
2698 static int try_merge_optimize_out(struct ast_bridge *chan_bridge,
2699         struct ast_bridge_channel *chan_bridge_channel, struct ast_bridge *peer_bridge,
2700         struct ast_bridge_channel *peer_bridge_channel,
2701         struct ast_unreal_pvt *pvt)
2702 {
2703         struct merge_direction merge;
2704         struct ast_bridge_channel *kick_me[] = {
2705                 chan_bridge_channel,
2706                 peer_bridge_channel,
2707         };
2708         unsigned int id;
2709
2710         switch (bridges_allow_merge_optimization(chan_bridge, peer_bridge, ARRAY_LEN(kick_me), &merge)) {
2711         case MERGE_ALLOWED:
2712                 break;
2713         case MERGE_PROHIBITED:
2714                 return 0;
2715         case MERGE_NOT_ENOUGH_CHANNELS:
2716                 ast_debug(4, "Can't optimize %s -- %s out, not enough channels in bridge %s.\n",
2717                         ast_channel_name(chan_bridge_channel->chan),
2718                         ast_channel_name(peer_bridge_channel->chan),
2719                         merge.src->uniqueid);
2720                 return 0;
2721         case MERGE_NO_MULTIMIX:
2722                 ast_debug(4, "Can't optimize %s -- %s out, multimix is needed and it cannot be acquired.\n",
2723                         ast_channel_name(chan_bridge_channel->chan),
2724                         ast_channel_name(peer_bridge_channel->chan));
2725                 return 0;
2726         }
2727
2728         ast_verb(4, "Merge optimizing %s -- %s out.\n",
2729                 ast_channel_name(chan_bridge_channel->chan),
2730                 ast_channel_name(peer_bridge_channel->chan));
2731
2732         id = ast_atomic_fetchadd_int((int *) &optimization_id, +1);
2733
2734         if (pvt && !ast_test_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN) && pvt->callbacks
2735                         && pvt->callbacks->optimization_started) {
2736                 pvt->callbacks->optimization_started(pvt, NULL,
2737                                 merge.dest == ast_channel_internal_bridge(pvt->owner) ? AST_UNREAL_OWNER : AST_UNREAL_CHAN,
2738                                 id);
2739                 ast_set_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN);
2740         }
2741         bridge_do_merge(merge.dest, merge.src, kick_me, ARRAY_LEN(kick_me), 1);
2742         if (pvt && pvt->callbacks && pvt->callbacks->optimization_finished) {
2743                 pvt->callbacks->optimization_finished(pvt, 1, id);
2744         }
2745
2746         return -1;
2747 }
2748
2749 int ast_bridge_unreal_optimize_out(struct ast_channel *chan, struct ast_channel *peer, struct ast_unreal_pvt *pvt)
2750 {
2751         struct ast_bridge *chan_bridge;
2752         struct ast_bridge *peer_bridge;
2753         struct ast_bridge_channel *chan_bridge_channel;
2754         struct ast_bridge_channel *peer_bridge_channel;
2755         int res = 0;
2756
2757         chan_bridge = optimize_lock_chan_stack(chan);
2758         if (!chan_bridge) {
2759                 return res;
2760         }
2761         chan_bridge_channel = ast_channel_internal_bridge_channel(chan);
2762
2763         peer_bridge = optimize_lock_peer_stack(peer);
2764         if (peer_bridge) {
2765                 peer_bridge_channel = ast_channel_internal_bridge_channel(peer);
2766
2767                 res = try_swap_optimize_out(chan_bridge, chan_bridge_channel,
2768                         peer_bridge, peer_bridge_channel, pvt);
2769                 if (!res) {
2770                         res = try_merge_optimize_out(chan_bridge, chan_bridge_channel,
2771                                 peer_bridge, peer_bridge_channel, pvt);
2772                 } else if (0 < res) {
2773                         res = 0;
2774                 }
2775
2776                 /* Release peer locks. */
2777                 ast_bridge_unlock(peer_bridge);
2778                 ast_bridge_channel_unlock(peer_bridge_channel);
2779                 ast_channel_unlock(peer);
2780         }
2781
2782         /* Release chan locks. */
2783         ast_bridge_unlock(chan_bridge);
2784         ast_bridge_channel_unlock(chan_bridge_channel);
2785
2786         return res;
2787 }
2788
2789 enum ast_bridge_optimization ast_bridges_allow_optimization(struct ast_bridge *chan_bridge,
2790                 struct ast_bridge *peer_bridge)
2791 {
2792         struct merge_direction merge;
2793
2794         if (!bridge_allows_optimization(chan_bridge) || !bridge_allows_optimization(peer_bridge)) {
2795                 return AST_BRIDGE_OPTIMIZE_PROHIBITED;
2796         }
2797
2798         switch (bridges_allow_swap_optimization(chan_bridge, peer_bridge)) {
2799         case SWAP_TO_CHAN_BRIDGE:
2800                 return AST_BRIDGE_OPTIMIZE_SWAP_TO_CHAN_BRIDGE;
2801         case SWAP_TO_PEER_BRIDGE:
2802                 return AST_BRIDGE_OPTIMIZE_SWAP_TO_PEER_BRIDGE;
2803         case SWAP_PROHIBITED:
2804         default:
2805                 break;
2806         }
2807
2808         /* Two channels will be kicked from the bridges, the unreal;1 and unreal;2 channels */
2809         if (bridges_allow_merge_optimization(chan_bridge, peer_bridge, 2, &merge) != MERGE_ALLOWED) {
2810                 return AST_BRIDGE_OPTIMIZE_PROHIBITED;
2811         }
2812
2813         if (merge.dest == chan_bridge) {
2814                 return AST_BRIDGE_OPTIMIZE_MERGE_TO_CHAN_BRIDGE;
2815         } else {
2816                 return AST_BRIDGE_OPTIMIZE_MERGE_TO_PEER_BRIDGE;
2817         }
2818 }
2819
2820 /*!
2821  * \internal
2822  * \brief Adjust the bridge merge inhibit request count.
2823  * \since 12.0.0
2824  *
2825  * \param bridge What to operate on.
2826  * \param request Inhibit request increment.
2827  *     (Positive to add requests.  Negative to remove requests.)
2828  *
2829  * \note This function assumes bridge is locked.
2830  *
2831  * \return Nothing
2832  */
2833 void bridge_merge_inhibit_nolock(struct ast_bridge *bridge, int request)
2834 {
2835         int new_request;
2836
2837         new_request = bridge->inhibit_merge + request;
2838         ast_assert(0 <= new_request);
2839         bridge->inhibit_merge = new_request;
2840 }
2841
2842 void ast_bridge_merge_inhibit(struct ast_bridge *bridge, int request)
2843 {
2844         ast_bridge_lock(bridge);
2845         bridge_merge_inhibit_nolock(bridge, request);
2846         ast_bridge_unlock(bridge);
2847 }
2848
2849 int ast_bridge_suspend(struct ast_bridge *bridge, struct ast_channel *chan)
2850 {
2851         struct ast_bridge_channel *bridge_channel;
2852 /* XXX ASTERISK-21271 the case of a disolved bridge while channel is suspended is not handled. */
2853 /* XXX ASTERISK-21271 suspend/unsuspend needs to be rethought. The caller must block until it has successfully suspended the channel for temporary control. */
2854 /* 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. */
2855
2856         ast_bridge_lock(bridge);
2857
2858         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
2859                 ast_bridge_unlock(bridge);
2860                 return -1;
2861         }
2862
2863         bridge_channel_internal_suspend_nolock(bridge_channel);
2864
2865         ast_bridge_unlock(bridge);
2866
2867         return 0;
2868 }
2869
2870 int ast_bridge_unsuspend(struct ast_bridge *bridge, struct ast_channel *chan)
2871 {
2872         struct ast_bridge_channel *bridge_channel;
2873 /* XXX ASTERISK-21271 the case of a disolved bridge while channel is suspended is not handled. */
2874
2875         ast_bridge_lock(bridge);
2876
2877         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
2878                 ast_bridge_unlock(bridge);
2879                 return -1;
2880         }
2881
2882         bridge_channel_internal_unsuspend_nolock(bridge_channel);
2883
2884         ast_bridge_unlock(bridge);
2885
2886         return 0;
2887 }
2888
2889 void ast_bridge_technology_suspend(struct ast_bridge_technology *technology)
2890 {
2891         technology->suspended = 1;
2892 }
2893
2894 void ast_bridge_technology_unsuspend(struct ast_bridge_technology *technology)
2895 {
2896         /*
2897          * XXX We may want the act of unsuspending a bridge technology
2898          * to prod all existing bridges to see if they should start
2899          * using it.
2900          */
2901         technology->suspended = 0;
2902 }
2903
2904 int ast_bridge_features_register(enum ast_bridge_builtin_feature feature, ast_bridge_hook_callback callback, const char *dtmf)
2905 {
2906         if (ARRAY_LEN(builtin_features_handlers) <= feature
2907                 || builtin_features_handlers[feature]) {
2908                 return -1;
2909         }
2910
2911         if (!ast_strlen_zero(dtmf)) {
2912                 ast_copy_string(builtin_features_dtmf[feature], dtmf, sizeof(builtin_features_dtmf[feature]));
2913         }
2914
2915         builtin_features_handlers[feature] = callback;
2916
2917         return 0;
2918 }
2919
2920 int ast_bridge_features_unregister(enum ast_bridge_builtin_feature feature)
2921 {
2922         if (ARRAY_LEN(builtin_features_handlers) <= feature
2923                 || !builtin_features_handlers[feature]) {
2924                 return -1;
2925         }
2926
2927         builtin_features_handlers[feature] = NULL;
2928
2929         return 0;
2930 }
2931
2932 int ast_bridge_features_do(enum ast_bridge_builtin_feature feature, struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2933 {
2934         ast_bridge_hook_callback callback;
2935
2936         if (ARRAY_LEN(builtin_features_handlers) <= feature) {
2937                 return -1;
2938         }
2939
2940         callback = builtin_features_handlers[feature];
2941         if (!callback) {
2942                 return -1;
2943         }
2944         callback(bridge_channel, hook_pvt);
2945
2946         return 0;
2947 }
2948
2949 int ast_bridge_interval_register(enum ast_bridge_builtin_interval interval, ast_bridge_builtin_set_limits_fn callback)
2950 {
2951         if (ARRAY_LEN(builtin_interval_handlers) <= interval
2952                 || builtin_interval_handlers[interval]) {
2953                 return -1;
2954         }
2955
2956         builtin_interval_handlers[interval] = callback;
2957
2958         return 0;
2959 }
2960
2961 int ast_bridge_interval_unregister(enum ast_bridge_builtin_interval interval)
2962 {
2963         if (ARRAY_LEN(builtin_interval_handlers) <= interval
2964                 || !builtin_interval_handlers[interval]) {
2965                 return -1;
2966         }
2967
2968         builtin_interval_handlers[interval] = NULL;
2969
2970         return 0;
2971
2972 }
2973
2974 /*!
2975  * \internal
2976  * \brief Bridge hook destructor.
2977  * \since 12.0.0
2978  *
2979  * \param vhook Object to destroy.
2980  *
2981  * \return Nothing
2982  */
2983 static void bridge_hook_destroy(void *vhook)
2984 {
2985         struct ast_bridge_hook *hook = vhook;
2986
2987         if (hook->destructor) {
2988                 hook->destructor(hook->hook_pvt);
2989         }
2990 }
2991
2992 /*!
2993  * \internal
2994  * \brief Allocate and setup a generic bridge hook.
2995  * \since 12.0.0
2996  *
2997  * \param size How big an object to allocate.
2998  * \param callback Function to execute upon activation
2999  * \param hook_pvt Unique data
3000  * \param destructor Optional destructor callback for hook_pvt data
3001  * \param remove_flags Dictates what situations the hook should be removed.
3002  *
3003  * \retval hook on success.
3004  * \retval NULL on error.
3005  */
3006 static struct ast_bridge_hook *bridge_hook_generic(size_t size,
3007         ast_bridge_hook_callback callback,
3008         void *hook_pvt,
3009         ast_bridge_hook_pvt_destructor destructor,
3010         enum ast_bridge_hook_remove_flags remove_flags)
3011 {
3012         struct ast_bridge_hook *hook;
3013
3014         /* Allocate new hook and setup it's basic variables */
3015         hook = ao2_alloc_options(size, bridge_hook_destroy, AO2_ALLOC_OPT_LOCK_NOLOCK);
3016         if (hook) {
3017                 hook->callback = callback;
3018                 hook->destructor = destructor;
3019                 hook->hook_pvt = hook_pvt;
3020                 ast_set_flag(&hook->remove_flags, remove_flags);
3021         }
3022
3023         return hook;
3024 }
3025
3026 int ast_bridge_dtmf_hook(struct ast_bridge_features *features,
3027         const char *dtmf,
3028         ast_bridge_hook_callback callback,
3029         void *hook_pvt,
3030         ast_bridge_hook_pvt_destructor destructor,
3031         enum ast_bridge_hook_remove_flags remove_flags)
3032 {
3033         struct ast_bridge_hook_dtmf *hook;
3034         int res;
3035
3036         /* Allocate new hook and setup it's various variables */
3037         hook = (struct ast_bridge_hook_dtmf *) bridge_hook_generic(sizeof(*hook), callback,
3038                 hook_pvt, destructor, remove_flags);
3039         if (!hook) {
3040                 return -1;
3041         }
3042         hook->generic.type = AST_BRIDGE_HOOK_TYPE_DTMF;
3043         ast_copy_string(hook->dtmf.code, dtmf, sizeof(hook->dtmf.code));
3044
3045         /* Once done we put it in the container. */
3046         res = ao2_link(features->dtmf_hooks, hook) ? 0 : -1;
3047         if (res) {
3048                 /*
3049                  * Could not link the hook into the container.
3050                  *
3051                  * Remove the hook_pvt destructor call from the hook since we
3052                  * are returning failure to install the hook.
3053                  */
3054                 hook->generic.destructor = NULL;
3055         }
3056         ao2_ref(hook, -1);
3057
3058         return res;
3059 }
3060
3061 /*!
3062  * \internal
3063  * \brief Attach an other hook to a bridge features structure
3064  *
3065  * \param features Bridge features structure
3066  * \param callback Function to execute upon activation
3067  * \param hook_pvt Unique data
3068  * \param destructor Optional destructor callback for hook_pvt data
3069  * \param remove_flags Dictates what situations the hook should be removed.
3070  * \param type What type of hook is being attached.
3071  *
3072  * \retval 0 on success
3073  * \retval -1 on failure (The caller must cleanup any hook_pvt resources.)
3074  */
3075 static int bridge_other_hook(struct ast_bridge_features *features,
3076         ast_bridge_hook_callback callback,
3077         void *hook_pvt,
3078         ast_bridge_hook_pvt_destructor destructor,
3079         enum ast_bridge_hook_remove_flags remove_flags,
3080         enum ast_bridge_hook_type type)
3081 {
3082         struct ast_bridge_hook *hook;
3083         int res;
3084
3085         /* Allocate new hook and setup it's various variables */
3086         hook = bridge_hook_generic(sizeof(*hook), callback, hook_pvt, destructor,
3087                 remove_flags);
3088         if (!hook) {
3089                 return -1;
3090         }
3091         hook->type = type;
3092
3093         /* Once done we put it in the container. */
3094         res = ao2_link(features->other_hooks, hook) ? 0 : -1;
3095         if (res) {
3096                 /*
3097                  * Could not link the hook into the container.
3098                  *
3099                  * Remove the hook_pvt destructor call from the hook since we
3100                  * are returning failure to install the hook.
3101                  */
3102                 hook->destructor = NULL;
3103         }
3104         ao2_ref(hook, -1);
3105
3106         return res;
3107 }
3108
3109 int ast_bridge_hangup_hook(struct ast_bridge_features *features,
3110         ast_bridge_hook_callback callback,
3111         void *hook_pvt,
3112         ast_bridge_hook_pvt_destructor destructor,
3113         enum ast_bridge_hook_remove_flags remove_flags)
3114 {
3115         return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
3116                 AST_BRIDGE_HOOK_TYPE_HANGUP);
3117 }
3118
3119 int ast_bridge_join_hook(struct ast_bridge_features *features,
3120         ast_bridge_hook_callback callback,
3121         void *hook_pvt,
3122         ast_bridge_hook_pvt_destructor destructor,
3123         enum ast_bridge_hook_remove_flags remove_flags)
3124 {
3125         return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
3126                 AST_BRIDGE_HOOK_TYPE_JOIN);
3127 }
3128
3129 int ast_bridge_leave_hook(struct ast_bridge_features *features,
3130         ast_bridge_hook_callback callback,
3131         void *hook_pvt,
3132         ast_bridge_hook_pvt_destructor destructor,
3133         enum ast_bridge_hook_remove_flags remove_flags)
3134 {
3135         return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
3136                 AST_BRIDGE_HOOK_TYPE_LEAVE);
3137 }
3138
3139 int ast_bridge_talk_detector_hook(struct ast_bridge_features *features,
3140         ast_bridge_talking_indicate_callback callback,
3141         void *hook_pvt,
3142         ast_bridge_hook_pvt_destructor destructor,
3143         enum ast_bridge_hook_remove_flags remove_flags)
3144 {
3145         ast_bridge_hook_callback hook_cb = (ast_bridge_hook_callback) callback;
3146
3147         return bridge_other_hook(features, hook_cb, hook_pvt, destructor, remove_flags,
3148                 AST_BRIDGE_HOOK_TYPE_TALK);
3149 }
3150
3151 int ast_bridge_move_hook(struct ast_bridge_features *features,
3152         ast_bridge_move_indicate_callback callback,
3153         void *hook_pvt,
3154         ast_bridge_hook_pvt_destructor destructor,
3155         enum ast_bridge_hook_remove_flags remove_flags)
3156 {
3157         ast_bridge_hook_callback hook_cb = (ast_bridge_hook_callback) callback;
3158
3159         return bridge_other_hook(features, hook_cb, hook_pvt, destructor, remove_flags,
3160                 AST_BRIDGE_HOOK_TYPE_MOVE);
3161 }
3162
3163 int ast_bridge_interval_hook(struct ast_bridge_features *features,
3164         enum ast_bridge_hook_timer_option flags,
3165         unsigned int interval,
3166         ast_bridge_hook_callback callback,
3167         void *hook_pvt,
3168         ast_bridge_hook_pvt_destructor destructor,
3169         enum ast_bridge_hook_remove_flags remove_flags)
3170 {
3171         struct ast_bridge_hook_timer *hook;
3172         int res;
3173
3174         if (!features ||!interval || !callback) {
3175                 return -1;
3176         }
3177
3178         /* Allocate new hook and setup it's various variables */
3179         hook = (struct ast_bridge_hook_timer *) bridge_hook_generic(sizeof(*hook), callback,
3180                 hook_pvt, destructor, remove_flags);
3181         if (!hook) {
3182                 return -1;
3183         }
3184         hook->generic.type = AST_BRIDGE_HOOK_TYPE_TIMER;
3185         hook->timer.interval = interval;
3186         hook->timer.trip_time = ast_tvadd(ast_tvnow(), ast_samp2tv(interval, 1000));
3187         hook->timer.seqno = ast_atomic_fetchadd_int((int *) &features->interval_sequence, +1);
3188         hook->timer.flags = flags;
3189
3190         ast_debug(1, "Putting interval hook %p with interval %u in the heap on features %p\n",
3191                 hook, hook->timer.interval, features);
3192         ast_heap_wrlock(features->interval_hooks);
3193         res = ast_heap_push(features->interval_hooks, hook);
3194         ast_heap_unlock(features->interval_hooks);
3195         if (res) {
3196                 /*
3197                  * Could not push the hook into the heap
3198                  *
3199                  * Remove the hook_pvt destructor call from the hook since we
3200                  * are returning failure to install the hook.
3201                  */
3202                 hook->generic.destructor = NULL;
3203                 ao2_ref(hook, -1);
3204         }
3205
3206         return res ? -1 : 0;
3207 }
3208
3209 int ast_bridge_features_enable(struct ast_bridge_features *features,
3210         enum ast_bridge_builtin_feature feature,
3211         const char *dtmf,
3212         void *config,
3213         ast_bridge_hook_pvt_destructor destructor,
3214         enum ast_bridge_hook_remove_flags remove_flags)
3215 {
3216         if (ARRAY_LEN(builtin_features_handlers) <= feature
3217                 || !builtin_features_handlers[feature]) {
3218                 return -1;
3219         }
3220
3221         /* If no alternate DTMF stream was provided use the default one */
3222         if (ast_strlen_zero(dtmf)) {
3223                 dtmf = builtin_features_dtmf[feature];
3224                 /* If no DTMF is still available (ie: it has been disabled) then error out now */
3225                 if (ast_strlen_zero(dtmf)) {
3226                         ast_debug(1, "Failed to enable built in feature %u on %p, no DTMF string is available for it.\n",
3227                                 feature, features);
3228                         return -1;
3229                 }
3230         }
3231
3232         /*
3233          * The rest is basically pretty easy.  We create another hook
3234          * using the built in feature's DTMF callback.  Easy as pie.
3235          */
3236         return ast_bridge_dtmf_hook(features, dtmf, builtin_features_handlers[feature],
3237                 config, destructor, remove_flags);
3238 }
3239
3240 int ast_bridge_features_limits_construct(struct ast_bridge_features_limits *limits)
3241 {
3242         memset(limits, 0, sizeof(*limits));
3243
3244         if (ast_string_field_init(limits, 256)) {
3245                 return -1;
3246         }
3247
3248         return 0;
3249 }
3250
3251 void ast_bridge_features_limits_destroy(struct ast_bridge_features_limits *limits)
3252 {
3253         ast_string_field_free_memory(limits);
3254 }
3255
3256 int ast_bridge_features_set_limits(struct ast_bridge_features *features,
3257         struct ast_bridge_features_limits *limits,
3258         enum ast_bridge_hook_remove_flags remove_flags)
3259 {
3260         if (builtin_interval_handlers[AST_BRIDGE_BUILTIN_INTERVAL_LIMITS]) {
3261                 ast_bridge_builtin_set_limits_fn callback;
3262
3263                 callback = builtin_interval_handlers[AST_BRIDGE_BUILTIN_INTERVAL_LIMITS];
3264                 return callback(features, limits, remove_flags);
3265         }
3266
3267         ast_log(LOG_ERROR, "Attempted to set limits without an AST_BRIDGE_BUILTIN_INTERVAL_LIMITS callback registered.\n");
3268         return -1;
3269 }
3270
3271 void ast_bridge_features_set_flag(struct ast_bridge_features *features, unsigned int flag)
3272 {
3273         ast_set_flag(&features->feature_flags, flag);
3274         features->usable = 1;
3275 }
3276
3277 /*!
3278  * \internal
3279  * \brief ao2 object match hooks with appropriate remove_flags.
3280  * \since 12.0.0
3281  *
3282  * \param obj Feature hook object.
3283  * \param arg Removal flags
3284  * \param flags Not used
3285  *
3286  * \retval CMP_MATCH if hook's remove_flags match the removal flags set.
3287  * \retval 0 if not match.
3288  */
3289 static int hook_remove_match(void *obj, void *arg, int flags)
3290 {
3291         struct ast_bridge_hook *hook = obj;
3292         enum ast_bridge_hook_remove_flags *remove_flags = arg;
3293
3294         if (ast_test_flag(&hook->remove_flags, *remove_flags)) {
3295                 return CMP_MATCH;
3296         } else {
3297                 return 0;
3298         }
3299 }
3300
3301 /*!
3302  * \internal
3303  * \brief Remove all hooks with appropriate remove_flags in the container.
3304  * \since 12.0.0
3305  *
3306  * \param hooks Hooks container to work on.
3307  * \param remove_flags Determinator for whether hook is removed
3308  *
3309  * \return Nothing
3310  */
3311 static void hooks_remove_container(struct ao2_container *hooks, enum ast_bridge_hook_remove_flags remove_flags)
3312 {
3313         ao2_callback(hooks, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
3314                 hook_remove_match, &remove_flags);
3315 }
3316
3317 /*!
3318  * \internal
3319  * \brief Remove all hooks in the heap with appropriate remove_flags set.
3320  * \since 12.0.0
3321  *
3322  * \param hooks Hooks heap to work on.
3323  * \param remove_flags Determinator for whether hook is removed
3324  *
3325  * \return Nothing
3326  */
3327 static void hooks_remove_heap(struct ast_heap *hooks, enum ast_bridge_hook_remove_flags remove_flags)
3328 {
3329         struct ast_bridge_hook *hook;
3330         int changed;
3331
3332         ast_heap_wrlock(hooks);
3333         do {
3334                 int idx;
3335
3336                 changed = 0;
3337                 for (idx = ast_heap_size(hooks); idx; --idx) {
3338                         hook = ast_heap_peek(hooks, idx);
3339                         if (ast_test_flag(&hook->remove_flags, remove_flags)) {
3340                                 ast_heap_remove(hooks, hook);
3341                                 ao2_ref(hook, -1);
3342                                 changed = 1;
3343                         }
3344                 }
3345         } while (changed);
3346         ast_heap_unlock(hooks);
3347 }
3348
3349 void ast_bridge_features_remove(struct ast_bridge_features *features, enum ast_bridge_hook_remove_flags remove_flags)
3350 {
3351         hooks_remove_container(features->dtmf_hooks, remove_flags);
3352         hooks_remove_container(features->other_hooks, remove_flags);
3353         hooks_remove_heap(features->interval_hooks, remove_flags);
3354 }
3355
3356 static int interval_hook_time_cmp(void *a, void *b)
3357 {
3358         struct ast_bridge_hook_timer *hook_a = a;
3359         struct ast_bridge_hook_timer *hook_b = b;
3360         int cmp;
3361
3362         cmp = ast_tvcmp(hook_b->timer.trip_time, hook_a->timer.trip_time);
3363         if (cmp) {
3364                 return cmp;
3365         }
3366
3367         cmp = hook_b->timer.seqno - hook_a->timer.seqno;
3368         return cmp;
3369 }
3370
3371 /*!
3372  * \internal
3373  * \brief DTMF hook container sort comparison function.
3374  * \since 12.0.0
3375  *
3376  * \param obj_left pointer to the (user-defined part) of an object.
3377  * \param obj_right pointer to the (user-defined part) of an object.
3378  * \param flags flags from ao2_callback()
3379  *   OBJ_POINTER - if set, 'obj_right', is an object.
3380  *   OBJ_KEY - if set, 'obj_right', is a search key item that is not an object.
3381  *   OBJ_PARTIAL_KEY - if set, 'obj_right', is a partial search key item that is not an object.
3382  *
3383  * \retval <0 if obj_left < obj_right
3384  * \retval =0 if obj_left == obj_right
3385  * \retval >0 if obj_left > obj_right
3386  */
3387 static int bridge_dtmf_hook_sort(const void *obj_left, const void *obj_right, int flags)
3388 {
3389         const struct ast_bridge_hook_dtmf *hook_left = obj_left;
3390         const struct ast_bridge_hook_dtmf *hook_right = obj_right;
3391         const char *right_key = obj_right;
3392         int cmp;
3393
3394         switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
3395         default:
3396         case OBJ_POINTER:
3397                 right_key = hook_right->dtmf.code;
3398                 /* Fall through */
3399         case OBJ_KEY:
3400                 cmp = strcasecmp(hook_left->dtmf.code, right_key);
3401                 break;
3402         case OBJ_PARTIAL_KEY:
3403                 cmp = strncasecmp(hook_left->dtmf.code, right_key, strlen(right_key));
3404                 break;
3405         }
3406         return cmp;
3407 }
3408
3409 /*! \brief Callback for merging hook ao2_containers */
3410 static int merge_container_cb(void *obj, void *data, int flags)
3411 {
3412         ao2_link(data, obj);
3413         return 0;
3414 }
3415
3416 /*! \brief Wrapper for interval hooks that calls into the wrapped hook */
3417 static int interval_wrapper_cb(struct ast_bridge_channel *bridge_channel, void *obj)
3418 {
3419         struct ast_bridge_hook_timer *hook = obj;
3420
3421         return hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
3422 }
3423
3424 /*! \brief Destructor for the hook wrapper */
3425 static void interval_wrapper_pvt_dtor(void *obj)
3426 {
3427         ao2_cleanup(obj);
3428 }
3429
3430 /*! \brief Wrap the provided interval hook and add it to features */
3431 static void wrap_hook(struct ast_bridge_features *features, struct ast_bridge_hook_timer *hook)
3432 {
3433         /* Break out of the current wrapper if it exists to avoid multiple layers */
3434         if (hook->generic.callback == interval_wrapper_cb) {
3435                 hook = hook->generic.hook_pvt;
3436         }
3437
3438         ast_bridge_interval_hook(features, hook->timer.flags, hook->timer.interval,
3439                 interval_wrapper_cb, ao2_bump(hook), interval_wrapper_pvt_dtor,
3440                 hook->generic.remove_flags.flags);
3441 }
3442
3443 void ast_bridge_features_merge(struct ast_bridge_features *into, const struct ast_bridge_features *from)
3444 {
3445         struct ast_bridge_hook_timer *hook;
3446         int idx;
3447
3448         /* Merge hook containers */
3449         ao2_callback(from->dtmf_hooks, 0, merge_container_cb, into->dtmf_hooks);
3450         ao2_callback(from->other_hooks, 0, merge_container_cb, into->other_hooks);
3451
3452         /* Merge hook heaps */
3453         ast_heap_wrlock(from->interval_hooks);
3454         for (idx = 1; (hook = ast_heap_peek(from->interval_hooks, idx)); idx++) {
3455                 wrap_hook(into, hook);
3456         }
3457         ast_heap_unlock(from->interval_hooks);
3458
3459         /* Merge feature flags */
3460         into->feature_flags.flags |= from->feature_flags.flags;
3461         into->usable |= from->usable;
3462
3463         into->mute |= from->mute;
3464         into->dtmf_passthrough |= from->dtmf_passthrough;
3465 }
3466
3467 /* XXX ASTERISK-21271 make ast_bridge_features_init() static when make ast_bridge_join() requires features to be allocated. */
3468 int ast_bridge_features_init(struct ast_bridge_features *features)
3469 {
3470         /* Zero out the structure */
3471         memset(features, 0, sizeof(*features));
3472
3473         /* Initialize the DTMF hooks container */
3474         features->dtmf_hooks = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX,
3475                 AO2_CONTAINER_ALLOC_OPT_DUPS_REPLACE, bridge_dtmf_hook_sort, NULL);
3476         if (!features->dtmf_hooks) {
3477                 return -1;
3478         }
3479
3480         /* Initialize the miscellaneous other hooks container */
3481         features->other_hooks = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL,
3482                 NULL);
3483         if (!features->other_hooks) {
3484                 return -1;
3485         }
3486
3487         /* Initialize the interval hooks heap */
3488         features->interval_hooks = ast_heap_create(8, interval_hook_time_cmp,
3489                 offsetof(struct ast_bridge_hook_timer, timer.heap_index));
3490         if (!features->interval_hooks) {
3491                 return -1;
3492         }
3493
3494         features->dtmf_passthrough = 1;
3495
3496         return 0;
3497 }
3498
3499 /* XXX ASTERISK-21271 make ast_bridge_features_cleanup() static when make ast_bridge_join() requires features to be allocated. */
3500 void ast_bridge_features_cleanup(struct ast_bridge_features *features)
3501 {
3502         struct ast_bridge_hook_timer *hook;
3503
3504         /* Destroy the interval hooks heap. */
3505         if (features->interval_hooks) {
3506                 while ((hook = ast_heap_pop(features->interval_hooks))) {
3507                         ao2_ref(hook, -1);
3508                 }
3509                 features->interval_hooks = ast_heap_destroy(features->interval_hooks);
3510         }
3511
3512         /* Destroy the miscellaneous other hooks container. */
3513         ao2_cleanup(features->other_hooks);
3514         features->other_hooks = NULL;
3515
3516         /* Destroy the DTMF hooks container. */
3517         ao2_cleanup(features->dtmf_hooks);
3518         features->dtmf_hooks = NULL;
3519 }
3520
3521 void ast_bridge_features_destroy(struct ast_bridge_features *features)
3522 {
3523         if (!features) {
3524                 return;
3525         }
3526         ast_bridge_features_cleanup(features);
3527         ast_free(features);
3528 }
3529
3530 struct ast_bridge_features *ast_bridge_features_new(void)
3531 {
3532         struct ast_bridge_features *features;
3533
3534         features = ast_malloc(sizeof(*features));
3535         if (features) {
3536                 if (ast_bridge_features_init(features)) {
3537                         ast_bridge_features_destroy(features);
3538                         features = NULL;
3539                 }
3540         }
3541
3542         return features;
3543 }
3544
3545 void ast_bridge_set_mixing_interval(struct ast_bridge *bridge, unsigned int mixing_interval)
3546 {
3547         ast_bridge_lock(bridge);
3548         bridge->softmix.internal_mixing_interval = mixing_interval;
3549         ast_bridge_unlock(bridge);
3550 }
3551
3552 void ast_bridge_set_internal_sample_rate(struct ast_bridge *bridge, unsigned int sample_rate)
3553 {
3554         ast_bridge_lock(bridge);
3555         bridge->softmix.internal_sample_rate = sample_rate;
3556         ast_bridge_unlock(bridge);
3557 }
3558
3559 static void cleanup_video_mode(struct ast_bridge *bridge)
3560 {
3561         switch (bridge->softmix.video_mode.mode) {
3562         case AST_BRIDGE_VIDEO_MODE_NONE:
3563                 break;
3564         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
3565                 if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc) {
3566                         ast_channel_unref(bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc);
3567                 }
3568                 break;
3569         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
3570                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc) {
3571                         ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc);
3572                 }
3573                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc) {
3574                         ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc);
3575                 }
3576         }
3577         memset(&bridge->softmix.video_mode, 0, sizeof(bridge->softmix.video_mode));
3578 }
3579
3580 void ast_bridge_set_single_src_video_mode(struct ast_bridge *bridge, struct ast_channel *video_src_chan)
3581 {
3582         ast_bridge_lock(bridge);
3583         cleanup_video_mode(bridge);
3584         bridge->softmix.video_mode.mode = AST_BRIDGE_VIDEO_MODE_SINGLE_SRC;
3585         bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc = ast_channel_ref(video_src_chan);
3586         ast_test_suite_event_notify("BRIDGE_VIDEO_MODE", "Message: video mode set to single source\r\nVideo Mode: %u\r\nVideo Channel: %s",
3587                 bridge->softmix.video_mode.mode, ast_channel_name(video_src_chan));
3588         ast_indicate(video_src_chan, AST_CONTROL_VIDUPDATE);
3589         ast_bridge_unlock(bridge);
3590 }
3591
3592 void ast_bridge_set_talker_src_video_mode(struct ast_bridge *bridge)
3593 {
3594         ast_bridge_lock(bridge);
3595         cleanup_video_mode(bridge);
3596         bridge->softmix.video_mode.mode = AST_BRIDGE_VIDEO_MODE_TALKER_SRC;
3597         ast_test_suite_event_notify("BRIDGE_VIDEO_MODE", "Message: video mode set to talker source\r\nVideo Mode: %u",
3598                 bridge->softmix.video_mode.mode);
3599         ast_bridge_unlock(bridge);
3600 }
3601
3602 void ast_bridge_update_talker_src_video_mode(struct ast_bridge *bridge, struct ast_channel *chan, int talker_energy, int is_keyframe)
3603 {
3604         struct ast_bridge_video_talker_src_data *data;
3605
3606         /* If the channel doesn't support video, we don't care about it */
3607         if (!ast_format_cap_has_type(ast_channel_nativeformats(chan), AST_MEDIA_TYPE_VIDEO)) {
3608                 return;
3609         }
3610
3611         ast_bridge_lock(bridge);
3612         data = &bridge->softmix.video_mode.mode_data.talker_src_data;
3613
3614         if (data->chan_vsrc == chan) {
3615                 data->average_talking_energy = talker_energy;
3616         } else if ((data->average_talking_energy < talker_energy) && is_keyframe) {
3617                 if (data->chan_old_vsrc) {
3618                         ast_channel_unref(data->chan_old_vsrc);
3619                 }
3620                 if (data->chan_vsrc) {
3621                         data->chan_old_vsrc = data->chan_vsrc;
3622                         ast_indicate(data->chan_old_vsrc, AST_CONTROL_VIDUPDATE);
3623                 }
3624                 data->chan_vsrc = ast_channel_ref(chan);
3625                 data->average_talking_energy = talker_energy;
3626                 ast_test_suite_event_notify("BRIDGE_VIDEO_SRC", "Message: video source updated\r\nVideo Channel: %s", ast_channel_name(data->chan_vsrc));
3627                 ast_indicate(data->chan_vsrc, AST_CONTROL_VIDUPDATE);
3628         } else if ((data->average_talking_energy < talker_energy) && !is_keyframe) {
3629                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
3630         } else if (!data->chan_vsrc && is_keyframe) {
3631                 data->chan_vsrc = ast_channel_ref(chan);
3632                 data->average_talking_energy = talker_energy;
3633                 ast_test_suite_event_notify("BRIDGE_VIDEO_SRC", "Message: video source updated\r\nVideo Channel: %s", ast_channel_name(data->chan_vsrc));
3634                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
3635         } else if (!data->chan_old_vsrc && is_keyframe) {
3636                 data->chan_old_vsrc = ast_channel_ref(chan);
3637                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
3638         }
3639         ast_bridge_unlock(bridge);
3640 }
3641
3642 int ast_bridge_number_video_src(struct ast_bridge *bridge)
3643 {
3644         int res = 0;
3645
3646         ast_bridge_lock(bridge);
3647         switch (bridge->softmix.video_mode.mode) {
3648         case AST_BRIDGE_VIDEO_MODE_NONE:
3649                 break;
3650         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
3651                 if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc) {
3652                         res = 1;
3653                 }
3654                 break;
3655         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
3656                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc) {
3657                         res++;
3658                 }
3659                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc) {
3660                         res++;
3661                 }
3662         }
3663         ast_bridge_unlock(bridge);
3664         return res;
3665 }
3666
3667 int ast_bridge_is_video_src(struct ast_bridge *bridge, struct ast_channel *chan)
3668 {
3669         int res = 0;
3670
3671         ast_bridge_lock(bridge);
3672         switch (bridge->softmix.video_mode.mode) {
3673         case AST_BRIDGE_VIDEO_MODE_NONE:
3674                 break;
3675         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
3676                 if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc == chan) {
3677                         res = 1;
3678                 }
3679                 break;
3680         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
3681                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc == chan) {
3682                         res = 1;
3683                 } else if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc == chan) {
3684                         res = 2;
3685                 }
3686
3687         }
3688         ast_bridge_unlock(bridge);
3689         return res;
3690 }
3691
3692 void ast_bridge_remove_video_src(struct ast_bridge *bridge, struct ast_channel *chan)
3693 {
3694         ast_bridge_lock(bridge);
3695         switch (bridge->softmix.video_mode.mode) {
3696         case AST_BRIDGE_VIDEO_MODE_NONE:
3697                 break;
3698         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
3699                 if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc == chan) {
3700                         if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc) {
3701                                 ast_channel_unref(bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc);
3702                         }
3703                         bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc = NULL;
3704                 }
3705                 break;
3706         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
3707                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc == chan) {
3708                         if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc) {
3709                                 ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc);
3710                         }
3711                         bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc = NULL;
3712                         bridge->softmix.video_mode.mode_data.talker_src_data.average_talking_energy = 0;
3713                 }
3714                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc == chan) {
3715                         if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc) {
3716                                 ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc);
3717                         }
3718                         bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc = NULL;
3719                 }
3720         }
3721         ast_bridge_unlock(bridge);
3722 }
3723
3724 static int channel_hash(const void *obj, int flags)
3725 {
3726         const struct ast_channel *chan = obj;
3727         const char *name = obj;
3728         int hash;
3729
3730         switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
3731         default:
3732         case OBJ_POINTER:
3733                 name = ast_channel_name(chan);
3734                 /* Fall through */
3735         case OBJ_KEY:
3736                 hash = ast_str_hash(name);
3737                 break;
3738         case OBJ_PARTIAL_KEY:
3739                 /* Should never happen in hash callback. */
3740                 ast_assert(0);
3741                 hash = 0;
3742                 break;
3743         }
3744         return hash;
3745 }
3746
3747 static int channel_cmp(void *obj, void *arg, int flags)
3748 {
3749         const struct ast_channel *left = obj;
3750         const struct ast_channel *right = arg;
3751         const char *right_name = arg;
3752         int cmp;
3753
3754         switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
3755         default:
3756         case OBJ_POINTER:
3757                 right_name = ast_channel_name(right);
3758                 /* Fall through */
3759         case OBJ_KEY:
3760                 cmp = strcmp(ast_channel_name(left), right_name);
3761                 break;
3762         case OBJ_PARTIAL_KEY:
3763                 cmp = strncmp(ast_channel_name(left), right_name, strlen(right_name));
3764                 break;
3765         }
3766         return cmp ? 0 : CMP_MATCH;
3767 }
3768
3769 struct ao2_container *ast_bridge_peers_nolock(struct ast_bridge *bridge)
3770 {
3771         struct ao2_container *channels;
3772         struct ast_bridge_channel *iter;
3773
3774         channels = ao2_container_alloc_options(AO2_ALLOC_OPT_LOCK_NOLOCK,
3775                 13, channel_hash, channel_cmp);
3776         if (!channels) {
3777                 return NULL;
3778         }
3779
3780         AST_LIST_TRAVERSE(&bridge->channels, iter, entry) {
3781                 ao2_link(channels, iter->chan);
3782         }
3783
3784         return channels;
3785 }
3786
3787 struct ao2_container *ast_bridge_peers(struct ast_bridge *bridge)
3788 {
3789         struct ao2_container *channels;
3790
3791         ast_bridge_lock(bridge);
3792         channels = ast_bridge_peers_nolock(bridge);
3793         ast_bridge_unlock(bridge);
3794
3795         return channels;
3796 }
3797
3798 struct ast_channel *ast_bridge_peer_nolock(struct ast_bridge *bridge, struct ast_channel *chan)
3799 {
3800         struct ast_channel *peer = NULL;
3801         struct ast_bridge_channel *iter;
3802
3803         /* Asking for the peer channel only makes sense on a two-party bridge. */
3804         if (bridge->num_channels == 2
3805                 && bridge->technology->capabilities
3806                         & (AST_BRIDGE_CAPABILITY_NATIVE | AST_BRIDGE_CAPABILITY_1TO1MIX)) {
3807                 int in_bridge = 0;
3808
3809                 AST_LIST_TRAVERSE(&bridge->channels, iter, entry) {
3810                         if (iter->chan != chan) {
3811                                 peer = iter->chan;
3812                         } else {
3813                                 in_bridge = 1;
3814                         }
3815                 }
3816                 if (in_bridge && peer) {
3817                         ast_channel_ref(peer);
3818                 } else {
3819                         peer = NULL;
3820                 }
3821         }
3822
3823         return peer;
3824 }
3825
3826 struct ast_channel *ast_bridge_peer(struct ast_bridge *bridge, struct ast_channel *chan)
3827 {
3828         struct ast_channel *peer;
3829
3830         ast_bridge_lock(bridge);
3831         peer = ast_bridge_peer_nolock(bridge, chan);
3832         ast_bridge_unlock(bridge);
3833
3834         return peer;
3835 }
3836
3837 static void publish_blind_transfer_full(int is_external, enum ast_transfer_result result,
3838                 struct ast_channel *transferer, struct ast_bridge *bridge,
3839                 const char *context, const char *exten, struct ast_channel *transferee_channel,
3840                 struct ast_channel *replace_channel)
3841 {
3842         struct ast_bridge_channel_pair pair;
3843
3844         pair.channel = transferer;
3845         pair.bridge = bridge;
3846
3847         if (bridge) {
3848                 ast_bridge_lock(bridge);
3849         }
3850         ast_bridge_publish_blind_transfer(is_external, result, &pair, context, exten,
3851                 transferee_channel, replace_channel);
3852         if (bridge) {
3853                 ast_bridge_unlock(bridge);
3854         }
3855 }
3856
3857 /*!
3858  * \internal
3859  * \brief Transfer an entire bridge to a specific destination.
3860  *
3861  * This creates a local channel to dial out and swaps the called local channel
3862  * with the transferer channel. By doing so, all participants in the bridge are
3863  * connected to the specified destination.
3864  *
3865  * While this means of transferring would work for both two-party and multi-party
3866  * bridges, this method is only used for multi-party bridges since this method would
3867  * be less efficient for two-party bridges.
3868  *
3869  * \param is_external Whether the transfer is externally initiated
3870  * \param transferer The channel performing a transfer
3871  * \param bridge The bridge where the transfer is being performed
3872  * \param exten The destination extension for the blind transfer
3873  * \param transferee The party being transferred if there is only one
3874  * \param context The destination context for the blind transfer
3875  * \param hook Framehook to attach to local channel
3876  *
3877  * \return The success or failure of the operation
3878  */
3879 static enum ast_transfer_result blind_transfer_bridge(int is_external,
3880                 struct ast_channel *transferer, struct ast_bridge *bridge,
3881                 const char *exten, const char *context, struct ast_channel *transferee,
3882                 transfer_channel_cb new_channel_cb,
3883                 struct transfer_channel_data *user_data_wrapper)
3884 {
3885         struct ast_channel *local;
3886         char chan_name[AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2];
3887         int cause;
3888
3889         snprintf(chan_name, sizeof(chan_name), "%s@%s", exten, context);
3890         local = ast_request("Local", ast_channel_nativeformats(transferer), NULL, transferer,
3891                         chan_name, &cause);
3892         if (!local) {
3893                 return AST_BRIDGE_TRANSFER_FAIL;
3894         }
3895
3896         ast_channel_lock_both(local, transferer);
3897         ast_channel_req_accountcodes(local, transferer, AST_CHANNEL_REQUESTOR_REPLACEMENT);
3898         pbx_builtin_setvar_helper(local, BLINDTRANSFER, ast_channel_name(transferer));
3899         ast_channel_unlock(local);
3900         ast_channel_unlock(transferer);
3901
3902         if (new_channel_cb) {
3903                 new_channel_cb(local, user_data_wrapper, AST_BRIDGE_TRANSFER_MULTI_PARTY);
3904         }
3905
3906         if (ast_call(local, chan_name, 0)) {
3907                 ast_hangup(local);
3908                 return AST_BRIDGE_TRANSFER_FAIL;
3909         }
3910         if (ast_bridge_impart(bridge, local, transferer, NULL,
3911                 AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
3912                 ast_hangup(local);
3913                 return AST_BRIDGE_TRANSFER_FAIL;
3914         }
3915         publish_blind_transfer_full(is_external, AST_BRIDGE_TRANSFER_SUCCESS, transferer, bridge,
3916                 context, exten, transferee, local);
3917         return AST_BRIDGE_TRANSFER_SUCCESS;
3918 }
3919
3920 /*!
3921  * \internal
3922  * \brief Base data to publish for stasis attended transfer messages
3923  */
3924 struct stasis_attended_transfer_publish_data {
3925         /* The bridge between the transferer and transferee, and the transferer channel in this bridge */
3926         struct ast_bridge_channel_pair to_transferee;
3927         /* The bridge between the transferer and transfer target, and the transferer channel in this bridge */
3928         struct ast_bridge_channel_pair to_transfer_target;
3929         /* The Local;1 that will replace the transferee bridge transferer channel */
3930         struct ast_channel *replace_channel;
3931         /* The transferee channel. NULL if there is no transferee channel or if multiple parties are transferred */
3932         struct ast_channel *transferee_channel;
3933         /* The transfer target channel. NULL if there is no transfer target channel or if multiple parties are transferred */
3934         struct ast_channel *target_channel;
3935 };
3936
3937 /*!
3938  * \internal
3939  * \brief Get the transferee channel
3940  *
3941  * This is only applicable to cases where a transfer is occurring on a
3942  * two-party bridge. The channels container passed in is expected to only
3943  * contain two channels, the transferer and the transferee. The transferer
3944  * channel is passed in as a parameter to ensure we don't return it as
3945  * the transferee channel.
3946  *
3947  * \param channels A two-channel container containing the transferer and transferee
3948  * \param transferer The party that is transfering the call
3949  * \return The party that is being transferred
3950  */
3951 static struct ast_channel *get_transferee(struct ao2_container *channels, struct ast_channel *transferer)
3952 {
3953         struct ao2_iterator channel_iter;
3954         struct ast_channel *transferee;
3955
3956         for (channel_iter = ao2_iterator_init(channels, 0);
3957                         (transferee = ao2_iterator_next(&channel_iter));
3958                         ao2_cleanup(transferee)) {
3959