Merge "Add primitive SFU support to bridge_softmix."
[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 onto the bridge channel
630  * \since 12.0.0
631  *
632  * \param bridge_channel Which channel to queue the frame onto.
633  * \param frame The frame to write onto the bridge_channel
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
642         ast_assert(frame->frametype != AST_FRAME_BRIDGE_ACTION_SYNC);
643
644         ast_bridge_channel_lock_bridge(bridge_channel);
645 /*
646  * XXX need to implement a deferred write queue for when there
647  * is no peer channel in the bridge (yet or it was kicked).
648  *
649  * The tech decides if a frame needs to be pushed back for deferral.
650  * simple_bridge/native_bridge are likely the only techs that will do this.
651  */
652         bridge_channel->bridge->technology->write(bridge_channel->bridge, bridge_channel, frame);
653
654         /* Remember any owed events to the bridge. */
655         switch (frame->frametype) {
656         case AST_FRAME_DTMF_BEGIN:
657                 bridge_channel->owed.dtmf_tv = ast_tvnow();
658                 bridge_channel->owed.dtmf_digit = frame->subclass.integer;
659                 break;
660         case AST_FRAME_DTMF_END:
661                 bridge_channel->owed.dtmf_digit = '\0';
662                 break;
663         case AST_FRAME_CONTROL:
664                 /*
665                  * We explicitly will not remember HOLD/UNHOLD frames because
666                  * things like attended transfers will handle them.
667                  */
668                 switch (frame->subclass.integer) {
669                 case AST_CONTROL_T38_PARAMETERS:
670                         t38_parameters = frame->data.ptr;
671                         switch (t38_parameters->request_response) {
672                         case AST_T38_REQUEST_NEGOTIATE:
673                         case AST_T38_NEGOTIATED:
674                                 bridge_channel->owed.t38_terminate = 1;
675                                 break;
676                         case AST_T38_REQUEST_TERMINATE:
677                         case AST_T38_TERMINATED:
678                         case AST_T38_REFUSED:
679                                 bridge_channel->owed.t38_terminate = 0;
680                                 break;
681                         default:
682                                 break;
683                         }
684                         break;
685                 default:
686                         break;
687                 }
688                 break;
689         default:
690                 break;
691         }
692         ast_bridge_unlock(bridge_channel->bridge);
693
694         /*
695          * Claim successful write to bridge.  If deferred frame
696          * support is added, claim successfully deferred.
697          */
698         return 0;
699 }
700
701 /*!
702  * \internal
703  * \brief Cancel owed events by the channel to the bridge.
704  * \since 13.8.0
705  *
706  * \param bridge_channel Channel that owes events to the bridge.
707  *
708  * \note On entry, the bridge_channel->bridge is already locked.
709  *
710  * \return Nothing
711  */
712 static void bridge_channel_cancel_owed_events(struct ast_bridge_channel *bridge_channel)
713 {
714         bridge_channel->owed.dtmf_digit = '\0';
715         bridge_channel->owed.t38_terminate = 0;
716 }
717
718 void bridge_channel_settle_owed_events(struct ast_bridge *orig_bridge, struct ast_bridge_channel *bridge_channel)
719 {
720         if (bridge_channel->owed.dtmf_digit) {
721                 struct ast_frame frame = {
722                         .frametype = AST_FRAME_DTMF_END,
723                         .subclass.integer = bridge_channel->owed.dtmf_digit,
724                         .src = "Bridge channel owed DTMF",
725                 };
726
727                 frame.len = ast_tvdiff_ms(ast_tvnow(), bridge_channel->owed.dtmf_tv);
728                 if (frame.len < option_dtmfminduration) {
729                         frame.len = option_dtmfminduration;
730                 }
731                 ast_log(LOG_DTMF, "DTMF end '%c' simulated to bridge %s because %s left.  Duration %ld ms.\n",
732                         bridge_channel->owed.dtmf_digit, orig_bridge->uniqueid,
733                         ast_channel_name(bridge_channel->chan), frame.len);
734                 bridge_channel->owed.dtmf_digit = '\0';
735                 orig_bridge->technology->write(orig_bridge, NULL, &frame);
736         }
737         if (bridge_channel->owed.t38_terminate) {
738                 struct ast_control_t38_parameters t38_parameters = {
739                         .request_response = AST_T38_TERMINATED,
740                 };
741                 struct ast_frame frame = {
742                         .frametype = AST_FRAME_CONTROL,
743                         .subclass.integer = AST_CONTROL_T38_PARAMETERS,
744                         .data.ptr = &t38_parameters,
745                         .datalen = sizeof(t38_parameters),
746                         .src = "Bridge channel owed T.38 terminate",
747                 };
748
749                 ast_debug(1, "T.38 terminate simulated to bridge %s because %s left.\n",
750                         orig_bridge->uniqueid, ast_channel_name(bridge_channel->chan));
751                 bridge_channel->owed.t38_terminate = 0;
752                 orig_bridge->technology->write(orig_bridge, NULL, &frame);
753         }
754 }
755
756 /*!
757  * \internal
758  * \brief Suspend a channel from a bridge.
759  *
760  * \param bridge_channel Channel to suspend.
761  *
762  * \note This function assumes bridge_channel->bridge is locked.
763  *
764  * \return Nothing
765  */
766 void bridge_channel_internal_suspend_nolock(struct ast_bridge_channel *bridge_channel)
767 {
768         bridge_channel->suspended = 1;
769         if (bridge_channel->in_bridge) {
770                 --bridge_channel->bridge->num_active;
771         }
772
773         /* Get technology bridge threads off of the channel. */
774         if (bridge_channel->bridge->technology->suspend) {
775                 bridge_channel->bridge->technology->suspend(bridge_channel->bridge, bridge_channel);
776         }
777 }
778
779 /*!
780  * \internal
781  * \brief Suspend a channel from a bridge.
782  *
783  * \param bridge_channel Channel to suspend.
784  *
785  * \return Nothing
786  */
787 static void bridge_channel_suspend(struct ast_bridge_channel *bridge_channel)
788 {
789         ast_bridge_channel_lock_bridge(bridge_channel);
790         bridge_channel_internal_suspend_nolock(bridge_channel);
791         ast_bridge_unlock(bridge_channel->bridge);
792 }
793
794 /*!
795  * \internal
796  * \brief Unsuspend a channel from a bridge.
797  *
798  * \param bridge_channel Channel to unsuspend.
799  *
800  * \note This function assumes bridge_channel->bridge is locked.
801  *
802  * \return Nothing
803  */
804 void bridge_channel_internal_unsuspend_nolock(struct ast_bridge_channel *bridge_channel)
805 {
806         bridge_channel->suspended = 0;
807         if (bridge_channel->in_bridge) {
808                 ++bridge_channel->bridge->num_active;
809         }
810
811         /* Wake technology bridge threads to take care of channel again. */
812         if (bridge_channel->bridge->technology->unsuspend) {
813                 bridge_channel->bridge->technology->unsuspend(bridge_channel->bridge, bridge_channel);
814         }
815
816         /* Wake suspended channel. */
817         ast_bridge_channel_lock(bridge_channel);
818         ast_cond_signal(&bridge_channel->cond);
819         ast_bridge_channel_unlock(bridge_channel);
820 }
821
822 /*!
823  * \internal
824  * \brief Unsuspend a channel from a bridge.
825  *
826  * \param bridge_channel Channel to unsuspend.
827  *
828  * \return Nothing
829  */
830 static void bridge_channel_unsuspend(struct ast_bridge_channel *bridge_channel)
831 {
832         ast_bridge_channel_lock_bridge(bridge_channel);
833         bridge_channel_internal_unsuspend_nolock(bridge_channel);
834         ast_bridge_unlock(bridge_channel->bridge);
835 }
836
837 /*!
838  * \internal
839  * \brief Queue an action frame onto the bridge channel with data.
840  * \since 12.0.0
841  *
842  * \param bridge_channel Which channel to queue the frame onto.
843  * \param action Type of bridge action frame.
844  * \param data Frame payload data to pass.
845  * \param datalen Frame payload data length to pass.
846  *
847  * \retval 0 on success.
848  * \retval -1 on error.
849  */
850 static int bridge_channel_queue_action_data(struct ast_bridge_channel *bridge_channel,
851         enum bridge_channel_action_type action, const void *data, size_t datalen)
852 {
853         struct ast_frame frame = {
854                 .frametype = AST_FRAME_BRIDGE_ACTION,
855                 .subclass.integer = action,
856                 .datalen = datalen,
857                 .data.ptr = (void *) data,
858         };
859
860         return ast_bridge_channel_queue_frame(bridge_channel, &frame);
861 }
862
863 /*!
864  * \internal
865  * \brief Queue an action frame onto the bridge channel with data synchronously.
866  * \since 12.2.0
867  *
868  * The function will not return until the queued frame is freed.
869  *
870  * \param bridge_channel Which channel to queue the frame onto.
871  * \param action Type of bridge action frame.
872  * \param data Frame payload data to pass.
873  * \param datalen Frame payload data length to pass.
874  *
875  * \retval 0 on success.
876  * \retval -1 on error.
877  */
878 static int bridge_channel_queue_action_data_sync(struct ast_bridge_channel *bridge_channel,
879         enum bridge_channel_action_type action, const void *data, size_t datalen)
880 {
881         struct sync_payload *sync_payload;
882         int sync_payload_len = sizeof(*sync_payload) + datalen;
883         struct bridge_sync sync_struct;
884         struct ast_frame frame = {
885                 .frametype = AST_FRAME_BRIDGE_ACTION_SYNC,
886                 .subclass.integer = action,
887         };
888
889         /* Make sure we don't end up trying to wait on ourself to deliver the frame */
890         ast_assert(!pthread_equal(pthread_self(), bridge_channel->thread));
891
892         sync_payload = ast_alloca(sync_payload_len);
893         sync_payload->id = ast_atomic_fetchadd_int(&sync_ids, +1);
894         memcpy(sync_payload->data, data, datalen);
895
896         frame.datalen = sync_payload_len;
897         frame.data.ptr = sync_payload;
898
899         bridge_sync_init(&sync_struct, sync_payload->id);
900         if (ast_bridge_channel_queue_frame(bridge_channel, &frame)) {
901                 bridge_sync_cleanup(&sync_struct);
902                 return -1;
903         }
904
905         bridge_sync_wait(&sync_struct);
906         bridge_sync_cleanup(&sync_struct);
907         return 0;
908 }
909 /*!
910  * \internal
911  * \brief Write an action frame onto the bridge channel with data.
912  * \since 12.0.0
913  *
914  * \param bridge_channel Which channel to queue the frame onto.
915  * \param action Type of bridge action frame.
916  * \param data Frame payload data to pass.
917  * \param datalen Frame payload data length to pass.
918  *
919  * \retval 0 on success.
920  * \retval -1 on error.
921  */
922 static int bridge_channel_write_action_data(struct ast_bridge_channel *bridge_channel,
923         enum bridge_channel_action_type action, const void *data, size_t datalen)
924 {
925         struct ast_frame frame = {
926                 .frametype = AST_FRAME_BRIDGE_ACTION,
927                 .subclass.integer = action,
928                 .datalen = datalen,
929                 .data.ptr = (void *) data,
930         };
931
932         return bridge_channel_write_frame(bridge_channel, &frame);
933 }
934
935 static void bridge_frame_free(struct ast_frame *frame)
936 {
937         if (frame->frametype == AST_FRAME_BRIDGE_ACTION_SYNC) {
938                 struct sync_payload *sync_payload = frame->data.ptr;
939                 struct bridge_sync *sync;
940
941                 AST_RWLIST_RDLOCK(&sync_structs);
942                 AST_RWLIST_TRAVERSE(&sync_structs, sync, list) {
943                         if (sync->id == sync_payload->id) {
944                                 break;
945                         }
946                 }
947                 if (sync) {
948                         bridge_sync_signal(sync);
949                 }
950                 AST_RWLIST_UNLOCK(&sync_structs);
951         }
952
953         ast_frfree(frame);
954 }
955
956 int ast_bridge_channel_queue_frame(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
957 {
958         struct ast_frame *dup;
959
960         if (bridge_channel->suspended
961                 /* Also defer DTMF frames. */
962                 && fr->frametype != AST_FRAME_DTMF_BEGIN
963                 && fr->frametype != AST_FRAME_DTMF_END
964                 && !ast_is_deferrable_frame(fr)) {
965                 /* Drop non-deferable frames when suspended. */
966                 return 0;
967         }
968         if (fr->frametype == AST_FRAME_NULL) {
969                 /* "Accept" the frame and discard it. */
970                 return 0;
971         }
972
973         dup = ast_frdup(fr);
974         if (!dup) {
975                 return -1;
976         }
977
978         ast_bridge_channel_lock(bridge_channel);
979         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
980                 /* Drop frames on channels leaving the bridge. */
981                 ast_bridge_channel_unlock(bridge_channel);
982                 bridge_frame_free(dup);
983                 return 0;
984         }
985
986         if (ast_channel_is_multistream(bridge_channel->chan) &&
987             (fr->frametype == AST_FRAME_IMAGE || fr->frametype == AST_FRAME_TEXT ||
988              fr->frametype == AST_FRAME_VIDEO || fr->frametype == AST_FRAME_VOICE)) {
989                 /* Media frames need to be mapped to an appropriate write stream */
990                 dup->stream_num = AST_VECTOR_GET(
991                         &bridge_channel->stream_map.to_bridge, fr->stream_num);
992                 if (dup->stream_num == -1) {
993                         ast_bridge_channel_unlock(bridge_channel);
994                         bridge_frame_free(dup);
995                         return 0;
996                 }
997         } else {
998                 dup->stream_num = -1;
999         }
1000
1001         AST_LIST_INSERT_TAIL(&bridge_channel->wr_queue, dup, frame_list);
1002         if (ast_alertpipe_write(bridge_channel->alert_pipe)) {
1003                 ast_log(LOG_ERROR, "We couldn't write alert pipe for %p(%s)... something is VERY wrong\n",
1004                         bridge_channel, ast_channel_name(bridge_channel->chan));
1005         }
1006         ast_bridge_channel_unlock(bridge_channel);
1007         return 0;
1008 }
1009
1010 int ast_bridge_queue_everyone_else(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
1011 {
1012         struct ast_bridge_channel *cur;
1013         int not_written = -1;
1014
1015         if (frame->frametype == AST_FRAME_NULL) {
1016                 /* "Accept" the frame and discard it. */
1017                 return 0;
1018         }
1019
1020         AST_LIST_TRAVERSE(&bridge->channels, cur, entry) {
1021                 if (cur == bridge_channel) {
1022                         continue;
1023                 }
1024                 if (!ast_bridge_channel_queue_frame(cur, frame)) {
1025                         not_written = 0;
1026                 }
1027         }
1028         return not_written;
1029 }
1030
1031 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)
1032 {
1033         struct ast_frame frame = {
1034                 .frametype = AST_FRAME_CONTROL,
1035                 .subclass.integer = control,
1036                 .datalen = datalen,
1037                 .data.ptr = (void *) data,
1038         };
1039
1040         return ast_bridge_channel_queue_frame(bridge_channel, &frame);
1041 }
1042
1043 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)
1044 {
1045         struct ast_frame frame = {
1046                 .frametype = AST_FRAME_CONTROL,
1047                 .subclass.integer = control,
1048                 .datalen = datalen,
1049                 .data.ptr = (void *) data,
1050         };
1051
1052         return bridge_channel_write_frame(bridge_channel, &frame);
1053 }
1054
1055 int ast_bridge_channel_write_hold(struct ast_bridge_channel *bridge_channel, const char *moh_class)
1056 {
1057         struct ast_json *blob;
1058         int res;
1059         size_t datalen;
1060
1061         if (!ast_strlen_zero(moh_class)) {
1062                 datalen = strlen(moh_class) + 1;
1063
1064                 blob = ast_json_pack("{s: s}",
1065                         "musicclass", moh_class);
1066         } else {
1067                 moh_class = NULL;
1068                 datalen = 0;
1069                 blob = NULL;
1070         }
1071
1072         ast_channel_publish_cached_blob(bridge_channel->chan, ast_channel_hold_type(), blob);
1073
1074         res = ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_HOLD,
1075                 moh_class, datalen);
1076
1077         ast_json_unref(blob);
1078         return res;
1079 }
1080
1081 int ast_bridge_channel_write_unhold(struct ast_bridge_channel *bridge_channel)
1082 {
1083         ast_channel_publish_cached_blob(bridge_channel->chan, ast_channel_unhold_type(), NULL);
1084
1085         return ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_UNHOLD, NULL, 0);
1086 }
1087
1088 /*!
1089  * \internal
1090  * \brief Helper function to kick off a PBX app on a bridge_channel
1091  */
1092 static int run_app_helper(struct ast_channel *chan, const char *app_name, const char *app_args)
1093 {
1094         int res = 0;
1095
1096         if (!strcasecmp("Gosub", app_name)) {
1097                 ast_app_exec_sub(NULL, chan, app_args, 0);
1098         } else if (!strcasecmp("Macro", app_name)) {
1099                 ast_app_exec_macro(NULL, chan, app_args);
1100         } else {
1101                 struct ast_app *app;
1102
1103                 app = pbx_findapp(app_name);
1104                 if (!app) {
1105                         ast_log(LOG_WARNING, "Could not find application (%s)\n", app_name);
1106                 } else {
1107                         struct ast_str *substituted_args = ast_str_create(16);
1108
1109                         if (substituted_args) {
1110                                 ast_str_substitute_variables(&substituted_args, 0, chan, app_args);
1111                                 res = pbx_exec(chan, app, ast_str_buffer(substituted_args));
1112                                 ast_free(substituted_args);
1113                         } else {
1114                                 ast_log(LOG_WARNING, "Could not substitute application argument variables for %s\n", app_name);
1115                                 res = pbx_exec(chan, app, app_args);
1116                         }
1117                 }
1118         }
1119         return res;
1120 }
1121
1122 void ast_bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1123 {
1124         if (moh_class) {
1125                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
1126         }
1127         if (run_app_helper(bridge_channel->chan, app_name, S_OR(app_args, ""))) {
1128                 /* Break the bridge if the app returns non-zero. */
1129                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1130         }
1131         if (moh_class) {
1132                 ast_bridge_channel_write_unhold(bridge_channel);
1133         }
1134 }
1135
1136 struct bridge_run_app {
1137         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
1138         int moh_offset;
1139         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
1140         int app_args_offset;
1141         /*! Application name to run. */
1142         char app_name[0];
1143 };
1144
1145 /*!
1146  * \internal
1147  * \brief Handle the run application bridge action.
1148  * \since 12.0.0
1149  *
1150  * \param bridge_channel Which channel to run the application on.
1151  * \param data Action frame data to run the application.
1152  *
1153  * \return Nothing
1154  */
1155 static void bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, struct bridge_run_app *data)
1156 {
1157         ast_bridge_channel_run_app(bridge_channel, data->app_name,
1158                 data->app_args_offset ? &data->app_name[data->app_args_offset] : NULL,
1159                 data->moh_offset ? &data->app_name[data->moh_offset] : NULL);
1160 }
1161
1162 /*!
1163  * \internal
1164  * \brief Marshal an application to be executed on a bridge_channel
1165  */
1166 static int payload_helper_app(ast_bridge_channel_post_action_data post_it,
1167         struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1168 {
1169         struct bridge_run_app *app_data;
1170         size_t len_name = strlen(app_name) + 1;
1171         size_t len_args = ast_strlen_zero(app_args) ? 0 : strlen(app_args) + 1;
1172         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
1173         size_t len_data = sizeof(*app_data) + len_name + len_args + len_moh;
1174
1175         /* Fill in application run frame data. */
1176         app_data = alloca(len_data);
1177         app_data->app_args_offset = len_args ? len_name : 0;
1178         app_data->moh_offset = len_moh ? len_name + len_args : 0;
1179         strcpy(app_data->app_name, app_name);/* Safe */
1180         if (len_args) {
1181                 strcpy(&app_data->app_name[app_data->app_args_offset], app_args);/* Safe */
1182         }
1183         if (moh_class) {
1184                 strcpy(&app_data->app_name[app_data->moh_offset], moh_class);/* Safe */
1185         }
1186
1187         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_RUN_APP, app_data, len_data);
1188 }
1189
1190 int ast_bridge_channel_write_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1191 {
1192         return payload_helper_app(bridge_channel_write_action_data,
1193                 bridge_channel, app_name, app_args, moh_class);
1194 }
1195
1196 int ast_bridge_channel_queue_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1197 {
1198         return payload_helper_app(bridge_channel_queue_action_data,
1199                 bridge_channel, app_name, app_args, moh_class);
1200 }
1201
1202 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)
1203 {
1204         if (moh_class) {
1205                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
1206         }
1207         if (custom_play) {
1208                 custom_play(bridge_channel, playfile);
1209         } else {
1210                 ast_stream_and_wait(bridge_channel->chan, playfile, AST_DIGIT_NONE);
1211         }
1212         if (moh_class) {
1213                 ast_bridge_channel_write_unhold(bridge_channel);
1214         }
1215
1216         /*
1217          * It may be necessary to resume music on hold after we finish
1218          * playing the announcment.
1219          */
1220         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_MOH)) {
1221                 const char *latest_musicclass;
1222
1223                 ast_channel_lock(bridge_channel->chan);
1224                 latest_musicclass = ast_strdupa(ast_channel_latest_musicclass(bridge_channel->chan));
1225                 ast_channel_unlock(bridge_channel->chan);
1226                 ast_moh_start(bridge_channel->chan, latest_musicclass, NULL);
1227         }
1228 }
1229
1230 struct bridge_playfile {
1231         /*! Call this function to play the playfile. (NULL if normal sound file to play) */
1232         ast_bridge_custom_play_fn custom_play;
1233         /*! Offset into playfile[] where the MOH class name starts.  (zero if no MOH)*/
1234         int moh_offset;
1235         /*! Filename to play. */
1236         char playfile[0];
1237 };
1238
1239 /*!
1240  * \internal
1241  * \brief Handle the playfile bridge action.
1242  * \since 12.0.0
1243  *
1244  * \param bridge_channel Which channel to play a file on.
1245  * \param payload Action frame payload to play a file.
1246  *
1247  * \return Nothing
1248  */
1249 static void bridge_channel_playfile(struct ast_bridge_channel *bridge_channel, struct bridge_playfile *payload)
1250 {
1251         ast_bridge_channel_playfile(bridge_channel, payload->custom_play, payload->playfile,
1252                 payload->moh_offset ? &payload->playfile[payload->moh_offset] : NULL);
1253 }
1254
1255 /*!
1256  * \internal
1257  * \brief Marshal a file to be played on a bridge_channel
1258  */
1259 static int payload_helper_playfile(ast_bridge_channel_post_action_data post_it,
1260         struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
1261 {
1262         struct bridge_playfile *payload;
1263         size_t len_name = strlen(playfile) + 1;
1264         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
1265         size_t len_payload = sizeof(*payload) + len_name + len_moh;
1266
1267         /* Fill in play file frame data. */
1268         payload = ast_alloca(len_payload);
1269         payload->custom_play = custom_play;
1270         payload->moh_offset = len_moh ? len_name : 0;
1271         strcpy(payload->playfile, playfile);/* Safe */
1272         if (moh_class) {
1273                 strcpy(&payload->playfile[payload->moh_offset], moh_class);/* Safe */
1274         }
1275
1276         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_PLAY_FILE, payload, len_payload);
1277 }
1278
1279 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)
1280 {
1281         return payload_helper_playfile(bridge_channel_write_action_data,
1282                 bridge_channel, custom_play, playfile, moh_class);
1283 }
1284
1285 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)
1286 {
1287         return payload_helper_playfile(bridge_channel_queue_action_data,
1288                 bridge_channel, custom_play, playfile, moh_class);
1289 }
1290
1291 int ast_bridge_channel_queue_playfile_sync(struct ast_bridge_channel *bridge_channel,
1292                 ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
1293 {
1294         return payload_helper_playfile(bridge_channel_queue_action_data_sync,
1295                 bridge_channel, custom_play, playfile, moh_class);
1296 }
1297
1298 struct bridge_custom_callback {
1299         /*! Call this function on the bridge channel thread. */
1300         ast_bridge_custom_callback_fn callback;
1301         /*! Size of the payload if it exists.  A number otherwise. */
1302         size_t payload_size;
1303         /*! Option flags determining how callback is called. */
1304         unsigned int flags;
1305         /*! Nonzero if the payload exists. */
1306         char payload_exists;
1307         /*! Payload to give to callback. */
1308         char payload[0];
1309 };
1310
1311 /*!
1312  * \internal
1313  * \brief Handle the do custom callback bridge action.
1314  * \since 12.0.0
1315  *
1316  * \param bridge_channel Which channel to call the callback on.
1317  * \param data Action frame data to call the callback.
1318  *
1319  * \return Nothing
1320  */
1321 static void bridge_channel_do_callback(struct ast_bridge_channel *bridge_channel, struct bridge_custom_callback *data)
1322 {
1323         if (ast_test_flag(data, AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA)) {
1324                 bridge_channel_suspend(bridge_channel);
1325                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1326         }
1327         data->callback(bridge_channel, data->payload_exists ? data->payload : NULL, data->payload_size);
1328         if (ast_test_flag(data, AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA)) {
1329                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1330                 bridge_channel_unsuspend(bridge_channel);
1331         }
1332 }
1333
1334 /*!
1335  * \internal
1336  * \brief Marshal a custom callback function to be called on a bridge_channel
1337  */
1338 static int payload_helper_cb(ast_bridge_channel_post_action_data post_it,
1339         struct ast_bridge_channel *bridge_channel,
1340         enum ast_bridge_channel_custom_callback_option flags,
1341         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1342 {
1343         struct bridge_custom_callback *cb_data;
1344         size_t len_data = sizeof(*cb_data) + (payload ? payload_size : 0);
1345
1346         /* Sanity check. */
1347         if (!callback) {
1348                 ast_assert(0);
1349                 return -1;
1350         }
1351
1352         /* Fill in custom callback frame data. */
1353         cb_data = alloca(len_data);
1354         cb_data->callback = callback;
1355         cb_data->payload_size = payload_size;
1356         cb_data->flags = flags;
1357         cb_data->payload_exists = payload && payload_size;
1358         if (cb_data->payload_exists) {
1359                 memcpy(cb_data->payload, payload, payload_size);/* Safe */
1360         }
1361
1362         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_CALLBACK, cb_data, len_data);
1363 }
1364
1365 int ast_bridge_channel_write_callback(struct ast_bridge_channel *bridge_channel,
1366         enum ast_bridge_channel_custom_callback_option flags,
1367         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1368 {
1369         return payload_helper_cb(bridge_channel_write_action_data,
1370                 bridge_channel, flags, callback, payload, payload_size);
1371 }
1372
1373 int ast_bridge_channel_queue_callback(struct ast_bridge_channel *bridge_channel,
1374         enum ast_bridge_channel_custom_callback_option flags,
1375         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1376 {
1377         return payload_helper_cb(bridge_channel_queue_action_data,
1378                 bridge_channel, flags, callback, payload, payload_size);
1379 }
1380
1381 struct bridge_park {
1382         int parker_uuid_offset;
1383         int app_data_offset;
1384         /* buffer used for holding those strings */
1385         char parkee_uuid[0];
1386 };
1387
1388 /*!
1389  * \internal
1390  * \brief Park a bridge_cahnnel
1391  */
1392 static void bridge_channel_park(struct ast_bridge_channel *bridge_channel, struct bridge_park *payload)
1393 {
1394         if (!ast_parking_provider_registered()) {
1395                 ast_log(AST_LOG_WARNING, "Unable to park %s: No parking provider loaded!\n",
1396                         ast_channel_name(bridge_channel->chan));
1397                 return;
1398         }
1399
1400         if (ast_parking_park_bridge_channel(bridge_channel, payload->parkee_uuid,
1401                 &payload->parkee_uuid[payload->parker_uuid_offset],
1402                 payload->app_data_offset ? &payload->parkee_uuid[payload->app_data_offset] : NULL)) {
1403                 ast_log(AST_LOG_WARNING, "Error occurred while parking %s\n",
1404                         ast_channel_name(bridge_channel->chan));
1405         }
1406 }
1407
1408 /*!
1409  * \internal
1410  * \brief Marshal a park action onto a bridge_channel
1411  */
1412 static int payload_helper_park(ast_bridge_channel_post_action_data post_it,
1413         struct ast_bridge_channel *bridge_channel,
1414         const char *parkee_uuid,
1415         const char *parker_uuid,
1416         const char *app_data)
1417 {
1418         struct bridge_park *payload;
1419         size_t len_parkee_uuid = strlen(parkee_uuid) + 1;
1420         size_t len_parker_uuid = strlen(parker_uuid) + 1;
1421         size_t len_app_data = !app_data ? 0 : strlen(app_data) + 1;
1422         size_t len_payload = sizeof(*payload) + len_parker_uuid + len_parkee_uuid + len_app_data;
1423
1424         payload = alloca(len_payload);
1425         payload->app_data_offset = len_app_data ? len_parkee_uuid + len_parker_uuid : 0;
1426         payload->parker_uuid_offset = len_parkee_uuid;
1427         strcpy(payload->parkee_uuid, parkee_uuid);
1428         strcpy(&payload->parkee_uuid[payload->parker_uuid_offset], parker_uuid);
1429         if (app_data) {
1430                 strcpy(&payload->parkee_uuid[payload->app_data_offset], app_data);
1431         }
1432
1433         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_PARK, payload, len_payload);
1434 }
1435
1436 int ast_bridge_channel_write_park(struct ast_bridge_channel *bridge_channel, const char *parkee_uuid, const char *parker_uuid, const char *app_data)
1437 {
1438         return payload_helper_park(bridge_channel_write_action_data,
1439                 bridge_channel, parkee_uuid, parker_uuid, app_data);
1440 }
1441
1442 /*!
1443  * \internal
1444  * \brief Handle bridge channel interval expiration.
1445  * \since 12.0.0
1446  *
1447  * \param bridge_channel Channel to run expired intervals on.
1448  *
1449  * \return Nothing
1450  */
1451 static void bridge_channel_handle_interval(struct ast_bridge_channel *bridge_channel)
1452 {
1453         struct ast_heap *interval_hooks;
1454         struct ast_bridge_hook_timer *hook;
1455         struct timeval start;
1456         int chan_suspended = 0;
1457
1458         interval_hooks = bridge_channel->features->interval_hooks;
1459         ast_heap_wrlock(interval_hooks);
1460         start = ast_tvnow();
1461         while ((hook = ast_heap_peek(interval_hooks, 1))) {
1462                 int interval;
1463                 unsigned int execution_time;
1464
1465                 if (ast_tvdiff_ms(hook->timer.trip_time, start) > 0) {
1466                         ast_debug(1, "Hook %p on %p(%s) wants to happen in the future, stopping our traversal\n",
1467                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1468                         break;
1469                 }
1470                 ao2_ref(hook, +1);
1471                 ast_heap_unlock(interval_hooks);
1472
1473                 if (!chan_suspended
1474                         && ast_test_flag(&hook->timer, AST_BRIDGE_HOOK_TIMER_OPTION_MEDIA)) {
1475                         chan_suspended = 1;
1476                         bridge_channel_suspend(bridge_channel);
1477                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1478                 }
1479
1480                 ast_debug(1, "Executing hook %p on %p(%s)\n",
1481                         hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1482                 interval = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1483
1484                 ast_heap_wrlock(interval_hooks);
1485                 if (ast_heap_peek(interval_hooks, hook->timer.heap_index) != hook
1486                         || !ast_heap_remove(interval_hooks, hook)) {
1487                         /* Interval hook is already removed from the bridge_channel. */
1488                         ao2_ref(hook, -1);
1489                         continue;
1490                 }
1491                 ao2_ref(hook, -1);
1492
1493                 if (interval < 0) {
1494                         ast_debug(1, "Removed interval hook %p from %p(%s)\n",
1495                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1496                         ao2_ref(hook, -1);
1497                         continue;
1498                 }
1499                 if (interval) {
1500                         /* Set new interval for the hook. */
1501                         hook->timer.interval = interval;
1502                 }
1503
1504                 ast_debug(1, "Updating interval hook %p with interval %u on %p(%s)\n",
1505                         hook, hook->timer.interval, bridge_channel,
1506                         ast_channel_name(bridge_channel->chan));
1507
1508                 /* resetting start */
1509                 start = ast_tvnow();
1510
1511                 /*
1512                  * Resetup the interval hook for the next interval.  We may need
1513                  * to skip over any missed intervals because the hook was
1514                  * delayed or took too long.
1515                  */
1516                 execution_time = ast_tvdiff_ms(start, hook->timer.trip_time);
1517                 while (hook->timer.interval < execution_time) {
1518                         execution_time -= hook->timer.interval;
1519                 }
1520                 hook->timer.trip_time = ast_tvadd(start, ast_samp2tv(hook->timer.interval - execution_time, 1000));
1521                 hook->timer.seqno = ast_atomic_fetchadd_int((int *) &bridge_channel->features->interval_sequence, +1);
1522
1523                 if (ast_heap_push(interval_hooks, hook)) {
1524                         /* Could not push the hook back onto the heap. */
1525                         ao2_ref(hook, -1);
1526                 }
1527         }
1528         ast_heap_unlock(interval_hooks);
1529
1530         if (chan_suspended) {
1531                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1532                 bridge_channel_unsuspend(bridge_channel);
1533         }
1534 }
1535
1536 /*!
1537  * \internal
1538  * \brief Write a DTMF stream out to a channel
1539  */
1540 static int bridge_channel_write_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1541 {
1542         return bridge_channel_write_action_data(bridge_channel,
1543                 BRIDGE_CHANNEL_ACTION_DTMF_STREAM, dtmf, strlen(dtmf) + 1);
1544 }
1545
1546 /*!
1547  * \internal
1548  * \brief Indicate to the testsuite a feature was successfully detected.
1549  *
1550  * Currently, this function only will relay built-in features to the testsuite,
1551  * but it could be modified to detect applicationmap items should the need arise.
1552  *
1553  * \param chan The channel that activated the feature
1554  * \param dtmf The DTMF sequence entered to activate the feature
1555  */
1556 static void testsuite_notify_feature_success(struct ast_channel *chan, const char *dtmf)
1557 {
1558 #ifdef TEST_FRAMEWORK
1559         char *feature = "unknown";
1560         struct ast_featuremap_config *featuremap;
1561         struct ast_features_xfer_config *xfer;
1562
1563         ast_channel_lock(chan);
1564         featuremap = ast_get_chan_featuremap_config(chan);
1565         xfer = ast_get_chan_features_xfer_config(chan);
1566         ast_channel_unlock(chan);
1567
1568         if (featuremap) {
1569                 if (!strcmp(dtmf, featuremap->blindxfer)) {
1570                         feature = "blindxfer";
1571                 } else if (!strcmp(dtmf, featuremap->atxfer)) {
1572                         feature = "atxfer";
1573                 } else if (!strcmp(dtmf, featuremap->disconnect)) {
1574                         feature = "disconnect";
1575                 } else if (!strcmp(dtmf, featuremap->automon)) {
1576                         feature = "automon";
1577                 } else if (!strcmp(dtmf, featuremap->automixmon)) {
1578                         feature = "automixmon";
1579                 } else if (!strcmp(dtmf, featuremap->parkcall)) {
1580                         feature = "parkcall";
1581                 }
1582         }
1583         if (xfer) {
1584                 if (!strcmp(dtmf, xfer->atxferthreeway)) {
1585                         feature = "atxferthreeway";
1586                 }
1587         }
1588
1589         ao2_cleanup(featuremap);
1590         ao2_cleanup(xfer);
1591
1592         ast_test_suite_event_notify("FEATURE_DETECTION",
1593                         "Result: success\r\n"
1594                         "Feature: %s", feature);
1595 #endif /* TEST_FRAMEWORK */
1596 }
1597
1598 static int bridge_channel_feature_digit_add(
1599         struct ast_bridge_channel *bridge_channel, int digit, size_t dtmf_len)
1600 {
1601         if (dtmf_len < ARRAY_LEN(bridge_channel->dtmf_hook_state.collected) - 1) {
1602                 /* Add the new digit to the DTMF string so we can do our matching */
1603                 bridge_channel->dtmf_hook_state.collected[dtmf_len++] = digit;
1604                 bridge_channel->dtmf_hook_state.collected[dtmf_len] = '\0';
1605
1606                 ast_debug(1, "DTMF feature string on %p(%s) is now '%s'\n",
1607                           bridge_channel, ast_channel_name(bridge_channel->chan),
1608                           bridge_channel->dtmf_hook_state.collected);
1609         }
1610
1611         return dtmf_len;
1612 }
1613
1614 static unsigned int bridge_channel_feature_digit_timeout(struct ast_bridge_channel *bridge_channel)
1615 {
1616         unsigned int digit_timeout;
1617         struct ast_features_general_config *gen_cfg;
1618
1619         /* Determine interdigit timeout */
1620         ast_channel_lock(bridge_channel->chan);
1621         gen_cfg = ast_get_chan_features_general_config(bridge_channel->chan);
1622         ast_channel_unlock(bridge_channel->chan);
1623
1624         if (!gen_cfg) {
1625                 ast_log(LOG_ERROR, "Unable to retrieve features configuration.\n");
1626                 return 3000; /* Pick a reasonable failsafe timeout in ms */
1627         }
1628
1629         digit_timeout = gen_cfg->featuredigittimeout;
1630         ao2_ref(gen_cfg, -1);
1631
1632         return digit_timeout;
1633 }
1634
1635 void ast_bridge_channel_feature_digit_add(struct ast_bridge_channel *bridge_channel, int digit)
1636 {
1637         if (digit) {
1638                 bridge_channel_feature_digit_add(
1639                         bridge_channel, digit, strlen(bridge_channel->dtmf_hook_state.collected));
1640         }
1641 }
1642
1643 void ast_bridge_channel_feature_digit(struct ast_bridge_channel *bridge_channel, int digit)
1644 {
1645         struct ast_bridge_features *features = bridge_channel->features;
1646         struct ast_bridge_hook_dtmf *hook = NULL;
1647         size_t dtmf_len;
1648
1649         struct sanity_check_of_dtmf_size {
1650                 char check[1 / (ARRAY_LEN(bridge_channel->dtmf_hook_state.collected) == ARRAY_LEN(hook->dtmf.code))];
1651         };
1652
1653         dtmf_len = strlen(bridge_channel->dtmf_hook_state.collected);
1654         if (!dtmf_len && !digit) {
1655                 /* Nothing to do */
1656                 return;
1657         }
1658
1659         if (digit) {
1660                 dtmf_len = bridge_channel_feature_digit_add(bridge_channel, digit, dtmf_len);
1661         }
1662
1663         while (digit) {
1664                 /* See if a DTMF feature hook matches or can match */
1665                 hook = ao2_find(features->dtmf_hooks, bridge_channel->dtmf_hook_state.collected,
1666                         OBJ_SEARCH_PARTIAL_KEY);
1667                 if (!hook) {
1668                         ast_debug(1, "No DTMF feature hooks on %p(%s) match '%s'\n",
1669                                 bridge_channel, ast_channel_name(bridge_channel->chan),
1670                                 bridge_channel->dtmf_hook_state.collected);
1671                         break;
1672                 } else if (dtmf_len != strlen(hook->dtmf.code)) {
1673                         unsigned int digit_timeout;
1674                         /* Need more digits to match */
1675                         ao2_ref(hook, -1);
1676                         digit_timeout = bridge_channel_feature_digit_timeout(bridge_channel);
1677                         bridge_channel->dtmf_hook_state.interdigit_timeout =
1678                                 ast_tvadd(ast_tvnow(), ast_samp2tv(digit_timeout, 1000));
1679                         return;
1680                 } else {
1681                         int remove_me;
1682                         int already_suspended;
1683
1684                         ast_debug(1, "DTMF feature hook %p matched DTMF string '%s' on %p(%s)\n",
1685                                 hook, bridge_channel->dtmf_hook_state.collected, bridge_channel,
1686                                 ast_channel_name(bridge_channel->chan));
1687
1688                         /*
1689                          * Clear the collected digits before executing the hook
1690                          * in case the hook starts another sequence.
1691                          */
1692                         bridge_channel->dtmf_hook_state.collected[0] = '\0';
1693
1694                         ast_bridge_channel_lock_bridge(bridge_channel);
1695                         already_suspended = bridge_channel->suspended;
1696                         if (!already_suspended) {
1697                                 bridge_channel_internal_suspend_nolock(bridge_channel);
1698                         }
1699                         ast_bridge_unlock(bridge_channel->bridge);
1700                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1701
1702                         /* Execute the matched hook on this channel. */
1703                         remove_me = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1704                         if (remove_me) {
1705                                 ast_debug(1, "DTMF hook %p is being removed from %p(%s)\n",
1706                                         hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1707                                 ao2_unlink(features->dtmf_hooks, hook);
1708                         }
1709                         testsuite_notify_feature_success(bridge_channel->chan, hook->dtmf.code);
1710                         ao2_ref(hook, -1);
1711
1712                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1713                         if (!already_suspended) {
1714                                 bridge_channel_unsuspend(bridge_channel);
1715                         }
1716
1717                         /*
1718                          * If we are handing the channel off to an external hook for
1719                          * ownership, we are not guaranteed what kind of state it will
1720                          * come back in.  If the channel hungup, we need to detect that
1721                          * here if the hook did not already change the state.
1722                          */
1723                         if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
1724                                 ast_bridge_channel_kick(bridge_channel, 0);
1725                                 bridge_channel->dtmf_hook_state.collected[0] = '\0';
1726                                 return;
1727                         }
1728
1729                         /* if there is dtmf that has been collected then loop back through,
1730                            but set digit to -1 so it doesn't try to do an add since the dtmf
1731                            is already in the buffer */
1732                         dtmf_len = strlen(bridge_channel->dtmf_hook_state.collected);
1733                         if (!dtmf_len) {
1734                                 return;
1735                         }
1736                 }
1737         }
1738
1739         if (!digit) {
1740                 ast_debug(1, "DTMF feature string collection on %p(%s) timed out\n",
1741                         bridge_channel, ast_channel_name(bridge_channel->chan));
1742         }
1743
1744         /* Timeout or DTMF digit didn't allow a match with any hooks. */
1745         if (features->dtmf_passthrough) {
1746                 /* Stream the collected DTMF to the other channels. */
1747                 bridge_channel_write_dtmf_stream(bridge_channel,
1748                         bridge_channel->dtmf_hook_state.collected);
1749         }
1750         bridge_channel->dtmf_hook_state.collected[0] = '\0';
1751
1752         ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
1753 }
1754
1755 /*!
1756  * \internal
1757  * \brief Handle bridge channel DTMF feature timeout expiration.
1758  * \since 12.8.0
1759  *
1760  * \param bridge_channel Channel to check expired interdigit timer on.
1761  *
1762  * \return Nothing
1763  */
1764 static void bridge_channel_handle_feature_timeout(struct ast_bridge_channel *bridge_channel)
1765 {
1766         if (!bridge_channel->dtmf_hook_state.collected[0]
1767                 || 0 < ast_tvdiff_ms(bridge_channel->dtmf_hook_state.interdigit_timeout,
1768                         ast_tvnow())) {
1769                 /* Not within a sequence or not timed out. */
1770                 return;
1771         }
1772
1773         ast_bridge_channel_feature_digit(bridge_channel, 0);
1774 }
1775
1776 /*!
1777  * \internal
1778  * \brief Indicate that a bridge_channel is talking
1779  */
1780 static void bridge_channel_talking(struct ast_bridge_channel *bridge_channel, int talking)
1781 {
1782         struct ast_bridge_features *features = bridge_channel->features;
1783         struct ast_bridge_hook *hook;
1784         struct ao2_iterator iter;
1785
1786         /* Run any talk detection hooks. */
1787         iter = ao2_iterator_init(features->other_hooks, 0);
1788         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1789                 int remove_me;
1790                 ast_bridge_talking_indicate_callback talk_cb;
1791
1792                 if (hook->type != AST_BRIDGE_HOOK_TYPE_TALK) {
1793                         continue;
1794                 }
1795                 talk_cb = (ast_bridge_talking_indicate_callback) hook->callback;
1796                 remove_me = talk_cb(bridge_channel, hook->hook_pvt, talking);
1797                 if (remove_me) {
1798                         ast_debug(1, "Talk detection hook %p is being removed from %p(%s)\n",
1799                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1800                         ao2_unlink(features->other_hooks, hook);
1801                 }
1802         }
1803         ao2_iterator_destroy(&iter);
1804 }
1805
1806 /*! \brief Internal function that plays back DTMF on a bridge channel */
1807 static void bridge_channel_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1808 {
1809         ast_debug(1, "Playing DTMF stream '%s' out to %p(%s)\n",
1810                 dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
1811         ast_dtmf_stream(bridge_channel->chan, NULL, dtmf, 0, 0);
1812 }
1813
1814 /*! \brief Data specifying where a blind transfer is going to */
1815 struct blind_transfer_data {
1816         char exten[AST_MAX_EXTENSION];
1817         char context[AST_MAX_CONTEXT];
1818 };
1819
1820 /*!
1821  * \internal
1822  * \brief Execute after bridge actions on a channel when it leaves a bridge
1823  */
1824 static void after_bridge_move_channel(struct ast_channel *chan_bridged, void *data)
1825 {
1826         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1827         struct ast_party_connected_line connected_target;
1828         unsigned char connected_line_data[1024];
1829         int payload_size;
1830
1831         ast_party_connected_line_init(&connected_target);
1832
1833         ast_channel_lock(chan_target);
1834         ast_party_connected_line_copy(&connected_target, ast_channel_connected(chan_target));
1835         ast_channel_unlock(chan_target);
1836         ast_party_id_reset(&connected_target.priv);
1837
1838         if (ast_channel_move(chan_target, chan_bridged)) {
1839                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1840                 ast_party_connected_line_free(&connected_target);
1841                 return;
1842         }
1843
1844         /* The ast_channel_move function will end up updating the connected line information
1845          * on chan_target to the value we have here, but will not inform it. To ensure that
1846          * AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO is executed we wipe it away here. If
1847          * we don't do this then the change will be considered redundant, since the connected
1848          * line information is already there (despite the channel not being told).
1849          */
1850         ast_channel_lock(chan_target);
1851         ast_party_connected_line_free(ast_channel_connected_indicated(chan_target));
1852         ast_party_connected_line_init(ast_channel_connected_indicated(chan_target));
1853         ast_channel_unlock(chan_target);
1854
1855         if ((payload_size = ast_connected_line_build_data(connected_line_data,
1856                 sizeof(connected_line_data), &connected_target, NULL)) != -1) {
1857                 struct ast_control_read_action_payload *frame_payload;
1858                 int frame_size;
1859
1860                 frame_size = payload_size + sizeof(*frame_payload);
1861                 frame_payload = ast_alloca(frame_size);
1862                 frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
1863                 frame_payload->payload_size = payload_size;
1864                 memcpy(frame_payload->payload, connected_line_data, payload_size);
1865                 ast_queue_control_data(chan_target, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
1866         }
1867
1868         /* A connected line update is queued so that if chan_target is remotely involved with
1869          * anything (such as dialing a channel) the other channel(s) will be informed of the
1870          * new channel they are involved with.
1871          */
1872         ast_channel_lock(chan_target);
1873         ast_connected_line_copy_from_caller(&connected_target, ast_channel_caller(chan_target));
1874         ast_channel_queue_connected_line_update(chan_target, &connected_target, NULL);
1875         ast_channel_unlock(chan_target);
1876
1877         ast_party_connected_line_free(&connected_target);
1878 }
1879
1880 /*!
1881  * \internal
1882  * \brief Execute logic to cleanup when after bridge fails
1883  */
1884 static void after_bridge_move_channel_fail(enum ast_bridge_after_cb_reason reason, void *data)
1885 {
1886         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1887
1888         ast_log(LOG_WARNING, "Unable to complete transfer: %s\n",
1889                 ast_bridge_after_cb_reason_string(reason));
1890         ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1891 }
1892
1893 /*!
1894  * \internal
1895  * \brief Perform a blind transfer on a channel in a bridge
1896  */
1897 static void bridge_channel_blind_transfer(struct ast_bridge_channel *bridge_channel,
1898                 struct blind_transfer_data *blind_data)
1899 {
1900         ast_async_goto(bridge_channel->chan, blind_data->context, blind_data->exten, 1);
1901         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1902 }
1903
1904 /*!
1905  * \internal
1906  * \brief Perform an attended transfer on a channel in a bridge
1907  */
1908 static void bridge_channel_attended_transfer(struct ast_bridge_channel *bridge_channel,
1909                 const char *target_chan_name)
1910 {
1911         RAII_VAR(struct ast_channel *, chan_target, NULL, ao2_cleanup);
1912         RAII_VAR(struct ast_channel *, chan_bridged, NULL, ao2_cleanup);
1913
1914         chan_target = ast_channel_get_by_name(target_chan_name);
1915         if (!chan_target) {
1916                 /* Dang, it disappeared somehow */
1917                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1918                 return;
1919         }
1920
1921         ast_bridge_channel_lock(bridge_channel);
1922         chan_bridged = bridge_channel->chan;
1923         ast_assert(chan_bridged != NULL);
1924         ao2_ref(chan_bridged, +1);
1925         ast_bridge_channel_unlock(bridge_channel);
1926
1927         if (ast_bridge_set_after_callback(chan_bridged, after_bridge_move_channel,
1928                 after_bridge_move_channel_fail, ast_channel_ref(chan_target))) {
1929                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1930
1931                 /* Release the ref we tried to pass to ast_bridge_set_after_callback(). */
1932                 ast_channel_unref(chan_target);
1933         }
1934         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1935 }
1936
1937 /*!
1938  * \internal
1939  * \brief Handle bridge channel bridge action frame.
1940  * \since 12.0.0
1941  *
1942  * \param bridge_channel Channel to execute the action on.
1943  * \param action What to do.
1944  * \param data data from the action.
1945  *
1946  * \return Nothing
1947  */
1948 static void bridge_channel_handle_action(struct ast_bridge_channel *bridge_channel,
1949         enum bridge_channel_action_type action, void *data)
1950 {
1951         switch (action) {
1952         case BRIDGE_CHANNEL_ACTION_DTMF_STREAM:
1953                 bridge_channel_suspend(bridge_channel);
1954                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1955                 bridge_channel_dtmf_stream(bridge_channel, data);
1956                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1957                 bridge_channel_unsuspend(bridge_channel);
1958                 break;
1959         case BRIDGE_CHANNEL_ACTION_TALKING_START:
1960         case BRIDGE_CHANNEL_ACTION_TALKING_STOP:
1961                 bridge_channel_talking(bridge_channel,
1962                         action == BRIDGE_CHANNEL_ACTION_TALKING_START);
1963                 break;
1964         case BRIDGE_CHANNEL_ACTION_PLAY_FILE:
1965                 bridge_channel_suspend(bridge_channel);
1966                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1967                 bridge_channel_playfile(bridge_channel, data);
1968                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1969                 bridge_channel_unsuspend(bridge_channel);
1970                 break;
1971         case BRIDGE_CHANNEL_ACTION_RUN_APP:
1972                 bridge_channel_suspend(bridge_channel);
1973                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1974                 bridge_channel_run_app(bridge_channel, data);
1975                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1976                 bridge_channel_unsuspend(bridge_channel);
1977                 break;
1978         case BRIDGE_CHANNEL_ACTION_CALLBACK:
1979                 bridge_channel_do_callback(bridge_channel, data);
1980                 break;
1981         case BRIDGE_CHANNEL_ACTION_PARK:
1982                 bridge_channel_suspend(bridge_channel);
1983                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1984                 bridge_channel_park(bridge_channel, data);
1985                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1986                 bridge_channel_unsuspend(bridge_channel);
1987                 break;
1988         case BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER:
1989                 bridge_channel_blind_transfer(bridge_channel, data);
1990                 break;
1991         case BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER:
1992                 bridge_channel_attended_transfer(bridge_channel, data);
1993                 break;
1994         default:
1995                 break;
1996         }
1997
1998         /* While invoking an action it is possible for the channel to be hung up. So
1999          * that the bridge respects this we check here and if hung up kick it out.
2000          */
2001         if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
2002                 ast_bridge_channel_kick(bridge_channel, 0);
2003         }
2004 }
2005
2006 /*!
2007  * \internal
2008  * \brief Check if a bridge should dissolve and do it.
2009  * \since 12.0.0
2010  *
2011  * \param bridge_channel Channel causing the check.
2012  *
2013  * \note On entry, bridge_channel->bridge is already locked.
2014  *
2015  * \return Nothing
2016  */
2017 static void bridge_channel_dissolve_check(struct ast_bridge_channel *bridge_channel)
2018 {
2019         struct ast_bridge *bridge = bridge_channel->bridge;
2020
2021         if (bridge->dissolved) {
2022                 return;
2023         }
2024
2025         if (!bridge->num_channels
2026                 && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY)) {
2027                 /* Last channel leaving the bridge turns off the lights. */
2028                 bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
2029                 return;
2030         }
2031
2032         switch (bridge_channel->state) {
2033         case BRIDGE_CHANNEL_STATE_END:
2034                 /* Do we need to dissolve the bridge because this channel hung up? */
2035                 if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_HANGUP)
2036                         || (bridge_channel->features->usable
2037                                 && ast_test_flag(&bridge_channel->features->feature_flags,
2038                                         AST_BRIDGE_CHANNEL_FLAG_DISSOLVE_HANGUP))) {
2039                         bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
2040                         return;
2041                 }
2042                 break;
2043         default:
2044                 break;
2045         }
2046
2047         if (bridge->num_lonely && bridge->num_lonely == bridge->num_channels) {
2048                 /*
2049                  * This will start a chain reaction where each channel leaving
2050                  * enters this function and causes the next to leave as long as
2051                  * there aren't non-lonely channels in the bridge.
2052                  */
2053                 ast_bridge_channel_leave_bridge(AST_LIST_FIRST(&bridge->channels),
2054                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE,
2055                         ast_channel_hangupcause(bridge_channel->chan));
2056         }
2057 }
2058
2059 void bridge_channel_internal_pull(struct ast_bridge_channel *bridge_channel)
2060 {
2061         struct ast_bridge *bridge = bridge_channel->bridge;
2062
2063         if (!bridge_channel->in_bridge) {
2064                 return;
2065         }
2066         bridge_channel->in_bridge = 0;
2067
2068         ast_debug(1, "Bridge %s: pulling %p(%s)\n",
2069                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
2070
2071         ast_verb(3, "Channel %s left '%s' %s-bridge <%s>\n",
2072                 ast_channel_name(bridge_channel->chan),
2073                 bridge->technology->name,
2074                 bridge->v_table->name,
2075                 bridge->uniqueid);
2076
2077         if (!bridge_channel->just_joined) {
2078                 /* Tell the bridge technology we are leaving so they tear us down */
2079                 ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology\n",
2080                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
2081                         bridge->technology->name);
2082                 if (bridge->technology->leave) {
2083                         bridge->technology->leave(bridge, bridge_channel);
2084                 }
2085         }
2086
2087         /* Remove channel from the bridge */
2088         if (!bridge_channel->suspended) {
2089                 --bridge->num_active;
2090         }
2091         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
2092                 --bridge->num_lonely;
2093         }
2094         --bridge->num_channels;
2095         AST_LIST_REMOVE(&bridge->channels, bridge_channel, entry);
2096
2097         bridge_channel_dissolve_check(bridge_channel);
2098         bridge->v_table->pull(bridge, bridge_channel);
2099
2100         ast_bridge_channel_clear_roles(bridge_channel);
2101
2102         /* If we are not going to be hung up after leaving a bridge, and we were an
2103          * outgoing channel, clear the outgoing flag.
2104          */
2105         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING)
2106             && (ast_channel_is_leaving_bridge(bridge_channel->chan)
2107                 || bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT)) {
2108                 ast_debug(2, "Channel %s will survive this bridge; clearing outgoing (dialed) flag\n", ast_channel_name(bridge_channel->chan));
2109                 ast_channel_clear_flag(bridge_channel->chan, AST_FLAG_OUTGOING);
2110         }
2111
2112         bridge->reconfigured = 1;
2113         ast_bridge_publish_leave(bridge, bridge_channel->chan);
2114 }
2115
2116 int bridge_channel_internal_push_full(struct ast_bridge_channel *bridge_channel, int optimized)
2117 {
2118         struct ast_bridge *bridge = bridge_channel->bridge;
2119         struct ast_bridge_channel *swap;
2120
2121         ast_assert(!bridge_channel->in_bridge);
2122
2123         swap = bridge_find_channel(bridge, bridge_channel->swap);
2124         bridge_channel->swap = NULL;
2125
2126         if (swap) {
2127                 ast_debug(1, "Bridge %s: pushing %p(%s) by swapping with %p(%s)\n",
2128                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
2129                         swap, ast_channel_name(swap->chan));
2130         } else {
2131                 ast_debug(1, "Bridge %s: pushing %p(%s)\n",
2132                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
2133         }
2134
2135         /* Add channel to the bridge */
2136         if (bridge->dissolved
2137                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
2138                 || (swap && swap->state != BRIDGE_CHANNEL_STATE_WAIT)
2139                 || bridge->v_table->push(bridge, bridge_channel, swap)) {
2140                 ast_debug(1, "Bridge %s: pushing %p(%s) into bridge failed\n",
2141                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
2142                 return -1;
2143         }
2144
2145         ast_bridge_channel_establish_roles(bridge_channel);
2146
2147         if (swap) {
2148                 int dissolve = ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY);
2149
2150                 /* This flag is cleared so the act of this channel leaving does not cause it to dissolve if need be */
2151                 ast_clear_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY);
2152
2153                 if (optimized) {
2154                         bridge_channel_cancel_owed_events(swap);
2155                 }
2156                 ast_bridge_channel_leave_bridge(swap, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, 0);
2157                 bridge_channel_internal_pull(swap);
2158
2159                 ast_set2_flag(&bridge->feature_flags, dissolve, AST_BRIDGE_FLAG_DISSOLVE_EMPTY);
2160         }
2161
2162         bridge_channel->in_bridge = 1;
2163         bridge_channel->just_joined = 1;
2164         AST_LIST_INSERT_TAIL(&bridge->channels, bridge_channel, entry);
2165         ++bridge->num_channels;
2166         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
2167                 ++bridge->num_lonely;
2168         }
2169         if (!bridge_channel->suspended) {
2170                 ++bridge->num_active;
2171         }
2172
2173         ast_verb(3, "Channel %s %s%s%s '%s' %s-bridge <%s>\n",
2174                 ast_channel_name(bridge_channel->chan),
2175                 swap ? "swapped with " : "joined",
2176                 swap ? ast_channel_name(swap->chan) : "",
2177                 swap ? " into" : "",
2178                 bridge->technology->name,
2179                 bridge->v_table->name,
2180                 bridge->uniqueid);
2181
2182         ast_bridge_publish_enter(bridge, bridge_channel->chan, swap ? swap->chan : NULL);
2183
2184         /* Clear any BLINDTRANSFER,ATTENDEDTRANSFER and FORWARDERNAME since the transfer has completed. */
2185         pbx_builtin_setvar_helper(bridge_channel->chan, "BLINDTRANSFER", NULL);
2186         pbx_builtin_setvar_helper(bridge_channel->chan, "ATTENDEDTRANSFER", NULL);
2187         pbx_builtin_setvar_helper(bridge_channel->chan, "FORWARDERNAME", NULL);
2188
2189         /* Wake up the bridge channel thread to reevaluate any interval timers. */
2190         ast_queue_frame(bridge_channel->chan, &ast_null_frame);
2191
2192         bridge->reconfigured = 1;
2193         return 0;
2194 }
2195
2196 int bridge_channel_internal_push(struct ast_bridge_channel *bridge_channel)
2197 {
2198         return bridge_channel_internal_push_full(bridge_channel, 0);
2199 }
2200
2201 /*!
2202  * \internal
2203  * \brief Handle bridge channel control frame action.
2204  * \since 12.0.0
2205  *
2206  * \param bridge_channel Channel to execute the control frame action on.
2207  * \param fr Control frame to handle.
2208  *
2209  * \return Nothing
2210  */
2211 static void bridge_channel_handle_control(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
2212 {
2213         struct ast_channel *chan;
2214         struct ast_option_header *aoh;
2215         int is_caller;
2216
2217         chan = bridge_channel->chan;
2218         switch (fr->subclass.integer) {
2219         case AST_CONTROL_REDIRECTING:
2220                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
2221                 if (ast_channel_redirecting_sub(NULL, chan, fr, 1) &&
2222                         ast_channel_redirecting_macro(NULL, chan, fr, is_caller, 1)) {
2223                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2224                 }
2225                 break;
2226         case AST_CONTROL_CONNECTED_LINE:
2227                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
2228                 if (ast_channel_connected_line_sub(NULL, chan, fr, 1) &&
2229                         ast_channel_connected_line_macro(NULL, chan, fr, is_caller, 1)) {
2230                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2231                 }
2232                 break;
2233         case AST_CONTROL_OPTION:
2234                 /*
2235                  * Forward option Requests, but only ones we know are safe These
2236                  * are ONLY sent by chan_iax2 and I'm not convinced that they
2237                  * are useful. I haven't deleted them entirely because I just am
2238                  * not sure of the ramifications of removing them.
2239                  */
2240                 aoh = fr->data.ptr;
2241                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
2242                         switch (ntohs(aoh->option)) {
2243                         case AST_OPTION_TONE_VERIFY:
2244                         case AST_OPTION_TDD:
2245                         case AST_OPTION_RELAXDTMF:
2246                         case AST_OPTION_AUDIO_MODE:
2247                         case AST_OPTION_DIGIT_DETECT:
2248                         case AST_OPTION_FAX_DETECT:
2249                                 ast_channel_setoption(chan, ntohs(aoh->option), aoh->data,
2250                                         fr->datalen - sizeof(*aoh), 0);
2251                                 break;
2252                         default:
2253                                 break;
2254                         }
2255                 }
2256                 break;
2257         case AST_CONTROL_ANSWER:
2258                 if (ast_channel_state(chan) != AST_STATE_UP) {
2259                         ast_answer(chan);
2260                 } else {
2261                         ast_indicate(chan, -1);
2262                 }
2263                 break;
2264         case AST_CONTROL_MASQUERADE_NOTIFY:
2265                 /* Should never happen. */
2266                 ast_assert(0);
2267                 break;
2268         case AST_CONTROL_STREAM_TOPOLOGY_CHANGED:
2269                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2270                 break;
2271         default:
2272                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2273                 break;
2274         }
2275 }
2276
2277 /*!
2278  * \internal
2279  * \brief Handle bridge channel write frame to channel.
2280  * \since 12.0.0
2281  *
2282  * \param bridge_channel Channel to write outgoing frame.
2283  *
2284  * \return Nothing
2285  */
2286 static void bridge_channel_handle_write(struct ast_bridge_channel *bridge_channel)
2287 {
2288         struct ast_frame *fr;
2289         struct sync_payload *sync_payload;
2290         int num;
2291
2292         ast_bridge_channel_lock(bridge_channel);
2293
2294         /* It's not good to have unbalanced frames and alert_pipe alerts. */
2295         ast_assert(!AST_LIST_EMPTY(&bridge_channel->wr_queue));
2296         if (AST_LIST_EMPTY(&bridge_channel->wr_queue)) {
2297                 /* No frame, flush the alert pipe of excess alerts. */
2298                 ast_log(LOG_WARNING, "Weird.  No frame from bridge for %s to process?\n",
2299                         ast_channel_name(bridge_channel->chan));
2300                 ast_alertpipe_read(bridge_channel->alert_pipe);
2301                 ast_bridge_channel_unlock(bridge_channel);
2302                 return;
2303         }
2304
2305         AST_LIST_TRAVERSE_SAFE_BEGIN(&bridge_channel->wr_queue, fr, frame_list) {
2306                 if (bridge_channel->dtmf_hook_state.collected[0]) {
2307                         switch (fr->frametype) {
2308                         case AST_FRAME_BRIDGE_ACTION:
2309                         case AST_FRAME_BRIDGE_ACTION_SYNC:
2310                                 /* Defer processing these frames while DTMF is collected. */
2311                                 continue;
2312                         default:
2313                                 break;
2314                         }
2315                 }
2316                 ast_alertpipe_read(bridge_channel->alert_pipe);
2317                 AST_LIST_REMOVE_CURRENT(frame_list);
2318                 break;
2319         }
2320         AST_LIST_TRAVERSE_SAFE_END;
2321
2322         ast_bridge_channel_unlock(bridge_channel);
2323         if (!fr) {
2324                 /*
2325                  * Wait some to reduce CPU usage from a tight loop
2326                  * without any wait because we only have deferred
2327                  * frames in the wr_queue.
2328                  */
2329                 usleep(1);
2330                 return;
2331         }
2332
2333         switch (fr->frametype) {
2334         case AST_FRAME_BRIDGE_ACTION:
2335                 bridge_channel_handle_action(bridge_channel, fr->subclass.integer, fr->data.ptr);
2336                 break;
2337         case AST_FRAME_BRIDGE_ACTION_SYNC:
2338                 sync_payload = fr->data.ptr;
2339                 bridge_channel_handle_action(bridge_channel, fr->subclass.integer, sync_payload->data);
2340                 break;
2341         case AST_FRAME_CONTROL:
2342                 bridge_channel_handle_control(bridge_channel, fr);
2343                 break;
2344         case AST_FRAME_NULL:
2345                 break;
2346         default:
2347                 if (fr->stream_num > 0 &&
2348                                 (fr->stream_num >= (int)AST_VECTOR_SIZE(&bridge_channel->stream_map.to_channel) ||
2349                                 AST_VECTOR_GET(&bridge_channel->stream_map.to_channel, fr->stream_num) == -1)) {
2350                         /* Nowhere to write to, so drop it */
2351                         break;
2352                 }
2353
2354                 /* Find what stream number to write to for the channel */
2355                 num = fr->stream_num < 0 ? -1 :
2356                         AST_VECTOR_GET(&bridge_channel->stream_map.to_channel, fr->stream_num);
2357
2358                 /* Write the frame to the channel. */
2359                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_SIMPLE;
2360                 ast_write_stream(bridge_channel->chan, num, fr);
2361                 break;
2362         }
2363         bridge_frame_free(fr);
2364 }
2365
2366 /*! \brief Internal function to handle DTMF from a channel */
2367 static struct ast_frame *bridge_handle_dtmf(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
2368 {
2369         struct ast_bridge_features *features = bridge_channel->features;
2370         struct ast_bridge_hook_dtmf *hook = NULL;
2371         char dtmf[2];
2372
2373         /*
2374          * See if we are already matching a DTMF feature hook sequence or
2375          * if this DTMF matches the beginning of any DTMF feature hooks.
2376          */
2377         dtmf[0] = frame->subclass.integer;
2378         dtmf[1] = '\0';
2379         if (bridge_channel->dtmf_hook_state.collected[0]
2380                 || (hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_SEARCH_PARTIAL_KEY))) {
2381                 enum ast_frame_type frametype = frame->frametype;
2382
2383                 bridge_frame_free(frame);
2384                 frame = NULL;
2385
2386                 ao2_cleanup(hook);
2387
2388                 switch (frametype) {
2389                 case AST_FRAME_DTMF_BEGIN:
2390                         /* Just eat the frame. */
2391                         break;
2392                 case AST_FRAME_DTMF_END:
2393                         ast_bridge_channel_feature_digit(bridge_channel, dtmf[0]);
2394                         break;
2395                 default:
2396                         /* Unexpected frame type. */
2397                         ast_assert(0);
2398                         break;
2399                 }
2400 #ifdef TEST_FRAMEWORK
2401         } else if (frame->frametype == AST_FRAME_DTMF_END) {
2402                 /* Only transmit this event on DTMF end or else every DTMF
2403                  * press will result in the event being broadcast twice
2404                  */
2405                 ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
2406 #endif
2407         }
2408
2409         return frame;
2410 }
2411
2412 static const char *controls[] = {
2413         [AST_CONTROL_RINGING] = "RINGING",
2414         [AST_CONTROL_PROCEEDING] = "PROCEEDING",
2415         [AST_CONTROL_PROGRESS] = "PROGRESS",
2416         [AST_CONTROL_BUSY] = "BUSY",
2417         [AST_CONTROL_CONGESTION] = "CONGESTION",
2418         [AST_CONTROL_ANSWER] = "ANSWER",
2419 };
2420
2421 /*!
2422  * \internal
2423  * \brief Feed notification that a frame is waiting on a channel into the bridging core
2424  *
2425  * \param bridge_channel Bridge channel the notification was received on
2426  */
2427 static void bridge_handle_trip(struct ast_bridge_channel *bridge_channel)
2428 {
2429         struct ast_frame *frame;
2430
2431         if (!ast_strlen_zero(ast_channel_call_forward(bridge_channel->chan))) {
2432                 /* TODO If early bridging is ever used by anything other than ARI,
2433                  * it's important that we actually attempt to handle the call forward
2434                  * attempt, as well as expand features on a bridge channel to allow/disallow
2435                  * call forwarding. For now, all we do is raise an event, showing that
2436                  * a call forward is being attempted.
2437                  */
2438                 ast_channel_publish_dial_forward(NULL, bridge_channel->chan, NULL, NULL, "CANCEL",
2439                         ast_channel_call_forward(bridge_channel->chan));
2440         }
2441
2442         if (bridge_channel->features->mute) {
2443                 frame = ast_read_noaudio(bridge_channel->chan);
2444         } else {
2445                 frame = ast_read(bridge_channel->chan);
2446         }
2447
2448         if (!frame) {
2449                 ast_bridge_channel_kick(bridge_channel, 0);
2450                 return;
2451         }
2452         switch (frame->frametype) {
2453         case AST_FRAME_CONTROL:
2454                 switch (frame->subclass.integer) {
2455                 case AST_CONTROL_CONGESTION:
2456                 case AST_CONTROL_BUSY:
2457                         ast_channel_publish_dial(NULL, bridge_channel->chan, NULL, controls[frame->subclass.integer]);
2458                         break;
2459                 case AST_CONTROL_HANGUP:
2460                         ast_bridge_channel_kick(bridge_channel, 0);
2461                         bridge_frame_free(frame);
2462                         return;
2463                 case AST_CONTROL_RINGING:
2464                 case AST_CONTROL_PROGRESS:
2465                 case AST_CONTROL_PROCEEDING:
2466                 case AST_CONTROL_ANSWER:
2467                         ast_channel_publish_dial(NULL, bridge_channel->chan, NULL, controls[frame->subclass.integer]);
2468                         break;
2469                 case AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE:
2470                         if (bridge_channel->bridge->technology->stream_topology_request_change &&
2471                             bridge_channel->bridge->technology->stream_topology_request_change(
2472                                     bridge_channel->bridge, bridge_channel)) {
2473                                 /* Topology change was denied so drop frame */
2474                                 bridge_frame_free(frame);
2475                                 return;
2476                         }
2477                         break;
2478                 case AST_CONTROL_STREAM_TOPOLOGY_CHANGED:
2479                         /*
2480                          * If a stream topology has changed then the bridge_channel's
2481                          * media mapping needs to be updated.
2482                          */
2483                         if (bridge_channel->bridge->technology->stream_topology_changed) {
2484                                 bridge_channel->bridge->technology->stream_topology_changed(
2485                                         bridge_channel->bridge, bridge_channel);
2486                         } else {
2487                                 ast_bridge_channel_stream_map(bridge_channel);
2488                         }
2489                         break;
2490                 default:
2491                         break;
2492                 }
2493                 break;
2494         case AST_FRAME_DTMF_BEGIN:
2495         case AST_FRAME_DTMF_END:
2496                 frame = bridge_handle_dtmf(bridge_channel, frame);
2497                 if (!frame) {
2498                         return;
2499                 }
2500                 if (!bridge_channel->features->dtmf_passthrough) {
2501                         bridge_frame_free(frame);
2502                         return;
2503                 }
2504                 break;
2505         default:
2506                 break;
2507         }
2508
2509         /* Simply write the frame out to the bridge technology. */
2510         bridge_channel_write_frame(bridge_channel, frame);
2511         bridge_frame_free(frame);
2512 }
2513
2514 /*!
2515  * \internal
2516  * \brief Determine how long till the next timer interval.
2517  * \since 12.0.0
2518  *
2519  * \param bridge_channel Channel to determine how long can wait.
2520  *
2521  * \retval ms Number of milliseconds to wait.
2522  * \retval -1 to wait forever.
2523  */
2524 static int bridge_channel_next_interval(struct ast_bridge_channel *bridge_channel)
2525 {
2526         struct ast_heap *interval_hooks = bridge_channel->features->interval_hooks;
2527         struct ast_bridge_hook_timer *hook;
2528         int ms;
2529
2530         ast_heap_wrlock(interval_hooks);
2531         hook = ast_heap_peek(interval_hooks, 1);
2532         if (hook) {
2533                 ms = ast_tvdiff_ms(hook->timer.trip_time, ast_tvnow());
2534                 if (ms < 0) {
2535                         /* Expire immediately.  An interval hook is ready to run. */
2536                         ms = 0;
2537                 }
2538         } else {
2539                 /* No hook so wait forever. */
2540                 ms = -1;
2541         }
2542         ast_heap_unlock(interval_hooks);
2543
2544         return ms;
2545 }
2546
2547 /*!
2548  * \internal
2549  * \brief Determine how long till the DTMF interdigit timeout.
2550  * \since 12.8.0
2551  *
2552  * \param bridge_channel Channel to determine how long can wait.
2553  *
2554  * \retval ms Number of milliseconds to wait.
2555  * \retval -1 to wait forever.
2556  */
2557 static int bridge_channel_feature_timeout(struct ast_bridge_channel *bridge_channel)
2558 {
2559         int ms;
2560
2561         if (bridge_channel->dtmf_hook_state.collected[0]) {
2562                 ms = ast_tvdiff_ms(bridge_channel->dtmf_hook_state.interdigit_timeout,
2563                         ast_tvnow());
2564                 if (ms < 0) {
2565                         /* Expire immediately. */
2566                         ms = 0;
2567                 }
2568         } else {
2569                 /* Timer is not active so wait forever. */
2570                 ms = -1;
2571         }
2572
2573         return ms;
2574 }
2575
2576 /*!
2577  * \internal
2578  * \brief Determine how long till a timeout.
2579  * \since 12.8.0
2580  *
2581  * \param bridge_channel Channel to determine how long can wait.
2582  *
2583  * \retval ms Number of milliseconds to wait.
2584  * \retval -1 to wait forever.
2585  */
2586 static int bridge_channel_next_timeout(struct ast_bridge_channel *bridge_channel)
2587 {
2588         int ms_interval;
2589         int ms;
2590
2591         ms_interval = bridge_channel_next_interval(bridge_channel);
2592         ms = bridge_channel_feature_timeout(bridge_channel);
2593         if (ms < 0 || (0 <= ms_interval && ms_interval < ms)) {
2594                 /* Interval hook timeout is next. */
2595                 ms = ms_interval;
2596         }
2597
2598         return ms;
2599 }
2600
2601 /*!
2602  * \internal
2603  * \brief Wait for something to happen on the bridge channel and handle it.
2604  * \since 12.0.0
2605  *
2606  * \param bridge_channel Channel to wait.
2607  *
2608  * \note Each channel does writing/reading in their own thread.
2609  *
2610  * \return Nothing
2611  */
2612 static void bridge_channel_wait(struct ast_bridge_channel *bridge_channel)
2613 {
2614         int ms;
2615         int outfd;
2616         struct ast_channel *chan;
2617
2618         /* Wait for data to either come from the channel or us to be signaled */
2619         ast_bridge_channel_lock(bridge_channel);
2620         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2621         } else if (bridge_channel->suspended) {
2622 /* XXX ASTERISK-21271 the external party use of suspended will go away as will these references because this is the bridge channel thread */
2623                 ast_debug(1, "Bridge %s: %p(%s) is going into a signal wait\n",
2624                         bridge_channel->bridge->uniqueid, bridge_channel,
2625                         ast_channel_name(bridge_channel->chan));
2626                 ast_cond_wait(&bridge_channel->cond, ao2_object_get_lockaddr(bridge_channel));
2627         } else {
2628                 ast_bridge_channel_unlock(bridge_channel);
2629                 outfd = -1;
2630                 ms = bridge_channel_next_timeout(bridge_channel);
2631                 chan = ast_waitfor_nandfds(&bridge_channel->chan, 1,
2632                         &bridge_channel->alert_pipe[0], 1, NULL, &outfd, &ms);
2633                 if (ast_channel_unbridged(bridge_channel->chan)) {
2634                         ast_channel_set_unbridged(bridge_channel->chan, 0);
2635                         ast_bridge_channel_lock_bridge(bridge_channel);
2636                         bridge_channel->bridge->reconfigured = 1;
2637                         bridge_reconfigured(bridge_channel->bridge, 0);
2638                         ast_bridge_unlock(bridge_channel->bridge);
2639                 }
2640                 ast_bridge_channel_lock(bridge_channel);
2641                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_FRAME;
2642                 ast_bridge_channel_unlock(bridge_channel);
2643                 if (!bridge_channel->suspended
2644                         && bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2645                         if (chan) {
2646                                 bridge_handle_trip(bridge_channel);
2647                         } else if (ms == 0) {
2648                                 /* An interdigit timeout or interval expired. */
2649                                 bridge_channel_handle_feature_timeout(bridge_channel);
2650                                 bridge_channel_handle_interval(bridge_channel);
2651                         } else if (-1 < outfd) {
2652                                 /*
2653                                  * Must do this after checking timeouts or may have
2654                                  * an infinite loop due to deferring write queue
2655                                  * actions while trying to match DTMF feature hooks.
2656                                  */
2657                                 bridge_channel_handle_write(bridge_channel);
2658                         }
2659                 }
2660                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_IDLE;
2661                 return;
2662         }
2663         ast_bridge_channel_unlock(bridge_channel);
2664 }
2665
2666 /*!
2667  * \internal
2668  * \brief Handle bridge channel join/leave event.
2669  * \since 12.0.0
2670  *
2671  * \param bridge_channel Which channel is involved.
2672  * \param type Specified join/leave event.
2673  *
2674  * \return Nothing
2675  */
2676 static void bridge_channel_event_join_leave(struct ast_bridge_channel *bridge_channel, enum ast_bridge_hook_type type)
2677 {
2678         struct ast_bridge_features *features = bridge_channel->features;
2679         struct ast_bridge_hook *hook;
2680         struct ao2_iterator iter;
2681
2682         /* Run the specified hooks. */
2683         iter = ao2_iterator_init(features->other_hooks, 0);
2684         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
2685                 if (hook->type == type) {
2686                         break;
2687                 }
2688         }
2689         if (hook) {
2690                 /* Found the first specified hook to run. */
2691                 bridge_channel_suspend(bridge_channel);
2692                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2693                 do {
2694                         if (hook->type == type) {
2695                                 hook->callback(bridge_channel, hook->hook_pvt);
2696                                 ao2_unlink(features->other_hooks, hook);
2697                         }
2698                         ao2_ref(hook, -1);
2699                 } while ((hook = ao2_iterator_next(&iter)));
2700                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2701                 bridge_channel_unsuspend(bridge_channel);
2702         }
2703         ao2_iterator_destroy(&iter);
2704 }
2705
2706 int bridge_channel_internal_join(struct ast_bridge_channel *bridge_channel)
2707 {
2708         int res = 0;
2709         struct ast_bridge_features *channel_features;
2710         struct ast_channel *swap;
2711
2712         ast_debug(1, "Bridge %s: %p(%s) is joining\n",
2713                 bridge_channel->bridge->uniqueid,
2714                 bridge_channel, ast_channel_name(bridge_channel->chan));
2715
2716         /*
2717          * Directly locking the bridge is safe here because nobody else
2718          * knows about this bridge_channel yet.
2719          */
2720         ast_bridge_lock(bridge_channel->bridge);
2721
2722         ast_channel_lock(bridge_channel->chan);
2723
2724         bridge_channel->read_format = ao2_bump(ast_channel_readformat(bridge_channel->chan));
2725         bridge_channel->write_format = ao2_bump(ast_channel_writeformat(bridge_channel->chan));
2726
2727         /* Make sure we're still good to be put into a bridge */
2728         if (ast_channel_internal_bridge(bridge_channel->chan)
2729                 || ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_ZOMBIE)) {
2730                 ast_channel_unlock(bridge_channel->chan);
2731                 ast_bridge_unlock(bridge_channel->bridge);
2732                 ast_debug(1, "Bridge %s: %p(%s) failed to join Bridge\n",
2733                         bridge_channel->bridge->uniqueid,
2734                         bridge_channel,
2735                         ast_channel_name(bridge_channel->chan));
2736                 return -1;
2737         }
2738         ast_channel_internal_bridge_set(bridge_channel->chan, bridge_channel->bridge);
2739
2740         /* Attach features requested by the channel */
2741         channel_features = ast_channel_feature_hooks_get(bridge_channel->chan);
2742         if (channel_features) {
2743                 ast_bridge_features_merge(bridge_channel->features, channel_features);
2744         }
2745         ast_channel_unlock(bridge_channel->chan);
2746
2747         /* Add the jitterbuffer if the channel requires it */
2748         ast_jb_enable_for_channel(bridge_channel->chan);
2749
2750         if (!bridge_channel->bridge->callid) {
2751                 bridge_channel->bridge->callid = ast_read_threadstorage_callid();
2752         }
2753
2754         /* Take the swap channel ref from the bridge_channel struct. */
2755         swap = bridge_channel->swap;
2756
2757         if (bridge_channel_internal_push(bridge_channel)) {
2758                 int cause = bridge_channel->bridge->cause;
2759
2760                 ast_bridge_unlock(bridge_channel->bridge);
2761                 ast_bridge_channel_kick(bridge_channel, cause);
2762                 ast_bridge_channel_lock_bridge(bridge_channel);
2763                 ast_bridge_features_remove(bridge_channel->features,
2764                         AST_BRIDGE_HOOK_REMOVE_ON_PULL);
2765                 bridge_channel_dissolve_check(bridge_channel);
2766                 res = -1;
2767         }
2768         bridge_reconfigured(bridge_channel->bridge, !bridge_channel->inhibit_colp);
2769
2770         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2771                 /*
2772                  * Indicate a source change since this channel is entering the
2773                  * bridge system only if the bridge technology is not MULTIMIX
2774                  * capable.  The MULTIMIX technology has already done it.
2775                  */
2776                 if (!(bridge_channel->bridge->technology->capabilities
2777                         & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
2778                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2779                 }
2780
2781                 bridge_channel_impart_signal(bridge_channel->chan);
2782                 ast_bridge_unlock(bridge_channel->bridge);
2783
2784                 /* Must release any swap ref after unlocking the bridge. */
2785                 ao2_t_cleanup(swap, "Bridge push with swap successful");
2786                 swap = NULL;
2787
2788                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_JOIN);
2789
2790                 while (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2791                         /* Wait for something to do. */
2792                         bridge_channel_wait(bridge_channel);
2793                 }
2794
2795                 /* Force a timeout on any accumulated DTMF hook digits. */
2796                 ast_bridge_channel_feature_digit(bridge_channel, 0);
2797
2798                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_LEAVE);
2799                 ast_bridge_channel_lock_bridge(bridge_channel);
2800         }
2801
2802         bridge_channel_internal_pull(bridge_channel);
2803         bridge_channel_settle_owed_events(bridge_channel->bridge, bridge_channel);
2804         bridge_reconfigured(bridge_channel->bridge, 1);
2805
2806         /* Remove ourselves if we are the video source */
2807         ast_bridge_remove_video_src(bridge_channel->bridge, bridge_channel->chan);
2808
2809         ast_bridge_unlock(bridge_channel->bridge);
2810
2811         /* Must release any swap ref after unlocking the bridge. */
2812         ao2_t_cleanup(swap, "Bridge push with swap failed or exited immediately");
2813
2814         /* Complete any active hold before exiting the bridge. */
2815         if (ast_channel_hold_state(bridge_channel->chan) == AST_CONTROL_HOLD) {
2816                 ast_debug(1, "Channel %s simulating UNHOLD for bridge end.\n",
2817                         ast_channel_name(bridge_channel->chan));
2818                 ast_indicate(bridge_channel->chan, AST_CONTROL_UNHOLD);
2819         }
2820
2821         /* Complete any partial DTMF digit before exiting the bridge. */
2822         if (ast_channel_sending_dtmf_digit(bridge_channel->chan)) {
2823                 ast_channel_end_dtmf(bridge_channel->chan,
2824                         ast_channel_sending_dtmf_digit(bridge_channel->chan),
2825                         ast_channel_sending_dtmf_tv(bridge_channel->chan), "bridge end");
2826         }
2827
2828         /* Complete any T.38 session before exiting the bridge. */
2829         if (ast_channel_is_t38_active(bridge_channel->chan)) {
2830                 struct ast_control_t38_parameters t38_parameters = {
2831                         .request_response = AST_T38_TERMINATED,
2832                 };
2833
2834                 ast_debug(1, "Channel %s simulating T.38 terminate for bridge end.\n",
2835                         ast_channel_name(bridge_channel->chan));
2836                 ast_indicate_data(bridge_channel->chan, AST_CONTROL_T38_PARAMETERS,
2837                         &t38_parameters, sizeof(t38_parameters));
2838         }
2839
2840         /* Indicate a source change since this channel is leaving the bridge system. */
2841         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2842
2843         /*
2844          * Wait for any dual redirect to complete.
2845          *
2846          * Must be done while "still in the bridge" for ast_async_goto()
2847          * to work right.
2848          */
2849         while (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT)) {
2850                 sched_yield();
2851         }
2852         ast_channel_lock(bridge_channel->chan);
2853         ast_channel_internal_bridge_set(bridge_channel->chan, NULL);
2854         ast_channel_unlock(bridge_channel->chan);
2855
2856         ast_bridge_channel_restore_formats(bridge_channel);
2857
2858         return res;
2859 }
2860
2861 int bridge_channel_internal_queue_blind_transfer(struct ast_channel *transferee,
2862                 const char *exten, const char *context,
2863                 transfer_channel_cb new_channel_cb, void *user_data)
2864 {
2865         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2866         struct blind_transfer_data blind_data;
2867
2868         ast_channel_lock(transferee);
2869         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2870         ast_channel_unlock(transferee);
2871
2872         if (!transferee_bridge_channel) {
2873                 return -1;
2874         }
2875
2876         if (new_channel_cb) {
2877                 new_channel_cb(transferee, user_data, AST_BRIDGE_TRANSFER_SINGLE_PARTY);
2878         }
2879
2880         ast_copy_string(blind_data.exten, exten, sizeof(blind_data.exten));
2881         ast_copy_string(blind_data.context, context, sizeof(blind_data.context));
2882
2883         return bridge_channel_queue_action_data(transferee_bridge_channel,
2884                 BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER, &blind_data, sizeof(blind_data));
2885 }
2886
2887 int bridge_channel_internal_queue_attended_transfer(struct ast_channel *transferee,
2888                 struct ast_channel *unbridged_chan)
2889 {
2890         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2891         char unbridged_chan_name[AST_CHANNEL_NAME];
2892
2893         ast_channel_lock(transferee);
2894         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2895         ast_channel_unlock(transferee);
2896
2897         if (!transferee_bridge_channel) {
2898                 return -1;
2899         }
2900
2901         ast_copy_string(unbridged_chan_name, ast_channel_name(unbridged_chan),
2902                 sizeof(unbridged_chan_name));
2903
2904         return bridge_channel_queue_action_data(transferee_bridge_channel,
2905                 BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER, unbridged_chan_name,
2906                 sizeof(unbridged_chan_name));
2907 }
2908
2909 int bridge_channel_internal_allows_optimization(struct ast_bridge_channel *bridge_channel)
2910 {
2911         return bridge_channel->in_bridge
2912                 && AST_LIST_EMPTY(&bridge_channel->wr_queue);
2913 }
2914
2915 /* Destroy elements of the bridge channel structure and the bridge channel structure itself */
2916 static void bridge_channel_destroy(void *obj)
2917 {
2918         struct ast_bridge_channel *bridge_channel = obj;
2919         struct ast_frame *fr;
2920
2921         if (bridge_channel->callid) {
2922                 bridge_channel->callid = 0;
2923         }
2924
2925         if (bridge_channel->bridge) {
2926                 ao2_ref(bridge_channel->bridge, -1);
2927                 bridge_channel->bridge = NULL;
2928         }
2929
2930         /* Flush any unhandled wr_queue frames. */
2931         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list))) {
2932                 bridge_frame_free(fr);
2933         }
2934         ast_alertpipe_close(bridge_channel->alert_pipe);
2935
2936         ast_cond_destroy(&bridge_channel->cond);
2937
2938         ao2_cleanup(bridge_channel->write_format);
2939         ao2_cleanup(bridge_channel->read_format);
2940
2941         AST_VECTOR_FREE(&bridge_channel->stream_map.to_bridge);
2942         AST_VECTOR_FREE(&bridge_channel->stream_map.to_channel);
2943 }
2944
2945 struct ast_bridge_channel *bridge_channel_internal_alloc(struct ast_bridge *bridge)
2946 {
2947         struct ast_bridge_channel *bridge_channel;
2948
2949         bridge_channel = ao2_alloc(sizeof(struct ast_bridge_channel), bridge_channel_destroy);
2950         if (!bridge_channel) {
2951                 return NULL;
2952         }
2953         ast_cond_init(&bridge_channel->cond, NULL);
2954         if (ast_alertpipe_init(bridge_channel->alert_pipe)) {
2955                 ao2_ref(bridge_channel, -1);
2956                 return NULL;
2957         }
2958         if (bridge) {
2959                 bridge_channel->bridge = bridge;
2960                 ao2_ref(bridge_channel->bridge, +1);
2961         }
2962
2963         /* The stream_map is initialized later - see ast_bridge_channel_stream_map */
2964
2965         return bridge_channel;
2966 }
2967
2968 void ast_bridge_channel_stream_map(struct ast_bridge_channel *bridge_channel)
2969 {
2970         ast_stream_topology_map(ast_channel_get_stream_topology(bridge_channel->chan),
2971                 &bridge_channel->bridge->media_types, &bridge_channel->stream_map.to_bridge,
2972                 &bridge_channel->stream_map.to_channel);
2973 }