Trivial misc bridge code changes.
[asterisk/asterisk.git] / bridges / bridge_multiplexed.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2008, 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 Two channel bridging module which groups bridges into batches of threads
22  *
23  * \author Joshua Colp <jcolp@digium.com>
24  *
25  * \ingroup bridges
26  */
27
28 /*** MODULEINFO
29         <support_level>core</support_level>
30  ***/
31
32 #include "asterisk.h"
33
34 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <fcntl.h>
42
43 #include "asterisk/module.h"
44 #include "asterisk/channel.h"
45 #include "asterisk/bridging.h"
46 #include "asterisk/bridging_technology.h"
47 #include "asterisk/frame.h"
48 #include "asterisk/astobj2.h"
49
50 /*! \brief Number of buckets our multiplexed thread container can have */
51 #define MULTIPLEXED_BUCKETS 53
52
53 /*! \brief Number of channels we handle in a single thread */
54 #define MULTIPLEXED_MAX_CHANNELS 8
55
56 /*! \brief Structure which represents a single thread handling multiple 2 channel bridges */
57 struct multiplexed_thread {
58         /*! Thread itself */
59         pthread_t thread;
60         /*! Pipe used to wake up the multiplexed thread */
61         int pipe[2];
62         /*! Channels in this thread */
63         struct ast_channel *chans[MULTIPLEXED_MAX_CHANNELS];
64         /*! Number of channels in this thread */
65         unsigned int count;
66         /*! Bit used to indicate that the thread is waiting on channels */
67         unsigned int waiting:1;
68         /*! Number of channels actually being serviced by this thread */
69         unsigned int service_count;
70 };
71
72 /*! \brief Container of all operating multiplexed threads */
73 static struct ao2_container *multiplexed_threads;
74
75 /*! \brief Callback function for finding a free multiplexed thread */
76 static int find_multiplexed_thread(void *obj, void *arg, int flags)
77 {
78         struct multiplexed_thread *multiplexed_thread = obj;
79         return (multiplexed_thread->count <= (MULTIPLEXED_MAX_CHANNELS - 2)) ? CMP_MATCH | CMP_STOP : 0;
80 }
81
82 /*! \brief Destroy callback for a multiplexed thread structure */
83 static void destroy_multiplexed_thread(void *obj)
84 {
85         struct multiplexed_thread *multiplexed_thread = obj;
86
87         if (multiplexed_thread->pipe[0] > -1) {
88                 close(multiplexed_thread->pipe[0]);
89         }
90         if (multiplexed_thread->pipe[1] > -1) {
91                 close(multiplexed_thread->pipe[1]);
92         }
93 }
94
95 /*! \brief Create function which finds/reserves/references a multiplexed thread structure */
96 static int multiplexed_bridge_create(struct ast_bridge *bridge)
97 {
98         struct multiplexed_thread *multiplexed_thread;
99
100         ao2_lock(multiplexed_threads);
101
102         /* Try to find an existing thread to handle our additional channels */
103         if (!(multiplexed_thread = ao2_callback(multiplexed_threads, 0, find_multiplexed_thread, NULL))) {
104                 int flags;
105
106                 /* If we failed we will have to create a new one from scratch */
107                 if (!(multiplexed_thread = ao2_alloc(sizeof(*multiplexed_thread), destroy_multiplexed_thread))) {
108                         ast_debug(1, "Failed to find or create a new multiplexed thread for bridge '%p'\n", bridge);
109                         ao2_unlock(multiplexed_threads);
110                         return -1;
111                 }
112
113                 multiplexed_thread->pipe[0] = multiplexed_thread->pipe[1] = -1;
114                 /* Setup a pipe so we can poke the thread itself when needed */
115                 if (pipe(multiplexed_thread->pipe)) {
116                         ast_debug(1, "Failed to create a pipe for poking a multiplexed thread for bridge '%p'\n", bridge);
117                         ao2_ref(multiplexed_thread, -1);
118                         ao2_unlock(multiplexed_threads);
119                         return -1;
120                 }
121
122                 /* Setup each pipe for non-blocking operation */
123                 flags = fcntl(multiplexed_thread->pipe[0], F_GETFL);
124                 if (fcntl(multiplexed_thread->pipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
125                         ast_log(LOG_WARNING, "Failed to setup first nudge pipe for non-blocking operation on %p (%d: %s)\n", bridge, errno, strerror(errno));
126                         ao2_ref(multiplexed_thread, -1);
127                         ao2_unlock(multiplexed_threads);
128                         return -1;
129                 }
130                 flags = fcntl(multiplexed_thread->pipe[1], F_GETFL);
131                 if (fcntl(multiplexed_thread->pipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
132                         ast_log(LOG_WARNING, "Failed to setup second nudge pipe for non-blocking operation on %p (%d: %s)\n", bridge, errno, strerror(errno));
133                         ao2_ref(multiplexed_thread, -1);
134                         ao2_unlock(multiplexed_threads);
135                         return -1;
136                 }
137
138                 /* Set up default parameters */
139                 multiplexed_thread->thread = AST_PTHREADT_NULL;
140
141                 /* Finally link us into the container so others may find us */
142                 ao2_link(multiplexed_threads, multiplexed_thread);
143                 ast_debug(1, "Created multiplexed thread '%p' for bridge '%p'\n", multiplexed_thread, bridge);
144         } else {
145                 ast_debug(1, "Found multiplexed thread '%p' for bridge '%p'\n", multiplexed_thread, bridge);
146         }
147
148         /* Bump the count of the thread structure up by two since the channels for this bridge will be joining shortly */
149         multiplexed_thread->count += 2;
150
151         ao2_unlock(multiplexed_threads);
152
153         bridge->bridge_pvt = multiplexed_thread;
154
155         return 0;
156 }
157
158 /*! \brief Internal function which nudges the thread */
159 static void multiplexed_nudge(struct multiplexed_thread *multiplexed_thread)
160 {
161         int nudge = 0;
162
163         if (multiplexed_thread->thread == AST_PTHREADT_NULL) {
164                 return;
165         }
166
167         if (write(multiplexed_thread->pipe[1], &nudge, sizeof(nudge)) != sizeof(nudge)) {
168                 ast_log(LOG_ERROR, "We couldn't poke multiplexed thread '%p'... something is VERY wrong\n", multiplexed_thread);
169         }
170
171         while (multiplexed_thread->waiting) {
172                 sched_yield();
173         }
174 }
175
176 /*! \brief Destroy function which unreserves/unreferences/removes a multiplexed thread structure */
177 static int multiplexed_bridge_destroy(struct ast_bridge *bridge)
178 {
179         struct multiplexed_thread *multiplexed_thread = bridge->bridge_pvt;
180
181         ao2_lock(multiplexed_threads);
182
183         multiplexed_thread->count -= 2;
184
185         if (!multiplexed_thread->count) {
186                 ast_debug(1, "Unlinking multiplexed thread '%p' since nobody is using it anymore\n", multiplexed_thread);
187                 ao2_unlink(multiplexed_threads, multiplexed_thread);
188         }
189
190         multiplexed_nudge(multiplexed_thread);
191
192         ao2_unlock(multiplexed_threads);
193
194         ao2_ref(multiplexed_thread, -1);
195
196         return 0;
197 }
198
199 /*! \brief Thread function that executes for multiplexed threads */
200 static void *multiplexed_thread_function(void *data)
201 {
202         struct multiplexed_thread *multiplexed_thread = data;
203         int fds = multiplexed_thread->pipe[0];
204
205         ao2_lock(multiplexed_thread);
206
207         ast_debug(1, "Starting actual thread for multiplexed thread '%p'\n", multiplexed_thread);
208
209         while (multiplexed_thread->thread != AST_PTHREADT_STOP) {
210                 struct ast_channel *winner = NULL, *first = multiplexed_thread->chans[0];
211                 int to = -1, outfd = -1;
212
213                 /* Move channels around so not just the first one gets priority */
214                 memmove(multiplexed_thread->chans, multiplexed_thread->chans + 1, sizeof(struct ast_channel *) * (multiplexed_thread->service_count - 1));
215                 multiplexed_thread->chans[multiplexed_thread->service_count - 1] = first;
216
217                 multiplexed_thread->waiting = 1;
218                 ao2_unlock(multiplexed_thread);
219                 winner = ast_waitfor_nandfds(multiplexed_thread->chans, multiplexed_thread->service_count, &fds, 1, NULL, &outfd, &to);
220                 multiplexed_thread->waiting = 0;
221                 ao2_lock(multiplexed_thread);
222                 if (multiplexed_thread->thread == AST_PTHREADT_STOP) {
223                         break;
224                 }
225
226                 if (outfd > -1) {
227                         int nudge;
228
229                         if (read(multiplexed_thread->pipe[0], &nudge, sizeof(nudge)) < 0) {
230                                 if (errno != EINTR && errno != EAGAIN) {
231                                         ast_log(LOG_WARNING, "read() failed for pipe on multiplexed thread '%p': %s\n", multiplexed_thread, strerror(errno));
232                                 }
233                         }
234                 }
235                 if (winner && ast_channel_internal_bridge(winner)) {
236                         struct ast_bridge *bridge = ast_channel_internal_bridge(winner);
237                         int stop = 0;
238                         ao2_unlock(multiplexed_thread);
239                         while ((bridge = ast_channel_internal_bridge(winner)) && ao2_trylock(bridge)) {
240                                 sched_yield();
241                                 if (multiplexed_thread->thread == AST_PTHREADT_STOP) {
242                                         stop = 1;
243                                         break;
244                                 }
245                         }
246                         if (!stop && bridge) {
247                                 ast_bridge_handle_trip(bridge, NULL, winner, -1);
248                                 ao2_unlock(bridge);
249                         }
250                         ao2_lock(multiplexed_thread);
251                 }
252         }
253
254         multiplexed_thread->thread = AST_PTHREADT_NULL;
255
256         ast_debug(1, "Stopping actual thread for multiplexed thread '%p'\n", multiplexed_thread);
257
258         ao2_unlock(multiplexed_thread);
259         ao2_ref(multiplexed_thread, -1);
260
261         return NULL;
262 }
263
264 /*! \brief Helper function which adds or removes a channel and nudges the thread */
265 static void multiplexed_add_or_remove(struct multiplexed_thread *multiplexed_thread, struct ast_channel *chan, int add)
266 {
267         int i, removed = 0;
268         pthread_t thread = AST_PTHREADT_NULL;
269
270         ao2_lock(multiplexed_thread);
271
272         multiplexed_nudge(multiplexed_thread);
273
274         for (i = 0; i < MULTIPLEXED_MAX_CHANNELS; i++) {
275                 if (multiplexed_thread->chans[i] == chan) {
276                         if (!add) {
277                                 multiplexed_thread->chans[i] = NULL;
278                                 multiplexed_thread->service_count--;
279                                 removed = 1;
280                         }
281                         break;
282                 } else if (!multiplexed_thread->chans[i] && add) {
283                         multiplexed_thread->chans[i] = chan;
284                         multiplexed_thread->service_count++;
285                         break;
286                 }
287         }
288
289         if (multiplexed_thread->service_count && multiplexed_thread->thread == AST_PTHREADT_NULL) {
290                 ao2_ref(multiplexed_thread, +1);
291                 if (ast_pthread_create(&multiplexed_thread->thread, NULL, multiplexed_thread_function, multiplexed_thread)) {
292                         ao2_ref(multiplexed_thread, -1);
293                         ast_debug(1, "Failed to create an actual thread for multiplexed thread '%p', trying next time\n", multiplexed_thread);
294                 }
295         } else if (!multiplexed_thread->service_count && multiplexed_thread->thread != AST_PTHREADT_NULL) {
296                 thread = multiplexed_thread->thread;
297                 multiplexed_thread->thread = AST_PTHREADT_STOP;
298         } else if (!add && removed) {
299                 memmove(multiplexed_thread->chans + i, multiplexed_thread->chans + i + 1, sizeof(struct ast_channel *) * (MULTIPLEXED_MAX_CHANNELS - (i + 1)));
300         }
301
302         ao2_unlock(multiplexed_thread);
303
304         if (thread != AST_PTHREADT_NULL) {
305                 pthread_join(thread, NULL);
306         }
307 }
308
309 /*! \brief Join function which actually adds the channel into the array to be monitored */
310 static int multiplexed_bridge_join(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
311 {
312         struct ast_channel *c0 = AST_LIST_FIRST(&bridge->channels)->chan, *c1 = AST_LIST_LAST(&bridge->channels)->chan;
313         struct multiplexed_thread *multiplexed_thread = bridge->bridge_pvt;
314
315         ast_debug(1, "Adding channel '%s' to multiplexed thread '%p' for monitoring\n", ast_channel_name(bridge_channel->chan), multiplexed_thread);
316
317         multiplexed_add_or_remove(multiplexed_thread, bridge_channel->chan, 1);
318
319         /* If the second channel has not yet joined do not make things compatible */
320         if (c0 == c1) {
321                 return 0;
322         }
323
324         if ((ast_format_cmp(ast_channel_writeformat(c0), ast_channel_readformat(c1)) == AST_FORMAT_CMP_EQUAL) &&
325                 (ast_format_cmp(ast_channel_readformat(c0), ast_channel_writeformat(c1)) == AST_FORMAT_CMP_EQUAL) &&
326                 (ast_format_cap_identical(ast_channel_nativeformats(c0), ast_channel_nativeformats(c1)))) {
327                 return 0;
328         }
329
330         return ast_channel_make_compatible(c0, c1);
331 }
332
333 /*! \brief Leave function which actually removes the channel from the array */
334 static int multiplexed_bridge_leave(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
335 {
336         struct multiplexed_thread *multiplexed_thread = bridge->bridge_pvt;
337
338         ast_debug(1, "Removing channel '%s' from multiplexed thread '%p'\n", ast_channel_name(bridge_channel->chan), multiplexed_thread);
339
340         multiplexed_add_or_remove(multiplexed_thread, bridge_channel->chan, 0);
341
342         return 0;
343 }
344
345 /*! \brief Suspend function which means control of the channel is going elsewhere */
346 static void multiplexed_bridge_suspend(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
347 {
348         struct multiplexed_thread *multiplexed_thread = bridge->bridge_pvt;
349
350         ast_debug(1, "Suspending channel '%s' from multiplexed thread '%p'\n", ast_channel_name(bridge_channel->chan), multiplexed_thread);
351
352         multiplexed_add_or_remove(multiplexed_thread, bridge_channel->chan, 0);
353 }
354
355 /*! \brief Unsuspend function which means control of the channel is coming back to us */
356 static void multiplexed_bridge_unsuspend(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
357 {
358         struct multiplexed_thread *multiplexed_thread = bridge->bridge_pvt;
359
360         ast_debug(1, "Unsuspending channel '%s' from multiplexed thread '%p'\n", ast_channel_name(bridge_channel->chan), multiplexed_thread);
361
362         multiplexed_add_or_remove(multiplexed_thread, bridge_channel->chan, 1);
363 }
364
365 /*! \brief Write function for writing frames into the bridge */
366 static enum ast_bridge_write_result multiplexed_bridge_write(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
367 {
368         struct ast_bridge_channel *other;
369
370         /* If this is the only channel in this bridge then immediately exit */
371         if (AST_LIST_FIRST(&bridge->channels) == AST_LIST_LAST(&bridge->channels)) {
372                 return AST_BRIDGE_WRITE_FAILED;
373         }
374
375         /* Find the channel we actually want to write to */
376         if (!(other = (AST_LIST_FIRST(&bridge->channels) == bridge_channel ? AST_LIST_LAST(&bridge->channels) : AST_LIST_FIRST(&bridge->channels)))) {
377                 return AST_BRIDGE_WRITE_FAILED;
378         }
379
380         /* Write the frame out if they are in the waiting state... don't worry about freeing it, the bridging core will take care of it */
381         if (other->state == AST_BRIDGE_CHANNEL_STATE_WAIT) {
382                 ast_write(other->chan, frame);
383         }
384
385         return AST_BRIDGE_WRITE_SUCCESS;
386 }
387
388 static struct ast_bridge_technology multiplexed_bridge = {
389         .name = "multiplexed_bridge",
390         .capabilities = AST_BRIDGE_CAPABILITY_1TO1MIX,
391         .preference = AST_BRIDGE_PREFERENCE_HIGH,
392         .create = multiplexed_bridge_create,
393         .destroy = multiplexed_bridge_destroy,
394         .join = multiplexed_bridge_join,
395         .leave = multiplexed_bridge_leave,
396         .suspend = multiplexed_bridge_suspend,
397         .unsuspend = multiplexed_bridge_unsuspend,
398         .write = multiplexed_bridge_write,
399 };
400
401 static int unload_module(void)
402 {
403         int res = ast_bridge_technology_unregister(&multiplexed_bridge);
404
405         ao2_ref(multiplexed_threads, -1);
406         multiplexed_bridge.format_capabilities = ast_format_cap_destroy(multiplexed_bridge.format_capabilities);
407
408         return res;
409 }
410
411 static int load_module(void)
412 {
413         if (!(multiplexed_threads = ao2_container_alloc(MULTIPLEXED_BUCKETS, NULL, NULL))) {
414                 return AST_MODULE_LOAD_DECLINE;
415         }
416         if (!(multiplexed_bridge.format_capabilities = ast_format_cap_alloc())) {
417                 return AST_MODULE_LOAD_DECLINE;
418         }
419         ast_format_cap_add_all_by_type(multiplexed_bridge.format_capabilities, AST_FORMAT_TYPE_AUDIO);
420         ast_format_cap_add_all_by_type(multiplexed_bridge.format_capabilities, AST_FORMAT_TYPE_VIDEO);
421         ast_format_cap_add_all_by_type(multiplexed_bridge.format_capabilities, AST_FORMAT_TYPE_TEXT);
422         return ast_bridge_technology_register(&multiplexed_bridge);
423 }
424
425 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Multiplexed two channel bridging module");