Merge "res_calendar: Specialized calendars depend on symbols of general calendar."
[asterisk/asterisk.git] / main / bridge_channel.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 Channel API
22  *
23  * \author Joshua Colp <jcolp@digium.com>
24  * \author Richard Mudgett <rmudgett@digium.com>
25  * \author Matt Jordan <mjordan@digium.com>
26  *
27  */
28
29 /*** MODULEINFO
30         <support_level>core</support_level>
31  ***/
32
33 #include "asterisk.h"
34
35 #include <signal.h>
36
37 #include "asterisk/heap.h"
38 #include "asterisk/alertpipe.h"
39 #include "asterisk/astobj2.h"
40 #include "asterisk/stringfields.h"
41 #include "asterisk/app.h"
42 #include "asterisk/pbx.h"
43 #include "asterisk/channel.h"
44 #include "asterisk/timing.h"
45 #include "asterisk/bridge.h"
46 #include "asterisk/bridge_channel.h"
47 #include "asterisk/bridge_after.h"
48 #include "asterisk/bridge_channel_internal.h"
49 #include "asterisk/bridge_internal.h"
50 #include "asterisk/stasis_bridges.h"
51 #include "asterisk/stasis_channels.h"
52 #include "asterisk/musiconhold.h"
53 #include "asterisk/features_config.h"
54 #include "asterisk/parking.h"
55 #include "asterisk/causes.h"
56 #include "asterisk/test.h"
57 #include "asterisk/sem.h"
58 #include "asterisk/stream.h"
59
60 /*!
61  * \brief Used to queue an action frame onto a bridge channel and write an action frame into a bridge.
62  * \since 12.0.0
63  *
64  * \param bridge_channel Which channel work with.
65  * \param action Type of bridge action frame.
66  * \param data Frame payload data to pass.
67  * \param datalen Frame payload data length to pass.
68  *
69  * \retval 0 on success.
70  * \retval -1 on error.
71  */
72 typedef int (*ast_bridge_channel_post_action_data)(struct ast_bridge_channel *bridge_channel, enum bridge_channel_action_type action, const void *data, size_t datalen);
73
74 /*!
75  * \brief Counter used for assigning synchronous bridge action IDs
76  */
77 static int sync_ids;
78
79 /*!
80  * \brief Frame payload for synchronous bridge actions.
81  *
82  * The payload serves as a wrapper around the actual payload of the
83  * frame, with the addition of an id used to find the associated
84  * bridge_sync object.
85  */
86 struct sync_payload {
87         /*! Unique ID for this synchronous action */
88         unsigned int id;
89         /*! Actual frame data to process */
90         unsigned char data[0];
91 };
92
93 /*!
94  * \brief Synchronous bridge action object.
95  *
96  * Synchronous bridge actions require the ability for one thread to wait
97  * and for another thread to indicate that the action has completed. This
98  * structure facilitates that goal by providing synchronization structures.
99  */
100 struct bridge_sync {
101         /*! Unique ID of this synchronization object. Corresponds with ID in synchronous frame payload */
102         unsigned int id;
103         /*! Semaphore used for synchronization */
104         struct ast_sem sem;
105         /*! Pointer to next entry in the list */
106         AST_LIST_ENTRY(bridge_sync) list;
107 };
108
109 /*!
110  * \brief List holding active synchronous action objects.
111  */
112 static AST_RWLIST_HEAD_STATIC(sync_structs, bridge_sync);
113
114 /*!
115  * \brief initialize a synchronous bridge object.
116  *
117  * This both initializes the structure and adds it to the list of
118  * synchronization structures.
119  *
120  * \param sync_struct The synchronization object to initialize.
121  * \param id ID to assign to the synchronization object.
122  */
123 static void bridge_sync_init(struct bridge_sync *sync_struct, unsigned int id)
124 {
125         memset(sync_struct, 0, sizeof(*sync_struct));
126         sync_struct->id = id;
127         ast_sem_init(&sync_struct->sem, 0, 0);
128
129         AST_RWLIST_WRLOCK(&sync_structs);
130         AST_RWLIST_INSERT_TAIL(&sync_structs, sync_struct, list);
131         AST_RWLIST_UNLOCK(&sync_structs);
132 }
133
134 /*!
135  * \brief Clean up a syncrhonization bridge object.
136  *
137  * This frees fields within the synchronization object and removes
138  * it from the list of active synchronization objects.
139  *
140  * Since synchronization objects are stack-allocated, it is vital
141  * that this is called before the synchronization object goes
142  * out of scope.
143  *
144  * \param sync_struct Synchronization object to clean up.
145  */
146 static void bridge_sync_cleanup(struct bridge_sync *sync_struct)
147 {
148         struct bridge_sync *iter;
149
150         AST_RWLIST_WRLOCK(&sync_structs);
151         AST_LIST_TRAVERSE_SAFE_BEGIN(&sync_structs, iter, list) {
152                 if (iter->id == sync_struct->id) {
153                         AST_LIST_REMOVE_CURRENT(list);
154                         break;
155                 }
156         }
157         AST_LIST_TRAVERSE_SAFE_END;
158         AST_RWLIST_UNLOCK(&sync_structs);
159
160         ast_sem_destroy(&sync_struct->sem);
161 }
162
163 /*!
164  * \brief Failsafe for synchronous bridge action waiting.
165  *
166  * When waiting for a synchronous bridge action to complete,
167  * if there is a frame resource leak somewhere, it is possible
168  * that we will never get notified that the synchronous action
169  * completed.
170  *
171  * If a significant amount of time passes, then we will abandon
172  * waiting for the synchrnous bridge action to complete.
173  *
174  * This constant represents the number of milliseconds we will
175  * wait for the bridge action to complete.
176  */
177 #define PLAYBACK_TIMEOUT (600 * 1000)
178
179 /*!
180  * \brief Wait for a synchronous bridge action to complete.
181  *
182  * \param sync_struct Synchronization object corresponding to the bridge action.
183  */
184 static void bridge_sync_wait(struct bridge_sync *sync_struct)
185 {
186         struct timeval timeout_val = ast_tvadd(ast_tvnow(), ast_samp2tv(PLAYBACK_TIMEOUT, 1000));
187         struct timespec timeout_spec = {
188                 .tv_sec = timeout_val.tv_sec,
189                 .tv_nsec = timeout_val.tv_usec * 1000,
190         };
191
192         ast_sem_timedwait(&sync_struct->sem, &timeout_spec);
193 }
194
195 /*!
196  * \brief Signal that waiting for a synchronous bridge action is no longer necessary.
197  *
198  * This may occur for several reasons
199  * \li The synchronous bridge action has completed.
200  * \li The bridge channel has been removed from the bridge.
201  * \li The synchronous bridge action could not be queued.
202  *
203  * \param sync_struct Synchronization object corresponding to the bridge action.
204  */
205 static void bridge_sync_signal(struct bridge_sync *sync_struct)
206 {
207         ast_sem_post(&sync_struct->sem);
208 }
209
210 void ast_bridge_channel_lock_bridge(struct ast_bridge_channel *bridge_channel)
211 {
212         struct ast_bridge *bridge;
213
214         for (;;) {
215                 /* Safely get the bridge pointer */
216                 ast_bridge_channel_lock(bridge_channel);
217                 bridge = bridge_channel->bridge;
218                 ao2_ref(bridge, +1);
219                 ast_bridge_channel_unlock(bridge_channel);
220
221                 /* Lock the bridge and see if it is still the bridge we need to lock. */
222                 ast_bridge_lock(bridge);
223                 if (bridge == bridge_channel->bridge) {
224                         ao2_ref(bridge, -1);
225                         return;
226                 }
227                 ast_bridge_unlock(bridge);
228                 ao2_ref(bridge, -1);
229         }
230 }
231
232 int ast_bridge_channel_notify_talking(struct ast_bridge_channel *bridge_channel, int started_talking)
233 {
234         struct ast_frame action = {
235                 .frametype = AST_FRAME_BRIDGE_ACTION,
236                 .subclass.integer = started_talking
237                         ? BRIDGE_CHANNEL_ACTION_TALKING_START : BRIDGE_CHANNEL_ACTION_TALKING_STOP,
238         };
239
240         return ast_bridge_channel_queue_frame(bridge_channel, &action);
241 }
242
243 /*!
244  * \internal
245  * \brief Poke the bridge_channel thread
246  */
247 static void bridge_channel_poke(struct ast_bridge_channel *bridge_channel)
248 {
249         if (!pthread_equal(pthread_self(), bridge_channel->thread)) {
250                 /* Wake up the bridge channel thread. */
251                 ast_queue_frame(bridge_channel->chan, &ast_null_frame);
252         }
253 }
254
255 /*!
256  * \internal
257  * \brief Set actual cause on channel.
258  * \since 12.0.0
259  *
260  * \param chan Channel to set cause.
261  * \param cause Cause to set on channel.
262  *   If cause <= 0 then use cause on channel if cause still <= 0 use AST_CAUSE_NORMAL_CLEARING.
263  *
264  * \return Actual cause set on channel.
265  */
266 static int channel_set_cause(struct ast_channel *chan, int cause)
267 {
268         ast_channel_lock(chan);
269         if (cause <= 0) {
270                 cause = ast_channel_hangupcause(chan);
271                 if (cause <= 0) {
272                         cause = AST_CAUSE_NORMAL_CLEARING;
273                 }
274         }
275         ast_channel_hangupcause_set(chan, cause);
276         ast_channel_unlock(chan);
277         return cause;
278 }
279
280 void ast_bridge_channel_leave_bridge_nolock(struct ast_bridge_channel *bridge_channel, enum bridge_channel_state new_state, int cause)
281 {
282         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
283                 return;
284         }
285
286         ast_debug(1, "Setting %p(%s) state from:%u to:%u\n",
287                 bridge_channel, ast_channel_name(bridge_channel->chan), bridge_channel->state,
288                 new_state);
289
290         channel_set_cause(bridge_channel->chan, cause);
291
292         ast_channel_lock(bridge_channel->chan);
293         ast_bridge_vars_set(bridge_channel->chan, NULL, NULL);
294         ast_channel_unlock(bridge_channel->chan);
295
296         /* Change the state on the bridge channel */
297         bridge_channel->state = new_state;
298
299         bridge_channel_poke(bridge_channel);
300 }
301
302 void ast_bridge_channel_leave_bridge(struct ast_bridge_channel *bridge_channel, enum bridge_channel_state new_state, int cause)
303 {
304         ast_bridge_channel_lock(bridge_channel);
305         ast_bridge_channel_leave_bridge_nolock(bridge_channel, new_state, cause);
306         ast_bridge_channel_unlock(bridge_channel);
307 }
308
309 struct ast_bridge_channel *ast_bridge_channel_peer(struct ast_bridge_channel *bridge_channel)
310 {
311         struct ast_bridge *bridge = bridge_channel->bridge;
312         struct ast_bridge_channel *other = NULL;
313
314         if (bridge_channel->in_bridge && bridge->num_channels == 2) {
315                 AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
316                         if (other != bridge_channel) {
317                                 break;
318                         }
319                 }
320         }
321
322         return other;
323 }
324
325 void ast_bridge_channel_restore_formats(struct ast_bridge_channel *bridge_channel)
326 {
327         ast_assert(bridge_channel->read_format != NULL);
328         ast_assert(bridge_channel->write_format != NULL);
329
330         ast_channel_lock(bridge_channel->chan);
331
332         /* Restore original formats of the channel as they came in */
333         if (ast_format_cmp(ast_channel_readformat(bridge_channel->chan), bridge_channel->read_format) == AST_FORMAT_CMP_NOT_EQUAL) {
334                 ast_debug(1, "Bridge is returning %p(%s) to read format %s\n",
335                         bridge_channel, ast_channel_name(bridge_channel->chan),
336                         ast_format_get_name(bridge_channel->read_format));
337                 if (ast_set_read_format(bridge_channel->chan, bridge_channel->read_format)) {
338                         ast_debug(1, "Bridge failed to return %p(%s) to read format %s\n",
339                                 bridge_channel, ast_channel_name(bridge_channel->chan),
340                                 ast_format_get_name(bridge_channel->read_format));
341                 }
342         }
343         if (ast_format_cmp(ast_channel_writeformat(bridge_channel->chan), bridge_channel->write_format) == AST_FORMAT_CMP_NOT_EQUAL) {
344                 ast_debug(1, "Bridge is returning %p(%s) to write format %s\n",
345                         bridge_channel, ast_channel_name(bridge_channel->chan),
346                         ast_format_get_name(bridge_channel->write_format));
347                 if (ast_set_write_format(bridge_channel->chan, bridge_channel->write_format)) {
348                         ast_debug(1, "Bridge failed to return %p(%s) to write format %s\n",
349                                 bridge_channel, ast_channel_name(bridge_channel->chan),
350                                 ast_format_get_name(bridge_channel->write_format));
351                 }
352         }
353
354         ast_channel_unlock(bridge_channel->chan);
355 }
356
357 struct ast_bridge *ast_bridge_channel_merge_inhibit(struct ast_bridge_channel *bridge_channel, int request)
358 {
359         struct ast_bridge *bridge;
360
361         ast_bridge_channel_lock_bridge(bridge_channel);
362         bridge = bridge_channel->bridge;
363         ao2_ref(bridge, +1);
364         bridge_merge_inhibit_nolock(bridge, request);
365         ast_bridge_unlock(bridge);
366         return bridge;
367 }
368
369 void ast_bridge_channel_update_linkedids(struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
370 {
371         struct ast_bridge_channel *other;
372         struct ast_bridge *bridge = bridge_channel->bridge;
373         struct ast_channel *oldest_linkedid_chan = bridge_channel->chan;
374
375         AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
376                 if (other == swap) {
377                         continue;
378                 }
379                 oldest_linkedid_chan = ast_channel_internal_oldest_linkedid(
380                         oldest_linkedid_chan, other->chan);
381         }
382
383         ast_channel_lock(bridge_channel->chan);
384         ast_channel_internal_copy_linkedid(bridge_channel->chan, oldest_linkedid_chan);
385         ast_channel_unlock(bridge_channel->chan);
386         AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
387                 if (other == swap) {
388                         continue;
389                 }
390                 ast_channel_lock(other->chan);
391                 ast_channel_internal_copy_linkedid(other->chan, oldest_linkedid_chan);
392                 ast_channel_unlock(other->chan);
393         }
394 }
395
396 /*!
397  * \internal
398  * \brief Set dest's empty peeraccount with the src's non-empty accountcode.
399  * \since 12.5.0
400  *
401  * \param dest Channel to update peeraccount.
402  * \param src Channel to get accountcode from.
403  *
404  * \note Both channels are already locked.
405  *
406  * \return Nothing
407  */
408 static void channel_fill_empty_peeraccount(struct ast_channel *dest, struct ast_channel *src)
409 {
410         if (ast_strlen_zero(ast_channel_peeraccount(dest))
411                 && !ast_strlen_zero(ast_channel_accountcode(src))) {
412                 ast_debug(1, "Setting channel %s peeraccount with channel %s accountcode '%s'.\n",
413                         ast_channel_name(dest),
414                         ast_channel_name(src), ast_channel_accountcode(src));
415                 ast_channel_peeraccount_set(dest, ast_channel_accountcode(src));
416         }
417 }
418
419 /*!
420  * \internal
421  * \brief Set dest's empty accountcode with the src's non-empty peeraccount.
422  * \since 12.5.0
423  *
424  * \param dest Channel to update accountcode.
425  * \param src Channel to get peeraccount from.
426  *
427  * \note Both channels are already locked.
428  *
429  * \return Nothing
430  */
431 static void channel_fill_empty_accountcode(struct ast_channel *dest, struct ast_channel *src)
432 {
433         if (ast_strlen_zero(ast_channel_accountcode(dest))
434                 && !ast_strlen_zero(ast_channel_peeraccount(src))) {
435                 ast_debug(1, "Setting channel %s accountcode with channel %s peeraccount '%s'.\n",
436                         ast_channel_name(dest),
437                         ast_channel_name(src), ast_channel_peeraccount(src));
438                 ast_channel_accountcode_set(dest, ast_channel_peeraccount(src));
439         }
440 }
441
442 /*!
443  * \internal
444  * \brief Set empty peeraccount and accountcode in a channel from the other channel.
445  * \since 12.5.0
446  *
447  * \param c0 First bridge channel to update.
448  * \param c1 Second bridge channel to update.
449  *
450  * \note Both channels are already locked.
451  *
452  * \return Nothing
453  */
454 static void channel_set_empty_accountcodes(struct ast_channel *c0, struct ast_channel *c1)
455 {
456         /* Set empty peeraccount from the other channel's accountcode. */
457         channel_fill_empty_peeraccount(c0, c1);
458         channel_fill_empty_peeraccount(c1, c0);
459
460         /* Set empty accountcode from the other channel's peeraccount. */
461         channel_fill_empty_accountcode(c0, c1);
462         channel_fill_empty_accountcode(c1, c0);
463 }
464
465 /*!
466  * \internal
467  * \brief Update dest's peeraccount with the src's different accountcode.
468  * \since 12.5.0
469  *
470  * \param dest Channel to update peeraccount.
471  * \param src Channel to get accountcode from.
472  *
473  * \note Both channels are already locked.
474  *
475  * \return Nothing
476  */
477 static void channel_update_peeraccount(struct ast_channel *dest, struct ast_channel *src)
478 {
479         if (strcmp(ast_channel_accountcode(src), ast_channel_peeraccount(dest))) {
480                 ast_debug(1, "Changing channel %s peeraccount '%s' to match channel %s accountcode '%s'.\n",
481                         ast_channel_name(dest), ast_channel_peeraccount(dest),
482                         ast_channel_name(src), ast_channel_accountcode(src));
483                 ast_channel_peeraccount_set(dest, ast_channel_accountcode(src));
484         }
485 }
486
487 /*!
488  * \internal
489  * \brief Update peeraccounts to match the other channel's accountcode.
490  * \since 12.5.0
491  *
492  * \param c0 First channel to update.
493  * \param c1 Second channel to update.
494  *
495  * \note Both channels are already locked.
496  *
497  * \return Nothing
498  */
499 static void channel_update_peeraccounts(struct ast_channel *c0, struct ast_channel *c1)
500 {
501         channel_update_peeraccount(c0, c1);
502         channel_update_peeraccount(c1, c0);
503 }
504
505 /*!
506  * \internal
507  * \brief Update channel accountcodes because a channel is joining a bridge.
508  * \since 12.5.0
509  *
510  * \param joining Channel joining the bridge.
511  * \param swap Channel being replaced by the joining channel.  May be NULL.
512  *
513  * \note The bridge must be locked prior to calling this function.
514  *
515  * \return Nothing
516  */
517 static void bridge_channel_update_accountcodes_joining(struct ast_bridge_channel *joining, struct ast_bridge_channel *swap)
518 {
519         struct ast_bridge *bridge = joining->bridge;
520         struct ast_bridge_channel *other;
521         unsigned int swap_in_bridge = 0;
522         unsigned int will_be_two_party;
523
524         /*
525          * Only update the peeraccount to match if the joining channel
526          * will make it a two party bridge.
527          */
528         if (bridge->num_channels <= 2 && swap) {
529                 AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
530                         if (other == swap) {
531                                 swap_in_bridge = 1;
532                                 break;
533                         }
534                 }
535         }
536         will_be_two_party = (1 == bridge->num_channels - swap_in_bridge);
537
538         AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
539                 if (other == swap) {
540                         continue;
541                 }
542                 ast_assert(joining != other);
543                 ast_channel_lock_both(joining->chan, other->chan);
544                 channel_set_empty_accountcodes(joining->chan, other->chan);
545                 if (will_be_two_party) {
546                         channel_update_peeraccounts(joining->chan, other->chan);
547                 }
548                 ast_channel_unlock(joining->chan);
549                 ast_channel_unlock(other->chan);
550         }
551 }
552
553 /*!
554  * \internal
555  * \brief Update channel peeraccount codes because a channel has left a bridge.
556  * \since 12.5.0
557  *
558  * \param leaving Channel leaving the bridge. (Has already been removed actually)
559  *
560  * \note The bridge must be locked prior to calling this function.
561  *
562  * \return Nothing
563  */
564 static void bridge_channel_update_accountcodes_leaving(struct ast_bridge_channel *leaving)
565 {
566         struct ast_bridge *bridge = leaving->bridge;
567         struct ast_bridge_channel *first;
568         struct ast_bridge_channel *second;
569
570         if (bridge->num_channels != 2 || bridge->dissolved) {
571                 return;
572         }
573
574         first = AST_LIST_FIRST(&bridge->channels);
575         second = AST_LIST_LAST(&bridge->channels);
576         ast_assert(first && first != second);
577         ast_channel_lock_both(first->chan, second->chan);
578         channel_set_empty_accountcodes(first->chan, second->chan);
579         channel_update_peeraccounts(first->chan, second->chan);
580         ast_channel_unlock(second->chan);
581         ast_channel_unlock(first->chan);
582 }
583
584 void ast_bridge_channel_update_accountcodes(struct ast_bridge_channel *joining, struct ast_bridge_channel *leaving)
585 {
586         if (joining) {
587                 bridge_channel_update_accountcodes_joining(joining, leaving);
588         } else {
589                 bridge_channel_update_accountcodes_leaving(leaving);
590         }
591 }
592
593 void ast_bridge_channel_kick(struct ast_bridge_channel *bridge_channel, int cause)
594 {
595         struct ast_bridge_features *features = bridge_channel->features;
596         struct ast_bridge_hook *hook;
597         struct ao2_iterator iter;
598
599         ast_bridge_channel_lock(bridge_channel);
600         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
601                 channel_set_cause(bridge_channel->chan, cause);
602                 cause = 0;
603         }
604         ast_bridge_channel_unlock(bridge_channel);
605
606         /* Run any hangup hooks. */
607         iter = ao2_iterator_init(features->other_hooks, 0);
608         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
609                 int remove_me;
610
611                 if (hook->type != AST_BRIDGE_HOOK_TYPE_HANGUP) {
612                         continue;
613                 }
614                 remove_me = hook->callback(bridge_channel, hook->hook_pvt);
615                 if (remove_me) {
616                         ast_debug(1, "Hangup hook %p is being removed from %p(%s)\n",
617                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
618                         ao2_unlink(features->other_hooks, hook);
619                 }
620         }
621         ao2_iterator_destroy(&iter);
622
623         /* Default hangup action. */
624         ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END, cause);
625 }
626
627 /*!
628  * \internal
629  * \brief Write an \ref ast_frame into the bridge
630  * \since 12.0.0
631  *
632  * \param bridge_channel Which channel is queueing the frame.
633  * \param frame The frame to write into the bridge
634  *
635  * \retval 0 on success.
636  * \retval -1 on error.
637  */
638 static int bridge_channel_write_frame(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
639 {
640         const struct ast_control_t38_parameters *t38_parameters;
641         int unmapped_stream_num;
642         int deferred;
643
644         ast_assert(frame->frametype != AST_FRAME_BRIDGE_ACTION_SYNC);
645
646         ast_bridge_channel_lock_bridge(bridge_channel);
647
648         /* Map the frame to the bridge. */
649         if (ast_channel_is_multistream(bridge_channel->chan)) {
650                 unmapped_stream_num = frame->stream_num;
651                 switch (frame->frametype) {
652                 case AST_FRAME_VOICE:
653                 case AST_FRAME_VIDEO:
654                 case AST_FRAME_TEXT:
655                 case AST_FRAME_IMAGE:
656                         /* Media frames need to be mapped to an appropriate write stream */
657                         if (frame->stream_num < 0) {
658                                 /* Map to default stream */
659                                 frame->stream_num = -1;
660                                 break;
661                         }
662                         ast_bridge_channel_lock(bridge_channel);
663                         if (frame->stream_num < (int)AST_VECTOR_SIZE(&bridge_channel->stream_map.to_bridge)) {
664                                 frame->stream_num = AST_VECTOR_GET(
665                                         &bridge_channel->stream_map.to_bridge, frame->stream_num);
666                                 if (0 <= frame->stream_num) {
667                                         ast_bridge_channel_unlock(bridge_channel);
668                                         break;
669                                 }
670                         }
671                         ast_bridge_channel_unlock(bridge_channel);
672                         ast_bridge_unlock(bridge_channel->bridge);
673                         /*
674                          * Ignore frame because we don't know how to map the frame
675                          * or the bridge is not expecting any media from that
676                          * stream.
677                          */
678                         return 0;
679                 case AST_FRAME_DTMF_BEGIN:
680                 case AST_FRAME_DTMF_END:
681                         /*
682                          * XXX It makes sense that DTMF could be on any audio stream.
683                          * For now we will only put it on the default audio stream.
684                          */
685                 default:
686                         frame->stream_num = -1;
687                         break;
688                 }
689         } else {
690                 unmapped_stream_num = -1;
691                 frame->stream_num = -1;
692         }
693
694         deferred = bridge_channel->bridge->technology->write(bridge_channel->bridge, bridge_channel, frame);
695         if (deferred) {
696                 struct ast_frame *dup;
697
698                 dup = ast_frdup(frame);
699                 if (dup) {
700                         /*
701                          * We have to unmap the deferred frame so it comes back
702                          * in like a new frame.
703                          */
704                         dup->stream_num = unmapped_stream_num;
705                         ast_bridge_channel_lock(bridge_channel);
706                         AST_LIST_INSERT_HEAD(&bridge_channel->deferred_queue, dup, frame_list);
707                         ast_bridge_channel_unlock(bridge_channel);
708                 }
709         }
710
711         /* Remember any owed events to the bridge. */
712         switch (frame->frametype) {
713         case AST_FRAME_DTMF_BEGIN:
714                 bridge_channel->owed.dtmf_tv = ast_tvnow();
715                 bridge_channel->owed.dtmf_digit = frame->subclass.integer;
716                 break;
717         case AST_FRAME_DTMF_END:
718                 bridge_channel->owed.dtmf_digit = '\0';
719                 break;
720         case AST_FRAME_CONTROL:
721                 /*
722                  * We explicitly will not remember HOLD/UNHOLD frames because
723                  * things like attended transfers will handle them.
724                  */
725                 switch (frame->subclass.integer) {
726                 case AST_CONTROL_T38_PARAMETERS:
727                         t38_parameters = frame->data.ptr;
728                         switch (t38_parameters->request_response) {
729                         case AST_T38_REQUEST_NEGOTIATE:
730                         case AST_T38_NEGOTIATED:
731                                 bridge_channel->owed.t38_terminate = 1;
732                                 break;
733                         case AST_T38_REQUEST_TERMINATE:
734                         case AST_T38_TERMINATED:
735                         case AST_T38_REFUSED:
736                                 bridge_channel->owed.t38_terminate = 0;
737                                 break;
738                         default:
739                                 break;
740                         }
741                         break;
742                 default:
743                         break;
744                 }
745                 break;
746         default:
747                 break;
748         }
749         ast_bridge_unlock(bridge_channel->bridge);
750
751         /*
752          * Claim successful write to bridge.  If deferred frame
753          * support is added, claim successfully deferred.
754          */
755         return 0;
756 }
757
758 /*!
759  * \internal
760  * \brief Cancel owed events by the channel to the bridge.
761  * \since 13.8.0
762  *
763  * \param bridge_channel Channel that owes events to the bridge.
764  *
765  * \note On entry, the bridge_channel->bridge is already locked.
766  *
767  * \return Nothing
768  */
769 static void bridge_channel_cancel_owed_events(struct ast_bridge_channel *bridge_channel)
770 {
771         bridge_channel->owed.dtmf_digit = '\0';
772         bridge_channel->owed.t38_terminate = 0;
773 }
774
775 void bridge_channel_settle_owed_events(struct ast_bridge *orig_bridge, struct ast_bridge_channel *bridge_channel)
776 {
777         if (bridge_channel->owed.dtmf_digit) {
778                 struct ast_frame frame = {
779                         .frametype = AST_FRAME_DTMF_END,
780                         .subclass.integer = bridge_channel->owed.dtmf_digit,
781                         .src = "Bridge channel owed DTMF",
782                 };
783
784                 frame.len = ast_tvdiff_ms(ast_tvnow(), bridge_channel->owed.dtmf_tv);
785                 if (frame.len < option_dtmfminduration) {
786                         frame.len = option_dtmfminduration;
787                 }
788                 ast_log(LOG_DTMF, "DTMF end '%c' simulated to bridge %s because %s left.  Duration %ld ms.\n",
789                         bridge_channel->owed.dtmf_digit, orig_bridge->uniqueid,
790                         ast_channel_name(bridge_channel->chan), frame.len);
791                 bridge_channel->owed.dtmf_digit = '\0';
792                 orig_bridge->technology->write(orig_bridge, NULL, &frame);
793         }
794         if (bridge_channel->owed.t38_terminate) {
795                 struct ast_control_t38_parameters t38_parameters = {
796                         .request_response = AST_T38_TERMINATED,
797                 };
798                 struct ast_frame frame = {
799                         .frametype = AST_FRAME_CONTROL,
800                         .subclass.integer = AST_CONTROL_T38_PARAMETERS,
801                         .data.ptr = &t38_parameters,
802                         .datalen = sizeof(t38_parameters),
803                         .src = "Bridge channel owed T.38 terminate",
804                 };
805
806                 ast_debug(1, "T.38 terminate simulated to bridge %s because %s left.\n",
807                         orig_bridge->uniqueid, ast_channel_name(bridge_channel->chan));
808                 bridge_channel->owed.t38_terminate = 0;
809                 orig_bridge->technology->write(orig_bridge, NULL, &frame);
810         }
811 }
812
813 void bridge_channel_queue_deferred_frames(struct ast_bridge_channel *bridge_channel)
814 {
815         struct ast_frame *frame;
816
817         ast_bridge_channel_lock(bridge_channel);
818         ast_channel_lock(bridge_channel->chan);
819         while ((frame = AST_LIST_REMOVE_HEAD(&bridge_channel->deferred_queue, frame_list))) {
820                 ast_queue_frame_head(bridge_channel->chan, frame);
821                 ast_frfree(frame);
822         }
823         ast_channel_unlock(bridge_channel->chan);
824         ast_bridge_channel_unlock(bridge_channel);
825 }
826
827 /*!
828  * \internal
829  * \brief Suspend a channel from a bridge.
830  *
831  * \param bridge_channel Channel to suspend.
832  *
833  * \note This function assumes bridge_channel->bridge is locked.
834  *
835  * \return Nothing
836  */
837 void bridge_channel_internal_suspend_nolock(struct ast_bridge_channel *bridge_channel)
838 {
839         bridge_channel->suspended = 1;
840         if (bridge_channel->in_bridge) {
841                 --bridge_channel->bridge->num_active;
842         }
843
844         /* Get technology bridge threads off of the channel. */
845         if (bridge_channel->bridge->technology->suspend) {
846                 bridge_channel->bridge->technology->suspend(bridge_channel->bridge, bridge_channel);
847         }
848 }
849
850 /*!
851  * \internal
852  * \brief Suspend a channel from a bridge.
853  *
854  * \param bridge_channel Channel to suspend.
855  *
856  * \return Nothing
857  */
858 static void bridge_channel_suspend(struct ast_bridge_channel *bridge_channel)
859 {
860         ast_bridge_channel_lock_bridge(bridge_channel);
861         bridge_channel_internal_suspend_nolock(bridge_channel);
862         ast_bridge_unlock(bridge_channel->bridge);
863 }
864
865 /*!
866  * \internal
867  * \brief Unsuspend a channel from a bridge.
868  *
869  * \param bridge_channel Channel to unsuspend.
870  *
871  * \note This function assumes bridge_channel->bridge is locked.
872  *
873  * \return Nothing
874  */
875 void bridge_channel_internal_unsuspend_nolock(struct ast_bridge_channel *bridge_channel)
876 {
877         bridge_channel->suspended = 0;
878         if (bridge_channel->in_bridge) {
879                 ++bridge_channel->bridge->num_active;
880         }
881
882         /* Wake technology bridge threads to take care of channel again. */
883         if (bridge_channel->bridge->technology->unsuspend) {
884                 bridge_channel->bridge->technology->unsuspend(bridge_channel->bridge, bridge_channel);
885         }
886
887         /* Wake suspended channel. */
888         ast_bridge_channel_lock(bridge_channel);
889         ast_cond_signal(&bridge_channel->cond);
890         ast_bridge_channel_unlock(bridge_channel);
891 }
892
893 /*!
894  * \internal
895  * \brief Unsuspend a channel from a bridge.
896  *
897  * \param bridge_channel Channel to unsuspend.
898  *
899  * \return Nothing
900  */
901 static void bridge_channel_unsuspend(struct ast_bridge_channel *bridge_channel)
902 {
903         ast_bridge_channel_lock_bridge(bridge_channel);
904         bridge_channel_internal_unsuspend_nolock(bridge_channel);
905         ast_bridge_unlock(bridge_channel->bridge);
906 }
907
908 /*!
909  * \internal
910  * \brief Queue an action frame onto the bridge channel with data.
911  * \since 12.0.0
912  *
913  * \param bridge_channel Which channel to queue the frame onto.
914  * \param action Type of bridge action frame.
915  * \param data Frame payload data to pass.
916  * \param datalen Frame payload data length to pass.
917  *
918  * \retval 0 on success.
919  * \retval -1 on error.
920  */
921 static int bridge_channel_queue_action_data(struct ast_bridge_channel *bridge_channel,
922         enum bridge_channel_action_type action, const void *data, size_t datalen)
923 {
924         struct ast_frame frame = {
925                 .frametype = AST_FRAME_BRIDGE_ACTION,
926                 .subclass.integer = action,
927                 .datalen = datalen,
928                 .data.ptr = (void *) data,
929         };
930
931         return ast_bridge_channel_queue_frame(bridge_channel, &frame);
932 }
933
934 /*!
935  * \internal
936  * \brief Queue an action frame onto the bridge channel with data synchronously.
937  * \since 12.2.0
938  *
939  * The function will not return until the queued frame is freed.
940  *
941  * \param bridge_channel Which channel to queue the frame onto.
942  * \param action Type of bridge action frame.
943  * \param data Frame payload data to pass.
944  * \param datalen Frame payload data length to pass.
945  *
946  * \retval 0 on success.
947  * \retval -1 on error.
948  */
949 static int bridge_channel_queue_action_data_sync(struct ast_bridge_channel *bridge_channel,
950         enum bridge_channel_action_type action, const void *data, size_t datalen)
951 {
952         struct sync_payload *sync_payload;
953         int sync_payload_len = sizeof(*sync_payload) + datalen;
954         struct bridge_sync sync_struct;
955         struct ast_frame frame = {
956                 .frametype = AST_FRAME_BRIDGE_ACTION_SYNC,
957                 .subclass.integer = action,
958         };
959
960         /* Make sure we don't end up trying to wait on ourself to deliver the frame */
961         ast_assert(!pthread_equal(pthread_self(), bridge_channel->thread));
962
963         sync_payload = ast_alloca(sync_payload_len);
964         sync_payload->id = ast_atomic_fetchadd_int(&sync_ids, +1);
965         memcpy(sync_payload->data, data, datalen);
966
967         frame.datalen = sync_payload_len;
968         frame.data.ptr = sync_payload;
969
970         bridge_sync_init(&sync_struct, sync_payload->id);
971         if (ast_bridge_channel_queue_frame(bridge_channel, &frame)) {
972                 bridge_sync_cleanup(&sync_struct);
973                 return -1;
974         }
975
976         bridge_sync_wait(&sync_struct);
977         bridge_sync_cleanup(&sync_struct);
978         return 0;
979 }
980 /*!
981  * \internal
982  * \brief Write an action frame onto the bridge channel with data.
983  * \since 12.0.0
984  *
985  * \param bridge_channel Which channel to queue the frame onto.
986  * \param action Type of bridge action frame.
987  * \param data Frame payload data to pass.
988  * \param datalen Frame payload data length to pass.
989  *
990  * \retval 0 on success.
991  * \retval -1 on error.
992  */
993 static int bridge_channel_write_action_data(struct ast_bridge_channel *bridge_channel,
994         enum bridge_channel_action_type action, const void *data, size_t datalen)
995 {
996         struct ast_frame frame = {
997                 .frametype = AST_FRAME_BRIDGE_ACTION,
998                 .subclass.integer = action,
999                 .datalen = datalen,
1000                 .data.ptr = (void *) data,
1001         };
1002
1003         return bridge_channel_write_frame(bridge_channel, &frame);
1004 }
1005
1006 static void bridge_frame_free(struct ast_frame *frame)
1007 {
1008         if (frame->frametype == AST_FRAME_BRIDGE_ACTION_SYNC) {
1009                 struct sync_payload *sync_payload = frame->data.ptr;
1010                 struct bridge_sync *sync;
1011
1012                 AST_RWLIST_RDLOCK(&sync_structs);
1013                 AST_RWLIST_TRAVERSE(&sync_structs, sync, list) {
1014                         if (sync->id == sync_payload->id) {
1015                                 break;
1016                         }
1017                 }
1018                 if (sync) {
1019                         bridge_sync_signal(sync);
1020                 }
1021                 AST_RWLIST_UNLOCK(&sync_structs);
1022         }
1023
1024         ast_frfree(frame);
1025 }
1026
1027 int ast_bridge_channel_queue_frame(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
1028 {
1029         struct ast_frame *dup;
1030
1031         if (bridge_channel->suspended
1032                 /* Also defer DTMF frames. */
1033                 && fr->frametype != AST_FRAME_DTMF_BEGIN
1034                 && fr->frametype != AST_FRAME_DTMF_END
1035                 && !ast_is_deferrable_frame(fr)) {
1036                 /* Drop non-deferable frames when suspended. */
1037                 return 0;
1038         }
1039         if (fr->frametype == AST_FRAME_NULL) {
1040                 /* "Accept" the frame and discard it. */
1041                 return 0;
1042         }
1043
1044         dup = ast_frdup(fr);
1045         if (!dup) {
1046                 return -1;
1047         }
1048
1049         ast_bridge_channel_lock(bridge_channel);
1050         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
1051                 /* Drop frames on channels leaving the bridge. */
1052                 ast_bridge_channel_unlock(bridge_channel);
1053                 bridge_frame_free(dup);
1054                 return 0;
1055         }
1056
1057         AST_LIST_INSERT_TAIL(&bridge_channel->wr_queue, dup, frame_list);
1058         if (ast_alertpipe_write(bridge_channel->alert_pipe)) {
1059                 ast_log(LOG_ERROR, "We couldn't write alert pipe for %p(%s)... something is VERY wrong\n",
1060                         bridge_channel, ast_channel_name(bridge_channel->chan));
1061         }
1062         ast_bridge_channel_unlock(bridge_channel);
1063         return 0;
1064 }
1065
1066 int ast_bridge_queue_everyone_else(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
1067 {
1068         struct ast_bridge_channel *cur;
1069         int not_written = -1;
1070
1071         if (frame->frametype == AST_FRAME_NULL) {
1072                 /* "Accept" the frame and discard it. */
1073                 return 0;
1074         }
1075
1076         AST_LIST_TRAVERSE(&bridge->channels, cur, entry) {
1077                 if (cur == bridge_channel) {
1078                         continue;
1079                 }
1080                 if (!ast_bridge_channel_queue_frame(cur, frame)) {
1081                         not_written = 0;
1082                 }
1083         }
1084         return not_written;
1085 }
1086
1087 int ast_bridge_channel_queue_control_data(struct ast_bridge_channel *bridge_channel, enum ast_control_frame_type control, const void *data, size_t datalen)
1088 {
1089         struct ast_frame frame = {
1090                 .frametype = AST_FRAME_CONTROL,
1091                 .subclass.integer = control,
1092                 .datalen = datalen,
1093                 .data.ptr = (void *) data,
1094         };
1095
1096         return ast_bridge_channel_queue_frame(bridge_channel, &frame);
1097 }
1098
1099 int ast_bridge_channel_write_control_data(struct ast_bridge_channel *bridge_channel, enum ast_control_frame_type control, const void *data, size_t datalen)
1100 {
1101         struct ast_frame frame = {
1102                 .frametype = AST_FRAME_CONTROL,
1103                 .subclass.integer = control,
1104                 .datalen = datalen,
1105                 .data.ptr = (void *) data,
1106         };
1107
1108         return bridge_channel_write_frame(bridge_channel, &frame);
1109 }
1110
1111 int ast_bridge_channel_write_hold(struct ast_bridge_channel *bridge_channel, const char *moh_class)
1112 {
1113         struct ast_json *blob;
1114         int res;
1115         size_t datalen;
1116
1117         if (!ast_strlen_zero(moh_class)) {
1118                 datalen = strlen(moh_class) + 1;
1119
1120                 blob = ast_json_pack("{s: s}",
1121                         "musicclass", moh_class);
1122         } else {
1123                 moh_class = NULL;
1124                 datalen = 0;
1125                 blob = NULL;
1126         }
1127
1128         ast_channel_publish_cached_blob(bridge_channel->chan, ast_channel_hold_type(), blob);
1129
1130         res = ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_HOLD,
1131                 moh_class, datalen);
1132
1133         ast_json_unref(blob);
1134         return res;
1135 }
1136
1137 int ast_bridge_channel_write_unhold(struct ast_bridge_channel *bridge_channel)
1138 {
1139         ast_channel_publish_cached_blob(bridge_channel->chan, ast_channel_unhold_type(), NULL);
1140
1141         return ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_UNHOLD, NULL, 0);
1142 }
1143
1144 /*!
1145  * \internal
1146  * \brief Helper function to kick off a PBX app on a bridge_channel
1147  */
1148 static int run_app_helper(struct ast_channel *chan, const char *app_name, const char *app_args)
1149 {
1150         int res = 0;
1151
1152         if (!strcasecmp("Gosub", app_name)) {
1153                 ast_app_exec_sub(NULL, chan, app_args, 0);
1154         } else if (!strcasecmp("Macro", app_name)) {
1155                 ast_app_exec_macro(NULL, chan, app_args);
1156         } else {
1157                 struct ast_app *app;
1158
1159                 app = pbx_findapp(app_name);
1160                 if (!app) {
1161                         ast_log(LOG_WARNING, "Could not find application (%s)\n", app_name);
1162                 } else {
1163                         struct ast_str *substituted_args = ast_str_create(16);
1164
1165                         if (substituted_args) {
1166                                 ast_str_substitute_variables(&substituted_args, 0, chan, app_args);
1167                                 res = pbx_exec(chan, app, ast_str_buffer(substituted_args));
1168                                 ast_free(substituted_args);
1169                         } else {
1170                                 ast_log(LOG_WARNING, "Could not substitute application argument variables for %s\n", app_name);
1171                                 res = pbx_exec(chan, app, app_args);
1172                         }
1173                 }
1174         }
1175         return res;
1176 }
1177
1178 void ast_bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1179 {
1180         if (moh_class) {
1181                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
1182         }
1183         if (run_app_helper(bridge_channel->chan, app_name, S_OR(app_args, ""))) {
1184                 /* Break the bridge if the app returns non-zero. */
1185                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1186         }
1187         if (moh_class) {
1188                 ast_bridge_channel_write_unhold(bridge_channel);
1189         }
1190 }
1191
1192 struct bridge_run_app {
1193         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
1194         int moh_offset;
1195         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
1196         int app_args_offset;
1197         /*! Application name to run. */
1198         char app_name[0];
1199 };
1200
1201 /*!
1202  * \internal
1203  * \brief Handle the run application bridge action.
1204  * \since 12.0.0
1205  *
1206  * \param bridge_channel Which channel to run the application on.
1207  * \param data Action frame data to run the application.
1208  *
1209  * \return Nothing
1210  */
1211 static void bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, struct bridge_run_app *data)
1212 {
1213         ast_bridge_channel_run_app(bridge_channel, data->app_name,
1214                 data->app_args_offset ? &data->app_name[data->app_args_offset] : NULL,
1215                 data->moh_offset ? &data->app_name[data->moh_offset] : NULL);
1216 }
1217
1218 /*!
1219  * \internal
1220  * \brief Marshal an application to be executed on a bridge_channel
1221  */
1222 static int payload_helper_app(ast_bridge_channel_post_action_data post_it,
1223         struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1224 {
1225         struct bridge_run_app *app_data;
1226         size_t len_name = strlen(app_name) + 1;
1227         size_t len_args = ast_strlen_zero(app_args) ? 0 : strlen(app_args) + 1;
1228         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
1229         size_t len_data = sizeof(*app_data) + len_name + len_args + len_moh;
1230
1231         /* Fill in application run frame data. */
1232         app_data = alloca(len_data);
1233         app_data->app_args_offset = len_args ? len_name : 0;
1234         app_data->moh_offset = len_moh ? len_name + len_args : 0;
1235         strcpy(app_data->app_name, app_name);/* Safe */
1236         if (len_args) {
1237                 strcpy(&app_data->app_name[app_data->app_args_offset], app_args);/* Safe */
1238         }
1239         if (moh_class) {
1240                 strcpy(&app_data->app_name[app_data->moh_offset], moh_class);/* Safe */
1241         }
1242
1243         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_RUN_APP, app_data, len_data);
1244 }
1245
1246 int ast_bridge_channel_write_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1247 {
1248         return payload_helper_app(bridge_channel_write_action_data,
1249                 bridge_channel, app_name, app_args, moh_class);
1250 }
1251
1252 int ast_bridge_channel_queue_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1253 {
1254         return payload_helper_app(bridge_channel_queue_action_data,
1255                 bridge_channel, app_name, app_args, moh_class);
1256 }
1257
1258 void ast_bridge_channel_playfile(struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
1259 {
1260         if (moh_class) {
1261                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
1262         }
1263         if (custom_play) {
1264                 custom_play(bridge_channel, playfile);
1265         } else {
1266                 ast_stream_and_wait(bridge_channel->chan, playfile, AST_DIGIT_NONE);
1267         }
1268         if (moh_class) {
1269                 ast_bridge_channel_write_unhold(bridge_channel);
1270         }
1271
1272         /*
1273          * It may be necessary to resume music on hold after we finish
1274          * playing the announcment.
1275          */
1276         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_MOH)) {
1277                 const char *latest_musicclass;
1278
1279                 ast_channel_lock(bridge_channel->chan);
1280                 latest_musicclass = ast_strdupa(ast_channel_latest_musicclass(bridge_channel->chan));
1281                 ast_channel_unlock(bridge_channel->chan);
1282                 ast_moh_start(bridge_channel->chan, latest_musicclass, NULL);
1283         }
1284 }
1285
1286 struct bridge_playfile {
1287         /*! Call this function to play the playfile. (NULL if normal sound file to play) */
1288         ast_bridge_custom_play_fn custom_play;
1289         /*! Offset into playfile[] where the MOH class name starts.  (zero if no MOH)*/
1290         int moh_offset;
1291         /*! Filename to play. */
1292         char playfile[0];
1293 };
1294
1295 /*!
1296  * \internal
1297  * \brief Handle the playfile bridge action.
1298  * \since 12.0.0
1299  *
1300  * \param bridge_channel Which channel to play a file on.
1301  * \param payload Action frame payload to play a file.
1302  *
1303  * \return Nothing
1304  */
1305 static void bridge_channel_playfile(struct ast_bridge_channel *bridge_channel, struct bridge_playfile *payload)
1306 {
1307         ast_bridge_channel_playfile(bridge_channel, payload->custom_play, payload->playfile,
1308                 payload->moh_offset ? &payload->playfile[payload->moh_offset] : NULL);
1309 }
1310
1311 /*!
1312  * \internal
1313  * \brief Marshal a file to be played on a bridge_channel
1314  */
1315 static int payload_helper_playfile(ast_bridge_channel_post_action_data post_it,
1316         struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
1317 {
1318         struct bridge_playfile *payload;
1319         size_t len_name = strlen(playfile) + 1;
1320         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
1321         size_t len_payload = sizeof(*payload) + len_name + len_moh;
1322
1323         /* Fill in play file frame data. */
1324         payload = ast_alloca(len_payload);
1325         payload->custom_play = custom_play;
1326         payload->moh_offset = len_moh ? len_name : 0;
1327         strcpy(payload->playfile, playfile);/* Safe */
1328         if (moh_class) {
1329                 strcpy(&payload->playfile[payload->moh_offset], moh_class);/* Safe */
1330         }
1331
1332         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_PLAY_FILE, payload, len_payload);
1333 }
1334
1335 int ast_bridge_channel_write_playfile(struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
1336 {
1337         return payload_helper_playfile(bridge_channel_write_action_data,
1338                 bridge_channel, custom_play, playfile, moh_class);
1339 }
1340
1341 int ast_bridge_channel_queue_playfile(struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
1342 {
1343         return payload_helper_playfile(bridge_channel_queue_action_data,
1344                 bridge_channel, custom_play, playfile, moh_class);
1345 }
1346
1347 int ast_bridge_channel_queue_playfile_sync(struct ast_bridge_channel *bridge_channel,
1348                 ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
1349 {
1350         return payload_helper_playfile(bridge_channel_queue_action_data_sync,
1351                 bridge_channel, custom_play, playfile, moh_class);
1352 }
1353
1354 struct bridge_custom_callback {
1355         /*! Call this function on the bridge channel thread. */
1356         ast_bridge_custom_callback_fn callback;
1357         /*! Size of the payload if it exists.  A number otherwise. */
1358         size_t payload_size;
1359         /*! Option flags determining how callback is called. */
1360         unsigned int flags;
1361         /*! Nonzero if the payload exists. */
1362         char payload_exists;
1363         /*! Payload to give to callback. */
1364         char payload[0];
1365 };
1366
1367 /*!
1368  * \internal
1369  * \brief Handle the do custom callback bridge action.
1370  * \since 12.0.0
1371  *
1372  * \param bridge_channel Which channel to call the callback on.
1373  * \param data Action frame data to call the callback.
1374  *
1375  * \return Nothing
1376  */
1377 static void bridge_channel_do_callback(struct ast_bridge_channel *bridge_channel, struct bridge_custom_callback *data)
1378 {
1379         if (ast_test_flag(data, AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA)) {
1380                 bridge_channel_suspend(bridge_channel);
1381                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1382         }
1383         data->callback(bridge_channel, data->payload_exists ? data->payload : NULL, data->payload_size);
1384         if (ast_test_flag(data, AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA)) {
1385                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1386                 bridge_channel_unsuspend(bridge_channel);
1387         }
1388 }
1389
1390 /*!
1391  * \internal
1392  * \brief Marshal a custom callback function to be called on a bridge_channel
1393  */
1394 static int payload_helper_cb(ast_bridge_channel_post_action_data post_it,
1395         struct ast_bridge_channel *bridge_channel,
1396         enum ast_bridge_channel_custom_callback_option flags,
1397         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1398 {
1399         struct bridge_custom_callback *cb_data;
1400         size_t len_data = sizeof(*cb_data) + (payload ? payload_size : 0);
1401
1402         /* Sanity check. */
1403         if (!callback) {
1404                 ast_assert(0);
1405                 return -1;
1406         }
1407
1408         /* Fill in custom callback frame data. */
1409         cb_data = alloca(len_data);
1410         cb_data->callback = callback;
1411         cb_data->payload_size = payload_size;
1412         cb_data->flags = flags;
1413         cb_data->payload_exists = payload && payload_size;
1414         if (cb_data->payload_exists) {
1415                 memcpy(cb_data->payload, payload, payload_size);/* Safe */
1416         }
1417
1418         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_CALLBACK, cb_data, len_data);
1419 }
1420
1421 int ast_bridge_channel_write_callback(struct ast_bridge_channel *bridge_channel,
1422         enum ast_bridge_channel_custom_callback_option flags,
1423         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1424 {
1425         return payload_helper_cb(bridge_channel_write_action_data,
1426                 bridge_channel, flags, callback, payload, payload_size);
1427 }
1428
1429 int ast_bridge_channel_queue_callback(struct ast_bridge_channel *bridge_channel,
1430         enum ast_bridge_channel_custom_callback_option flags,
1431         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1432 {
1433         return payload_helper_cb(bridge_channel_queue_action_data,
1434                 bridge_channel, flags, callback, payload, payload_size);
1435 }
1436
1437 struct bridge_park {
1438         int parker_uuid_offset;
1439         int app_data_offset;
1440         /* buffer used for holding those strings */
1441         char parkee_uuid[0];
1442 };
1443
1444 /*!
1445  * \internal
1446  * \brief Park a bridge_cahnnel
1447  */
1448 static void bridge_channel_park(struct ast_bridge_channel *bridge_channel, struct bridge_park *payload)
1449 {
1450         if (!ast_parking_provider_registered()) {
1451                 ast_log(AST_LOG_WARNING, "Unable to park %s: No parking provider loaded!\n",
1452                         ast_channel_name(bridge_channel->chan));
1453                 return;
1454         }
1455
1456         if (ast_parking_park_bridge_channel(bridge_channel, payload->parkee_uuid,
1457                 &payload->parkee_uuid[payload->parker_uuid_offset],
1458                 payload->app_data_offset ? &payload->parkee_uuid[payload->app_data_offset] : NULL)) {
1459                 ast_log(AST_LOG_WARNING, "Error occurred while parking %s\n",
1460                         ast_channel_name(bridge_channel->chan));
1461         }
1462 }
1463
1464 /*!
1465  * \internal
1466  * \brief Marshal a park action onto a bridge_channel
1467  */
1468 static int payload_helper_park(ast_bridge_channel_post_action_data post_it,
1469         struct ast_bridge_channel *bridge_channel,
1470         const char *parkee_uuid,
1471         const char *parker_uuid,
1472         const char *app_data)
1473 {
1474         struct bridge_park *payload;
1475         size_t len_parkee_uuid = strlen(parkee_uuid) + 1;
1476         size_t len_parker_uuid = strlen(parker_uuid) + 1;
1477         size_t len_app_data = !app_data ? 0 : strlen(app_data) + 1;
1478         size_t len_payload = sizeof(*payload) + len_parker_uuid + len_parkee_uuid + len_app_data;
1479
1480         payload = alloca(len_payload);
1481         payload->app_data_offset = len_app_data ? len_parkee_uuid + len_parker_uuid : 0;
1482         payload->parker_uuid_offset = len_parkee_uuid;
1483         strcpy(payload->parkee_uuid, parkee_uuid);
1484         strcpy(&payload->parkee_uuid[payload->parker_uuid_offset], parker_uuid);
1485         if (app_data) {
1486                 strcpy(&payload->parkee_uuid[payload->app_data_offset], app_data);
1487         }
1488
1489         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_PARK, payload, len_payload);
1490 }
1491
1492 int ast_bridge_channel_write_park(struct ast_bridge_channel *bridge_channel, const char *parkee_uuid, const char *parker_uuid, const char *app_data)
1493 {
1494         return payload_helper_park(bridge_channel_write_action_data,
1495                 bridge_channel, parkee_uuid, parker_uuid, app_data);
1496 }
1497
1498 /*!
1499  * \internal
1500  * \brief Handle bridge channel interval expiration.
1501  * \since 12.0.0
1502  *
1503  * \param bridge_channel Channel to run expired intervals on.
1504  *
1505  * \return Nothing
1506  */
1507 static void bridge_channel_handle_interval(struct ast_bridge_channel *bridge_channel)
1508 {
1509         struct ast_heap *interval_hooks;
1510         struct ast_bridge_hook_timer *hook;
1511         struct timeval start;
1512         int chan_suspended = 0;
1513
1514         interval_hooks = bridge_channel->features->interval_hooks;
1515         ast_heap_wrlock(interval_hooks);
1516         start = ast_tvnow();
1517         while ((hook = ast_heap_peek(interval_hooks, 1))) {
1518                 int interval;
1519                 unsigned int execution_time;
1520
1521                 if (ast_tvdiff_ms(hook->timer.trip_time, start) > 0) {
1522                         ast_debug(1, "Hook %p on %p(%s) wants to happen in the future, stopping our traversal\n",
1523                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1524                         break;
1525                 }
1526                 ao2_ref(hook, +1);
1527                 ast_heap_unlock(interval_hooks);
1528
1529                 if (!chan_suspended
1530                         && ast_test_flag(&hook->timer, AST_BRIDGE_HOOK_TIMER_OPTION_MEDIA)) {
1531                         chan_suspended = 1;
1532                         bridge_channel_suspend(bridge_channel);
1533                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1534                 }
1535
1536                 ast_debug(1, "Executing hook %p on %p(%s)\n",
1537                         hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1538                 interval = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1539
1540                 ast_heap_wrlock(interval_hooks);
1541                 if (ast_heap_peek(interval_hooks, hook->timer.heap_index) != hook
1542                         || !ast_heap_remove(interval_hooks, hook)) {
1543                         /* Interval hook is already removed from the bridge_channel. */
1544                         ao2_ref(hook, -1);
1545                         continue;
1546                 }
1547                 ao2_ref(hook, -1);
1548
1549                 if (interval < 0) {
1550                         ast_debug(1, "Removed interval hook %p from %p(%s)\n",
1551                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1552                         ao2_ref(hook, -1);
1553                         continue;
1554                 }
1555                 if (interval) {
1556                         /* Set new interval for the hook. */
1557                         hook->timer.interval = interval;
1558                 }
1559
1560                 ast_debug(1, "Updating interval hook %p with interval %u on %p(%s)\n",
1561                         hook, hook->timer.interval, bridge_channel,
1562                         ast_channel_name(bridge_channel->chan));
1563
1564                 /* resetting start */
1565                 start = ast_tvnow();
1566
1567                 /*
1568                  * Resetup the interval hook for the next interval.  We may need
1569                  * to skip over any missed intervals because the hook was
1570                  * delayed or took too long.
1571                  */
1572                 execution_time = ast_tvdiff_ms(start, hook->timer.trip_time);
1573                 while (hook->timer.interval < execution_time) {
1574                         execution_time -= hook->timer.interval;
1575                 }
1576                 hook->timer.trip_time = ast_tvadd(start, ast_samp2tv(hook->timer.interval - execution_time, 1000));
1577                 hook->timer.seqno = ast_atomic_fetchadd_int((int *) &bridge_channel->features->interval_sequence, +1);
1578
1579                 if (ast_heap_push(interval_hooks, hook)) {
1580                         /* Could not push the hook back onto the heap. */
1581                         ao2_ref(hook, -1);
1582                 }
1583         }
1584         ast_heap_unlock(interval_hooks);
1585
1586         if (chan_suspended) {
1587                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1588                 bridge_channel_unsuspend(bridge_channel);
1589         }
1590 }
1591
1592 /*!
1593  * \internal
1594  * \brief Write a DTMF stream out to a channel
1595  */
1596 static int bridge_channel_write_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1597 {
1598         return bridge_channel_write_action_data(bridge_channel,
1599                 BRIDGE_CHANNEL_ACTION_DTMF_STREAM, dtmf, strlen(dtmf) + 1);
1600 }
1601
1602 /*!
1603  * \internal
1604  * \brief Indicate to the testsuite a feature was successfully detected.
1605  *
1606  * Currently, this function only will relay built-in features to the testsuite,
1607  * but it could be modified to detect applicationmap items should the need arise.
1608  *
1609  * \param chan The channel that activated the feature
1610  * \param dtmf The DTMF sequence entered to activate the feature
1611  */
1612 static void testsuite_notify_feature_success(struct ast_channel *chan, const char *dtmf)
1613 {
1614 #ifdef TEST_FRAMEWORK
1615         char *feature = "unknown";
1616         struct ast_featuremap_config *featuremap;
1617         struct ast_features_xfer_config *xfer;
1618
1619         ast_channel_lock(chan);
1620         featuremap = ast_get_chan_featuremap_config(chan);
1621         xfer = ast_get_chan_features_xfer_config(chan);
1622         ast_channel_unlock(chan);
1623
1624         if (featuremap) {
1625                 if (!strcmp(dtmf, featuremap->blindxfer)) {
1626                         feature = "blindxfer";
1627                 } else if (!strcmp(dtmf, featuremap->atxfer)) {
1628                         feature = "atxfer";
1629                 } else if (!strcmp(dtmf, featuremap->disconnect)) {
1630                         feature = "disconnect";
1631                 } else if (!strcmp(dtmf, featuremap->automon)) {
1632                         feature = "automon";
1633                 } else if (!strcmp(dtmf, featuremap->automixmon)) {
1634                         feature = "automixmon";
1635                 } else if (!strcmp(dtmf, featuremap->parkcall)) {
1636                         feature = "parkcall";
1637                 }
1638         }
1639         if (xfer) {
1640                 if (!strcmp(dtmf, xfer->atxferthreeway)) {
1641                         feature = "atxferthreeway";
1642                 }
1643         }
1644
1645         ao2_cleanup(featuremap);
1646         ao2_cleanup(xfer);
1647
1648         ast_test_suite_event_notify("FEATURE_DETECTION",
1649                         "Result: success\r\n"
1650                         "Feature: %s", feature);
1651 #endif /* TEST_FRAMEWORK */
1652 }
1653
1654 static int bridge_channel_feature_digit_add(
1655         struct ast_bridge_channel *bridge_channel, int digit, size_t dtmf_len)
1656 {
1657         if (dtmf_len < ARRAY_LEN(bridge_channel->dtmf_hook_state.collected) - 1) {
1658                 /* Add the new digit to the DTMF string so we can do our matching */
1659                 bridge_channel->dtmf_hook_state.collected[dtmf_len++] = digit;
1660                 bridge_channel->dtmf_hook_state.collected[dtmf_len] = '\0';
1661
1662                 ast_debug(1, "DTMF feature string on %p(%s) is now '%s'\n",
1663                           bridge_channel, ast_channel_name(bridge_channel->chan),
1664                           bridge_channel->dtmf_hook_state.collected);
1665         }
1666
1667         return dtmf_len;
1668 }
1669
1670 static unsigned int bridge_channel_feature_digit_timeout(struct ast_bridge_channel *bridge_channel)
1671 {
1672         unsigned int digit_timeout;
1673         struct ast_features_general_config *gen_cfg;
1674
1675         /* Determine interdigit timeout */
1676         ast_channel_lock(bridge_channel->chan);
1677         gen_cfg = ast_get_chan_features_general_config(bridge_channel->chan);
1678         ast_channel_unlock(bridge_channel->chan);
1679
1680         if (!gen_cfg) {
1681                 ast_log(LOG_ERROR, "Unable to retrieve features configuration.\n");
1682                 return 3000; /* Pick a reasonable failsafe timeout in ms */
1683         }
1684
1685         digit_timeout = gen_cfg->featuredigittimeout;
1686         ao2_ref(gen_cfg, -1);
1687
1688         return digit_timeout;
1689 }
1690
1691 void ast_bridge_channel_feature_digit_add(struct ast_bridge_channel *bridge_channel, int digit)
1692 {
1693         if (digit) {
1694                 bridge_channel_feature_digit_add(
1695                         bridge_channel, digit, strlen(bridge_channel->dtmf_hook_state.collected));
1696         }
1697 }
1698
1699 void ast_bridge_channel_feature_digit(struct ast_bridge_channel *bridge_channel, int digit)
1700 {
1701         struct ast_bridge_features *features = bridge_channel->features;
1702         struct ast_bridge_hook_dtmf *hook = NULL;
1703         size_t dtmf_len;
1704
1705         struct sanity_check_of_dtmf_size {
1706                 char check[1 / (ARRAY_LEN(bridge_channel->dtmf_hook_state.collected) == ARRAY_LEN(hook->dtmf.code))];
1707         };
1708
1709         dtmf_len = strlen(bridge_channel->dtmf_hook_state.collected);
1710         if (!dtmf_len && !digit) {
1711                 /* Nothing to do */
1712                 return;
1713         }
1714
1715         if (digit) {
1716                 dtmf_len = bridge_channel_feature_digit_add(bridge_channel, digit, dtmf_len);
1717         }
1718
1719         while (digit) {
1720                 /* See if a DTMF feature hook matches or can match */
1721                 hook = ao2_find(features->dtmf_hooks, bridge_channel->dtmf_hook_state.collected,
1722                         OBJ_SEARCH_PARTIAL_KEY);
1723                 if (!hook) {
1724                         ast_debug(1, "No DTMF feature hooks on %p(%s) match '%s'\n",
1725                                 bridge_channel, ast_channel_name(bridge_channel->chan),
1726                                 bridge_channel->dtmf_hook_state.collected);
1727                         break;
1728                 } else if (dtmf_len != strlen(hook->dtmf.code)) {
1729                         unsigned int digit_timeout;
1730                         /* Need more digits to match */
1731                         ao2_ref(hook, -1);
1732                         digit_timeout = bridge_channel_feature_digit_timeout(bridge_channel);
1733                         bridge_channel->dtmf_hook_state.interdigit_timeout =
1734                                 ast_tvadd(ast_tvnow(), ast_samp2tv(digit_timeout, 1000));
1735                         return;
1736                 } else {
1737                         int remove_me;
1738                         int already_suspended;
1739
1740                         ast_debug(1, "DTMF feature hook %p matched DTMF string '%s' on %p(%s)\n",
1741                                 hook, bridge_channel->dtmf_hook_state.collected, bridge_channel,
1742                                 ast_channel_name(bridge_channel->chan));
1743
1744                         /*
1745                          * Clear the collected digits before executing the hook
1746                          * in case the hook starts another sequence.
1747                          */
1748                         bridge_channel->dtmf_hook_state.collected[0] = '\0';
1749
1750                         ast_bridge_channel_lock_bridge(bridge_channel);
1751                         already_suspended = bridge_channel->suspended;
1752                         if (!already_suspended) {
1753                                 bridge_channel_internal_suspend_nolock(bridge_channel);
1754                         }
1755                         ast_bridge_unlock(bridge_channel->bridge);
1756                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1757
1758                         /* Execute the matched hook on this channel. */
1759                         remove_me = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1760                         if (remove_me) {
1761                                 ast_debug(1, "DTMF hook %p is being removed from %p(%s)\n",
1762                                         hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1763                                 ao2_unlink(features->dtmf_hooks, hook);
1764                         }
1765                         testsuite_notify_feature_success(bridge_channel->chan, hook->dtmf.code);
1766                         ao2_ref(hook, -1);
1767
1768                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1769                         if (!already_suspended) {
1770                                 bridge_channel_unsuspend(bridge_channel);
1771                         }
1772
1773                         /*
1774                          * If we are handing the channel off to an external hook for
1775                          * ownership, we are not guaranteed what kind of state it will
1776                          * come back in.  If the channel hungup, we need to detect that
1777                          * here if the hook did not already change the state.
1778                          */
1779                         if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
1780                                 ast_bridge_channel_kick(bridge_channel, 0);
1781                                 bridge_channel->dtmf_hook_state.collected[0] = '\0';
1782                                 return;
1783                         }
1784
1785                         /* if there is dtmf that has been collected then loop back through,
1786                            but set digit to -1 so it doesn't try to do an add since the dtmf
1787                            is already in the buffer */
1788                         dtmf_len = strlen(bridge_channel->dtmf_hook_state.collected);
1789                         if (!dtmf_len) {
1790                                 return;
1791                         }
1792                 }
1793         }
1794
1795         if (!digit) {
1796                 ast_debug(1, "DTMF feature string collection on %p(%s) timed out\n",
1797                         bridge_channel, ast_channel_name(bridge_channel->chan));
1798         }
1799
1800         /* Timeout or DTMF digit didn't allow a match with any hooks. */
1801         if (features->dtmf_passthrough) {
1802                 /* Stream the collected DTMF to the other channels. */
1803                 bridge_channel_write_dtmf_stream(bridge_channel,
1804                         bridge_channel->dtmf_hook_state.collected);
1805         }
1806         bridge_channel->dtmf_hook_state.collected[0] = '\0';
1807
1808         ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
1809 }
1810
1811 /*!
1812  * \internal
1813  * \brief Handle bridge channel DTMF feature timeout expiration.
1814  * \since 12.8.0
1815  *
1816  * \param bridge_channel Channel to check expired interdigit timer on.
1817  *
1818  * \return Nothing
1819  */
1820 static void bridge_channel_handle_feature_timeout(struct ast_bridge_channel *bridge_channel)
1821 {
1822         if (!bridge_channel->dtmf_hook_state.collected[0]
1823                 || 0 < ast_tvdiff_ms(bridge_channel->dtmf_hook_state.interdigit_timeout,
1824                         ast_tvnow())) {
1825                 /* Not within a sequence or not timed out. */
1826                 return;
1827         }
1828
1829         ast_bridge_channel_feature_digit(bridge_channel, 0);
1830 }
1831
1832 /*!
1833  * \internal
1834  * \brief Indicate that a bridge_channel is talking
1835  */
1836 static void bridge_channel_talking(struct ast_bridge_channel *bridge_channel, int talking)
1837 {
1838         struct ast_bridge_features *features = bridge_channel->features;
1839         struct ast_bridge_hook *hook;
1840         struct ao2_iterator iter;
1841
1842         /* Run any talk detection hooks. */
1843         iter = ao2_iterator_init(features->other_hooks, 0);
1844         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1845                 int remove_me;
1846                 ast_bridge_talking_indicate_callback talk_cb;
1847
1848                 if (hook->type != AST_BRIDGE_HOOK_TYPE_TALK) {
1849                         continue;
1850                 }
1851                 talk_cb = (ast_bridge_talking_indicate_callback) hook->callback;
1852                 remove_me = talk_cb(bridge_channel, hook->hook_pvt, talking);
1853                 if (remove_me) {
1854                         ast_debug(1, "Talk detection hook %p is being removed from %p(%s)\n",
1855                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1856                         ao2_unlink(features->other_hooks, hook);
1857                 }
1858         }
1859         ao2_iterator_destroy(&iter);
1860 }
1861
1862 /*! \brief Internal function that plays back DTMF on a bridge channel */
1863 static void bridge_channel_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1864 {
1865         ast_debug(1, "Playing DTMF stream '%s' out to %p(%s)\n",
1866                 dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
1867         ast_dtmf_stream(bridge_channel->chan, NULL, dtmf, 0, 0);
1868 }
1869
1870 /*! \brief Data specifying where a blind transfer is going to */
1871 struct blind_transfer_data {
1872         char exten[AST_MAX_EXTENSION];
1873         char context[AST_MAX_CONTEXT];
1874 };
1875
1876 /*!
1877  * \internal
1878  * \brief Execute after bridge actions on a channel when it leaves a bridge
1879  */
1880 static void after_bridge_move_channel(struct ast_channel *chan_bridged, void *data)
1881 {
1882         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1883         struct ast_party_connected_line connected_target;
1884         unsigned char connected_line_data[1024];
1885         int payload_size;
1886
1887         ast_party_connected_line_init(&connected_target);
1888
1889         ast_channel_lock(chan_target);
1890         ast_party_connected_line_copy(&connected_target, ast_channel_connected(chan_target));
1891         ast_channel_unlock(chan_target);
1892         ast_party_id_reset(&connected_target.priv);
1893
1894         if (ast_channel_move(chan_target, chan_bridged)) {
1895                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1896                 ast_party_connected_line_free(&connected_target);
1897                 return;
1898         }
1899
1900         /* The ast_channel_move function will end up updating the connected line information
1901          * on chan_target to the value we have here, but will not inform it. To ensure that
1902          * AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO is executed we wipe it away here. If
1903          * we don't do this then the change will be considered redundant, since the connected
1904          * line information is already there (despite the channel not being told).
1905          */
1906         ast_channel_lock(chan_target);
1907         ast_party_connected_line_free(ast_channel_connected_indicated(chan_target));
1908         ast_party_connected_line_init(ast_channel_connected_indicated(chan_target));
1909         ast_channel_unlock(chan_target);
1910
1911         if ((payload_size = ast_connected_line_build_data(connected_line_data,
1912                 sizeof(connected_line_data), &connected_target, NULL)) != -1) {
1913                 struct ast_control_read_action_payload *frame_payload;
1914                 int frame_size;
1915
1916                 frame_size = payload_size + sizeof(*frame_payload);
1917                 frame_payload = ast_alloca(frame_size);
1918                 frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
1919                 frame_payload->payload_size = payload_size;
1920                 memcpy(frame_payload->payload, connected_line_data, payload_size);
1921                 ast_queue_control_data(chan_target, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
1922         }
1923
1924         /* A connected line update is queued so that if chan_target is remotely involved with
1925          * anything (such as dialing a channel) the other channel(s) will be informed of the
1926          * new channel they are involved with.
1927          */
1928         ast_channel_lock(chan_target);
1929         ast_connected_line_copy_from_caller(&connected_target, ast_channel_caller(chan_target));
1930         ast_channel_queue_connected_line_update(chan_target, &connected_target, NULL);
1931         ast_channel_unlock(chan_target);
1932
1933         ast_party_connected_line_free(&connected_target);
1934 }
1935
1936 /*!
1937  * \internal
1938  * \brief Execute logic to cleanup when after bridge fails
1939  */
1940 static void after_bridge_move_channel_fail(enum ast_bridge_after_cb_reason reason, void *data)
1941 {
1942         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1943
1944         ast_log(LOG_WARNING, "Unable to complete transfer: %s\n",
1945                 ast_bridge_after_cb_reason_string(reason));
1946         ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1947 }
1948
1949 /*!
1950  * \internal
1951  * \brief Perform a blind transfer on a channel in a bridge
1952  */
1953 static void bridge_channel_blind_transfer(struct ast_bridge_channel *bridge_channel,
1954                 struct blind_transfer_data *blind_data)
1955 {
1956         ast_async_goto(bridge_channel->chan, blind_data->context, blind_data->exten, 1);
1957         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1958 }
1959
1960 /*!
1961  * \internal
1962  * \brief Perform an attended transfer on a channel in a bridge
1963  */
1964 static void bridge_channel_attended_transfer(struct ast_bridge_channel *bridge_channel,
1965                 const char *target_chan_name)
1966 {
1967         RAII_VAR(struct ast_channel *, chan_target, NULL, ao2_cleanup);
1968         RAII_VAR(struct ast_channel *, chan_bridged, NULL, ao2_cleanup);
1969
1970         chan_target = ast_channel_get_by_name(target_chan_name);
1971         if (!chan_target) {
1972                 /* Dang, it disappeared somehow */
1973                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1974                 return;
1975         }
1976
1977         ast_bridge_channel_lock(bridge_channel);
1978         chan_bridged = bridge_channel->chan;
1979         ast_assert(chan_bridged != NULL);
1980         ao2_ref(chan_bridged, +1);
1981         ast_bridge_channel_unlock(bridge_channel);
1982
1983         if (ast_bridge_set_after_callback(chan_bridged, after_bridge_move_channel,
1984                 after_bridge_move_channel_fail, ast_channel_ref(chan_target))) {
1985                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1986
1987                 /* Release the ref we tried to pass to ast_bridge_set_after_callback(). */
1988                 ast_channel_unref(chan_target);
1989         }
1990         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1991 }
1992
1993 /*!
1994  * \internal
1995  * \brief Handle bridge channel bridge action frame.
1996  * \since 12.0.0
1997  *
1998  * \param bridge_channel Channel to execute the action on.
1999  * \param action What to do.
2000  * \param data data from the action.
2001  *
2002  * \return Nothing
2003  */
2004 static void bridge_channel_handle_action(struct ast_bridge_channel *bridge_channel,
2005         enum bridge_channel_action_type action, void *data)
2006 {
2007         switch (action) {
2008         case BRIDGE_CHANNEL_ACTION_DTMF_STREAM:
2009                 bridge_channel_suspend(bridge_channel);
2010                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2011                 bridge_channel_dtmf_stream(bridge_channel, data);
2012                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2013                 bridge_channel_unsuspend(bridge_channel);
2014                 break;
2015         case BRIDGE_CHANNEL_ACTION_TALKING_START:
2016         case BRIDGE_CHANNEL_ACTION_TALKING_STOP:
2017                 bridge_channel_talking(bridge_channel,
2018                         action == BRIDGE_CHANNEL_ACTION_TALKING_START);
2019                 break;
2020         case BRIDGE_CHANNEL_ACTION_PLAY_FILE:
2021                 bridge_channel_suspend(bridge_channel);
2022                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2023                 bridge_channel_playfile(bridge_channel, data);
2024                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2025                 bridge_channel_unsuspend(bridge_channel);
2026                 break;
2027         case BRIDGE_CHANNEL_ACTION_RUN_APP:
2028                 bridge_channel_suspend(bridge_channel);
2029                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2030                 bridge_channel_run_app(bridge_channel, data);
2031                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2032                 bridge_channel_unsuspend(bridge_channel);
2033                 break;
2034         case BRIDGE_CHANNEL_ACTION_CALLBACK:
2035                 bridge_channel_do_callback(bridge_channel, data);
2036                 break;
2037         case BRIDGE_CHANNEL_ACTION_PARK:
2038                 bridge_channel_suspend(bridge_channel);
2039                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2040                 bridge_channel_park(bridge_channel, data);
2041                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2042                 bridge_channel_unsuspend(bridge_channel);
2043                 break;
2044         case BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER:
2045                 bridge_channel_blind_transfer(bridge_channel, data);
2046                 break;
2047         case BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER:
2048                 bridge_channel_attended_transfer(bridge_channel, data);
2049                 break;
2050         default:
2051                 break;
2052         }
2053
2054         /* While invoking an action it is possible for the channel to be hung up. So
2055          * that the bridge respects this we check here and if hung up kick it out.
2056          */
2057         if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
2058                 ast_bridge_channel_kick(bridge_channel, 0);
2059         }
2060 }
2061
2062 /*!
2063  * \internal
2064  * \brief Check if a bridge should dissolve and do it.
2065  * \since 12.0.0
2066  *
2067  * \param bridge_channel Channel causing the check.
2068  *
2069  * \note On entry, bridge_channel->bridge is already locked.
2070  *
2071  * \return Nothing
2072  */
2073 static void bridge_channel_dissolve_check(struct ast_bridge_channel *bridge_channel)
2074 {
2075         struct ast_bridge *bridge = bridge_channel->bridge;
2076
2077         if (bridge->dissolved) {
2078                 return;
2079         }
2080
2081         if (!bridge->num_channels
2082                 && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY)) {
2083                 /* Last channel leaving the bridge turns off the lights. */
2084                 bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
2085                 return;
2086         }
2087
2088         switch (bridge_channel->state) {
2089         case BRIDGE_CHANNEL_STATE_END:
2090                 /* Do we need to dissolve the bridge because this channel hung up? */
2091                 if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_HANGUP)
2092                         || (bridge_channel->features->usable
2093                                 && ast_test_flag(&bridge_channel->features->feature_flags,
2094                                         AST_BRIDGE_CHANNEL_FLAG_DISSOLVE_HANGUP))) {
2095                         bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
2096                         return;
2097                 }
2098                 break;
2099         default:
2100                 break;
2101         }
2102
2103         if (bridge->num_lonely && bridge->num_lonely == bridge->num_channels) {
2104                 /*
2105                  * This will start a chain reaction where each channel leaving
2106                  * enters this function and causes the next to leave as long as
2107                  * there aren't non-lonely channels in the bridge.
2108                  */
2109                 ast_bridge_channel_leave_bridge(AST_LIST_FIRST(&bridge->channels),
2110                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE,
2111                         ast_channel_hangupcause(bridge_channel->chan));
2112         }
2113 }
2114
2115 void bridge_channel_internal_pull(struct ast_bridge_channel *bridge_channel)
2116 {
2117         struct ast_bridge *bridge = bridge_channel->bridge;
2118
2119         if (!bridge_channel->in_bridge) {
2120                 return;
2121         }
2122         bridge_channel->in_bridge = 0;
2123
2124         ast_debug(1, "Bridge %s: pulling %p(%s)\n",
2125                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
2126
2127         ast_verb(3, "Channel %s left '%s' %s-bridge <%s>\n",
2128                 ast_channel_name(bridge_channel->chan),
2129                 bridge->technology->name,
2130                 bridge->v_table->name,
2131                 bridge->uniqueid);
2132
2133         if (!bridge_channel->just_joined) {
2134                 /* Tell the bridge technology we are leaving so they tear us down */
2135                 ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology\n",
2136                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
2137                         bridge->technology->name);
2138                 if (bridge->technology->leave) {
2139                         bridge->technology->leave(bridge, bridge_channel);
2140                 }
2141         }
2142
2143         /* Remove channel from the bridge */
2144         if (!bridge_channel->suspended) {
2145                 --bridge->num_active;
2146         }
2147         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
2148                 --bridge->num_lonely;
2149         }
2150         --bridge->num_channels;
2151         AST_LIST_REMOVE(&bridge->channels, bridge_channel, entry);
2152
2153         bridge_channel_dissolve_check(bridge_channel);
2154         bridge->v_table->pull(bridge, bridge_channel);
2155
2156         ast_bridge_channel_clear_roles(bridge_channel);
2157
2158         /* If we are not going to be hung up after leaving a bridge, and we were an
2159          * outgoing channel, clear the outgoing flag.
2160          */
2161         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING)
2162             && (ast_channel_is_leaving_bridge(bridge_channel->chan)
2163                 || bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT)) {
2164                 ast_debug(2, "Channel %s will survive this bridge; clearing outgoing (dialed) flag\n", ast_channel_name(bridge_channel->chan));
2165                 ast_channel_clear_flag(bridge_channel->chan, AST_FLAG_OUTGOING);
2166         }
2167
2168         bridge->reconfigured = 1;
2169         ast_bridge_publish_leave(bridge, bridge_channel->chan);
2170 }
2171
2172 int bridge_channel_internal_push_full(struct ast_bridge_channel *bridge_channel, int optimized)
2173 {
2174         struct ast_bridge *bridge = bridge_channel->bridge;
2175         struct ast_bridge_channel *swap;
2176
2177         ast_assert(!bridge_channel->in_bridge);
2178
2179         swap = bridge_find_channel(bridge, bridge_channel->swap);
2180         bridge_channel->swap = NULL;
2181
2182         if (swap) {
2183                 ast_debug(1, "Bridge %s: pushing %p(%s) by swapping with %p(%s)\n",
2184                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
2185                         swap, ast_channel_name(swap->chan));
2186         } else {
2187                 ast_debug(1, "Bridge %s: pushing %p(%s)\n",
2188                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
2189         }
2190
2191         /* Add channel to the bridge */
2192         if (bridge->dissolved
2193                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
2194                 || (swap && swap->state != BRIDGE_CHANNEL_STATE_WAIT)
2195                 || bridge->v_table->push(bridge, bridge_channel, swap)) {
2196                 ast_debug(1, "Bridge %s: pushing %p(%s) into bridge failed\n",
2197                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
2198                 return -1;
2199         }
2200
2201         ast_bridge_channel_establish_roles(bridge_channel);
2202
2203         if (swap) {
2204                 int dissolve = ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY);
2205
2206                 /* This flag is cleared so the act of this channel leaving does not cause it to dissolve if need be */
2207                 ast_clear_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY);
2208
2209                 if (optimized) {
2210                         bridge_channel_cancel_owed_events(swap);
2211                 }
2212                 ast_bridge_channel_leave_bridge(swap, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, 0);
2213                 bridge_channel_internal_pull(swap);
2214
2215                 ast_set2_flag(&bridge->feature_flags, dissolve, AST_BRIDGE_FLAG_DISSOLVE_EMPTY);
2216         }
2217
2218         bridge_channel->in_bridge = 1;
2219         bridge_channel->just_joined = 1;
2220         AST_LIST_INSERT_TAIL(&bridge->channels, bridge_channel, entry);
2221         ++bridge->num_channels;
2222         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
2223                 ++bridge->num_lonely;
2224         }
2225         if (!bridge_channel->suspended) {
2226                 ++bridge->num_active;
2227         }
2228
2229         ast_verb(3, "Channel %s %s%s%s '%s' %s-bridge <%s>\n",
2230                 ast_channel_name(bridge_channel->chan),
2231                 swap ? "swapped with " : "joined",
2232                 swap ? ast_channel_name(swap->chan) : "",
2233                 swap ? " into" : "",
2234                 bridge->technology->name,
2235                 bridge->v_table->name,
2236                 bridge->uniqueid);
2237
2238         ast_bridge_publish_enter(bridge, bridge_channel->chan, swap ? swap->chan : NULL);
2239
2240         /* Clear any BLINDTRANSFER,ATTENDEDTRANSFER and FORWARDERNAME since the transfer has completed. */
2241         pbx_builtin_setvar_helper(bridge_channel->chan, "BLINDTRANSFER", NULL);
2242         pbx_builtin_setvar_helper(bridge_channel->chan, "ATTENDEDTRANSFER", NULL);
2243         pbx_builtin_setvar_helper(bridge_channel->chan, "FORWARDERNAME", NULL);
2244
2245         /* Wake up the bridge channel thread to reevaluate any interval timers. */
2246         ast_queue_frame(bridge_channel->chan, &ast_null_frame);
2247
2248         bridge->reconfigured = 1;
2249         return 0;
2250 }
2251
2252 int bridge_channel_internal_push(struct ast_bridge_channel *bridge_channel)
2253 {
2254         return bridge_channel_internal_push_full(bridge_channel, 0);
2255 }
2256
2257 /*!
2258  * \internal
2259  * \brief Handle bridge channel control frame action.
2260  * \since 12.0.0
2261  *
2262  * \param bridge_channel Channel to execute the control frame action on.
2263  * \param fr Control frame to handle.
2264  *
2265  * \return Nothing
2266  */
2267 static void bridge_channel_handle_control(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
2268 {
2269         struct ast_channel *chan;
2270         struct ast_option_header *aoh;
2271         int is_caller;
2272
2273         chan = bridge_channel->chan;
2274         switch (fr->subclass.integer) {
2275         case AST_CONTROL_REDIRECTING:
2276                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
2277                 if (ast_channel_redirecting_sub(NULL, chan, fr, 1) &&
2278                         ast_channel_redirecting_macro(NULL, chan, fr, is_caller, 1)) {
2279                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2280                 }
2281                 break;
2282         case AST_CONTROL_CONNECTED_LINE:
2283                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
2284                 if (ast_channel_connected_line_sub(NULL, chan, fr, 1) &&
2285                         ast_channel_connected_line_macro(NULL, chan, fr, is_caller, 1)) {
2286                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2287                 }
2288                 break;
2289         case AST_CONTROL_OPTION:
2290                 /*
2291                  * Forward option Requests, but only ones we know are safe These
2292                  * are ONLY sent by chan_iax2 and I'm not convinced that they
2293                  * are useful. I haven't deleted them entirely because I just am
2294                  * not sure of the ramifications of removing them.
2295                  */
2296                 aoh = fr->data.ptr;
2297                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
2298                         switch (ntohs(aoh->option)) {
2299                         case AST_OPTION_TONE_VERIFY:
2300                         case AST_OPTION_TDD:
2301                         case AST_OPTION_RELAXDTMF:
2302                         case AST_OPTION_AUDIO_MODE:
2303                         case AST_OPTION_DIGIT_DETECT:
2304                         case AST_OPTION_FAX_DETECT:
2305                                 ast_channel_setoption(chan, ntohs(aoh->option), aoh->data,
2306                                         fr->datalen - sizeof(*aoh), 0);
2307                                 break;
2308                         default:
2309                                 break;
2310                         }
2311                 }
2312                 break;
2313         case AST_CONTROL_ANSWER:
2314                 if (ast_channel_state(chan) != AST_STATE_UP) {
2315                         ast_answer(chan);
2316                         ast_bridge_channel_lock_bridge(bridge_channel);
2317                         bridge_channel->bridge->reconfigured = 1;
2318                         bridge_reconfigured(bridge_channel->bridge, 0);
2319                         ast_bridge_unlock(bridge_channel->bridge);
2320                 } else {
2321                         ast_indicate(chan, -1);
2322                 }
2323                 break;
2324         case AST_CONTROL_MASQUERADE_NOTIFY:
2325                 /* Should never happen. */
2326                 ast_assert(0);
2327                 break;
2328         case AST_CONTROL_STREAM_TOPOLOGY_CHANGED:
2329                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2330                 break;
2331         default:
2332                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2333                 break;
2334         }
2335 }
2336
2337 /*!
2338  * \internal
2339  * \brief Handle bridge channel write frame to channel.
2340  * \since 12.0.0
2341  *
2342  * \param bridge_channel Channel to write outgoing frame.
2343  *
2344  * \return Nothing
2345  */
2346 static void bridge_channel_handle_write(struct ast_bridge_channel *bridge_channel)
2347 {
2348         struct ast_frame *fr;
2349         struct sync_payload *sync_payload;
2350         int num;
2351
2352         ast_bridge_channel_lock(bridge_channel);
2353
2354         /* It's not good to have unbalanced frames and alert_pipe alerts. */
2355         ast_assert(!AST_LIST_EMPTY(&bridge_channel->wr_queue));
2356         if (AST_LIST_EMPTY(&bridge_channel->wr_queue)) {
2357                 /* No frame, flush the alert pipe of excess alerts. */
2358                 ast_log(LOG_WARNING, "Weird.  No frame from bridge for %s to process?\n",
2359                         ast_channel_name(bridge_channel->chan));
2360                 ast_alertpipe_read(bridge_channel->alert_pipe);
2361                 ast_bridge_channel_unlock(bridge_channel);
2362                 return;
2363         }
2364
2365         AST_LIST_TRAVERSE_SAFE_BEGIN(&bridge_channel->wr_queue, fr, frame_list) {
2366                 if (bridge_channel->dtmf_hook_state.collected[0]) {
2367                         switch (fr->frametype) {
2368                         case AST_FRAME_BRIDGE_ACTION:
2369                         case AST_FRAME_BRIDGE_ACTION_SYNC:
2370                                 /* Defer processing these frames while DTMF is collected. */
2371                                 continue;
2372                         default:
2373                                 break;
2374                         }
2375                 }
2376                 ast_alertpipe_read(bridge_channel->alert_pipe);
2377                 AST_LIST_REMOVE_CURRENT(frame_list);
2378                 break;
2379         }
2380         AST_LIST_TRAVERSE_SAFE_END;
2381
2382         ast_bridge_channel_unlock(bridge_channel);
2383         if (!fr) {
2384                 /*
2385                  * Wait some to reduce CPU usage from a tight loop
2386                  * without any wait because we only have deferred
2387                  * frames in the wr_queue.
2388                  */
2389                 usleep(1);
2390                 return;
2391         }
2392
2393         switch (fr->frametype) {
2394         case AST_FRAME_BRIDGE_ACTION:
2395                 bridge_channel_handle_action(bridge_channel, fr->subclass.integer, fr->data.ptr);
2396                 break;
2397         case AST_FRAME_BRIDGE_ACTION_SYNC:
2398                 sync_payload = fr->data.ptr;
2399                 bridge_channel_handle_action(bridge_channel, fr->subclass.integer, sync_payload->data);
2400                 break;
2401         case AST_FRAME_CONTROL:
2402                 bridge_channel_handle_control(bridge_channel, fr);
2403                 break;
2404         case AST_FRAME_NULL:
2405                 break;
2406         default:
2407                 /* Assume that there is no mapped stream for this */
2408                 num = -1;
2409
2410                 if (fr->stream_num > -1) {
2411                         ast_bridge_channel_lock(bridge_channel);
2412                         if (fr->stream_num < (int)AST_VECTOR_SIZE(&bridge_channel->stream_map.to_channel)) {
2413                                 num = AST_VECTOR_GET(&bridge_channel->stream_map.to_channel, fr->stream_num);
2414                         }
2415                         ast_bridge_channel_unlock(bridge_channel);
2416
2417                         /* If there is no mapped stream after checking the mapping then there is nowhere
2418                          * to write this frame to, so drop it.
2419                          */
2420                         if (num == -1) {
2421                                 break;
2422                         }
2423                 }
2424
2425                 /* Write the frame to the channel. */
2426                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_SIMPLE;
2427                 ast_write_stream(bridge_channel->chan, num, fr);
2428                 break;
2429         }
2430         bridge_frame_free(fr);
2431 }
2432
2433 /*! \brief Internal function to handle DTMF from a channel */
2434 static struct ast_frame *bridge_handle_dtmf(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
2435 {
2436         struct ast_bridge_features *features = bridge_channel->features;
2437         struct ast_bridge_hook_dtmf *hook = NULL;
2438         char dtmf[2];
2439
2440         /*
2441          * See if we are already matching a DTMF feature hook sequence or
2442          * if this DTMF matches the beginning of any DTMF feature hooks.
2443          */
2444         dtmf[0] = frame->subclass.integer;
2445         dtmf[1] = '\0';
2446         if (bridge_channel->dtmf_hook_state.collected[0]
2447                 || (hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_SEARCH_PARTIAL_KEY))) {
2448                 enum ast_frame_type frametype = frame->frametype;
2449
2450                 bridge_frame_free(frame);
2451                 frame = NULL;
2452
2453                 ao2_cleanup(hook);
2454
2455                 switch (frametype) {
2456                 case AST_FRAME_DTMF_BEGIN:
2457                         /* Just eat the frame. */
2458                         break;
2459                 case AST_FRAME_DTMF_END:
2460                         ast_bridge_channel_feature_digit(bridge_channel, dtmf[0]);
2461                         break;
2462                 default:
2463                         /* Unexpected frame type. */
2464                         ast_assert(0);
2465                         break;
2466                 }
2467 #ifdef TEST_FRAMEWORK
2468         } else if (frame->frametype == AST_FRAME_DTMF_END) {
2469                 /* Only transmit this event on DTMF end or else every DTMF
2470                  * press will result in the event being broadcast twice
2471                  */
2472                 ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
2473 #endif
2474         }
2475
2476         return frame;
2477 }
2478
2479 static const char *controls[] = {
2480         [AST_CONTROL_RINGING] = "RINGING",
2481         [AST_CONTROL_PROCEEDING] = "PROCEEDING",
2482         [AST_CONTROL_PROGRESS] = "PROGRESS",
2483         [AST_CONTROL_BUSY] = "BUSY",
2484         [AST_CONTROL_CONGESTION] = "CONGESTION",
2485         [AST_CONTROL_ANSWER] = "ANSWER",
2486 };
2487
2488 /*!
2489  * \internal
2490  * \brief Feed notification that a frame is waiting on a channel into the bridging core
2491  *
2492  * \param bridge_channel Bridge channel the notification was received on
2493  */
2494 static void bridge_handle_trip(struct ast_bridge_channel *bridge_channel)
2495 {
2496         struct ast_frame *frame;
2497         int blocked;
2498
2499         if (!ast_strlen_zero(ast_channel_call_forward(bridge_channel->chan))) {
2500                 /* TODO If early bridging is ever used by anything other than ARI,
2501                  * it's important that we actually attempt to handle the call forward
2502                  * attempt, as well as expand features on a bridge channel to allow/disallow
2503                  * call forwarding. For now, all we do is raise an event, showing that
2504                  * a call forward is being attempted.
2505                  */
2506                 ast_channel_publish_dial_forward(NULL, bridge_channel->chan, NULL, NULL, "CANCEL",
2507                         ast_channel_call_forward(bridge_channel->chan));
2508         }
2509
2510         if (bridge_channel->features->mute) {
2511                 frame = ast_read_stream_noaudio(bridge_channel->chan);
2512         } else {
2513                 frame = ast_read_stream(bridge_channel->chan);
2514         }
2515
2516         if (!frame) {
2517                 ast_bridge_channel_kick(bridge_channel, 0);
2518                 return;
2519         }
2520
2521         if (!ast_channel_is_multistream(bridge_channel->chan)) {
2522                 /* This may not be initialized by non-multistream channel drivers */
2523                 frame->stream_num = -1;
2524         }
2525
2526         switch (frame->frametype) {
2527         case AST_FRAME_CONTROL:
2528                 switch (frame->subclass.integer) {
2529                 case AST_CONTROL_CONGESTION:
2530                 case AST_CONTROL_BUSY:
2531                         ast_channel_publish_dial(NULL, bridge_channel->chan, NULL, controls[frame->subclass.integer]);
2532                         break;
2533                 case AST_CONTROL_HANGUP:
2534                         ast_bridge_channel_kick(bridge_channel, 0);
2535                         bridge_frame_free(frame);
2536                         return;
2537                 case AST_CONTROL_RINGING:
2538                 case AST_CONTROL_PROGRESS:
2539                 case AST_CONTROL_PROCEEDING:
2540                 case AST_CONTROL_ANSWER:
2541                         ast_channel_publish_dial(NULL, bridge_channel->chan, NULL, controls[frame->subclass.integer]);
2542                         break;
2543                 case AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE:
2544                         ast_bridge_channel_lock_bridge(bridge_channel);
2545                         blocked = bridge_channel->bridge->technology->stream_topology_request_change
2546                                 && bridge_channel->bridge->technology->stream_topology_request_change(
2547                                         bridge_channel->bridge, bridge_channel);
2548                         ast_bridge_unlock(bridge_channel->bridge);
2549                         if (blocked) {
2550                                 /*
2551                                  * Topology change was intercepted by the bridge technology
2552                                  * so drop frame.
2553                                  */
2554                                 bridge_frame_free(frame);
2555                                 return;
2556                         }
2557                         break;
2558                 case AST_CONTROL_STREAM_TOPOLOGY_CHANGED:
2559                         /*
2560                          * If a stream topology has changed then the bridge_channel's
2561                          * media mapping needs to be updated.
2562                          */
2563                         ast_bridge_channel_lock_bridge(bridge_channel);
2564                         if (bridge_channel->bridge->technology->stream_topology_changed) {
2565                                 bridge_channel->bridge->technology->stream_topology_changed(
2566                                         bridge_channel->bridge, bridge_channel);
2567                         } else {
2568                                 ast_bridge_channel_stream_map(bridge_channel);
2569                         }
2570                         ast_bridge_unlock(bridge_channel->bridge);
2571                         break;
2572                 default:
2573                         break;
2574                 }
2575                 break;
2576         case AST_FRAME_DTMF_BEGIN:
2577         case AST_FRAME_DTMF_END:
2578                 frame = bridge_handle_dtmf(bridge_channel, frame);
2579                 if (!frame) {
2580                         return;
2581                 }
2582                 if (!bridge_channel->features->dtmf_passthrough) {
2583                         bridge_frame_free(frame);
2584                         return;
2585                 }
2586                 break;
2587         default:
2588                 break;
2589         }
2590
2591         /* Simply write the frame out to the bridge technology. */
2592         bridge_channel_write_frame(bridge_channel, frame);
2593         bridge_frame_free(frame);
2594 }
2595
2596 /*!
2597  * \internal
2598  * \brief Determine how long till the next timer interval.
2599  * \since 12.0.0
2600  *
2601  * \param bridge_channel Channel to determine how long can wait.
2602  *
2603  * \retval ms Number of milliseconds to wait.
2604  * \retval -1 to wait forever.
2605  */
2606 static int bridge_channel_next_interval(struct ast_bridge_channel *bridge_channel)
2607 {
2608         struct ast_heap *interval_hooks = bridge_channel->features->interval_hooks;
2609         struct ast_bridge_hook_timer *hook;
2610         int ms;
2611
2612         ast_heap_wrlock(interval_hooks);
2613         hook = ast_heap_peek(interval_hooks, 1);
2614         if (hook) {
2615                 ms = ast_tvdiff_ms(hook->timer.trip_time, ast_tvnow());
2616                 if (ms < 0) {
2617                         /* Expire immediately.  An interval hook is ready to run. */
2618                         ms = 0;
2619                 }
2620         } else {
2621                 /* No hook so wait forever. */
2622                 ms = -1;
2623         }
2624         ast_heap_unlock(interval_hooks);
2625
2626         return ms;
2627 }
2628
2629 /*!
2630  * \internal
2631  * \brief Determine how long till the DTMF interdigit timeout.
2632  * \since 12.8.0
2633  *
2634  * \param bridge_channel Channel to determine how long can wait.
2635  *
2636  * \retval ms Number of milliseconds to wait.
2637  * \retval -1 to wait forever.
2638  */
2639 static int bridge_channel_feature_timeout(struct ast_bridge_channel *bridge_channel)
2640 {
2641         int ms;
2642
2643         if (bridge_channel->dtmf_hook_state.collected[0]) {
2644                 ms = ast_tvdiff_ms(bridge_channel->dtmf_hook_state.interdigit_timeout,
2645                         ast_tvnow());
2646                 if (ms < 0) {
2647                         /* Expire immediately. */
2648                         ms = 0;
2649                 }
2650         } else {
2651                 /* Timer is not active so wait forever. */
2652                 ms = -1;
2653         }
2654
2655         return ms;
2656 }
2657
2658 /*!
2659  * \internal
2660  * \brief Determine how long till a timeout.
2661  * \since 12.8.0
2662  *
2663  * \param bridge_channel Channel to determine how long can wait.
2664  *
2665  * \retval ms Number of milliseconds to wait.
2666  * \retval -1 to wait forever.
2667  */
2668 static int bridge_channel_next_timeout(struct ast_bridge_channel *bridge_channel)
2669 {
2670         int ms_interval;
2671         int ms;
2672
2673         ms_interval = bridge_channel_next_interval(bridge_channel);
2674         ms = bridge_channel_feature_timeout(bridge_channel);
2675         if (ms < 0 || (0 <= ms_interval && ms_interval < ms)) {
2676                 /* Interval hook timeout is next. */
2677                 ms = ms_interval;
2678         }
2679
2680         return ms;
2681 }
2682
2683 /*!
2684  * \internal
2685  * \brief Wait for something to happen on the bridge channel and handle it.
2686  * \since 12.0.0
2687  *
2688  * \param bridge_channel Channel to wait.
2689  *
2690  * \note Each channel does writing/reading in their own thread.
2691  *
2692  * \return Nothing
2693  */
2694 static void bridge_channel_wait(struct ast_bridge_channel *bridge_channel)
2695 {
2696         int ms;
2697         int outfd;
2698         struct ast_channel *chan;
2699
2700         /* Wait for data to either come from the channel or us to be signaled */
2701         ast_bridge_channel_lock(bridge_channel);
2702         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2703         } else if (bridge_channel->suspended) {
2704 /* XXX ASTERISK-21271 the external party use of suspended will go away as will these references because this is the bridge channel thread */
2705                 ast_debug(1, "Bridge %s: %p(%s) is going into a signal wait\n",
2706                         bridge_channel->bridge->uniqueid, bridge_channel,
2707                         ast_channel_name(bridge_channel->chan));
2708                 ast_cond_wait(&bridge_channel->cond, ao2_object_get_lockaddr(bridge_channel));
2709         } else {
2710                 ast_bridge_channel_unlock(bridge_channel);
2711                 outfd = -1;
2712                 ms = bridge_channel_next_timeout(bridge_channel);
2713                 chan = ast_waitfor_nandfds(&bridge_channel->chan, 1,
2714                         &bridge_channel->alert_pipe[0], 1, NULL, &outfd, &ms);
2715                 if (ast_channel_unbridged(bridge_channel->chan)) {
2716                         ast_channel_set_unbridged(bridge_channel->chan, 0);
2717                         ast_bridge_channel_lock_bridge(bridge_channel);
2718                         bridge_channel->bridge->reconfigured = 1;
2719                         bridge_reconfigured(bridge_channel->bridge, 0);
2720                         ast_bridge_unlock(bridge_channel->bridge);
2721                 }
2722                 ast_bridge_channel_lock(bridge_channel);
2723                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_FRAME;
2724                 ast_bridge_channel_unlock(bridge_channel);
2725                 if (!bridge_channel->suspended
2726                         && bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2727                         if (chan) {
2728                                 bridge_handle_trip(bridge_channel);
2729                         } else if (ms == 0) {
2730                                 /* An interdigit timeout or interval expired. */
2731                                 bridge_channel_handle_feature_timeout(bridge_channel);
2732                                 bridge_channel_handle_interval(bridge_channel);
2733                         } else if (-1 < outfd) {
2734                                 /*
2735                                  * Must do this after checking timeouts or may have
2736                                  * an infinite loop due to deferring write queue
2737                                  * actions while trying to match DTMF feature hooks.
2738                                  */
2739                                 bridge_channel_handle_write(bridge_channel);
2740                         }
2741                 }
2742                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_IDLE;
2743                 return;
2744         }
2745         ast_bridge_channel_unlock(bridge_channel);
2746 }
2747
2748 /*!
2749  * \internal
2750  * \brief Handle bridge channel join/leave event.
2751  * \since 12.0.0
2752  *
2753  * \param bridge_channel Which channel is involved.
2754  * \param type Specified join/leave event.
2755  *
2756  * \return Nothing
2757  */
2758 static void bridge_channel_event_join_leave(struct ast_bridge_channel *bridge_channel, enum ast_bridge_hook_type type)
2759 {
2760         struct ast_bridge_features *features = bridge_channel->features;
2761         struct ast_bridge_hook *hook;
2762         struct ao2_iterator iter;
2763
2764         /* Run the specified hooks. */
2765         iter = ao2_iterator_init(features->other_hooks, 0);
2766         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
2767                 if (hook->type == type) {
2768                         break;
2769                 }
2770         }
2771         if (hook) {
2772                 /* Found the first specified hook to run. */
2773                 bridge_channel_suspend(bridge_channel);
2774                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2775                 do {
2776                         if (hook->type == type) {
2777                                 hook->callback(bridge_channel, hook->hook_pvt);
2778                                 ao2_unlink(features->other_hooks, hook);
2779                         }
2780                         ao2_ref(hook, -1);
2781                 } while ((hook = ao2_iterator_next(&iter)));
2782                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2783                 bridge_channel_unsuspend(bridge_channel);
2784         }
2785         ao2_iterator_destroy(&iter);
2786 }
2787
2788 int bridge_channel_internal_join(struct ast_bridge_channel *bridge_channel)
2789 {
2790         int res = 0;
2791         struct ast_bridge_features *channel_features;
2792         struct ast_channel *swap;
2793
2794         ast_debug(1, "Bridge %s: %p(%s) is joining\n",
2795                 bridge_channel->bridge->uniqueid,
2796                 bridge_channel, ast_channel_name(bridge_channel->chan));
2797
2798         /*
2799          * Directly locking the bridge is safe here because nobody else
2800          * knows about this bridge_channel yet.
2801          */
2802         ast_bridge_lock(bridge_channel->bridge);
2803
2804         ast_channel_lock(bridge_channel->chan);
2805
2806         bridge_channel->read_format = ao2_bump(ast_channel_readformat(bridge_channel->chan));
2807         bridge_channel->write_format = ao2_bump(ast_channel_writeformat(bridge_channel->chan));
2808
2809         /* Make sure we're still good to be put into a bridge */
2810         if (ast_channel_internal_bridge(bridge_channel->chan)
2811                 || ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_ZOMBIE)) {
2812                 ast_channel_unlock(bridge_channel->chan);
2813                 ast_bridge_unlock(bridge_channel->bridge);
2814                 ast_debug(1, "Bridge %s: %p(%s) failed to join Bridge\n",
2815                         bridge_channel->bridge->uniqueid,
2816                         bridge_channel,
2817                         ast_channel_name(bridge_channel->chan));
2818                 return -1;
2819         }
2820         ast_channel_internal_bridge_set(bridge_channel->chan, bridge_channel->bridge);
2821
2822         /* Attach features requested by the channel */
2823         channel_features = ast_channel_feature_hooks_get(bridge_channel->chan);
2824         if (channel_features) {
2825                 ast_bridge_features_merge(bridge_channel->features, channel_features);
2826         }
2827         ast_channel_unlock(bridge_channel->chan);
2828
2829         /* Add the jitterbuffer if the channel requires it */
2830         ast_jb_enable_for_channel(bridge_channel->chan);
2831
2832         if (!bridge_channel->bridge->callid) {
2833                 bridge_channel->bridge->callid = ast_read_threadstorage_callid();
2834         }
2835
2836         /* Take the swap channel ref from the bridge_channel struct. */
2837         swap = bridge_channel->swap;
2838
2839         if (bridge_channel_internal_push(bridge_channel)) {
2840                 int cause = bridge_channel->bridge->cause;
2841
2842                 ast_bridge_unlock(bridge_channel->bridge);
2843                 ast_bridge_channel_kick(bridge_channel, cause);
2844                 ast_bridge_channel_lock_bridge(bridge_channel);
2845                 ast_bridge_features_remove(bridge_channel->features,
2846                         AST_BRIDGE_HOOK_REMOVE_ON_PULL);
2847                 bridge_channel_dissolve_check(bridge_channel);
2848                 res = -1;
2849         }
2850         bridge_reconfigured(bridge_channel->bridge, !bridge_channel->inhibit_colp);
2851
2852         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2853                 /*
2854                  * Indicate a source change since this channel is entering the
2855                  * bridge system only if the bridge technology is not MULTIMIX
2856                  * capable.  The MULTIMIX technology has already done it.
2857                  */
2858                 if (!(bridge_channel->bridge->technology->capabilities
2859                         & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
2860                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2861                 }
2862
2863                 bridge_channel_impart_signal(bridge_channel->chan);
2864                 ast_bridge_unlock(bridge_channel->bridge);
2865
2866                 /* Must release any swap ref after unlocking the bridge. */
2867                 ao2_t_cleanup(swap, "Bridge push with swap successful");
2868                 swap = NULL;
2869
2870                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_JOIN);
2871
2872                 while (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2873                         /* Wait for something to do. */
2874                         bridge_channel_wait(bridge_channel);
2875                 }
2876
2877                 /* Force a timeout on any accumulated DTMF hook digits. */
2878                 ast_bridge_channel_feature_digit(bridge_channel, 0);
2879
2880                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_LEAVE);
2881                 ast_bridge_channel_lock_bridge(bridge_channel);
2882         }
2883
2884         bridge_channel_internal_pull(bridge_channel);
2885         bridge_channel_settle_owed_events(bridge_channel->bridge, bridge_channel);
2886         bridge_reconfigured(bridge_channel->bridge, 1);
2887
2888         /* Remove ourselves if we are the video source */
2889         ast_bridge_remove_video_src(bridge_channel->bridge, bridge_channel->chan);
2890
2891         ast_bridge_unlock(bridge_channel->bridge);
2892
2893         /* Must release any swap ref after unlocking the bridge. */
2894         ao2_t_cleanup(swap, "Bridge push with swap failed or exited immediately");
2895
2896         /* Complete any active hold before exiting the bridge. */
2897         if (ast_channel_hold_state(bridge_channel->chan) == AST_CONTROL_HOLD) {
2898                 ast_debug(1, "Channel %s simulating UNHOLD for bridge end.\n",
2899                         ast_channel_name(bridge_channel->chan));
2900                 ast_indicate(bridge_channel->chan, AST_CONTROL_UNHOLD);
2901         }
2902
2903         /* Complete any partial DTMF digit before exiting the bridge. */
2904         if (ast_channel_sending_dtmf_digit(bridge_channel->chan)) {
2905                 ast_channel_end_dtmf(bridge_channel->chan,
2906                         ast_channel_sending_dtmf_digit(bridge_channel->chan),
2907                         ast_channel_sending_dtmf_tv(bridge_channel->chan), "bridge end");
2908         }
2909
2910         /* Complete any T.38 session before exiting the bridge. */
2911         if (ast_channel_is_t38_active(bridge_channel->chan)) {
2912                 struct ast_control_t38_parameters t38_parameters = {
2913                         .request_response = AST_T38_TERMINATED,
2914                 };
2915
2916                 ast_debug(1, "Channel %s simulating T.38 terminate for bridge end.\n",
2917                         ast_channel_name(bridge_channel->chan));
2918                 ast_indicate_data(bridge_channel->chan, AST_CONTROL_T38_PARAMETERS,
2919                         &t38_parameters, sizeof(t38_parameters));
2920         }
2921
2922         /* Indicate a source change since this channel is leaving the bridge system. */
2923         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2924
2925         /*
2926          * Wait for any dual redirect to complete.
2927          *
2928          * Must be done while "still in the bridge" for ast_async_goto()
2929          * to work right.
2930          */
2931         while (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT)) {
2932                 sched_yield();
2933         }
2934         ast_channel_lock(bridge_channel->chan);
2935         ast_channel_internal_bridge_set(bridge_channel->chan, NULL);
2936         ast_channel_unlock(bridge_channel->chan);
2937
2938         ast_bridge_channel_restore_formats(bridge_channel);
2939
2940         return res;
2941 }
2942
2943 int bridge_channel_internal_queue_blind_transfer(struct ast_channel *transferee,
2944                 const char *exten, const char *context,
2945                 transfer_channel_cb new_channel_cb, void *user_data)
2946 {
2947         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2948         struct blind_transfer_data blind_data;
2949
2950         ast_channel_lock(transferee);
2951         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2952         ast_channel_unlock(transferee);
2953
2954         if (!transferee_bridge_channel) {
2955                 return -1;
2956         }
2957
2958         if (new_channel_cb) {
2959                 new_channel_cb(transferee, user_data, AST_BRIDGE_TRANSFER_SINGLE_PARTY);
2960         }
2961
2962         ast_copy_string(blind_data.exten, exten, sizeof(blind_data.exten));
2963         ast_copy_string(blind_data.context, context, sizeof(blind_data.context));
2964
2965         return bridge_channel_queue_action_data(transferee_bridge_channel,
2966                 BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER, &blind_data, sizeof(blind_data));
2967 }
2968
2969 int bridge_channel_internal_queue_attended_transfer(struct ast_channel *transferee,
2970                 struct ast_channel *unbridged_chan)
2971 {
2972         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2973         char unbridged_chan_name[AST_CHANNEL_NAME];
2974
2975         ast_channel_lock(transferee);
2976         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2977         ast_channel_unlock(transferee);
2978
2979         if (!transferee_bridge_channel) {
2980                 return -1;
2981         }
2982
2983         ast_copy_string(unbridged_chan_name, ast_channel_name(unbridged_chan),
2984                 sizeof(unbridged_chan_name));
2985
2986         return bridge_channel_queue_action_data(transferee_bridge_channel,
2987                 BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER, unbridged_chan_name,
2988                 sizeof(unbridged_chan_name));
2989 }
2990
2991 int bridge_channel_internal_allows_optimization(struct ast_bridge_channel *bridge_channel)
2992 {
2993         return bridge_channel->in_bridge
2994                 && AST_LIST_EMPTY(&bridge_channel->wr_queue);
2995 }
2996
2997 /* Destroy elements of the bridge channel structure and the bridge channel structure itself */
2998 static void bridge_channel_destroy(void *obj)
2999 {
3000         struct ast_bridge_channel *bridge_channel = obj;
3001         struct ast_frame *fr;
3002
3003         if (bridge_channel->callid) {
3004                 bridge_channel->callid = 0;
3005         }
3006
3007         if (bridge_channel->bridge) {
3008                 ao2_ref(bridge_channel->bridge, -1);
3009                 bridge_channel->bridge = NULL;
3010         }
3011
3012         /* Flush any unhandled wr_queue frames. */
3013         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list))) {
3014                 bridge_frame_free(fr);
3015         }
3016         ast_alertpipe_close(bridge_channel->alert_pipe);
3017
3018         /* Flush any unhandled deferred_queue frames. */
3019         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->deferred_queue, frame_list))) {
3020                 ast_frfree(fr);
3021         }
3022
3023         ast_cond_destroy(&bridge_channel->cond);
3024
3025         ao2_cleanup(bridge_channel->write_format);
3026         ao2_cleanup(bridge_channel->read_format);
3027
3028         AST_VECTOR_FREE(&bridge_channel->stream_map.to_bridge);
3029         AST_VECTOR_FREE(&bridge_channel->stream_map.to_channel);
3030 }
3031
3032 struct ast_bridge_channel *bridge_channel_internal_alloc(struct ast_bridge *bridge)
3033 {
3034         struct ast_bridge_channel *bridge_channel;
3035
3036         bridge_channel = ao2_alloc(sizeof(struct ast_bridge_channel), bridge_channel_destroy);
3037         if (!bridge_channel) {
3038                 return NULL;
3039         }
3040         ast_cond_init(&bridge_channel->cond, NULL);
3041         if (ast_alertpipe_init(bridge_channel->alert_pipe)) {
3042                 ao2_ref(bridge_channel, -1);
3043                 return NULL;
3044         }
3045         if (bridge) {
3046                 bridge_channel->bridge = bridge;
3047                 ao2_ref(bridge_channel->bridge, +1);
3048         }
3049
3050         /* The stream_map is initialized later - see ast_bridge_channel_stream_map */
3051
3052         return bridge_channel;
3053 }
3054
3055 void ast_bridge_channel_stream_map(struct ast_bridge_channel *bridge_channel)
3056 {
3057         ast_bridge_channel_lock(bridge_channel);
3058         ast_channel_lock(bridge_channel->chan);
3059         ast_stream_topology_map(ast_channel_get_stream_topology(bridge_channel->chan),
3060                 &bridge_channel->bridge->media_types, &bridge_channel->stream_map.to_bridge,
3061                 &bridge_channel->stream_map.to_channel);
3062         ast_channel_unlock(bridge_channel->chan);
3063         ast_bridge_channel_unlock(bridge_channel);
3064 }