Merged revisions 30874 via svnmerge from
[asterisk-bristuff.git] / channel.c
blob597b180764fad154f92a88b623bcfaf0bd151508
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
19 /*! \file
21 * \brief Channel Management
23 * \author Mark Spencer <markster@digium.com>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/time.h>
30 #include <signal.h>
31 #include <errno.h>
32 #include <unistd.h>
33 #include <math.h> /* For PI */
35 #include "asterisk.h"
37 #ifdef HAVE_ZAPTEL
38 #include <sys/ioctl.h>
39 #ifdef __linux__
40 #include <linux/zaptel.h>
41 #else
42 #include <zaptel.h>
43 #endif /* __linux__ */
44 #ifndef ZT_TIMERPING
45 #error "You need newer zaptel! Please cvs update zaptel"
46 #endif
47 #endif
49 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
51 #include "asterisk/pbx.h"
52 #include "asterisk/frame.h"
53 #include "asterisk/sched.h"
54 #include "asterisk/options.h"
55 #include "asterisk/channel.h"
56 #include "asterisk/chanspy.h"
57 #include "asterisk/musiconhold.h"
58 #include "asterisk/logger.h"
59 #include "asterisk/say.h"
60 #include "asterisk/file.h"
61 #include "asterisk/cli.h"
62 #include "asterisk/translate.h"
63 #include "asterisk/manager.h"
64 #include "asterisk/chanvars.h"
65 #include "asterisk/linkedlists.h"
66 #include "asterisk/indications.h"
67 #include "asterisk/monitor.h"
68 #include "asterisk/causes.h"
69 #include "asterisk/callerid.h"
70 #include "asterisk/utils.h"
71 #include "asterisk/lock.h"
72 #include "asterisk/app.h"
73 #include "asterisk/transcap.h"
74 #include "asterisk/devicestate.h"
75 #include "asterisk/sha1.h"
77 struct channel_spy_trans {
78 int last_format;
79 struct ast_trans_pvt *path;
82 struct ast_channel_spy_list {
83 struct channel_spy_trans read_translator;
84 struct channel_spy_trans write_translator;
85 AST_LIST_HEAD_NOLOCK(, ast_channel_spy) list;
88 /* uncomment if you have problems with 'monitoring' synchronized files */
89 #if 0
90 #define MONITOR_CONSTANT_DELAY
91 #define MONITOR_DELAY 150 * 8 /* 150 ms of MONITORING DELAY */
92 #endif
94 /*! Prevent new channel allocation if shutting down. */
95 static int shutting_down = 0;
97 AST_MUTEX_DEFINE_STATIC(uniquelock);
98 static int uniqueint = 0;
100 unsigned long global_fin = 0, global_fout = 0;
102 /* XXX Lock appropriately in more functions XXX */
104 struct chanlist {
105 const struct ast_channel_tech *tech;
106 AST_LIST_ENTRY(chanlist) list;
109 /*! the list of registered channel types */
110 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
112 /*! the list of channels we have. Note that the lock for this list is used for
113 both the channels list and the backends list. */
114 static AST_LIST_HEAD_STATIC(channels, ast_channel);
116 /*! map AST_CAUSE's to readable string representations */
117 const struct ast_cause {
118 int cause;
119 const char *name;
120 const char *desc;
121 } causes[] = {
122 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
123 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
124 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
125 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
126 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
127 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
128 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
129 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
130 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
131 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
132 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
133 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
134 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
135 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
136 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
137 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
138 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
139 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
140 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
141 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
142 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
143 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
144 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
145 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
146 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
147 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
148 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
149 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
150 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
151 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
152 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
153 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
154 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
155 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
156 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
157 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
158 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
159 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
160 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
161 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
162 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
163 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
164 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
165 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
169 struct ast_variable *ast_channeltype_list(void)
171 struct chanlist *cl;
172 struct ast_variable *var=NULL, *prev = NULL;
173 AST_LIST_TRAVERSE(&backends, cl, list) {
174 if (prev) {
175 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description)))
176 prev = prev->next;
177 } else {
178 var = ast_variable_new(cl->tech->type, cl->tech->description);
179 prev = var;
182 return var;
185 static int show_channeltypes(int fd, int argc, char *argv[])
187 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
188 struct chanlist *cl;
189 int count_chan = 0;
191 ast_cli(fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
192 ast_cli(fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
193 if (AST_LIST_LOCK(&channels)) {
194 ast_log(LOG_WARNING, "Unable to lock channel list\n");
195 return -1;
197 AST_LIST_TRAVERSE(&backends, cl, list) {
198 ast_cli(fd, FORMAT, cl->tech->type, cl->tech->description,
199 (cl->tech->devicestate) ? "yes" : "no",
200 (cl->tech->indicate) ? "yes" : "no",
201 (cl->tech->transfer) ? "yes" : "no");
202 count_chan++;
204 AST_LIST_UNLOCK(&channels);
205 ast_cli(fd, "----------\n%d channel drivers registered.\n", count_chan);
206 return RESULT_SUCCESS;
208 #undef FORMAT
212 static int show_channeltype(int fd, int argc, char *argv[])
214 struct chanlist *cl = NULL;
216 if (argc != 3)
217 return RESULT_SHOWUSAGE;
219 if (AST_LIST_LOCK(&channels)) {
220 ast_log(LOG_WARNING, "Unable to lock channel list\n");
221 return RESULT_FAILURE;
224 AST_LIST_TRAVERSE(&backends, cl, list) {
225 if (!strncasecmp(cl->tech->type, argv[2], strlen(cl->tech->type))) {
226 break;
231 if (!cl) {
232 ast_cli(fd, "\n%s is not a registered channel driver.\n", argv[2]);
233 AST_LIST_UNLOCK(&channels);
234 return RESULT_FAILURE;
237 ast_cli(fd,
238 "-- Info about channel driver: %s --\n"
239 " Device State: %s\n"
240 " Indication: %s\n"
241 " Transfer : %s\n"
242 " Capabilities: %d\n"
243 " Send Digit: %s\n"
244 " Send HTML : %s\n"
245 " Image Support: %s\n"
246 " Text Support: %s\n",
247 cl->tech->type,
248 (cl->tech->devicestate) ? "yes" : "no",
249 (cl->tech->indicate) ? "yes" : "no",
250 (cl->tech->transfer) ? "yes" : "no",
251 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
252 (cl->tech->send_digit) ? "yes" : "no",
253 (cl->tech->send_html) ? "yes" : "no",
254 (cl->tech->send_image) ? "yes" : "no",
255 (cl->tech->send_text) ? "yes" : "no"
259 AST_LIST_UNLOCK(&channels);
260 return RESULT_SUCCESS;
263 static char *complete_channeltypes(const char *line, const char *word, int pos, int state)
265 struct chanlist *cl;
266 int which = 0;
267 int wordlen;
268 char *ret = NULL;
270 if (pos != 2)
271 return NULL;
273 wordlen = strlen(word);
275 AST_LIST_TRAVERSE(&backends, cl, list) {
276 if (!strncasecmp(word, cl->tech->type, wordlen) && ++which > state) {
277 ret = strdup(cl->tech->type);
278 break;
282 return ret;
285 static char show_channeltypes_usage[] =
286 "Usage: show channeltypes\n"
287 " Shows available channel types registered in your Asterisk server.\n";
289 static char show_channeltype_usage[] =
290 "Usage: show channeltype <name>\n"
291 " Show details about the specified channel type, <name>.\n";
293 static struct ast_cli_entry cli_show_channeltypes =
294 { { "show", "channeltypes", NULL }, show_channeltypes, "Show available channel types", show_channeltypes_usage };
296 static struct ast_cli_entry cli_show_channeltype =
297 { { "show", "channeltype", NULL }, show_channeltype, "Give more details on that channel type", show_channeltype_usage, complete_channeltypes };
299 /*! \brief Checks to see if a channel is needing hang up */
300 int ast_check_hangup(struct ast_channel *chan)
302 if (chan->_softhangup) /* yes if soft hangup flag set */
303 return 1;
304 if (!chan->tech_pvt) /* yes if no technology private data */
305 return 1;
306 if (!chan->whentohangup) /* no if no hangup scheduled */
307 return 0;
308 if (chan->whentohangup > time(NULL)) /* no if hangup time has not come yet. */
309 return 0;
310 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
311 return 1;
314 static int ast_check_hangup_locked(struct ast_channel *chan)
316 int res;
317 ast_channel_lock(chan);
318 res = ast_check_hangup(chan);
319 ast_channel_unlock(chan);
320 return res;
323 /*! \brief Initiate system shutdown */
324 void ast_begin_shutdown(int hangup)
326 struct ast_channel *c;
327 shutting_down = 1;
328 if (hangup) {
329 AST_LIST_LOCK(&channels);
330 AST_LIST_TRAVERSE(&channels, c, chan_list)
331 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
332 AST_LIST_UNLOCK(&channels);
336 /*! \brief returns number of active/allocated channels */
337 int ast_active_channels(void)
339 struct ast_channel *c;
340 int cnt = 0;
341 AST_LIST_LOCK(&channels);
342 AST_LIST_TRAVERSE(&channels, c, chan_list)
343 cnt++;
344 AST_LIST_UNLOCK(&channels);
345 return cnt;
348 /*! \brief Cancel a shutdown in progress */
349 void ast_cancel_shutdown(void)
351 shutting_down = 0;
354 /*! \brief Returns non-zero if Asterisk is being shut down */
355 int ast_shutting_down(void)
357 return shutting_down;
360 /*! \brief Set when to hangup channel */
361 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
363 chan->whentohangup = offset ? time(NULL) + offset : 0;
364 ast_queue_frame(chan, &ast_null_frame);
365 return;
368 /*! \brief Compare a offset with when to hangup channel */
369 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
371 time_t whentohangup;
373 if (chan->whentohangup == 0) {
374 return (offset == 0) ? 0 : -1;
375 } else {
376 if (offset == 0) /* XXX why is this special ? */
377 return (1);
378 else {
379 whentohangup = offset + time (NULL);
380 if (chan->whentohangup < whentohangup)
381 return (1);
382 else if (chan->whentohangup == whentohangup)
383 return (0);
384 else
385 return (-1);
390 /*! \brief Register a new telephony channel in Asterisk */
391 int ast_channel_register(const struct ast_channel_tech *tech)
393 struct chanlist *chan;
395 AST_LIST_LOCK(&channels);
397 AST_LIST_TRAVERSE(&backends, chan, list) {
398 if (!strcasecmp(tech->type, chan->tech->type)) {
399 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
400 AST_LIST_UNLOCK(&channels);
401 return -1;
405 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
406 AST_LIST_UNLOCK(&channels);
407 return -1;
409 chan->tech = tech;
410 AST_LIST_INSERT_HEAD(&backends, chan, list);
412 if (option_debug)
413 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
415 if (option_verbose > 1)
416 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
417 chan->tech->description);
419 AST_LIST_UNLOCK(&channels);
420 return 0;
423 void ast_channel_unregister(const struct ast_channel_tech *tech)
425 struct chanlist *chan;
427 if (option_debug)
428 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
430 AST_LIST_LOCK(&channels);
432 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
433 if (chan->tech == tech) {
434 AST_LIST_REMOVE_CURRENT(&backends, list);
435 free(chan);
436 if (option_verbose > 1)
437 ast_verbose(VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
438 break;
441 AST_LIST_TRAVERSE_SAFE_END
443 AST_LIST_UNLOCK(&channels);
446 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
448 struct chanlist *chanls;
449 const struct ast_channel_tech *ret = NULL;
451 if (AST_LIST_LOCK(&channels)) {
452 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
453 return NULL;
456 AST_LIST_TRAVERSE(&backends, chanls, list) {
457 if (!strcasecmp(name, chanls->tech->type)) {
458 ret = chanls->tech;
459 break;
463 AST_LIST_UNLOCK(&channels);
465 return ret;
468 /*! \brief Gives the string form of a given hangup cause */
469 const char *ast_cause2str(int cause)
471 int x;
473 for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++) {
474 if (causes[x].cause == cause)
475 return causes[x].desc;
478 return "Unknown";
481 /*! \brief Convert a symbolic hangup cause to number */
482 int ast_str2cause(const char *name)
484 int x;
486 for (x = 0; x < sizeof(causes) / sizeof(causes[0]); x++)
487 if (strncasecmp(causes[x].name, name, strlen(causes[x].name)) == 0)
488 return causes[x].cause;
490 return -1;
493 /*! \brief Gives the string form of a given channel state */
494 char *ast_state2str(int state)
496 /* XXX Not reentrant XXX */
497 static char localtmp[256];
498 switch(state) {
499 case AST_STATE_DOWN:
500 return "Down";
501 case AST_STATE_RESERVED:
502 return "Rsrvd";
503 case AST_STATE_OFFHOOK:
504 return "OffHook";
505 case AST_STATE_DIALING:
506 return "Dialing";
507 case AST_STATE_RING:
508 return "Ring";
509 case AST_STATE_RINGING:
510 return "Ringing";
511 case AST_STATE_UP:
512 return "Up";
513 case AST_STATE_BUSY:
514 return "Busy";
515 default:
516 snprintf(localtmp, sizeof(localtmp), "Unknown (%d)\n", state);
517 return localtmp;
521 /*! \brief Gives the string form of a given transfer capability */
522 char *ast_transfercapability2str(int transfercapability)
524 switch(transfercapability) {
525 case AST_TRANS_CAP_SPEECH:
526 return "SPEECH";
527 case AST_TRANS_CAP_DIGITAL:
528 return "DIGITAL";
529 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
530 return "RESTRICTED_DIGITAL";
531 case AST_TRANS_CAP_3_1K_AUDIO:
532 return "3K1AUDIO";
533 case AST_TRANS_CAP_DIGITAL_W_TONES:
534 return "DIGITAL_W_TONES";
535 case AST_TRANS_CAP_VIDEO:
536 return "VIDEO";
537 default:
538 return "UNKNOWN";
542 /*! \brief Pick the best codec */
543 int ast_best_codec(int fmts)
545 /* This just our opinion, expressed in code. We are asked to choose
546 the best codec to use, given no information */
547 int x;
548 static int prefs[] =
550 /*! Okay, ulaw is used by all telephony equipment, so start with it */
551 AST_FORMAT_ULAW,
552 /*! Unless of course, you're a silly European, so then prefer ALAW */
553 AST_FORMAT_ALAW,
554 /*! Okay, well, signed linear is easy to translate into other stuff */
555 AST_FORMAT_SLINEAR,
556 /*! G.726 is standard ADPCM */
557 AST_FORMAT_G726,
558 /*! ADPCM has great sound quality and is still pretty easy to translate */
559 AST_FORMAT_ADPCM,
560 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
561 translate and sounds pretty good */
562 AST_FORMAT_GSM,
563 /*! iLBC is not too bad */
564 AST_FORMAT_ILBC,
565 /*! Speex is free, but computationally more expensive than GSM */
566 AST_FORMAT_SPEEX,
567 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
568 to use it */
569 AST_FORMAT_LPC10,
570 /*! G.729a is faster than 723 and slightly less expensive */
571 AST_FORMAT_G729A,
572 /*! Down to G.723.1 which is proprietary but at least designed for voice */
573 AST_FORMAT_G723_1,
577 /* Find the first preferred codec in the format given */
578 for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
579 if (fmts & prefs[x])
580 return prefs[x];
581 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
582 return 0;
585 static const struct ast_channel_tech null_tech = {
586 .type = "NULL",
587 .description = "Null channel (should not see this)",
590 /*! \brief Create a new channel structure */
591 struct ast_channel *ast_channel_alloc(int needqueue)
593 struct ast_channel *tmp;
594 int x;
595 int flags;
596 struct varshead *headp;
598 /* If shutting down, don't allocate any new channels */
599 if (shutting_down) {
600 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
601 return NULL;
604 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
605 return NULL;
607 if (!(tmp->sched = sched_context_create())) {
608 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
609 free(tmp);
610 return NULL;
613 ast_string_field_init(tmp, 128);
615 /* Don't bother initializing the last two FD here, because they
616 will *always* be set just a few lines down (AST_TIMING_FD,
617 AST_ALERT_FD). */
618 for (x=0; x<AST_MAX_FDS - 2; x++)
619 tmp->fds[x] = -1;
621 #ifdef HAVE_ZAPTEL
622 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
623 if (tmp->timingfd > -1) {
624 /* Check if timing interface supports new
625 ping/pong scheme */
626 flags = 1;
627 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
628 needqueue = 0;
630 #else
631 tmp->timingfd = -1;
632 #endif
634 if (needqueue) {
635 if (pipe(tmp->alertpipe)) {
636 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
637 free(tmp);
638 return NULL;
639 } else {
640 flags = fcntl(tmp->alertpipe[0], F_GETFL);
641 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
642 flags = fcntl(tmp->alertpipe[1], F_GETFL);
643 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
645 } else /* Make sure we've got it done right if they don't */
646 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
648 /* Always watch the alertpipe */
649 tmp->fds[AST_ALERT_FD] = tmp->alertpipe[0];
650 /* And timing pipe */
651 tmp->fds[AST_TIMING_FD] = tmp->timingfd;
652 ast_string_field_set(tmp, name, "**Unknown**");
653 /* Initial state */
654 tmp->_state = AST_STATE_DOWN;
655 tmp->streamid = -1;
656 tmp->appl = NULL;
657 tmp->data = NULL;
658 tmp->fin = global_fin;
659 tmp->fout = global_fout;
660 ast_mutex_lock(&uniquelock);
661 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME))
662 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL), uniqueint++);
663 else
664 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME, (long) time(NULL), uniqueint++);
665 ast_mutex_unlock(&uniquelock);
666 headp = &tmp->varshead;
667 ast_mutex_init(&tmp->lock);
668 AST_LIST_HEAD_INIT_NOLOCK(headp);
669 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
670 strcpy(tmp->context, "default");
671 ast_string_field_set(tmp, language, defaultlanguage);
672 strcpy(tmp->exten, "s");
673 tmp->priority = 1;
674 tmp->amaflags = ast_default_amaflags;
675 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
677 tmp->tech = &null_tech;
679 AST_LIST_LOCK(&channels);
680 AST_LIST_INSERT_HEAD(&channels, tmp, chan_list);
681 AST_LIST_UNLOCK(&channels);
682 return tmp;
685 /*! \brief Queue an outgoing media frame */
686 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
688 struct ast_frame *f;
689 struct ast_frame *prev, *cur;
690 int blah = 1;
691 int qlen = 0;
693 /* Build us a copy and free the original one */
694 if (!(f = ast_frdup(fin))) {
695 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
696 return -1;
698 ast_channel_lock(chan);
699 prev = NULL;
700 for (cur = chan->readq; cur; cur = cur->next) {
701 if ((cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
702 /* Don't bother actually queueing anything after a hangup */
703 ast_frfree(f);
704 ast_channel_unlock(chan);
705 return 0;
707 prev = cur;
708 qlen++;
710 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
711 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
712 if (fin->frametype != AST_FRAME_VOICE) {
713 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
714 CRASH;
715 } else {
716 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
717 ast_frfree(f);
718 ast_channel_unlock(chan);
719 return 0;
722 if (prev)
723 prev->next = f;
724 else
725 chan->readq = f;
726 if (chan->alertpipe[1] > -1) {
727 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
728 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
729 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
730 #ifdef HAVE_ZAPTEL
731 } else if (chan->timingfd > -1) {
732 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
733 #endif
734 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
735 pthread_kill(chan->blocker, SIGURG);
737 ast_channel_unlock(chan);
738 return 0;
741 /*! \brief Queue a hangup frame for channel */
742 int ast_queue_hangup(struct ast_channel *chan)
744 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
745 /* Yeah, let's not change a lock-critical value without locking */
746 if (!ast_channel_trylock(chan)) {
747 chan->_softhangup |= AST_SOFTHANGUP_DEV;
748 ast_channel_unlock(chan);
750 return ast_queue_frame(chan, &f);
753 /*! \brief Queue a control frame */
754 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
756 struct ast_frame f = { AST_FRAME_CONTROL, };
758 f.subclass = control;
760 return ast_queue_frame(chan, &f);
763 /*! \brief Queue a control frame with payload */
764 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
765 const void *data, size_t datalen)
767 struct ast_frame f = { AST_FRAME_CONTROL, };
769 f.subclass = control;
770 f.data = (void *) data;
771 f.datalen = datalen;
773 return ast_queue_frame(chan, &f);
776 /*! \brief Set defer DTMF flag on channel */
777 int ast_channel_defer_dtmf(struct ast_channel *chan)
779 int pre = 0;
781 if (chan) {
782 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
783 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
785 return pre;
788 /*! \brief Unset defer DTMF flag on channel */
789 void ast_channel_undefer_dtmf(struct ast_channel *chan)
791 if (chan)
792 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
796 * \brief Helper function to find channels.
798 * It supports these modes:
800 * prev != NULL : get channel next in list after prev
801 * name != NULL : get channel with matching name
802 * name != NULL && namelen != 0 : get channel whose name starts with prefix
803 * exten != NULL : get channel whose exten or macroexten matches
804 * context != NULL && exten != NULL : get channel whose context or macrocontext
806 * It returns with the channel's lock held. If getting the individual lock fails,
807 * unlock and retry quickly up to 10 times, then give up.
809 * \note XXX Note that this code has cost O(N) because of the need to verify
810 * that the object is still on the global list.
812 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
813 * can only be done with the lock held or someone could delete the
814 * object while we work on it. This causes some ugliness in the code.
815 * Note that removing the first ast_log() may be harmful, as it would
816 * shorten the retry period and possibly cause failures.
817 * We should definitely go for a better scheme that is deadlock-free.
819 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
820 const char *name, const int namelen,
821 const char *context, const char *exten)
823 const char *msg = prev ? "deadlock" : "initial deadlock";
824 int retries;
825 struct ast_channel *c;
827 for (retries = 0; retries < 10; retries++) {
828 int done;
829 AST_LIST_LOCK(&channels);
830 AST_LIST_TRAVERSE(&channels, c, chan_list) {
831 if (prev) { /* look for next item */
832 if (c != prev) /* not this one */
833 continue;
834 /* found, prepare to return c->next */
835 c = AST_LIST_NEXT(c, chan_list);
836 } else if (name) { /* want match by name */
837 if ( (!namelen && strcasecmp(c->name, name)) ||
838 (namelen && strncasecmp(c->name, name, namelen)) )
839 continue; /* name match failed */
840 } else if (exten) {
841 if (context && strcasecmp(c->context, context) &&
842 strcasecmp(c->macrocontext, context))
843 continue; /* context match failed */
844 if (strcasecmp(c->exten, exten) &&
845 strcasecmp(c->macroexten, exten))
846 continue; /* exten match failed */
848 /* if we get here, c points to the desired record */
849 break;
851 /* exit if chan not found or mutex acquired successfully */
852 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
853 done = c == NULL || ast_channel_trylock(c) == 0;
854 if (!done)
855 ast_log(LOG_DEBUG, "Avoiding %s for channel '%p'\n", msg, c);
856 AST_LIST_UNLOCK(&channels);
857 if (done)
858 return c;
859 usleep(1); /* give other threads a chance before retrying */
862 * c is surely not null, but we don't have the lock so cannot
863 * access c->name
865 ast_log(LOG_DEBUG, "Failure, could not lock '%p' after %d retries!\n",
866 c, retries);
868 return NULL;
871 /*! \brief Browse channels in use */
872 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
874 return channel_find_locked(prev, NULL, 0, NULL, NULL);
877 /*! \brief Get channel by name and lock it */
878 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
880 return channel_find_locked(NULL, name, 0, NULL, NULL);
883 /*! \brief Get channel by name prefix and lock it */
884 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
886 return channel_find_locked(NULL, name, namelen, NULL, NULL);
889 /*! \brief Get next channel by name prefix and lock it */
890 struct ast_channel *ast_walk_channel_by_name_prefix_locked(struct ast_channel *chan, const char *name, const int namelen)
892 return channel_find_locked(chan, name, namelen, NULL, NULL);
895 /*! \brief Get channel by exten (and optionally context) and lock it */
896 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
898 return channel_find_locked(NULL, NULL, 0, context, exten);
901 /*! \brief Wait, look for hangups and condition arg */
902 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
904 struct ast_frame *f;
906 while (ms > 0) {
907 if (cond && ((*cond)(data) == 0))
908 return 0;
909 ms = ast_waitfor(chan, ms);
910 if (ms < 0)
911 return -1;
912 if (ms > 0) {
913 f = ast_read(chan);
914 if (!f)
915 return -1;
916 ast_frfree(f);
919 return 0;
922 /*! \brief Wait, look for hangups */
923 int ast_safe_sleep(struct ast_channel *chan, int ms)
925 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
928 static void free_cid(struct ast_callerid *cid)
930 if (cid->cid_dnid)
931 free(cid->cid_dnid);
932 if (cid->cid_num)
933 free(cid->cid_num);
934 if (cid->cid_name)
935 free(cid->cid_name);
936 if (cid->cid_ani)
937 free(cid->cid_ani);
938 if (cid->cid_rdnis)
939 free(cid->cid_rdnis);
942 /*! \brief Free a channel structure */
943 void ast_channel_free(struct ast_channel *chan)
945 int fd;
946 struct ast_var_t *vardata;
947 struct ast_frame *f, *fp;
948 struct varshead *headp;
949 struct ast_datastore *datastore = NULL;
950 char name[AST_CHANNEL_NAME];
952 headp=&chan->varshead;
954 AST_LIST_LOCK(&channels);
955 AST_LIST_REMOVE(&channels, chan, chan_list);
956 /* Lock and unlock the channel just to be sure nobody
957 has it locked still */
958 ast_channel_lock(chan);
959 ast_channel_unlock(chan);
960 if (chan->tech_pvt) {
961 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
962 free(chan->tech_pvt);
965 if (chan->sched)
966 sched_context_destroy(chan->sched);
968 ast_copy_string(name, chan->name, sizeof(name));
970 /* Stop monitoring */
971 if (chan->monitor) {
972 chan->monitor->stop( chan, 0 );
975 /* If there is native format music-on-hold state, free it */
976 if(chan->music_state)
977 ast_moh_cleanup(chan);
979 /* Free translators */
980 if (chan->readtrans)
981 ast_translator_free_path(chan->readtrans);
982 if (chan->writetrans)
983 ast_translator_free_path(chan->writetrans);
984 if (chan->pbx)
985 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
986 free_cid(&chan->cid);
987 ast_mutex_destroy(&chan->lock);
988 /* Close pipes if appropriate */
989 if ((fd = chan->alertpipe[0]) > -1)
990 close(fd);
991 if ((fd = chan->alertpipe[1]) > -1)
992 close(fd);
993 if ((fd = chan->timingfd) > -1)
994 close(fd);
995 f = chan->readq;
996 chan->readq = NULL;
997 while(f) {
998 fp = f;
999 f = f->next;
1000 ast_frfree(fp);
1003 /* Get rid of each of the data stores on the channel */
1004 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1005 /* Free the data store */
1006 ast_channel_datastore_free(datastore);
1007 AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1009 /* loop over the variables list, freeing all data and deleting list items */
1010 /* no need to lock the list, as the channel is already locked */
1012 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1013 ast_var_delete(vardata);
1015 ast_string_field_free_all(chan);
1016 free(chan);
1017 AST_LIST_UNLOCK(&channels);
1019 ast_device_state_changed_literal(name);
1022 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
1024 struct ast_datastore *datastore = NULL;
1026 /* Make sure we at least have type so we can identify this */
1027 if (info == NULL) {
1028 return NULL;
1031 /* Allocate memory for datastore and clear it */
1032 datastore = ast_calloc(1, sizeof(*datastore));
1033 if (datastore == NULL) {
1034 return NULL;
1037 datastore->info = info;
1039 datastore->uid = ast_strdup(uid);
1041 return datastore;
1044 int ast_channel_datastore_free(struct ast_datastore *datastore)
1046 int res = 0;
1048 /* Using the destroy function (if present) destroy the data */
1049 if (datastore->info->destroy != NULL && datastore->data != NULL) {
1050 datastore->info->destroy(datastore->data);
1051 datastore->data = NULL;
1054 /* Free allocated UID memory */
1055 if (datastore->uid != NULL) {
1056 free(datastore->uid);
1057 datastore->uid = NULL;
1060 /* Finally free memory used by ourselves */
1061 free(datastore);
1063 return res;
1066 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1068 int res = 0;
1070 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1072 return res;
1075 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1077 struct ast_datastore *datastore2 = NULL;
1078 int res = -1;
1080 /* Find our position and remove ourselves */
1081 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1082 if (datastore2 == datastore) {
1083 AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1084 res = 0;
1085 break;
1088 AST_LIST_TRAVERSE_SAFE_END
1090 return res;
1093 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
1095 struct ast_datastore *datastore = NULL;
1097 if (info == NULL)
1098 return NULL;
1100 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1101 if (datastore->info == info) {
1102 if (uid != NULL && datastore->uid != NULL) {
1103 if (!strcasecmp(uid, datastore->uid)) {
1104 /* Matched by type AND uid */
1105 break;
1107 } else {
1108 /* Matched by type at least */
1109 break;
1113 AST_LIST_TRAVERSE_SAFE_END
1115 return datastore;
1118 int ast_channel_spy_add(struct ast_channel *chan, struct ast_channel_spy *spy)
1120 if (!ast_test_flag(spy, CHANSPY_FORMAT_AUDIO)) {
1121 ast_log(LOG_WARNING, "Could not add channel spy '%s' to channel '%s', only audio format spies are supported.\n",
1122 spy->type, chan->name);
1123 return -1;
1126 if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST) && (spy->read_queue.format != AST_FORMAT_SLINEAR)) {
1127 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1128 ast_getformatname(spy->read_queue.format));
1129 return -1;
1132 if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST) && (spy->write_queue.format != AST_FORMAT_SLINEAR)) {
1133 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1134 ast_getformatname(spy->write_queue.format));
1135 return -1;
1138 if (ast_test_flag(spy, CHANSPY_MIXAUDIO) &&
1139 ((spy->read_queue.format != AST_FORMAT_SLINEAR) ||
1140 (spy->write_queue.format != AST_FORMAT_SLINEAR))) {
1141 ast_log(LOG_WARNING, "Cannot provide audio mixing on '%s'-'%s' format spies\n",
1142 ast_getformatname(spy->read_queue.format), ast_getformatname(spy->write_queue.format));
1143 return -1;
1146 if (!chan->spies) {
1147 if (!(chan->spies = ast_calloc(1, sizeof(*chan->spies)))) {
1148 return -1;
1151 AST_LIST_HEAD_INIT_NOLOCK(&chan->spies->list);
1152 AST_LIST_INSERT_HEAD(&chan->spies->list, spy, list);
1153 } else {
1154 AST_LIST_INSERT_TAIL(&chan->spies->list, spy, list);
1157 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1158 ast_cond_init(&spy->trigger, NULL);
1159 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1160 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1163 ast_log(LOG_DEBUG, "Spy %s added to channel %s\n",
1164 spy->type, chan->name);
1166 return 0;
1169 void ast_channel_spy_stop_by_type(struct ast_channel *chan, const char *type)
1171 struct ast_channel_spy *spy;
1173 if (!chan->spies)
1174 return;
1176 AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1177 ast_mutex_lock(&spy->lock);
1178 if ((spy->type == type) && (spy->status == CHANSPY_RUNNING)) {
1179 spy->status = CHANSPY_STOP;
1180 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1181 ast_cond_signal(&spy->trigger);
1183 ast_mutex_unlock(&spy->lock);
1187 void ast_channel_spy_trigger_wait(struct ast_channel_spy *spy)
1189 ast_cond_wait(&spy->trigger, &spy->lock);
1192 void ast_channel_spy_remove(struct ast_channel *chan, struct ast_channel_spy *spy)
1194 struct ast_frame *f;
1196 if (!chan->spies)
1197 return;
1199 AST_LIST_REMOVE(&chan->spies->list, spy, list);
1201 ast_mutex_lock(&spy->lock);
1203 for (f = spy->read_queue.head; f; f = spy->read_queue.head) {
1204 spy->read_queue.head = f->next;
1205 ast_frfree(f);
1207 for (f = spy->write_queue.head; f; f = spy->write_queue.head) {
1208 spy->write_queue.head = f->next;
1209 ast_frfree(f);
1212 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1213 ast_cond_destroy(&spy->trigger);
1215 ast_mutex_unlock(&spy->lock);
1217 ast_log(LOG_DEBUG, "Spy %s removed from channel %s\n",
1218 spy->type, chan->name);
1220 if (AST_LIST_EMPTY(&chan->spies->list)) {
1221 if (chan->spies->read_translator.path)
1222 ast_translator_free_path(chan->spies->read_translator.path);
1223 if (chan->spies->write_translator.path)
1224 ast_translator_free_path(chan->spies->write_translator.path);
1225 free(chan->spies);
1226 chan->spies = NULL;
1230 static void detach_spies(struct ast_channel *chan)
1232 struct ast_channel_spy *spy;
1234 if (!chan->spies)
1235 return;
1237 /* Marking the spies as done is sufficient. Chanspy or spy users will get the picture. */
1238 AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1239 ast_mutex_lock(&spy->lock);
1240 if (spy->status == CHANSPY_RUNNING)
1241 spy->status = CHANSPY_DONE;
1242 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1243 ast_cond_signal(&spy->trigger);
1244 ast_mutex_unlock(&spy->lock);
1247 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list)
1248 ast_channel_spy_remove(chan, spy);
1249 AST_LIST_TRAVERSE_SAFE_END;
1252 /*! \brief Softly hangup a channel, don't lock */
1253 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1255 if (option_debug)
1256 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
1257 /* Inform channel driver that we need to be hung up, if it cares */
1258 chan->_softhangup |= cause;
1259 ast_queue_frame(chan, &ast_null_frame);
1260 /* Interrupt any poll call or such */
1261 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1262 pthread_kill(chan->blocker, SIGURG);
1263 return 0;
1266 /*! \brief Softly hangup a channel, lock */
1267 int ast_softhangup(struct ast_channel *chan, int cause)
1269 int res;
1270 ast_channel_lock(chan);
1271 res = ast_softhangup_nolock(chan, cause);
1272 ast_channel_unlock(chan);
1273 return res;
1276 enum spy_direction {
1277 SPY_READ,
1278 SPY_WRITE,
1281 #define SPY_QUEUE_SAMPLE_LIMIT 4000 /* half of one second */
1283 static void queue_frame_to_spies(struct ast_channel *chan, struct ast_frame *f, enum spy_direction dir)
1285 struct ast_frame *translated_frame = NULL;
1286 struct ast_channel_spy *spy;
1287 struct channel_spy_trans *trans;
1289 trans = (dir == SPY_READ) ? &chan->spies->read_translator : &chan->spies->write_translator;
1291 AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1292 struct ast_frame *last;
1293 struct ast_frame *f1; /* the frame to append */
1294 struct ast_channel_spy_queue *queue;
1296 ast_mutex_lock(&spy->lock);
1298 queue = (dir == SPY_READ) ? &spy->read_queue : &spy->write_queue;
1300 if ((queue->format == AST_FORMAT_SLINEAR) && (f->subclass != AST_FORMAT_SLINEAR)) {
1301 if (!translated_frame) {
1302 if (trans->path && (trans->last_format != f->subclass)) {
1303 ast_translator_free_path(trans->path);
1304 trans->path = NULL;
1306 if (!trans->path) {
1307 ast_log(LOG_DEBUG, "Building translator from %s to SLINEAR for spies on channel %s\n",
1308 ast_getformatname(f->subclass), chan->name);
1309 if ((trans->path = ast_translator_build_path(AST_FORMAT_SLINEAR, f->subclass)) == NULL) {
1310 ast_log(LOG_WARNING, "Cannot build a path from %s to %s\n",
1311 ast_getformatname(f->subclass), ast_getformatname(AST_FORMAT_SLINEAR));
1312 ast_mutex_unlock(&spy->lock);
1313 continue;
1314 } else {
1315 trans->last_format = f->subclass;
1318 if (!(translated_frame = ast_translate(trans->path, f, 0))) {
1319 ast_log(LOG_ERROR, "Translation to %s failed, dropping frame for spies\n",
1320 ast_getformatname(AST_FORMAT_SLINEAR));
1321 ast_mutex_unlock(&spy->lock);
1322 break;
1325 f1 = translated_frame;
1326 } else {
1327 if (f->subclass != queue->format) {
1328 ast_log(LOG_WARNING, "Spy '%s' on channel '%s' wants format '%s', but frame is '%s', dropping\n",
1329 spy->type, chan->name,
1330 ast_getformatname(queue->format), ast_getformatname(f->subclass));
1331 ast_mutex_unlock(&spy->lock);
1332 continue;
1334 f1 = f;
1336 /* duplicate and append f1 to the tail */
1337 f1 = ast_frdup(f1);
1339 for (last = queue->head; last && last->next; last = last->next)
1341 if (last)
1342 last->next = f1;
1343 else
1344 queue->head = f1;
1346 queue->samples += f->samples;
1348 if (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1349 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1350 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1351 case CHANSPY_TRIGGER_READ:
1352 if (dir == SPY_WRITE) {
1353 ast_set_flag(spy, CHANSPY_TRIGGER_WRITE);
1354 ast_clear_flag(spy, CHANSPY_TRIGGER_READ);
1355 if (option_debug)
1356 ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to write-trigger mode\n",
1357 spy->type, chan->name);
1359 break;
1360 case CHANSPY_TRIGGER_WRITE:
1361 if (dir == SPY_READ) {
1362 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1363 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1364 if (option_debug)
1365 ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to read-trigger mode\n",
1366 spy->type, chan->name);
1368 break;
1370 if (option_debug)
1371 ast_log(LOG_DEBUG, "Triggering queue flush for spy '%s' on '%s'\n",
1372 spy->type, chan->name);
1373 ast_set_flag(spy, CHANSPY_TRIGGER_FLUSH);
1374 ast_cond_signal(&spy->trigger);
1375 } else {
1376 if (option_debug)
1377 ast_log(LOG_DEBUG, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1378 spy->type, chan->name, (dir == SPY_READ) ? "read" : "write");
1379 while (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1380 struct ast_frame *drop = queue->head;
1382 queue->samples -= drop->samples;
1383 queue->head = drop->next;
1384 ast_frfree(drop);
1387 } else {
1388 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1389 case CHANSPY_TRIGGER_READ:
1390 if (dir == SPY_READ)
1391 ast_cond_signal(&spy->trigger);
1392 break;
1393 case CHANSPY_TRIGGER_WRITE:
1394 if (dir == SPY_WRITE)
1395 ast_cond_signal(&spy->trigger);
1396 break;
1400 ast_mutex_unlock(&spy->lock);
1403 if (translated_frame)
1404 ast_frfree(translated_frame);
1407 static void free_translation(struct ast_channel *clone)
1409 if (clone->writetrans)
1410 ast_translator_free_path(clone->writetrans);
1411 if (clone->readtrans)
1412 ast_translator_free_path(clone->readtrans);
1413 clone->writetrans = NULL;
1414 clone->readtrans = NULL;
1415 clone->rawwriteformat = clone->nativeformats;
1416 clone->rawreadformat = clone->nativeformats;
1419 /*! \brief Hangup a channel */
1420 int ast_hangup(struct ast_channel *chan)
1422 int res = 0;
1424 /* Don't actually hang up a channel that will masquerade as someone else, or
1425 if someone is going to masquerade as us */
1426 ast_channel_lock(chan);
1428 detach_spies(chan); /* get rid of spies */
1430 if (chan->masq) {
1431 if (ast_do_masquerade(chan))
1432 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1435 if (chan->masq) {
1436 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1437 ast_channel_unlock(chan);
1438 return 0;
1440 /* If this channel is one which will be masqueraded into something,
1441 mark it as a zombie already, so we know to free it later */
1442 if (chan->masqr) {
1443 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1444 ast_channel_unlock(chan);
1445 return 0;
1447 free_translation(chan);
1448 if (chan->stream) /* Close audio stream */
1449 ast_closestream(chan->stream);
1450 if (chan->vstream) /* Close video stream */
1451 ast_closestream(chan->vstream);
1452 if (chan->sched) {
1453 sched_context_destroy(chan->sched);
1454 chan->sched = NULL;
1457 if (chan->generatordata) /* Clear any tone stuff remaining */
1458 chan->generator->release(chan, chan->generatordata);
1459 chan->generatordata = NULL;
1460 chan->generator = NULL;
1461 if (chan->cdr) { /* End the CDR if it hasn't already */
1462 ast_cdr_end(chan->cdr);
1463 ast_cdr_detach(chan->cdr); /* Post and Free the CDR */
1464 chan->cdr = NULL;
1466 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1467 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1468 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1469 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1470 CRASH;
1472 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1473 if (option_debug)
1474 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1475 if (chan->tech->hangup)
1476 res = chan->tech->hangup(chan);
1477 } else {
1478 if (option_debug)
1479 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1482 ast_channel_unlock(chan);
1483 manager_event(EVENT_FLAG_CALL, "Hangup",
1484 "Channel: %s\r\n"
1485 "Uniqueid: %s\r\n"
1486 "Cause: %d\r\n"
1487 "Cause-txt: %s\r\n",
1488 chan->name,
1489 chan->uniqueid,
1490 chan->hangupcause,
1491 ast_cause2str(chan->hangupcause)
1493 ast_channel_free(chan);
1494 return res;
1497 int ast_answer(struct ast_channel *chan)
1499 int res = 0;
1500 ast_channel_lock(chan);
1501 /* You can't answer an outbound call */
1502 if (ast_test_flag(chan, AST_FLAG_OUTGOING))
1503 return 0;
1504 /* Stop if we're a zombie or need a soft hangup */
1505 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1506 ast_channel_unlock(chan);
1507 return -1;
1509 switch(chan->_state) {
1510 case AST_STATE_RINGING:
1511 case AST_STATE_RING:
1512 if (chan->tech->answer)
1513 res = chan->tech->answer(chan);
1514 ast_setstate(chan, AST_STATE_UP);
1515 ast_cdr_answer(chan->cdr);
1516 break;
1517 case AST_STATE_UP:
1518 ast_cdr_answer(chan->cdr);
1519 break;
1521 ast_channel_unlock(chan);
1522 return res;
1525 void ast_deactivate_generator(struct ast_channel *chan)
1527 ast_channel_lock(chan);
1528 if (chan->generatordata) {
1529 if (chan->generator && chan->generator->release)
1530 chan->generator->release(chan, chan->generatordata);
1531 chan->generatordata = NULL;
1532 chan->generator = NULL;
1533 chan->fds[AST_GENERATOR_FD] = -1;
1534 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1535 ast_settimeout(chan, 0, NULL, NULL);
1537 ast_channel_unlock(chan);
1540 static int generator_force(void *data)
1542 /* Called if generator doesn't have data */
1543 void *tmp;
1544 int res;
1545 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1546 struct ast_channel *chan = data;
1547 tmp = chan->generatordata;
1548 chan->generatordata = NULL;
1549 generate = chan->generator->generate;
1550 res = generate(chan, tmp, 0, 160);
1551 chan->generatordata = tmp;
1552 if (res) {
1553 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1554 ast_deactivate_generator(chan);
1556 return 0;
1559 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1561 int res = 0;
1563 ast_channel_lock(chan);
1565 if (chan->generatordata) {
1566 if (chan->generator && chan->generator->release)
1567 chan->generator->release(chan, chan->generatordata);
1568 chan->generatordata = NULL;
1571 ast_prod(chan);
1572 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1573 res = -1;
1576 if (!res) {
1577 ast_settimeout(chan, 160, generator_force, chan);
1578 chan->generator = gen;
1581 ast_channel_unlock(chan);
1583 return res;
1586 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1587 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1589 int winner = -1;
1590 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1591 return winner;
1594 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1595 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1596 int *exception, int *outfd, int *ms)
1598 struct timeval start = { 0 , 0 };
1599 struct pollfd *pfds;
1600 int res;
1601 long rms;
1602 int x, y, max;
1603 int sz;
1604 time_t now = 0;
1605 long whentohangup = 0, diff;
1606 struct ast_channel *winner = NULL;
1607 struct fdmap {
1608 int chan;
1609 int fdno;
1610 } *fdmap;
1612 sz = n * AST_MAX_FDS + nfds;
1613 pfds = alloca(sizeof(*pfds) * sz);
1614 fdmap = alloca(sizeof(*fdmap) * sz);
1616 if (outfd)
1617 *outfd = -99999;
1618 if (exception)
1619 *exception = 0;
1621 /* Perform any pending masquerades */
1622 for (x=0; x < n; x++) {
1623 ast_channel_lock(c[x]);
1624 if (c[x]->masq) {
1625 if (ast_do_masquerade(c[x])) {
1626 ast_log(LOG_WARNING, "Masquerade failed\n");
1627 *ms = -1;
1628 ast_channel_unlock(c[x]);
1629 return NULL;
1632 if (c[x]->whentohangup) {
1633 if (!whentohangup)
1634 time(&now);
1635 diff = c[x]->whentohangup - now;
1636 if (diff < 1) {
1637 /* Should already be hungup */
1638 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1639 ast_channel_unlock(c[x]);
1640 return c[x];
1642 if (!whentohangup || (diff < whentohangup))
1643 whentohangup = diff;
1645 ast_channel_unlock(c[x]);
1647 /* Wait full interval */
1648 rms = *ms;
1649 if (whentohangup) {
1650 rms = (whentohangup - now) * 1000; /* timeout in milliseconds */
1651 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1652 rms = *ms;
1655 * Build the pollfd array, putting the channels' fds first,
1656 * followed by individual fds. Order is important because
1657 * individual fd's must have priority over channel fds.
1659 max = 0;
1660 for (x=0; x<n; x++) {
1661 for (y=0; y<AST_MAX_FDS; y++) {
1662 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1663 fdmap[max].chan = x; /* channel x is linked to this pfds */
1664 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1666 CHECK_BLOCKING(c[x]);
1668 /* Add the individual fds */
1669 for (x=0; x<nfds; x++) {
1670 fdmap[max].chan = -1;
1671 max += ast_add_fd(&pfds[max], fds[x]);
1674 if (*ms > 0)
1675 start = ast_tvnow();
1677 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1678 do {
1679 int kbrms = rms;
1680 if (kbrms > 600000)
1681 kbrms = 600000;
1682 res = poll(pfds, max, kbrms);
1683 if (!res)
1684 rms -= kbrms;
1685 } while (!res && (rms > 0));
1686 } else {
1687 res = poll(pfds, max, rms);
1689 for (x=0; x<n; x++)
1690 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1691 if (res < 0) { /* Simulate a timeout if we were interrupted */
1692 if (errno != EINTR)
1693 *ms = -1;
1694 return NULL;
1696 if (whentohangup) { /* if we have a timeout, check who expired */
1697 time(&now);
1698 for (x=0; x<n; x++) {
1699 if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1700 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1701 if (winner == NULL)
1702 winner = c[x];
1706 if (res == 0) { /* no fd ready, reset timeout and done */
1707 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1708 return winner;
1711 * Then check if any channel or fd has a pending event.
1712 * Remember to check channels first and fds last, as they
1713 * must have priority on setting 'winner'
1715 for (x = 0; x < max; x++) {
1716 res = pfds[x].revents;
1717 if (res == 0)
1718 continue;
1719 if (fdmap[x].chan >= 0) { /* this is a channel */
1720 winner = c[fdmap[x].chan]; /* override previous winners */
1721 if (res & POLLPRI)
1722 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1723 else
1724 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1725 winner->fdno = fdmap[x].fdno;
1726 } else { /* this is an fd */
1727 if (outfd)
1728 *outfd = pfds[x].fd;
1729 if (exception)
1730 *exception = (res & POLLPRI) ? -1 : 0;
1731 winner = NULL;
1734 if (*ms > 0) {
1735 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1736 if (*ms < 0)
1737 *ms = 0;
1739 return winner;
1742 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1744 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1747 int ast_waitfor(struct ast_channel *c, int ms)
1749 int oldms = ms; /* -1 if no timeout */
1751 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1752 if ((ms < 0) && (oldms < 0))
1753 ms = 0;
1754 return ms;
1757 /* XXX never to be called with ms = -1 */
1758 int ast_waitfordigit(struct ast_channel *c, int ms)
1760 return ast_waitfordigit_full(c, ms, -1, -1);
1763 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1765 int res = -1;
1766 #ifdef HAVE_ZAPTEL
1767 if (c->timingfd > -1) {
1768 if (!func) {
1769 samples = 0;
1770 data = 0;
1772 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1773 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1774 c->timingfunc = func;
1775 c->timingdata = data;
1777 #endif
1778 return res;
1781 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1784 /* Stop if we're a zombie or need a soft hangup */
1785 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1786 return -1;
1787 /* Wait for a digit, no more than ms milliseconds total. */
1788 while (ms) {
1789 struct ast_channel *rchan;
1790 int outfd;
1792 errno = 0;
1793 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1794 if (!rchan && outfd < 0 && ms) {
1795 if (errno == 0 || errno == EINTR)
1796 continue;
1797 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1798 return -1;
1799 } else if (outfd > -1) {
1800 /* The FD we were watching has something waiting */
1801 return 1;
1802 } else if (rchan) {
1803 int res;
1804 struct ast_frame *f = ast_read(c);
1805 if (!f)
1806 return -1;
1808 switch(f->frametype) {
1809 case AST_FRAME_DTMF:
1810 res = f->subclass;
1811 ast_frfree(f);
1812 return res;
1813 case AST_FRAME_CONTROL:
1814 switch(f->subclass) {
1815 case AST_CONTROL_HANGUP:
1816 ast_frfree(f);
1817 return -1;
1818 case AST_CONTROL_RINGING:
1819 case AST_CONTROL_ANSWER:
1820 /* Unimportant */
1821 break;
1822 default:
1823 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1825 case AST_FRAME_VOICE:
1826 /* Write audio if appropriate */
1827 if (audiofd > -1)
1828 write(audiofd, f->data, f->datalen);
1830 /* Ignore */
1831 ast_frfree(f);
1834 return 0; /* Time is up */
1837 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
1839 struct ast_frame *f = NULL; /* the return value */
1840 int blah;
1841 int prestate;
1843 /* this function is very long so make sure there is only one return
1844 * point at the end (there is only one exception to this).
1846 ast_channel_lock(chan);
1847 if (chan->masq) {
1848 if (ast_do_masquerade(chan)) {
1849 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1850 } else {
1851 f = &ast_null_frame;
1853 goto done;
1856 /* Stop if we're a zombie or need a soft hangup */
1857 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1858 if (chan->generator)
1859 ast_deactivate_generator(chan);
1860 goto done;
1862 prestate = chan->_state;
1864 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1865 /* We have DTMF that has been deferred. Return it now */
1866 chan->dtmff.frametype = AST_FRAME_DTMF;
1867 chan->dtmff.subclass = chan->dtmfq[0];
1868 /* Drop first digit from the buffer */
1869 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1870 f = &chan->dtmff;
1871 goto done;
1874 /* Read and ignore anything on the alertpipe, but read only
1875 one sizeof(blah) per frame that we send from it */
1876 if (chan->alertpipe[0] > -1)
1877 read(chan->alertpipe[0], &blah, sizeof(blah));
1879 #ifdef HAVE_ZAPTEL
1880 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1881 int res;
1883 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1884 blah = -1;
1885 /* IF we can't get event, assume it's an expired as-per the old interface */
1886 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1887 if (res)
1888 blah = ZT_EVENT_TIMER_EXPIRED;
1890 if (blah == ZT_EVENT_TIMER_PING) {
1891 if (!chan->readq || !chan->readq->next) {
1892 /* Acknowledge PONG unless we need it again */
1893 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1894 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1897 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1898 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1899 if (chan->timingfunc) {
1900 /* save a copy of func/data before unlocking the channel */
1901 int (*func)(void *) = chan->timingfunc;
1902 void *data = chan->timingdata;
1903 ast_channel_unlock(chan);
1904 func(data);
1905 } else {
1906 blah = 0;
1907 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1908 chan->timingdata = NULL;
1909 ast_channel_unlock(chan);
1911 /* cannot 'goto done' because the channel is already unlocked */
1912 return &ast_null_frame;
1913 } else
1914 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1915 } else
1916 #endif
1917 if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
1918 /* if the AST_GENERATOR_FD is set, call the generator with args
1919 * set to -1 so it can do whatever it needs to.
1921 void *tmp = chan->generatordata;
1922 chan->generatordata = NULL; /* reset to let ast_write get through */
1923 chan->generator->generate(chan, tmp, -1, -1);
1924 chan->generatordata = tmp;
1925 f = &ast_null_frame;
1926 goto done;
1929 /* Check for pending read queue */
1930 if (chan->readq) {
1931 f = chan->readq;
1932 chan->readq = f->next;
1933 f->next = NULL;
1934 /* Interpret hangup and return NULL */
1935 /* XXX why not the same for frames from the channel ? */
1936 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
1937 ast_frfree(f);
1938 f = NULL;
1940 } else {
1941 chan->blocker = pthread_self();
1942 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1943 if (chan->tech->exception)
1944 f = chan->tech->exception(chan);
1945 else {
1946 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1947 f = &ast_null_frame;
1949 /* Clear the exception flag */
1950 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1951 } else if (chan->tech->read)
1952 f = chan->tech->read(chan);
1953 else
1954 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1957 if (f) {
1958 /* if the channel driver returned more than one frame, stuff the excess
1959 into the readq for the next ast_read call
1961 if (f->next) {
1962 chan->readq = f->next;
1963 f->next = NULL;
1966 switch (f->frametype) {
1967 case AST_FRAME_CONTROL:
1968 if (f->subclass == AST_CONTROL_ANSWER) {
1969 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1970 ast_log(LOG_DEBUG, "Ignoring answer on an inbound call!\n");
1971 ast_frfree(f);
1972 f = &ast_null_frame;
1973 } else if (prestate == AST_STATE_UP) {
1974 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1975 ast_frfree(f);
1976 f = &ast_null_frame;
1977 } else {
1978 /* Answer the CDR */
1979 ast_setstate(chan, AST_STATE_UP);
1980 ast_cdr_answer(chan->cdr);
1983 break;
1984 case AST_FRAME_DTMF:
1985 ast_log(LOG_DTMF, "DTMF '%c' received on %s\n", f->subclass, chan->name);
1986 if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF)) {
1987 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1988 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1989 else
1990 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1991 ast_frfree(f);
1992 f = &ast_null_frame;
1994 break;
1995 case AST_FRAME_DTMF_BEGIN:
1996 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
1997 break;
1998 case AST_FRAME_DTMF_END:
1999 ast_log(LOG_DTMF, "DTMF end '%c' received on %s\n", f->subclass, chan->name);
2000 break;
2001 case AST_FRAME_VOICE:
2002 if (dropaudio) {
2003 ast_frfree(f);
2004 f = &ast_null_frame;
2005 } else if (!(f->subclass & chan->nativeformats)) {
2006 /* This frame can't be from the current native formats -- drop it on the
2007 floor */
2008 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2009 chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2010 ast_frfree(f);
2011 f = &ast_null_frame;
2012 } else {
2013 if (chan->spies)
2014 queue_frame_to_spies(chan, f, SPY_READ);
2016 if (chan->monitor && chan->monitor->read_stream ) {
2017 /* XXX what does this do ? */
2018 #ifndef MONITOR_CONSTANT_DELAY
2019 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2020 if (jump >= 0) {
2021 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2022 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2023 chan->insmpl += jump + 4 * f->samples;
2024 } else
2025 chan->insmpl+= f->samples;
2026 #else
2027 int jump = chan->outsmpl - chan->insmpl;
2028 if (jump - MONITOR_DELAY >= 0) {
2029 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2030 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2031 chan->insmpl += jump;
2032 } else
2033 chan->insmpl += f->samples;
2034 #endif
2035 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2036 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2037 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2041 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2042 f = &ast_null_frame;
2044 /* Run generator sitting on the line if timing device not available
2045 * and synchronous generation of outgoing frames is necessary */
2046 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
2047 void *tmp = chan->generatordata;
2048 int res;
2050 if (chan->timingfunc) {
2051 if (option_debug > 1)
2052 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2053 ast_settimeout(chan, 0, NULL, NULL);
2056 chan->generatordata = NULL; /* reset, to let writes go through */
2057 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2058 chan->generatordata = tmp;
2059 if (res) {
2060 if (option_debug > 1)
2061 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2062 ast_deactivate_generator(chan);
2065 } else if (f->frametype == AST_FRAME_CNG) {
2066 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2067 if (option_debug > 1)
2068 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2069 ast_settimeout(chan, 160, generator_force, chan);
2074 } else {
2075 /* Make sure we always return NULL in the future */
2076 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2077 if (chan->generator)
2078 ast_deactivate_generator(chan);
2079 /* End the CDR if appropriate */
2080 if (chan->cdr)
2081 ast_cdr_end(chan->cdr);
2084 /* High bit prints debugging */
2085 if (chan->fin & DEBUGCHAN_FLAG)
2086 ast_frame_dump(chan->name, f, "<<");
2087 chan->fin = FRAMECOUNT_INC(chan->fin);
2089 done:
2090 ast_channel_unlock(chan);
2091 return f;
2094 int ast_internal_timing_enabled(struct ast_channel *chan)
2096 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2097 if (option_debug > 3)
2098 ast_log(LOG_DEBUG, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2099 return ret;
2102 struct ast_frame *ast_read(struct ast_channel *chan)
2104 return __ast_read(chan, 0);
2107 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2109 return __ast_read(chan, 1);
2112 int ast_indicate(struct ast_channel *chan, int condition)
2114 return ast_indicate_data(chan, condition, NULL, 0);
2117 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2119 int res = -1;
2121 ast_channel_lock(chan);
2122 /* Stop if we're a zombie or need a soft hangup */
2123 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2124 ast_channel_unlock(chan);
2125 return -1;
2127 if (chan->tech->indicate)
2128 res = chan->tech->indicate(chan, condition, data, datalen);
2129 ast_channel_unlock(chan);
2130 if (!chan->tech->indicate || res) {
2132 * Device does not support (that) indication, lets fake
2133 * it by doing our own tone generation. (PM2002)
2135 if (condition < 0)
2136 ast_playtones_stop(chan);
2137 else {
2138 const struct tone_zone_sound *ts = NULL;
2139 switch (condition) {
2140 case AST_CONTROL_RINGING:
2141 ts = ast_get_indication_tone(chan->zone, "ring");
2142 break;
2143 case AST_CONTROL_BUSY:
2144 ts = ast_get_indication_tone(chan->zone, "busy");
2145 break;
2146 case AST_CONTROL_CONGESTION:
2147 ts = ast_get_indication_tone(chan->zone, "congestion");
2148 break;
2150 if (ts && ts->data[0]) {
2151 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2152 ast_playtones_start(chan,0,ts->data, 1);
2153 res = 0;
2154 } else if (condition == AST_CONTROL_PROGRESS) {
2155 /* ast_playtones_stop(chan); */
2156 } else if (condition == AST_CONTROL_PROCEEDING) {
2157 /* Do nothing, really */
2158 } else if (condition == AST_CONTROL_HOLD) {
2159 /* Do nothing.... */
2160 } else if (condition == AST_CONTROL_UNHOLD) {
2161 /* Do nothing.... */
2162 } else if (condition == AST_CONTROL_VIDUPDATE) {
2163 /* Do nothing.... */
2164 } else {
2165 /* not handled */
2166 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2167 res = -1;
2171 return res;
2174 int ast_recvchar(struct ast_channel *chan, int timeout)
2176 int c;
2177 char *buf = ast_recvtext(chan, timeout);
2178 if (buf == NULL)
2179 return -1; /* error or timeout */
2180 c = *(unsigned char *)buf;
2181 free(buf);
2182 return c;
2185 char *ast_recvtext(struct ast_channel *chan, int timeout)
2187 int res, done = 0;
2188 char *buf = NULL;
2190 while (!done) {
2191 struct ast_frame *f;
2192 if (ast_check_hangup(chan))
2193 break;
2194 res = ast_waitfor(chan, timeout);
2195 if (res <= 0) /* timeout or error */
2196 break;
2197 timeout = res; /* update timeout */
2198 f = ast_read(chan);
2199 if (f == NULL)
2200 break; /* no frame */
2201 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2202 done = 1; /* force a break */
2203 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2204 buf = ast_strndup((char *) f->data, f->datalen); /* dup and break */
2205 done = 1;
2207 ast_frfree(f);
2209 return buf;
2212 int ast_sendtext(struct ast_channel *chan, const char *text)
2214 int res = 0;
2215 /* Stop if we're a zombie or need a soft hangup */
2216 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2217 return -1;
2218 CHECK_BLOCKING(chan);
2219 if (chan->tech->send_text)
2220 res = chan->tech->send_text(chan, text);
2221 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2222 return res;
2225 static int do_senddigit(struct ast_channel *chan, char digit)
2227 int res = -1;
2229 if (chan->tech->send_digit)
2230 res = chan->tech->send_digit(chan, digit);
2231 if (res) {
2233 * Device does not support DTMF tones, lets fake
2234 * it by doing our own generation. (PM2002)
2236 static const char* dtmf_tones[] = {
2237 "!941+1336/100,!0/100", /* 0 */
2238 "!697+1209/100,!0/100", /* 1 */
2239 "!697+1336/100,!0/100", /* 2 */
2240 "!697+1477/100,!0/100", /* 3 */
2241 "!770+1209/100,!0/100", /* 4 */
2242 "!770+1336/100,!0/100", /* 5 */
2243 "!770+1477/100,!0/100", /* 6 */
2244 "!852+1209/100,!0/100", /* 7 */
2245 "!852+1336/100,!0/100", /* 8 */
2246 "!852+1477/100,!0/100", /* 9 */
2247 "!697+1633/100,!0/100", /* A */
2248 "!770+1633/100,!0/100", /* B */
2249 "!852+1633/100,!0/100", /* C */
2250 "!941+1633/100,!0/100", /* D */
2251 "!941+1209/100,!0/100", /* * */
2252 "!941+1477/100,!0/100" }; /* # */
2253 if (digit >= '0' && digit <='9')
2254 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2255 else if (digit >= 'A' && digit <= 'D')
2256 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2257 else if (digit == '*')
2258 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2259 else if (digit == '#')
2260 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2261 else {
2262 /* not handled */
2263 ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2266 return 0;
2269 int ast_senddigit(struct ast_channel *chan, char digit)
2271 return do_senddigit(chan, digit);
2274 int ast_prod(struct ast_channel *chan)
2276 struct ast_frame a = { AST_FRAME_VOICE };
2277 char nothing[128];
2279 /* Send an empty audio frame to get things moving */
2280 if (chan->_state != AST_STATE_UP) {
2281 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
2282 a.subclass = chan->rawwriteformat;
2283 a.data = nothing + AST_FRIENDLY_OFFSET;
2284 a.src = "ast_prod";
2285 if (ast_write(chan, &a))
2286 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2288 return 0;
2291 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2293 int res;
2294 if (!chan->tech->write_video)
2295 return 0;
2296 res = ast_write(chan, fr);
2297 if (!res)
2298 res = 1;
2299 return res;
2302 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2304 int res = -1;
2305 struct ast_frame *f = NULL;
2307 /* Stop if we're a zombie or need a soft hangup */
2308 ast_channel_lock(chan);
2309 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2310 goto done;
2312 /* Handle any pending masquerades */
2313 if (chan->masq && ast_do_masquerade(chan)) {
2314 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2315 goto done;
2317 if (chan->masqr) {
2318 res = 0; /* XXX explain, why 0 ? */
2319 goto done;
2321 if (chan->generatordata) {
2322 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2323 ast_deactivate_generator(chan);
2324 else {
2325 res = 0; /* XXX explain, why 0 ? */
2326 goto done;
2329 /* High bit prints debugging */
2330 if (chan->fout & DEBUGCHAN_FLAG)
2331 ast_frame_dump(chan->name, fr, ">>");
2332 CHECK_BLOCKING(chan);
2333 switch(fr->frametype) {
2334 case AST_FRAME_CONTROL:
2335 /* XXX Interpret control frames XXX */
2336 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
2337 break;
2338 case AST_FRAME_DTMF_BEGIN:
2339 res = (chan->tech->send_digit_begin == NULL) ? 0 :
2340 chan->tech->send_digit_begin(chan, fr->subclass);
2341 break;
2342 case AST_FRAME_DTMF_END:
2343 res = (chan->tech->send_digit_end == NULL) ? 0 :
2344 chan->tech->send_digit_end(chan);
2345 break;
2346 case AST_FRAME_DTMF:
2347 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2348 ast_channel_unlock(chan);
2349 res = do_senddigit(chan,fr->subclass);
2350 ast_channel_lock(chan);
2351 CHECK_BLOCKING(chan);
2352 break;
2353 case AST_FRAME_TEXT:
2354 res = (chan->tech->send_text == NULL) ? 0 :
2355 chan->tech->send_text(chan, (char *) fr->data);
2356 break;
2357 case AST_FRAME_HTML:
2358 res = (chan->tech->send_html == NULL) ? 0 :
2359 chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2360 break;
2361 case AST_FRAME_VIDEO:
2362 /* XXX Handle translation of video codecs one day XXX */
2363 res = (chan->tech->write_video == NULL) ? 0 :
2364 chan->tech->write_video(chan, fr);
2365 break;
2366 case AST_FRAME_VOICE:
2367 if (chan->tech->write == NULL)
2368 break; /*! \todo XXX should return 0 maybe ? */
2370 /* Bypass translator if we're writing format in the raw write format. This
2371 allows mixing of native / non-native formats */
2372 if (fr->subclass == chan->rawwriteformat)
2373 f = fr;
2374 else
2375 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2376 if (f == NULL) {
2377 res = 0;
2378 } else {
2379 if (chan->spies)
2380 queue_frame_to_spies(chan, f, SPY_WRITE);
2382 if (chan->monitor && chan->monitor->write_stream) {
2383 /* XXX must explain this code */
2384 #ifndef MONITOR_CONSTANT_DELAY
2385 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2386 if (jump >= 0) {
2387 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2388 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2389 chan->outsmpl += jump + 4 * f->samples;
2390 } else
2391 chan->outsmpl += f->samples;
2392 #else
2393 int jump = chan->insmpl - chan->outsmpl;
2394 if (jump - MONITOR_DELAY >= 0) {
2395 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2396 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2397 chan->outsmpl += jump;
2398 } else
2399 chan->outsmpl += f->samples;
2400 #endif
2401 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2402 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2403 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2407 res = chan->tech->write(chan, f);
2409 break;
2412 if (f && f != fr)
2413 ast_frfree(f);
2414 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2415 /* Consider a write failure to force a soft hangup */
2416 if (res < 0)
2417 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2418 else {
2419 chan->fout = FRAMECOUNT_INC(chan->fout);
2421 done:
2422 ast_channel_unlock(chan);
2423 return res;
2426 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2427 struct ast_trans_pvt **trans, const int direction)
2429 int native;
2430 int res;
2432 /* Make sure we only consider audio */
2433 fmt &= AST_FORMAT_AUDIO_MASK;
2435 native = chan->nativeformats;
2436 /* Find a translation path from the native format to one of the desired formats */
2437 if (!direction)
2438 /* reading */
2439 res = ast_translator_best_choice(&fmt, &native);
2440 else
2441 /* writing */
2442 res = ast_translator_best_choice(&native, &fmt);
2444 if (res < 0) {
2445 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2446 ast_getformatname(native), ast_getformatname(fmt));
2447 return -1;
2450 /* Now we have a good choice for both. */
2451 ast_channel_lock(chan);
2452 *rawformat = native;
2453 /* User perspective is fmt */
2454 *format = fmt;
2455 /* Free any read translation we have right now */
2456 if (*trans)
2457 ast_translator_free_path(*trans);
2458 /* Build a translation path from the raw format to the desired format */
2459 if (!direction)
2460 /* reading */
2461 *trans = ast_translator_build_path(*format, *rawformat);
2462 else
2463 /* writing */
2464 *trans = ast_translator_build_path(*rawformat, *format);
2465 ast_channel_unlock(chan);
2466 if (option_debug)
2467 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2468 direction ? "write" : "read", ast_getformatname(fmt));
2469 return 0;
2472 int ast_set_read_format(struct ast_channel *chan, int fmt)
2474 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2475 &chan->readtrans, 0);
2478 int ast_set_write_format(struct ast_channel *chan, int fmt)
2480 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2481 &chan->writetrans, 1);
2484 struct ast_channel *__ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cid_num, const char *cid_name, struct outgoing_helper *oh)
2486 int dummy_outstate;
2487 int cause = 0;
2488 struct ast_channel *chan;
2489 int res = 0;
2491 if (outstate)
2492 *outstate = 0;
2493 else
2494 outstate = &dummy_outstate; /* make outstate always a valid pointer */
2496 chan = ast_request(type, format, data, &cause);
2497 if (!chan) {
2498 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2499 /* compute error and return */
2500 if (cause == AST_CAUSE_BUSY)
2501 *outstate = AST_CONTROL_BUSY;
2502 else if (cause == AST_CAUSE_CONGESTION)
2503 *outstate = AST_CONTROL_CONGESTION;
2504 return NULL;
2507 if (oh) {
2508 if (oh->vars)
2509 ast_set_variables(chan, oh->vars);
2510 /* XXX why is this necessary, for the parent_channel perhaps ? */
2511 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2512 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2513 if (oh->parent_channel)
2514 ast_channel_inherit_variables(oh->parent_channel, chan);
2515 if (oh->account)
2516 ast_cdr_setaccount(chan, oh->account);
2518 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2520 if (ast_call(chan, data, 0)) { /* ast_call failed... */
2521 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2522 } else {
2523 res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
2524 while (timeout && chan->_state != AST_STATE_UP) {
2525 struct ast_frame *f;
2526 res = ast_waitfor(chan, timeout);
2527 if (res <= 0) /* error, timeout, or done */
2528 break;
2529 if (timeout > -1)
2530 timeout = res;
2531 f = ast_read(chan);
2532 if (!f) {
2533 *outstate = AST_CONTROL_HANGUP;
2534 res = 0;
2535 break;
2537 if (f->frametype == AST_FRAME_CONTROL) {
2538 switch (f->subclass) {
2539 case AST_CONTROL_RINGING: /* record but keep going */
2540 *outstate = f->subclass;
2541 break;
2543 case AST_CONTROL_BUSY:
2544 case AST_CONTROL_CONGESTION:
2545 case AST_CONTROL_ANSWER:
2546 *outstate = f->subclass;
2547 timeout = 0; /* trick to force exit from the while() */
2548 break;
2550 case AST_CONTROL_PROGRESS: /* Ignore */
2551 case -1: /* Ignore -- just stopping indications */
2552 break;
2554 default:
2555 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2558 ast_frfree(f);
2562 /* Final fixups */
2563 if (oh) {
2564 if (!ast_strlen_zero(oh->context))
2565 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2566 if (!ast_strlen_zero(oh->exten))
2567 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2568 if (oh->priority)
2569 chan->priority = oh->priority;
2571 if (chan->_state == AST_STATE_UP)
2572 *outstate = AST_CONTROL_ANSWER;
2574 if (res <= 0) {
2575 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
2576 ast_cdr_init(chan->cdr, chan);
2577 if (chan->cdr) {
2578 char tmp[256];
2579 snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
2580 ast_cdr_setapp(chan->cdr,"Dial",tmp);
2581 ast_cdr_update(chan);
2582 ast_cdr_start(chan->cdr);
2583 ast_cdr_end(chan->cdr);
2584 /* If the cause wasn't handled properly */
2585 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2586 ast_cdr_failed(chan->cdr);
2588 ast_hangup(chan);
2589 chan = NULL;
2591 return chan;
2594 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2596 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2599 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2601 struct chanlist *chan;
2602 struct ast_channel *c;
2603 int capabilities;
2604 int fmt;
2605 int res;
2606 int foo;
2608 if (!cause)
2609 cause = &foo;
2610 *cause = AST_CAUSE_NOTDEFINED;
2612 if (AST_LIST_LOCK(&channels)) {
2613 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2614 return NULL;
2617 AST_LIST_TRAVERSE(&backends, chan, list) {
2618 if (strcasecmp(type, chan->tech->type))
2619 continue;
2621 capabilities = chan->tech->capabilities;
2622 fmt = format;
2623 res = ast_translator_best_choice(&fmt, &capabilities);
2624 if (res < 0) {
2625 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2626 AST_LIST_UNLOCK(&channels);
2627 return NULL;
2629 AST_LIST_UNLOCK(&channels);
2630 if (!chan->tech->requester)
2631 return NULL;
2633 if (!(c = chan->tech->requester(type, capabilities, data, cause)))
2634 return NULL;
2636 if (c->_state == AST_STATE_DOWN) {
2637 manager_event(EVENT_FLAG_CALL, "Newchannel",
2638 "Channel: %s\r\n"
2639 "State: %s\r\n"
2640 "CallerID: %s\r\n"
2641 "CallerIDName: %s\r\n"
2642 "Uniqueid: %s\r\n",
2643 c->name, ast_state2str(c->_state),
2644 S_OR(c->cid.cid_num, "<unknown>"),
2645 S_OR(c->cid.cid_name, "<unknown>"),
2646 c->uniqueid);
2648 return c;
2651 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2652 *cause = AST_CAUSE_NOSUCHDRIVER;
2653 AST_LIST_UNLOCK(&channels);
2655 return NULL;
2658 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2660 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2661 If the remote end does not answer within the timeout, then do NOT hang up, but
2662 return anyway. */
2663 int res = -1;
2664 /* Stop if we're a zombie or need a soft hangup */
2665 ast_channel_lock(chan);
2666 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2667 if (chan->tech->call)
2668 res = chan->tech->call(chan, addr, timeout);
2669 ast_set_flag(chan, AST_FLAG_OUTGOING);
2671 ast_channel_unlock(chan);
2672 return res;
2676 \brief Transfer a call to dest, if the channel supports transfer
2678 Called by:
2679 \arg app_transfer
2680 \arg the manager interface
2682 int ast_transfer(struct ast_channel *chan, char *dest)
2684 int res = -1;
2686 /* Stop if we're a zombie or need a soft hangup */
2687 ast_channel_lock(chan);
2688 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2689 if (chan->tech->transfer) {
2690 res = chan->tech->transfer(chan, dest);
2691 if (!res)
2692 res = 1;
2693 } else
2694 res = 0;
2696 ast_channel_unlock(chan);
2697 return res;
2700 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2702 return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
2705 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2707 int pos = 0; /* index in the buffer where we accumulate digits */
2708 int to = ftimeout;
2710 /* Stop if we're a zombie or need a soft hangup */
2711 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2712 return -1;
2713 if (!len)
2714 return -1;
2715 for (;;) {
2716 int d;
2717 if (c->stream) {
2718 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2719 ast_stopstream(c);
2720 usleep(1000);
2721 if (!d)
2722 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2723 } else {
2724 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2726 if (d < 0)
2727 return -1;
2728 if (d == 0) {
2729 s[pos]='\0';
2730 return 1;
2732 if (d == 1) {
2733 s[pos]='\0';
2734 return 2;
2736 if (!strchr(enders, d))
2737 s[pos++] = d;
2738 if (strchr(enders, d) || (pos >= len)) {
2739 s[pos]='\0';
2740 return 0;
2742 to = timeout;
2744 /* Never reached */
2745 return 0;
2748 int ast_channel_supports_html(struct ast_channel *chan)
2750 return (chan->tech->send_html) ? 1 : 0;
2753 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2755 if (chan->tech->send_html)
2756 return chan->tech->send_html(chan, subclass, data, datalen);
2757 return -1;
2760 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2762 return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
2765 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2767 int src;
2768 int dst;
2770 /* Set up translation from the chan to the peer */
2771 src = chan->nativeformats;
2772 dst = peer->nativeformats;
2773 if (ast_translator_best_choice(&dst, &src) < 0) {
2774 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2775 return -1;
2778 /* if the best path is not 'pass through', then
2779 transcoding is needed; if desired, force transcode path
2780 to use SLINEAR between channels, but only if there is
2781 no direct conversion available */
2782 if ((src != dst) && ast_opt_transcode_via_slin &&
2783 (ast_translate_path_steps(dst, src) != 1))
2784 dst = AST_FORMAT_SLINEAR;
2785 if (ast_set_read_format(chan, dst) < 0) {
2786 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2787 return -1;
2789 if (ast_set_write_format(peer, dst) < 0) {
2790 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
2791 return -1;
2794 /* Set up translation from the peer to the chan */
2795 src = peer->nativeformats;
2796 dst = chan->nativeformats;
2797 if (ast_translator_best_choice(&dst, &src) < 0) {
2798 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
2799 return -1;
2802 /* if the best path is not 'pass through', then
2803 transcoding is needed; if desired, force transcode path
2804 to use SLINEAR between channels, but only if there is
2805 no direct conversion available */
2806 if ((src != dst) && ast_opt_transcode_via_slin &&
2807 (ast_translate_path_steps(dst, src) != 1))
2808 dst = AST_FORMAT_SLINEAR;
2809 if (ast_set_read_format(peer, dst) < 0) {
2810 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
2811 return -1;
2813 if (ast_set_write_format(chan, dst) < 0) {
2814 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
2815 return -1;
2817 return 0;
2820 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2822 int res = -1;
2824 if (original == clone) {
2825 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2826 return -1;
2828 ast_channel_lock(original);
2829 while(ast_channel_trylock(clone)) {
2830 ast_channel_unlock(original);
2831 usleep(1);
2832 ast_channel_lock(original);
2834 ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
2835 clone->name, original->name);
2836 if (original->masq) {
2837 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2838 original->masq->name, original->name);
2839 } else if (clone->masqr) {
2840 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2841 clone->name, clone->masqr->name);
2842 } else {
2843 original->masq = clone;
2844 clone->masqr = original;
2845 ast_queue_frame(original, &ast_null_frame);
2846 ast_queue_frame(clone, &ast_null_frame);
2847 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
2848 res = 0;
2850 ast_channel_unlock(clone);
2851 ast_channel_unlock(original);
2852 return res;
2855 void ast_change_name(struct ast_channel *chan, char *newname)
2857 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
2858 ast_string_field_set(chan, name, newname);
2861 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2863 struct ast_var_t *current, *newvar;
2864 const char *varname;
2866 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2867 int vartype = 0;
2869 varname = ast_var_full_name(current);
2870 if (!varname)
2871 continue;
2873 if (varname[0] == '_') {
2874 vartype = 1;
2875 if (varname[1] == '_')
2876 vartype = 2;
2879 switch (vartype) {
2880 case 1:
2881 newvar = ast_var_assign(&varname[1], ast_var_value(current));
2882 if (newvar) {
2883 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2884 if (option_debug)
2885 ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2887 break;
2888 case 2:
2889 newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2890 if (newvar) {
2891 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2892 if (option_debug)
2893 ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2895 break;
2896 default:
2897 if (option_debug)
2898 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2899 break;
2905 \brief Clone channel variables from 'clone' channel into 'original' channel
2907 All variables except those related to app_groupcount are cloned.
2908 Variables are actually _removed_ from 'clone' channel, presumably
2909 because it will subsequently be destroyed.
2911 \note Assumes locks will be in place on both channels when called.
2913 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2915 struct ast_var_t *varptr;
2917 /* we need to remove all app_groupcount related variables from the original
2918 channel before merging in the clone's variables; any groups assigned to the
2919 original channel should be released, only those assigned to the clone
2920 should remain
2923 AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2924 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2925 AST_LIST_REMOVE(&original->varshead, varptr, entries);
2926 ast_var_delete(varptr);
2929 AST_LIST_TRAVERSE_SAFE_END;
2931 /* Append variables from clone channel into original channel */
2932 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
2933 if (AST_LIST_FIRST(&clone->varshead))
2934 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2938 \brief Masquerade a channel
2940 \note Assumes channel will be locked when called
2942 int ast_do_masquerade(struct ast_channel *original)
2944 int x,i;
2945 int res=0;
2946 int origstate;
2947 struct ast_frame *cur, *prev;
2948 const struct ast_channel_tech *t;
2949 void *t_pvt;
2950 struct ast_callerid tmpcid;
2951 struct ast_channel *clone = original->masq;
2952 int rformat = original->readformat;
2953 int wformat = original->writeformat;
2954 char newn[100];
2955 char orig[100];
2956 char masqn[100];
2957 char zombn[100];
2959 if (option_debug > 3)
2960 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2961 clone->name, clone->_state, original->name, original->_state);
2963 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
2964 the clone channel into the original channel. Start by killing off the original
2965 channel's backend. I'm not sure we're going to keep this function, because
2966 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2968 /* We need the clone's lock, too */
2969 ast_channel_lock(clone);
2971 if (option_debug > 1)
2972 ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
2974 /* Having remembered the original read/write formats, we turn off any translation on either
2975 one */
2976 free_translation(clone);
2977 free_translation(original);
2980 /* Unlink the masquerade */
2981 original->masq = NULL;
2982 clone->masqr = NULL;
2984 /* Save the original name */
2985 ast_copy_string(orig, original->name, sizeof(orig));
2986 /* Save the new name */
2987 ast_copy_string(newn, clone->name, sizeof(newn));
2988 /* Create the masq name */
2989 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2991 /* Copy the name from the clone channel */
2992 ast_string_field_set(original, name, newn);
2994 /* Mangle the name of the clone channel */
2995 ast_string_field_set(clone, name, masqn);
2997 /* Notify any managers of the change, first the masq then the other */
2998 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2999 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
3001 /* Swap the technologies */
3002 t = original->tech;
3003 original->tech = clone->tech;
3004 clone->tech = t;
3006 t_pvt = original->tech_pvt;
3007 original->tech_pvt = clone->tech_pvt;
3008 clone->tech_pvt = t_pvt;
3010 /* Swap the readq's */
3011 cur = original->readq;
3012 original->readq = clone->readq;
3013 clone->readq = cur;
3015 /* Swap the alertpipes */
3016 for (i = 0; i < 2; i++) {
3017 x = original->alertpipe[i];
3018 original->alertpipe[i] = clone->alertpipe[i];
3019 clone->alertpipe[i] = x;
3022 /* Swap the raw formats */
3023 x = original->rawreadformat;
3024 original->rawreadformat = clone->rawreadformat;
3025 clone->rawreadformat = x;
3026 x = original->rawwriteformat;
3027 original->rawwriteformat = clone->rawwriteformat;
3028 clone->rawwriteformat = x;
3030 /* Save any pending frames on both sides. Start by counting
3031 * how many we're going to need... */
3032 prev = NULL;
3033 x = 0;
3034 for (cur = clone->readq; cur; cur = cur->next) {
3035 x++;
3036 prev = cur;
3038 /* If we had any, prepend them to the ones already in the queue, and
3039 * load up the alertpipe */
3040 if (prev) {
3041 prev->next = original->readq;
3042 original->readq = clone->readq;
3043 clone->readq = NULL;
3044 if (original->alertpipe[1] > -1) {
3045 for (i = 0; i < x; i++)
3046 write(original->alertpipe[1], &x, sizeof(x));
3049 clone->_softhangup = AST_SOFTHANGUP_DEV;
3052 /* And of course, so does our current state. Note we need not
3053 call ast_setstate since the event manager doesn't really consider
3054 these separate. We do this early so that the clone has the proper
3055 state of the original channel. */
3056 origstate = original->_state;
3057 original->_state = clone->_state;
3058 clone->_state = origstate;
3060 if (clone->tech->fixup){
3061 res = clone->tech->fixup(original, clone);
3062 if (res)
3063 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
3066 /* Start by disconnecting the original's physical side */
3067 if (clone->tech->hangup)
3068 res = clone->tech->hangup(clone);
3069 if (res) {
3070 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
3071 ast_channel_unlock(clone);
3072 return -1;
3075 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
3076 /* Mangle the name of the clone channel */
3077 ast_string_field_set(clone, name, zombn);
3078 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
3080 /* Update the type. */
3081 t_pvt = original->monitor;
3082 original->monitor = clone->monitor;
3083 clone->monitor = t_pvt;
3085 /* Keep the same language. */
3086 ast_string_field_set(original, language, clone->language);
3087 /* Copy the FD's other than the generator fd */
3088 for (x = 0; x < AST_MAX_FDS; x++) {
3089 if (x != AST_GENERATOR_FD)
3090 original->fds[x] = clone->fds[x];
3092 /* Move data stores over */
3093 if (AST_LIST_FIRST(&clone->datastores))
3094 AST_LIST_INSERT_TAIL(&original->datastores, AST_LIST_FIRST(&clone->datastores), entry);
3095 AST_LIST_HEAD_INIT_NOLOCK(&clone->datastores);
3097 clone_variables(original, clone);
3098 AST_LIST_HEAD_INIT_NOLOCK(&clone->varshead);
3099 /* Presense of ADSI capable CPE follows clone */
3100 original->adsicpe = clone->adsicpe;
3101 /* Bridge remains the same */
3102 /* CDR fields remain the same */
3103 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3104 /* Application and data remain the same */
3105 /* Clone exception becomes real one, as with fdno */
3106 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
3107 original->fdno = clone->fdno;
3108 /* Schedule context remains the same */
3109 /* Stream stuff stays the same */
3110 /* Keep the original state. The fixup code will need to work with it most likely */
3112 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3113 out. */
3114 tmpcid = original->cid;
3115 original->cid = clone->cid;
3116 clone->cid = tmpcid;
3118 /* Restore original timing file descriptor */
3119 original->fds[AST_TIMING_FD] = original->timingfd;
3121 /* Our native formats are different now */
3122 original->nativeformats = clone->nativeformats;
3124 /* Context, extension, priority, app data, jump table, remain the same */
3125 /* pvt switches. pbx stays the same, as does next */
3127 /* Set the write format */
3128 ast_set_write_format(original, wformat);
3130 /* Set the read format */
3131 ast_set_read_format(original, rformat);
3133 /* Copy the music class */
3134 ast_string_field_set(original, musicclass, clone->musicclass);
3136 if (option_debug)
3137 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
3139 /* Okay. Last thing is to let the channel driver know about all this mess, so he
3140 can fix up everything as best as possible */
3141 if (original->tech->fixup) {
3142 res = original->tech->fixup(clone, original);
3143 if (res) {
3144 ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
3145 original->tech->type, original->name);
3146 ast_channel_unlock(clone);
3147 return -1;
3149 } else
3150 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
3151 original->tech->type, original->name);
3153 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
3154 a zombie so nothing tries to touch it. If it's already been marked as a
3155 zombie, then free it now (since it already is considered invalid). */
3156 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
3157 if (option_debug)
3158 ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
3159 ast_channel_unlock(clone);
3160 manager_event(EVENT_FLAG_CALL, "Hangup",
3161 "Channel: %s\r\n"
3162 "Uniqueid: %s\r\n"
3163 "Cause: %d\r\n"
3164 "Cause-txt: %s\r\n",
3165 clone->name,
3166 clone->uniqueid,
3167 clone->hangupcause,
3168 ast_cause2str(clone->hangupcause)
3170 ast_channel_free(clone);
3171 } else {
3172 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
3173 ast_set_flag(clone, AST_FLAG_ZOMBIE);
3174 ast_queue_frame(clone, &ast_null_frame);
3175 ast_channel_unlock(clone);
3178 /* Signal any blocker */
3179 if (ast_test_flag(original, AST_FLAG_BLOCKING))
3180 pthread_kill(original->blocker, SIGURG);
3181 if (option_debug)
3182 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
3183 return 0;
3186 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
3188 if (callerid) {
3189 if (chan->cid.cid_num)
3190 free(chan->cid.cid_num);
3191 chan->cid.cid_num = ast_strdup(callerid);
3193 if (calleridname) {
3194 if (chan->cid.cid_name)
3195 free(chan->cid.cid_name);
3196 chan->cid.cid_name = ast_strdup(calleridname);
3198 if (ani) {
3199 if (chan->cid.cid_ani)
3200 free(chan->cid.cid_ani);
3201 chan->cid.cid_ani = ast_strdup(ani);
3203 if (chan->cdr)
3204 ast_cdr_setcid(chan->cdr, chan);
3205 manager_event(EVENT_FLAG_CALL, "Newcallerid",
3206 "Channel: %s\r\n"
3207 "CallerID: %s\r\n"
3208 "CallerIDName: %s\r\n"
3209 "Uniqueid: %s\r\n"
3210 "CID-CallingPres: %d (%s)\r\n",
3211 chan->name,
3212 S_OR(chan->cid.cid_num, "<Unknown>"),
3213 S_OR(chan->cid.cid_name, "<Unknown>"),
3214 chan->uniqueid,
3215 chan->cid.cid_pres,
3216 ast_describe_caller_presentation(chan->cid.cid_pres)
3220 int ast_setstate(struct ast_channel *chan, int state)
3222 int oldstate = chan->_state;
3224 if (oldstate == state)
3225 return 0;
3227 chan->_state = state;
3228 ast_device_state_changed_literal(chan->name);
3229 manager_event(EVENT_FLAG_CALL,
3230 (oldstate == AST_STATE_DOWN) ? "Newchannel" : "Newstate",
3231 "Channel: %s\r\n"
3232 "State: %s\r\n"
3233 "CallerID: %s\r\n"
3234 "CallerIDName: %s\r\n"
3235 "Uniqueid: %s\r\n",
3236 chan->name, ast_state2str(chan->_state),
3237 S_OR(chan->cid.cid_num, "<unknown>"),
3238 S_OR(chan->cid.cid_name, "<unknown>"),
3239 chan->uniqueid);
3241 return 0;
3244 /*! \brief Find bridged channel */
3245 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
3247 struct ast_channel *bridged;
3248 bridged = chan->_bridge;
3249 if (bridged && bridged->tech->bridged_channel)
3250 bridged = bridged->tech->bridged_channel(chan, bridged);
3251 return bridged;
3254 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
3256 int min = 0, sec = 0, check;
3258 check = ast_autoservice_start(peer);
3259 if (check)
3260 return;
3262 if (remain > 0) {
3263 if (remain / 60 > 1) {
3264 min = remain / 60;
3265 sec = remain % 60;
3266 } else {
3267 sec = remain;
3271 if (!strcmp(sound,"timeleft")) { /* Queue support */
3272 ast_stream_and_wait(chan, "vm-youhave", chan->language, "");
3273 if (min) {
3274 ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, NULL);
3275 ast_stream_and_wait(chan, "queue-minutes", chan->language, "");
3277 if (sec) {
3278 ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, NULL);
3279 ast_stream_and_wait(chan, "queue-seconds", chan->language, "");
3281 } else {
3282 ast_stream_and_wait(chan, sound, chan->language, "");
3285 ast_autoservice_stop(peer);
3288 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
3289 struct ast_bridge_config *config, struct ast_frame **fo,
3290 struct ast_channel **rc, struct timeval bridge_end)
3292 /* Copy voice back and forth between the two channels. */
3293 struct ast_channel *cs[3];
3294 struct ast_frame *f;
3295 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3296 int o0nativeformats;
3297 int o1nativeformats;
3298 int watch_c0_dtmf;
3299 int watch_c1_dtmf;
3300 void *pvt0, *pvt1;
3301 int to;
3303 cs[0] = c0;
3304 cs[1] = c1;
3305 pvt0 = c0->tech_pvt;
3306 pvt1 = c1->tech_pvt;
3307 o0nativeformats = c0->nativeformats;
3308 o1nativeformats = c1->nativeformats;
3309 watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
3310 watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
3312 for (;;) {
3313 struct ast_channel *who, *other;
3315 if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
3316 (o0nativeformats != c0->nativeformats) ||
3317 (o1nativeformats != c1->nativeformats)) {
3318 /* Check for Masquerade, codec changes, etc */
3319 res = AST_BRIDGE_RETRY;
3320 break;
3322 if (bridge_end.tv_sec) {
3323 to = ast_tvdiff_ms(bridge_end, ast_tvnow());
3324 if (to <= 0) {
3325 res = AST_BRIDGE_RETRY;
3326 break;
3328 } else
3329 to = -1;
3330 who = ast_waitfor_n(cs, 2, &to);
3331 if (!who) {
3332 ast_log(LOG_DEBUG, "Nobody there, continuing...\n");
3333 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3334 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3335 c0->_softhangup = 0;
3336 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3337 c1->_softhangup = 0;
3338 c0->_bridge = c1;
3339 c1->_bridge = c0;
3341 continue;
3343 f = ast_read(who);
3344 if (!f) {
3345 *fo = NULL;
3346 *rc = who;
3347 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
3348 break;
3351 other = (who == c0) ? c1 : c0; /* the 'other' channel */
3353 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
3354 int bridge_exit = 0;
3356 switch (f->subclass) {
3357 case AST_CONTROL_HOLD:
3358 case AST_CONTROL_UNHOLD:
3359 case AST_CONTROL_VIDUPDATE:
3360 ast_indicate_data(other, f->subclass, f->data, f->datalen);
3361 break;
3362 default:
3363 *fo = f;
3364 *rc = who;
3365 bridge_exit = 1;
3366 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
3367 break;
3369 if (bridge_exit)
3370 break;
3372 if ((f->frametype == AST_FRAME_VOICE) ||
3373 (f->frametype == AST_FRAME_DTMF) ||
3374 (f->frametype == AST_FRAME_VIDEO) ||
3375 (f->frametype == AST_FRAME_IMAGE) ||
3376 (f->frametype == AST_FRAME_HTML) ||
3377 (f->frametype == AST_FRAME_MODEM) ||
3378 (f->frametype == AST_FRAME_TEXT)) {
3379 /* monitored dtmf causes exit from bridge */
3380 int monitored_source = (who == c0) ? watch_c0_dtmf : watch_c1_dtmf;
3382 if (f->frametype == AST_FRAME_DTMF && monitored_source) {
3383 *fo = f;
3384 *rc = who;
3385 ast_log(LOG_DEBUG, "Got DTMF on channel (%s)\n", who->name);
3386 break;
3388 /* other frames go to the other side */
3389 ast_write(other, f);
3391 /* XXX do we want to pass on also frames not matched above ? */
3392 ast_frfree(f);
3394 /* Swap who gets priority */
3395 cs[2] = cs[0];
3396 cs[0] = cs[1];
3397 cs[1] = cs[2];
3399 return res;
3402 /*! \brief Bridge two channels together */
3403 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
3404 struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
3406 struct ast_channel *who = NULL;
3407 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3408 int nativefailed=0;
3409 int firstpass;
3410 int o0nativeformats;
3411 int o1nativeformats;
3412 long time_left_ms=0;
3413 struct timeval nexteventts = { 0, };
3414 char caller_warning = 0;
3415 char callee_warning = 0;
3416 int to;
3418 if (c0->_bridge) {
3419 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3420 c0->name, c0->_bridge->name);
3421 return -1;
3423 if (c1->_bridge) {
3424 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3425 c1->name, c1->_bridge->name);
3426 return -1;
3429 /* Stop if we're a zombie or need a soft hangup */
3430 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3431 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
3432 return -1;
3434 *fo = NULL;
3435 firstpass = config->firstpass;
3436 config->firstpass = 0;
3438 if (ast_tvzero(config->start_time))
3439 config->start_time = ast_tvnow();
3440 time_left_ms = config->timelimit;
3442 caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
3443 callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
3445 if (config->start_sound && firstpass) {
3446 if (caller_warning)
3447 bridge_playfile(c0, c1, config->start_sound, time_left_ms / 1000);
3448 if (callee_warning)
3449 bridge_playfile(c1, c0, config->start_sound, time_left_ms / 1000);
3452 /* Keep track of bridge */
3453 c0->_bridge = c1;
3454 c1->_bridge = c0;
3456 /* \todo XXX here should check that cid_num is not NULL */
3457 manager_event(EVENT_FLAG_CALL, "Link",
3458 "Channel1: %s\r\n"
3459 "Channel2: %s\r\n"
3460 "Uniqueid1: %s\r\n"
3461 "Uniqueid2: %s\r\n"
3462 "CallerID1: %s\r\n"
3463 "CallerID2: %s\r\n",
3464 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3466 o0nativeformats = c0->nativeformats;
3467 o1nativeformats = c1->nativeformats;
3469 if (config->timelimit) {
3470 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3471 if (caller_warning || callee_warning)
3472 nexteventts = ast_tvsub(nexteventts, ast_samp2tv(config->play_warning, 1000));
3475 for (/* ever */;;) {
3476 to = -1;
3477 if (config->timelimit) {
3478 struct timeval now;
3479 now = ast_tvnow();
3480 to = ast_tvdiff_ms(nexteventts, now);
3481 if (to < 0)
3482 to = 0;
3483 time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
3484 if (time_left_ms < to)
3485 to = time_left_ms;
3487 if (time_left_ms <= 0) {
3488 if (caller_warning && config->end_sound)
3489 bridge_playfile(c0, c1, config->end_sound, 0);
3490 if (callee_warning && config->end_sound)
3491 bridge_playfile(c1, c0, config->end_sound, 0);
3492 *fo = NULL;
3493 if (who)
3494 *rc = who;
3495 res = 0;
3496 break;
3499 if (!to) {
3500 if (time_left_ms >= 5000 && config->warning_sound && config->play_warning) {
3501 int t = (time_left_ms + 500) / 1000; /* round to nearest second */
3502 if (caller_warning)
3503 bridge_playfile(c0, c1, config->warning_sound, t);
3504 if (callee_warning)
3505 bridge_playfile(c1, c0, config->warning_sound, t);
3507 if (config->warning_freq) {
3508 nexteventts = ast_tvadd(nexteventts, ast_samp2tv(config->warning_freq, 1000));
3509 } else
3510 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3514 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3515 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3516 c0->_softhangup = 0;
3517 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3518 c1->_softhangup = 0;
3519 c0->_bridge = c1;
3520 c1->_bridge = c0;
3521 ast_log(LOG_DEBUG, "Unbridge signal received. Ending native bridge.\n");
3522 continue;
3525 /* Stop if we're a zombie or need a soft hangup */
3526 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3527 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
3528 *fo = NULL;
3529 if (who)
3530 *rc = who;
3531 res = 0;
3532 ast_log(LOG_DEBUG, "Bridge stops because we're zombie or need a soft hangup: c0=%s, c1=%s, flags: %s,%s,%s,%s\n",
3533 c0->name, c1->name,
3534 ast_test_flag(c0, AST_FLAG_ZOMBIE) ? "Yes" : "No",
3535 ast_check_hangup(c0) ? "Yes" : "No",
3536 ast_test_flag(c1, AST_FLAG_ZOMBIE) ? "Yes" : "No",
3537 ast_check_hangup(c1) ? "Yes" : "No");
3538 break;
3541 if (c0->tech->bridge &&
3542 (config->timelimit == 0) &&
3543 (c0->tech->bridge == c1->tech->bridge) &&
3544 !nativefailed && !c0->monitor && !c1->monitor &&
3545 !c0->spies && !c1->spies) {
3546 /* Looks like they share a bridge method and nothing else is in the way */
3547 ast_set_flag(c0, AST_FLAG_NBRIDGE);
3548 ast_set_flag(c1, AST_FLAG_NBRIDGE);
3549 if ((res = c0->tech->bridge(c0, c1, config->flags, fo, rc, to)) == AST_BRIDGE_COMPLETE) {
3550 /* \todo XXX here should check that cid_num is not NULL */
3551 manager_event(EVENT_FLAG_CALL, "Unlink",
3552 "Channel1: %s\r\n"
3553 "Channel2: %s\r\n"
3554 "Uniqueid1: %s\r\n"
3555 "Uniqueid2: %s\r\n"
3556 "CallerID1: %s\r\n"
3557 "CallerID2: %s\r\n",
3558 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3559 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n", c0->name, c1->name);
3561 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
3562 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
3564 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3565 continue;
3567 c0->_bridge = NULL;
3568 c1->_bridge = NULL;
3570 return res;
3571 } else {
3572 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
3573 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
3575 switch (res) {
3576 case AST_BRIDGE_RETRY:
3577 continue;
3578 default:
3579 if (option_verbose > 2)
3580 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s ended\n",
3581 c0->name, c1->name);
3582 /* fallthrough */
3583 case AST_BRIDGE_FAILED_NOWARN:
3584 nativefailed++;
3585 break;
3589 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) ||
3590 (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
3591 !(c0->generator || c1->generator)) {
3592 if (ast_channel_make_compatible(c0, c1)) {
3593 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
3594 /* \todo XXX here should check that cid_num is not NULL */
3595 manager_event(EVENT_FLAG_CALL, "Unlink",
3596 "Channel1: %s\r\n"
3597 "Channel2: %s\r\n"
3598 "Uniqueid1: %s\r\n"
3599 "Uniqueid2: %s\r\n"
3600 "CallerID1: %s\r\n"
3601 "CallerID2: %s\r\n",
3602 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3603 return AST_BRIDGE_FAILED;
3605 o0nativeformats = c0->nativeformats;
3606 o1nativeformats = c1->nativeformats;
3608 res = ast_generic_bridge(c0, c1, config, fo, rc, nexteventts);
3609 if (res != AST_BRIDGE_RETRY)
3610 break;
3613 c0->_bridge = NULL;
3614 c1->_bridge = NULL;
3616 /* \todo XXX here should check that cid_num is not NULL */
3617 manager_event(EVENT_FLAG_CALL, "Unlink",
3618 "Channel1: %s\r\n"
3619 "Channel2: %s\r\n"
3620 "Uniqueid1: %s\r\n"
3621 "Uniqueid2: %s\r\n"
3622 "CallerID1: %s\r\n"
3623 "CallerID2: %s\r\n",
3624 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3625 ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n", c0->name, c1->name);
3627 return res;
3630 /*! \brief Sets an option on a channel */
3631 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
3633 int res;
3635 if (chan->tech->setoption) {
3636 res = chan->tech->setoption(chan, option, data, datalen);
3637 if (res < 0)
3638 return res;
3639 } else {
3640 errno = ENOSYS;
3641 return -1;
3643 if (block) {
3644 /* XXX Implement blocking -- just wait for our option frame reply, discarding
3645 intermediate packets. XXX */
3646 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
3647 return -1;
3649 return 0;
3652 struct tonepair_def {
3653 int freq1;
3654 int freq2;
3655 int duration;
3656 int vol;
3659 struct tonepair_state {
3660 float freq1;
3661 float freq2;
3662 float vol;
3663 int duration;
3664 int pos;
3665 int origwfmt;
3666 struct ast_frame f;
3667 unsigned char offset[AST_FRIENDLY_OFFSET];
3668 short data[4000];
3671 static void tonepair_release(struct ast_channel *chan, void *params)
3673 struct tonepair_state *ts = params;
3675 if (chan)
3676 ast_set_write_format(chan, ts->origwfmt);
3677 free(ts);
3680 static void *tonepair_alloc(struct ast_channel *chan, void *params)
3682 struct tonepair_state *ts;
3683 struct tonepair_def *td = params;
3685 if (!(ts = ast_calloc(1, sizeof(*ts))))
3686 return NULL;
3687 ts->origwfmt = chan->writeformat;
3688 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
3689 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
3690 tonepair_release(NULL, ts);
3691 ts = NULL;
3692 } else {
3693 ts->freq1 = td->freq1;
3694 ts->freq2 = td->freq2;
3695 ts->duration = td->duration;
3696 ts->vol = td->vol;
3698 /* Let interrupts interrupt :) */
3699 ast_set_flag(chan, AST_FLAG_WRITE_INT);
3700 return ts;
3703 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
3705 struct tonepair_state *ts = data;
3706 int x;
3708 /* we need to prepare a frame with 16 * timelen samples as we're
3709 * generating SLIN audio
3711 len = samples * 2;
3713 if (len > sizeof(ts->data) / 2 - 1) {
3714 ast_log(LOG_WARNING, "Can't generate that much data!\n");
3715 return -1;
3717 memset(&ts->f, 0, sizeof(ts->f));
3718 for (x = 0; x < (len / 2); x++) {
3719 ts->data[x] = ts->vol * (
3720 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
3721 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
3724 ts->f.frametype = AST_FRAME_VOICE;
3725 ts->f.subclass = AST_FORMAT_SLINEAR;
3726 ts->f.datalen = len;
3727 ts->f.samples = samples;
3728 ts->f.offset = AST_FRIENDLY_OFFSET;
3729 ts->f.data = ts->data;
3730 ast_write(chan, &ts->f);
3731 ts->pos += x;
3732 if (ts->duration > 0) {
3733 if (ts->pos >= ts->duration * 8)
3734 return -1;
3736 return 0;
3739 static struct ast_generator tonepair = {
3740 alloc: tonepair_alloc,
3741 release: tonepair_release,
3742 generate: tonepair_generator,
3745 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
3747 struct tonepair_def d = { 0, };
3749 d.freq1 = freq1;
3750 d.freq2 = freq2;
3751 d.duration = duration;
3752 d.vol = (vol < 1) ? 8192 : vol; /* force invalid to 8192 */
3753 if (ast_activate_generator(chan, &tonepair, &d))
3754 return -1;
3755 return 0;
3758 void ast_tonepair_stop(struct ast_channel *chan)
3760 ast_deactivate_generator(chan);
3763 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
3765 int res;
3767 if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
3768 return res;
3770 /* Give us some wiggle room */
3771 while (chan->generatordata && ast_waitfor(chan, 100) >= 0) {
3772 struct ast_frame *f = ast_read(chan);
3773 if (f)
3774 ast_frfree(f);
3775 else
3776 return -1;
3778 return 0;
3781 ast_group_t ast_get_group(char *s)
3783 char *piece;
3784 char *c;
3785 int start=0, finish=0, x;
3786 ast_group_t group = 0;
3788 c = ast_strdupa(s);
3790 while ((piece = strsep(&c, ","))) {
3791 if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
3792 /* Range */
3793 } else if (sscanf(piece, "%d", &start)) {
3794 /* Just one */
3795 finish = start;
3796 } else {
3797 ast_log(LOG_ERROR, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s, piece);
3798 continue;
3800 for (x = start; x <= finish; x++) {
3801 if ((x > 63) || (x < 0)) {
3802 ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x);
3803 } else
3804 group |= ((ast_group_t) 1 << x);
3807 return group;
3810 static int (*ast_moh_start_ptr)(struct ast_channel *, const char *) = NULL;
3811 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
3812 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
3814 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, const char *),
3815 void (*stop_ptr)(struct ast_channel *),
3816 void (*cleanup_ptr)(struct ast_channel *))
3818 ast_moh_start_ptr = start_ptr;
3819 ast_moh_stop_ptr = stop_ptr;
3820 ast_moh_cleanup_ptr = cleanup_ptr;
3823 void ast_uninstall_music_functions(void)
3825 ast_moh_start_ptr = NULL;
3826 ast_moh_stop_ptr = NULL;
3827 ast_moh_cleanup_ptr = NULL;
3830 /*! \brief Turn on music on hold on a given channel */
3831 int ast_moh_start(struct ast_channel *chan, const char *mclass)
3833 if (ast_moh_start_ptr)
3834 return ast_moh_start_ptr(chan, mclass);
3836 if (option_verbose > 2)
3837 ast_verbose(VERBOSE_PREFIX_3 "Music class %s requested but no musiconhold loaded.\n", mclass ? mclass : "default");
3839 return 0;
3842 /*! \brief Turn off music on hold on a given channel */
3843 void ast_moh_stop(struct ast_channel *chan)
3845 if (ast_moh_stop_ptr)
3846 ast_moh_stop_ptr(chan);
3849 void ast_moh_cleanup(struct ast_channel *chan)
3851 if (ast_moh_cleanup_ptr)
3852 ast_moh_cleanup_ptr(chan);
3855 void ast_channels_init(void)
3857 ast_cli_register(&cli_show_channeltypes);
3858 ast_cli_register(&cli_show_channeltype);
3861 /*! \brief Print call group and pickup group ---*/
3862 char *ast_print_group(char *buf, int buflen, ast_group_t group)
3864 unsigned int i;
3865 int first=1;
3866 char num[3];
3868 buf[0] = '\0';
3870 if (!group) /* Return empty string if no group */
3871 return buf;
3873 for (i = 0; i <= 63; i++) { /* Max group is 63 */
3874 if (group & ((ast_group_t) 1 << i)) {
3875 if (!first) {
3876 strncat(buf, ", ", buflen);
3877 } else {
3878 first=0;
3880 snprintf(num, sizeof(num), "%u", i);
3881 strncat(buf, num, buflen);
3884 return buf;
3887 void ast_set_variables(struct ast_channel *chan, struct ast_variable *vars)
3889 struct ast_variable *cur;
3891 for (cur = vars; cur; cur = cur->next)
3892 pbx_builtin_setvar_helper(chan, cur->name, cur->value);
3895 static void copy_data_from_queue(struct ast_channel_spy_queue *queue, short *buf, unsigned int samples)
3897 struct ast_frame *f;
3898 int tocopy;
3899 int bytestocopy;
3901 while (samples) {
3902 f = queue->head;
3904 if (!f) {
3905 ast_log(LOG_ERROR, "Ran out of frames before buffer filled!\n");
3906 break;
3909 tocopy = (f->samples > samples) ? samples : f->samples;
3910 bytestocopy = ast_codec_get_len(queue->format, tocopy);
3911 memcpy(buf, f->data, bytestocopy);
3912 samples -= tocopy;
3913 buf += tocopy;
3914 f->samples -= tocopy;
3915 f->data += bytestocopy;
3916 f->datalen -= bytestocopy;
3917 f->offset += bytestocopy;
3918 queue->samples -= tocopy;
3919 if (!f->samples) {
3920 queue->head = f->next;
3921 ast_frfree(f);
3926 struct ast_frame *ast_channel_spy_read_frame(struct ast_channel_spy *spy, unsigned int samples)
3928 struct ast_frame *result;
3929 /* buffers are allocated to hold SLINEAR, which is the largest format */
3930 short read_buf[samples];
3931 short write_buf[samples];
3932 struct ast_frame *read_frame;
3933 struct ast_frame *write_frame;
3934 int need_dup;
3935 struct ast_frame stack_read_frame = { .frametype = AST_FRAME_VOICE,
3936 .subclass = spy->read_queue.format,
3937 .data = read_buf,
3938 .samples = samples,
3939 .datalen = ast_codec_get_len(spy->read_queue.format, samples),
3941 struct ast_frame stack_write_frame = { .frametype = AST_FRAME_VOICE,
3942 .subclass = spy->write_queue.format,
3943 .data = write_buf,
3944 .samples = samples,
3945 .datalen = ast_codec_get_len(spy->write_queue.format, samples),
3948 /* if a flush has been requested, dump everything in whichever queue is larger */
3949 if (ast_test_flag(spy, CHANSPY_TRIGGER_FLUSH)) {
3950 if (spy->read_queue.samples > spy->write_queue.samples) {
3951 if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST)) {
3952 for (result = spy->read_queue.head; result; result = result->next)
3953 ast_frame_adjust_volume(result, spy->read_vol_adjustment);
3955 result = spy->read_queue.head;
3956 spy->read_queue.head = NULL;
3957 spy->read_queue.samples = 0;
3958 } else {
3959 if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST)) {
3960 for (result = spy->write_queue.head; result; result = result->next)
3961 ast_frame_adjust_volume(result, spy->write_vol_adjustment);
3963 result = spy->write_queue.head;
3964 spy->write_queue.head = NULL;
3965 spy->write_queue.samples = 0;
3967 ast_clear_flag(spy, CHANSPY_TRIGGER_FLUSH);
3968 return result;
3971 if ((spy->read_queue.samples < samples) || (spy->write_queue.samples < samples))
3972 return NULL;
3974 /* short-circuit if both head frames have exactly what we want */
3975 if ((spy->read_queue.head->samples == samples) &&
3976 (spy->write_queue.head->samples == samples)) {
3977 read_frame = spy->read_queue.head;
3978 spy->read_queue.head = read_frame->next;
3979 read_frame->next = NULL;
3981 write_frame = spy->write_queue.head;
3982 spy->write_queue.head = write_frame->next;
3983 write_frame->next = NULL;
3985 spy->read_queue.samples -= samples;
3986 spy->write_queue.samples -= samples;
3988 need_dup = 0;
3989 } else {
3990 copy_data_from_queue(&spy->read_queue, read_buf, samples);
3991 copy_data_from_queue(&spy->write_queue, write_buf, samples);
3993 read_frame = &stack_read_frame;
3994 write_frame = &stack_write_frame;
3995 need_dup = 1;
3998 if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST))
3999 ast_frame_adjust_volume(read_frame, spy->read_vol_adjustment);
4001 if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST))
4002 ast_frame_adjust_volume(write_frame, spy->write_vol_adjustment);
4004 if (ast_test_flag(spy, CHANSPY_MIXAUDIO)) {
4005 ast_frame_slinear_sum(read_frame, write_frame);
4007 if (need_dup)
4008 result = ast_frdup(read_frame);
4009 else {
4010 result = read_frame;
4011 ast_frfree(write_frame);
4013 } else {
4014 if (need_dup) {
4015 result = ast_frdup(read_frame);
4016 result->next = ast_frdup(write_frame);
4017 } else {
4018 result = read_frame;
4019 result->next = write_frame;
4023 return result;
4026 static void *silence_generator_alloc(struct ast_channel *chan, void *data)
4028 /* just store the data pointer in the channel structure */
4029 return data;
4032 static void silence_generator_release(struct ast_channel *chan, void *data)
4034 /* nothing to do */
4037 static int silence_generator_generate(struct ast_channel *chan, void *data, int len, int samples)
4039 short buf[samples];
4040 struct ast_frame frame = {
4041 .frametype = AST_FRAME_VOICE,
4042 .subclass = AST_FORMAT_SLINEAR,
4043 .data = buf,
4044 .samples = samples,
4045 .datalen = sizeof(buf),
4047 memset(buf, 0, sizeof(buf));
4048 if (ast_write(chan, &frame))
4049 return -1;
4050 return 0;
4053 static struct ast_generator silence_generator = {
4054 .alloc = silence_generator_alloc,
4055 .release = silence_generator_release,
4056 .generate = silence_generator_generate,
4059 struct ast_silence_generator {
4060 int old_write_format;
4063 struct ast_silence_generator *ast_channel_start_silence_generator(struct ast_channel *chan)
4065 struct ast_silence_generator *state;
4067 if (!(state = ast_calloc(1, sizeof(*state)))) {
4068 return NULL;
4071 state->old_write_format = chan->writeformat;
4073 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
4074 ast_log(LOG_ERROR, "Could not set write format to SLINEAR\n");
4075 free(state);
4076 return NULL;
4079 ast_activate_generator(chan, &silence_generator, state);
4081 if (option_debug)
4082 ast_log(LOG_DEBUG, "Started silence generator on '%s'\n", chan->name);
4084 return state;
4087 void ast_channel_stop_silence_generator(struct ast_channel *chan, struct ast_silence_generator *state)
4089 if (!state)
4090 return;
4092 ast_deactivate_generator(chan);
4094 if (option_debug)
4095 ast_log(LOG_DEBUG, "Stopped silence generator on '%s'\n", chan->name);
4097 if (ast_set_write_format(chan, state->old_write_format) < 0)
4098 ast_log(LOG_ERROR, "Could not return write format to its original state\n");
4100 free(state);
4104 /*! \ brief Convert channel reloadreason (ENUM) to text string for manager event */
4105 const char *channelreloadreason2txt(enum channelreloadreason reason)
4107 switch (reason) {
4108 case CHANNEL_MODULE_LOAD:
4109 return "LOAD (Channel module load)";
4111 case CHANNEL_MODULE_RELOAD:
4112 return "RELOAD (Channel module reload)";
4114 case CHANNEL_CLI_RELOAD:
4115 return "CLIRELOAD (Channel module reload by CLI command)";
4117 default:
4118 return "MANAGERRELOAD (Channel module reload by manager)";
4122 #ifdef DEBUG_CHANNEL_LOCKS
4124 /*! \brief Unlock AST channel (and print debugging output)
4125 \note You need to enable DEBUG_CHANNEL_LOCKS for this function
4127 int ast_channel_unlock(struct ast_channel *chan)
4129 int res = 0;
4130 if (option_debug > 2)
4131 ast_log(LOG_DEBUG, "::::==== Unlocking AST channel %s\n", chan->name);
4133 if (!chan) {
4134 ast_log(LOG_DEBUG, "::::==== Unlocking non-existing channel \n");
4135 return 0;
4138 res = ast_mutex_unlock(&chan->lock);
4140 if (option_debug > 2) {
4141 /* Try to find counter if possible on your platform
4142 I've only found out how to do this on Linux
4143 DEBUG_THREADS changes the lock structure
4145 #ifdef __linux__
4146 int count = 0;
4147 #ifdef DEBUG_THREADS
4148 if ((count = chan->lock.mutex.__m_count))
4149 #else
4150 if ((count = chan->lock.__m_count))
4151 #endif
4152 ast_log(LOG_DEBUG, ":::=== Still have %d locks (recursive)\n", count);
4153 #endif
4154 if (!res)
4155 ast_log(LOG_DEBUG, "::::==== Channel %s was unlocked\n", chan->name);
4156 if (res == EINVAL) {
4157 ast_log(LOG_DEBUG, "::::==== Channel %s had no lock by this thread. Failed unlocking\n", chan->name);
4160 if (res == EPERM) {
4161 /* We had no lock, so okay any way*/
4162 if (option_debug > 3)
4163 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked at all \n", chan->name);
4164 res = 0;
4166 return res;
4169 /*! \brief Lock AST channel (and print debugging output)
4170 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4171 int ast_channel_lock(struct ast_channel *chan)
4173 int res;
4175 if (option_debug > 3)
4176 ast_log(LOG_DEBUG, "====:::: Locking AST channel %s\n", chan->name);
4178 res = ast_mutex_lock(&chan->lock);
4180 if (option_debug > 3) {
4181 #ifdef __linux__
4182 int count = 0;
4183 #ifdef DEBUG_THREADS
4184 if ((count = chan->lock.mutex.__m_count))
4185 #else
4186 if ((count = chan->lock.__m_count))
4187 #endif
4188 ast_log(LOG_DEBUG, ":::=== Now have %d locks (recursive)\n", count);
4189 #endif
4190 if (!res)
4191 ast_log(LOG_DEBUG, "::::==== Channel %s was locked\n", chan->name);
4192 if (res == EDEADLK) {
4193 /* We had no lock, so okey any way */
4194 if (option_debug > 3)
4195 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked by us. Lock would cause deadlock.\n", chan->name);
4197 if (res == EINVAL) {
4198 if (option_debug > 3)
4199 ast_log(LOG_DEBUG, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
4202 return res;
4205 /*! \brief Lock AST channel (and print debugging output)
4206 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4207 int ast_channel_trylock(struct ast_channel *chan)
4209 int res;
4211 if (option_debug > 2)
4212 ast_log(LOG_DEBUG, "====:::: Trying to lock AST channel %s\n", chan->name);
4214 res = ast_mutex_trylock(&chan->lock);
4216 if (option_debug > 2) {
4217 #ifdef __linux__
4218 int count = 0;
4219 #ifdef DEBUG_THREADS
4220 if ((count = chan->lock.mutex.__m_count))
4221 #else
4222 if ((count = chan->lock.__m_count))
4223 #endif
4224 ast_log(LOG_DEBUG, ":::=== Now have %d locks (recursive)\n", count);
4225 #endif
4226 if (!res)
4227 ast_log(LOG_DEBUG, "::::==== Channel %s was locked\n", chan->name);
4228 if (res == EBUSY) {
4229 /* We failed to lock */
4230 if (option_debug > 2)
4231 ast_log(LOG_DEBUG, "::::==== Channel %s failed to lock. Not waiting around...\n", chan->name);
4233 if (res == EDEADLK) {
4234 /* We had no lock, so okey any way*/
4235 if (option_debug > 2)
4236 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked. Lock would cause deadlock.\n", chan->name);
4238 if (res == EINVAL && option_debug > 2)
4239 ast_log(LOG_DEBUG, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
4241 return res;
4244 #endif
4247 * Wrappers for various ast_say_*() functions that call the full version
4248 * of the same functions.
4249 * The proper place would be say.c, but that file is optional and one
4250 * must be able to build asterisk even without it (using a loadable 'say'
4251 * implementation that only supplies the 'full' version of the functions.
4254 int ast_say_number(struct ast_channel *chan, int num,
4255 const char *ints, const char *language, const char *options)
4257 return ast_say_number_full(chan, num, ints, language, options, -1, -1);
4260 int ast_say_enumeration(struct ast_channel *chan, int num,
4261 const char *ints, const char *language, const char *options)
4263 return ast_say_enumeration_full(chan, num, ints, language, options, -1, -1);
4266 int ast_say_digits(struct ast_channel *chan, int num,
4267 const char *ints, const char *lang)
4269 return ast_say_digits_full(chan, num, ints, lang, -1, -1);
4272 int ast_say_digit_str(struct ast_channel *chan, const char *str,
4273 const char *ints, const char *lang)
4275 return ast_say_digit_str_full(chan, str, ints, lang, -1, -1);
4278 int ast_say_character_str(struct ast_channel *chan, const char *str,
4279 const char *ints, const char *lang)
4281 return ast_say_character_str_full(chan, str, ints, lang, -1, -1);
4284 int ast_say_phonetic_str(struct ast_channel *chan, const char *str,
4285 const char *ints, const char *lang)
4287 return ast_say_phonetic_str_full(chan, str, ints, lang, -1, -1);
4290 int ast_say_digits_full(struct ast_channel *chan, int num,
4291 const char *ints, const char *lang, int audiofd, int ctrlfd)
4293 char buf[256];
4295 snprintf(buf, sizeof(buf), "%d", num);
4296 return ast_say_digit_str_full(chan, buf, ints, lang, audiofd, ctrlfd);
4299 /* end of file */