clarify the fact that voicemail IMAP storage cannot be built against a distro's binar...
[asterisk-bristuff.git] / main / channel.c
blob39c4e8e16e88538cf74dd7e9f38583a3f3239b8c
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 "asterisk.h"
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <string.h>
34 #include <sys/time.h>
35 #include <signal.h>
36 #include <errno.h>
37 #include <unistd.h>
38 #include <math.h>
40 #ifdef HAVE_ZAPTEL
41 #include <sys/ioctl.h>
42 #include <zaptel/zaptel.h>
43 #endif
45 #include "asterisk/pbx.h"
46 #include "asterisk/frame.h"
47 #include "asterisk/sched.h"
48 #include "asterisk/options.h"
49 #include "asterisk/channel.h"
50 #include "asterisk/chanspy.h"
51 #include "asterisk/musiconhold.h"
52 #include "asterisk/logger.h"
53 #include "asterisk/say.h"
54 #include "asterisk/file.h"
55 #include "asterisk/cli.h"
56 #include "asterisk/translate.h"
57 #include "asterisk/manager.h"
58 #include "asterisk/chanvars.h"
59 #include "asterisk/linkedlists.h"
60 #include "asterisk/indications.h"
61 #include "asterisk/monitor.h"
62 #include "asterisk/causes.h"
63 #include "asterisk/callerid.h"
64 #include "asterisk/utils.h"
65 #include "asterisk/lock.h"
66 #include "asterisk/app.h"
67 #include "asterisk/transcap.h"
68 #include "asterisk/devicestate.h"
69 #include "asterisk/sha1.h"
70 #include "asterisk/threadstorage.h"
71 #include "asterisk/slinfactory.h"
73 struct channel_spy_trans {
74 int last_format;
75 struct ast_trans_pvt *path;
78 struct ast_channel_spy_list {
79 struct channel_spy_trans read_translator;
80 struct channel_spy_trans write_translator;
81 AST_LIST_HEAD_NOLOCK(, ast_channel_spy) list;
84 struct ast_channel_whisper_buffer {
85 ast_mutex_t lock;
86 struct ast_slinfactory sf;
87 unsigned int original_format;
88 struct ast_trans_pvt *path;
91 /* uncomment if you have problems with 'monitoring' synchronized files */
92 #if 0
93 #define MONITOR_CONSTANT_DELAY
94 #define MONITOR_DELAY 150 * 8 /* 150 ms of MONITORING DELAY */
95 #endif
97 /*! Prevent new channel allocation if shutting down. */
98 static int shutting_down;
100 static int uniqueint;
102 unsigned long global_fin, global_fout;
104 AST_THREADSTORAGE(state2str_threadbuf, state2str_threadbuf_init);
105 #define STATE2STR_BUFSIZE 32
107 /*! 100ms */
108 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
110 struct chanlist {
111 const struct ast_channel_tech *tech;
112 AST_LIST_ENTRY(chanlist) list;
115 /*! the list of registered channel types */
116 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
118 /*! the list of channels we have. Note that the lock for this list is used for
119 both the channels list and the backends list. */
120 static AST_LIST_HEAD_STATIC(channels, ast_channel);
122 /*! map AST_CAUSE's to readable string representations */
123 const struct ast_cause {
124 int cause;
125 const char *name;
126 const char *desc;
127 } causes[] = {
128 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
129 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
130 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
131 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
132 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
133 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
134 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
135 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
136 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
137 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
138 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
139 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
140 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
141 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
142 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
143 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
144 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
145 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
146 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
147 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
148 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
149 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
150 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
151 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
152 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
153 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
154 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
155 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
156 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
157 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
158 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
159 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
160 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
161 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
162 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
163 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
164 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
165 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
166 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
167 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
168 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
169 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
170 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
171 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
174 struct ast_variable *ast_channeltype_list(void)
176 struct chanlist *cl;
177 struct ast_variable *var=NULL, *prev = NULL;
178 AST_LIST_TRAVERSE(&backends, cl, list) {
179 if (prev) {
180 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description)))
181 prev = prev->next;
182 } else {
183 var = ast_variable_new(cl->tech->type, cl->tech->description);
184 prev = var;
187 return var;
190 static int show_channeltypes(int fd, int argc, char *argv[])
192 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
193 struct chanlist *cl;
194 int count_chan = 0;
196 ast_cli(fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
197 ast_cli(fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
198 if (AST_LIST_LOCK(&channels)) {
199 ast_log(LOG_WARNING, "Unable to lock channel list\n");
200 return -1;
202 AST_LIST_TRAVERSE(&backends, cl, list) {
203 ast_cli(fd, FORMAT, cl->tech->type, cl->tech->description,
204 (cl->tech->devicestate) ? "yes" : "no",
205 (cl->tech->indicate) ? "yes" : "no",
206 (cl->tech->transfer) ? "yes" : "no");
207 count_chan++;
209 AST_LIST_UNLOCK(&channels);
210 ast_cli(fd, "----------\n%d channel drivers registered.\n", count_chan);
211 return RESULT_SUCCESS;
213 #undef FORMAT
217 static int show_channeltype_deprecated(int fd, int argc, char *argv[])
219 struct chanlist *cl = NULL;
221 if (argc != 3)
222 return RESULT_SHOWUSAGE;
224 if (AST_LIST_LOCK(&channels)) {
225 ast_log(LOG_WARNING, "Unable to lock channel list\n");
226 return RESULT_FAILURE;
229 AST_LIST_TRAVERSE(&backends, cl, list) {
230 if (!strncasecmp(cl->tech->type, argv[2], strlen(cl->tech->type))) {
231 break;
236 if (!cl) {
237 ast_cli(fd, "\n%s is not a registered channel driver.\n", argv[2]);
238 AST_LIST_UNLOCK(&channels);
239 return RESULT_FAILURE;
242 ast_cli(fd,
243 "-- Info about channel driver: %s --\n"
244 " Device State: %s\n"
245 " Indication: %s\n"
246 " Transfer : %s\n"
247 " Capabilities: %d\n"
248 " Digit Begin: %s\n"
249 " Digit End: %s\n"
250 " Send HTML : %s\n"
251 " Image Support: %s\n"
252 " Text Support: %s\n",
253 cl->tech->type,
254 (cl->tech->devicestate) ? "yes" : "no",
255 (cl->tech->indicate) ? "yes" : "no",
256 (cl->tech->transfer) ? "yes" : "no",
257 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
258 (cl->tech->send_digit_begin) ? "yes" : "no",
259 (cl->tech->send_digit_end) ? "yes" : "no",
260 (cl->tech->send_html) ? "yes" : "no",
261 (cl->tech->send_image) ? "yes" : "no",
262 (cl->tech->send_text) ? "yes" : "no"
266 AST_LIST_UNLOCK(&channels);
267 return RESULT_SUCCESS;
270 static int show_channeltype(int fd, int argc, char *argv[])
272 struct chanlist *cl = NULL;
274 if (argc != 4)
275 return RESULT_SHOWUSAGE;
277 if (AST_LIST_LOCK(&channels)) {
278 ast_log(LOG_WARNING, "Unable to lock channel list\n");
279 return RESULT_FAILURE;
282 AST_LIST_TRAVERSE(&backends, cl, list) {
283 if (!strncasecmp(cl->tech->type, argv[3], strlen(cl->tech->type))) {
284 break;
289 if (!cl) {
290 ast_cli(fd, "\n%s is not a registered channel driver.\n", argv[3]);
291 AST_LIST_UNLOCK(&channels);
292 return RESULT_FAILURE;
295 ast_cli(fd,
296 "-- Info about channel driver: %s --\n"
297 " Device State: %s\n"
298 " Indication: %s\n"
299 " Transfer : %s\n"
300 " Capabilities: %d\n"
301 " Digit Begin: %s\n"
302 " Digit End: %s\n"
303 " Send HTML : %s\n"
304 " Image Support: %s\n"
305 " Text Support: %s\n",
306 cl->tech->type,
307 (cl->tech->devicestate) ? "yes" : "no",
308 (cl->tech->indicate) ? "yes" : "no",
309 (cl->tech->transfer) ? "yes" : "no",
310 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
311 (cl->tech->send_digit_begin) ? "yes" : "no",
312 (cl->tech->send_digit_end) ? "yes" : "no",
313 (cl->tech->send_html) ? "yes" : "no",
314 (cl->tech->send_image) ? "yes" : "no",
315 (cl->tech->send_text) ? "yes" : "no"
319 AST_LIST_UNLOCK(&channels);
320 return RESULT_SUCCESS;
323 static char *complete_channeltypes_deprecated(const char *line, const char *word, int pos, int state)
325 struct chanlist *cl;
326 int which = 0;
327 int wordlen;
328 char *ret = NULL;
330 if (pos != 2)
331 return NULL;
333 wordlen = strlen(word);
335 AST_LIST_TRAVERSE(&backends, cl, list) {
336 if (!strncasecmp(word, cl->tech->type, wordlen) && ++which > state) {
337 ret = strdup(cl->tech->type);
338 break;
342 return ret;
345 static char *complete_channeltypes(const char *line, const char *word, int pos, int state)
347 struct chanlist *cl;
348 int which = 0;
349 int wordlen;
350 char *ret = NULL;
352 if (pos != 3)
353 return NULL;
355 wordlen = strlen(word);
357 AST_LIST_TRAVERSE(&backends, cl, list) {
358 if (!strncasecmp(word, cl->tech->type, wordlen) && ++which > state) {
359 ret = strdup(cl->tech->type);
360 break;
364 return ret;
367 static char show_channeltypes_usage[] =
368 "Usage: core show channeltypes\n"
369 " Lists available channel types registered in your Asterisk server.\n";
371 static char show_channeltype_usage[] =
372 "Usage: core show channeltype <name>\n"
373 " Show details about the specified channel type, <name>.\n";
375 static struct ast_cli_entry cli_show_channeltypes_deprecated = {
376 { "show", "channeltypes", NULL },
377 show_channeltypes, NULL,
378 NULL };
380 static struct ast_cli_entry cli_show_channeltype_deprecated = {
381 { "show", "channeltype", NULL },
382 show_channeltype_deprecated, NULL,
383 NULL, complete_channeltypes_deprecated };
385 static struct ast_cli_entry cli_channel[] = {
386 { { "core", "show", "channeltypes", NULL },
387 show_channeltypes, "List available channel types",
388 show_channeltypes_usage, NULL, &cli_show_channeltypes_deprecated },
390 { { "core", "show", "channeltype", NULL },
391 show_channeltype, "Give more details on that channel type",
392 show_channeltype_usage, complete_channeltypes, &cli_show_channeltype_deprecated },
395 /*! \brief Checks to see if a channel is needing hang up */
396 int ast_check_hangup(struct ast_channel *chan)
398 if (chan->_softhangup) /* yes if soft hangup flag set */
399 return 1;
400 if (!chan->tech_pvt) /* yes if no technology private data */
401 return 1;
402 if (!chan->whentohangup) /* no if no hangup scheduled */
403 return 0;
404 if (chan->whentohangup > time(NULL)) /* no if hangup time has not come yet. */
405 return 0;
406 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
407 return 1;
410 static int ast_check_hangup_locked(struct ast_channel *chan)
412 int res;
413 ast_channel_lock(chan);
414 res = ast_check_hangup(chan);
415 ast_channel_unlock(chan);
416 return res;
419 /*! \brief printf the string into a correctly sized mallocd buffer, and return the buffer */
420 char *ast_safe_string_alloc(const char *fmt, ...)
422 char *b2,buf[1];
423 int len;
425 va_list args;
426 va_start(args, fmt);
427 len = vsnprintf(buf, 1, fmt, args);
428 b2 = ast_malloc(len+1);
429 vsnprintf(b2, len+1, fmt, args);
430 va_end(args);
431 return b2;
434 /*! \brief Initiate system shutdown */
435 void ast_begin_shutdown(int hangup)
437 struct ast_channel *c;
438 shutting_down = 1;
439 if (hangup) {
440 AST_LIST_LOCK(&channels);
441 AST_LIST_TRAVERSE(&channels, c, chan_list)
442 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
443 AST_LIST_UNLOCK(&channels);
447 /*! \brief returns number of active/allocated channels */
448 int ast_active_channels(void)
450 struct ast_channel *c;
451 int cnt = 0;
452 AST_LIST_LOCK(&channels);
453 AST_LIST_TRAVERSE(&channels, c, chan_list)
454 cnt++;
455 AST_LIST_UNLOCK(&channels);
456 return cnt;
459 /*! \brief Cancel a shutdown in progress */
460 void ast_cancel_shutdown(void)
462 shutting_down = 0;
465 /*! \brief Returns non-zero if Asterisk is being shut down */
466 int ast_shutting_down(void)
468 return shutting_down;
471 /*! \brief Set when to hangup channel */
472 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
474 chan->whentohangup = offset ? time(NULL) + offset : 0;
475 ast_queue_frame(chan, &ast_null_frame);
476 return;
479 /*! \brief Compare a offset with when to hangup channel */
480 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
482 time_t whentohangup;
484 if (chan->whentohangup == 0) {
485 return (offset == 0) ? 0 : -1;
486 } else {
487 if (offset == 0) /* XXX why is this special ? */
488 return (1);
489 else {
490 whentohangup = offset + time (NULL);
491 if (chan->whentohangup < whentohangup)
492 return (1);
493 else if (chan->whentohangup == whentohangup)
494 return (0);
495 else
496 return (-1);
501 /*! \brief Register a new telephony channel in Asterisk */
502 int ast_channel_register(const struct ast_channel_tech *tech)
504 struct chanlist *chan;
506 AST_LIST_LOCK(&channels);
508 AST_LIST_TRAVERSE(&backends, chan, list) {
509 if (!strcasecmp(tech->type, chan->tech->type)) {
510 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
511 AST_LIST_UNLOCK(&channels);
512 return -1;
516 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
517 AST_LIST_UNLOCK(&channels);
518 return -1;
520 chan->tech = tech;
521 AST_LIST_INSERT_HEAD(&backends, chan, list);
523 if (option_debug)
524 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
526 if (option_verbose > 1)
527 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
528 chan->tech->description);
530 AST_LIST_UNLOCK(&channels);
531 return 0;
534 void ast_channel_unregister(const struct ast_channel_tech *tech)
536 struct chanlist *chan;
538 if (option_debug)
539 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
541 AST_LIST_LOCK(&channels);
543 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
544 if (chan->tech == tech) {
545 AST_LIST_REMOVE_CURRENT(&backends, list);
546 free(chan);
547 if (option_verbose > 1)
548 ast_verbose(VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
549 break;
552 AST_LIST_TRAVERSE_SAFE_END
554 AST_LIST_UNLOCK(&channels);
557 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
559 struct chanlist *chanls;
560 const struct ast_channel_tech *ret = NULL;
562 if (AST_LIST_LOCK(&channels)) {
563 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
564 return NULL;
567 AST_LIST_TRAVERSE(&backends, chanls, list) {
568 if (!strcasecmp(name, chanls->tech->type)) {
569 ret = chanls->tech;
570 break;
574 AST_LIST_UNLOCK(&channels);
576 return ret;
579 /*! \brief Gives the string form of a given hangup cause */
580 const char *ast_cause2str(int cause)
582 int x;
584 for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++) {
585 if (causes[x].cause == cause)
586 return causes[x].desc;
589 return "Unknown";
592 /*! \brief Convert a symbolic hangup cause to number */
593 int ast_str2cause(const char *name)
595 int x;
597 for (x = 0; x < sizeof(causes) / sizeof(causes[0]); x++)
598 if (strncasecmp(causes[x].name, name, strlen(causes[x].name)) == 0)
599 return causes[x].cause;
601 return -1;
604 /*! \brief Gives the string form of a given channel state */
605 char *ast_state2str(enum ast_channel_state state)
607 char *buf;
609 switch(state) {
610 case AST_STATE_DOWN:
611 return "Down";
612 case AST_STATE_RESERVED:
613 return "Rsrvd";
614 case AST_STATE_OFFHOOK:
615 return "OffHook";
616 case AST_STATE_DIALING:
617 return "Dialing";
618 case AST_STATE_RING:
619 return "Ring";
620 case AST_STATE_RINGING:
621 return "Ringing";
622 case AST_STATE_UP:
623 return "Up";
624 case AST_STATE_BUSY:
625 return "Busy";
626 case AST_STATE_DIALING_OFFHOOK:
627 return "Dialing Offhook";
628 case AST_STATE_PRERING:
629 return "Pre-ring";
630 default:
631 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
632 return "Unknown";
633 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
634 return buf;
638 /*! \brief Gives the string form of a given transfer capability */
639 char *ast_transfercapability2str(int transfercapability)
641 switch(transfercapability) {
642 case AST_TRANS_CAP_SPEECH:
643 return "SPEECH";
644 case AST_TRANS_CAP_DIGITAL:
645 return "DIGITAL";
646 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
647 return "RESTRICTED_DIGITAL";
648 case AST_TRANS_CAP_3_1K_AUDIO:
649 return "3K1AUDIO";
650 case AST_TRANS_CAP_DIGITAL_W_TONES:
651 return "DIGITAL_W_TONES";
652 case AST_TRANS_CAP_VIDEO:
653 return "VIDEO";
654 default:
655 return "UNKNOWN";
659 /*! \brief Pick the best audio codec */
660 int ast_best_codec(int fmts)
662 /* This just our opinion, expressed in code. We are asked to choose
663 the best codec to use, given no information */
664 int x;
665 static int prefs[] =
667 /*! Okay, ulaw is used by all telephony equipment, so start with it */
668 AST_FORMAT_ULAW,
669 /*! Unless of course, you're a silly European, so then prefer ALAW */
670 AST_FORMAT_ALAW,
671 /*! Okay, well, signed linear is easy to translate into other stuff */
672 AST_FORMAT_SLINEAR,
673 /*! G.726 is standard ADPCM, in RFC3551 packing order */
674 AST_FORMAT_G726,
675 /*! G.726 is standard ADPCM, in AAL2 packing order */
676 AST_FORMAT_G726_AAL2,
677 /*! ADPCM has great sound quality and is still pretty easy to translate */
678 AST_FORMAT_ADPCM,
679 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
680 translate and sounds pretty good */
681 AST_FORMAT_GSM,
682 /*! iLBC is not too bad */
683 AST_FORMAT_ILBC,
684 /*! Speex is free, but computationally more expensive than GSM */
685 AST_FORMAT_SPEEX,
686 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
687 to use it */
688 AST_FORMAT_LPC10,
689 /*! G.729a is faster than 723 and slightly less expensive */
690 AST_FORMAT_G729A,
691 /*! Down to G.723.1 which is proprietary but at least designed for voice */
692 AST_FORMAT_G723_1,
695 /* Strip out video */
696 fmts &= AST_FORMAT_AUDIO_MASK;
698 /* Find the first preferred codec in the format given */
699 for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
700 if (fmts & prefs[x])
701 return prefs[x];
702 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
703 return 0;
706 static const struct ast_channel_tech null_tech = {
707 .type = "NULL",
708 .description = "Null channel (should not see this)",
711 /*! \brief Create a new channel structure */
712 struct ast_channel *ast_channel_alloc(int needqueue, int state, const char *cid_num, const char *cid_name, const char *name_fmt, ...)
714 struct ast_channel *tmp;
715 int x;
716 int flags;
717 struct varshead *headp;
718 va_list ap1, ap2;
720 /* If shutting down, don't allocate any new channels */
721 if (shutting_down) {
722 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
723 return NULL;
726 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
727 return NULL;
729 if (!(tmp->sched = sched_context_create())) {
730 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
731 free(tmp);
732 return NULL;
735 ast_string_field_init(tmp, 128);
737 /* Don't bother initializing the last two FD here, because they
738 will *always* be set just a few lines down (AST_TIMING_FD,
739 AST_ALERT_FD). */
740 for (x = 0; x < AST_MAX_FDS - 2; x++)
741 tmp->fds[x] = -1;
743 #ifdef HAVE_ZAPTEL
744 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
745 if (tmp->timingfd > -1) {
746 /* Check if timing interface supports new
747 ping/pong scheme */
748 flags = 1;
749 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
750 needqueue = 0;
752 #else
753 tmp->timingfd = -1;
754 #endif
756 if (needqueue) {
757 if (pipe(tmp->alertpipe)) {
758 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
759 ast_string_field_free_pools(tmp);
760 free(tmp);
761 return NULL;
762 } else {
763 flags = fcntl(tmp->alertpipe[0], F_GETFL);
764 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
765 flags = fcntl(tmp->alertpipe[1], F_GETFL);
766 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
768 } else /* Make sure we've got it done right if they don't */
769 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
771 /* Always watch the alertpipe */
772 tmp->fds[AST_ALERT_FD] = tmp->alertpipe[0];
773 /* And timing pipe */
774 tmp->fds[AST_TIMING_FD] = tmp->timingfd;
775 ast_string_field_set(tmp, name, "**Unknown**");
777 /* Initial state */
778 tmp->_state = state;
780 tmp->streamid = -1;
782 tmp->fin = global_fin;
783 tmp->fout = global_fout;
785 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
786 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
787 ast_atomic_fetchadd_int(&uniqueint, 1));
788 } else {
789 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
790 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
793 if (!ast_strlen_zero(name_fmt)) {
794 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
795 * And they all use slightly different formats for their name string.
796 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
797 * This means, that the stringfields must have a routine that takes the va_lists directly, and
798 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
799 * This new function was written so this can be accomplished.
801 va_start(ap1, name_fmt);
802 va_start(ap2, name_fmt);
803 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
804 va_end(ap1);
805 va_end(ap2);
807 /* and now, since the channel structure is built, and has its name, let's call the
808 * manager event generator with this Newchannel event. This is the proper and correct
809 * place to make this call, but you sure do have to pass a lot of data into this func
810 * to do it here!
812 manager_event(EVENT_FLAG_CALL, "Newchannel",
813 "Channel: %s\r\n"
814 "State: %s\r\n"
815 "CallerIDNum: %s\r\n"
816 "CallerIDName: %s\r\n"
817 "Uniqueid: %s\r\n",
818 tmp->name, ast_state2str(state),
819 S_OR(cid_num, "<unknown>"),
820 S_OR(cid_name, "<unknown>"),
821 tmp->uniqueid);
824 headp = &tmp->varshead;
825 AST_LIST_HEAD_INIT_NOLOCK(headp);
827 ast_mutex_init(&tmp->lock);
829 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
831 strcpy(tmp->context, "default");
832 strcpy(tmp->exten, "s");
833 tmp->priority = 1;
835 ast_string_field_set(tmp, language, defaultlanguage);
836 tmp->amaflags = ast_default_amaflags;
837 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
839 tmp->tech = &null_tech;
841 AST_LIST_LOCK(&channels);
842 AST_LIST_INSERT_HEAD(&channels, tmp, chan_list);
843 AST_LIST_UNLOCK(&channels);
845 return tmp;
848 /*! \brief Queue an outgoing media frame */
849 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
851 struct ast_frame *f;
852 struct ast_frame *cur;
853 int blah = 1;
854 int qlen = 0;
856 /* Build us a copy and free the original one */
857 if (!(f = ast_frdup(fin))) {
858 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
859 return -1;
861 ast_channel_lock(chan);
863 /* See if the last frame on the queue is a hangup, if so don't queue anything */
864 if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
865 ast_frfree(f);
866 ast_channel_unlock(chan);
867 return 0;
870 /* Count how many frames exist on the queue */
871 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
872 qlen++;
875 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
876 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
877 if (fin->frametype != AST_FRAME_VOICE) {
878 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
879 CRASH;
880 } else {
881 if (option_debug)
882 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
883 ast_frfree(f);
884 ast_channel_unlock(chan);
885 return 0;
888 AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
889 if (chan->alertpipe[1] > -1) {
890 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
891 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
892 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
893 #ifdef HAVE_ZAPTEL
894 } else if (chan->timingfd > -1) {
895 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
896 #endif
897 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
898 pthread_kill(chan->blocker, SIGURG);
900 ast_channel_unlock(chan);
901 return 0;
904 /*! \brief Queue a hangup frame for channel */
905 int ast_queue_hangup(struct ast_channel *chan)
907 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
908 /* Yeah, let's not change a lock-critical value without locking */
909 if (!ast_channel_trylock(chan)) {
910 chan->_softhangup |= AST_SOFTHANGUP_DEV;
911 ast_channel_unlock(chan);
913 return ast_queue_frame(chan, &f);
916 /*! \brief Queue a control frame */
917 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
919 struct ast_frame f = { AST_FRAME_CONTROL, };
921 f.subclass = control;
923 return ast_queue_frame(chan, &f);
926 /*! \brief Queue a control frame with payload */
927 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
928 const void *data, size_t datalen)
930 struct ast_frame f = { AST_FRAME_CONTROL, };
932 f.subclass = control;
933 f.data = (void *) data;
934 f.datalen = datalen;
936 return ast_queue_frame(chan, &f);
939 /*! \brief Set defer DTMF flag on channel */
940 int ast_channel_defer_dtmf(struct ast_channel *chan)
942 int pre = 0;
944 if (chan) {
945 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
946 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
948 return pre;
951 /*! \brief Unset defer DTMF flag on channel */
952 void ast_channel_undefer_dtmf(struct ast_channel *chan)
954 if (chan)
955 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
959 * \brief Helper function to find channels.
961 * It supports these modes:
963 * prev != NULL : get channel next in list after prev
964 * name != NULL : get channel with matching name
965 * name != NULL && namelen != 0 : get channel whose name starts with prefix
966 * exten != NULL : get channel whose exten or macroexten matches
967 * context != NULL && exten != NULL : get channel whose context or macrocontext
969 * It returns with the channel's lock held. If getting the individual lock fails,
970 * unlock and retry quickly up to 10 times, then give up.
972 * \note XXX Note that this code has cost O(N) because of the need to verify
973 * that the object is still on the global list.
975 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
976 * can only be done with the lock held or someone could delete the
977 * object while we work on it. This causes some ugliness in the code.
978 * Note that removing the first ast_log() may be harmful, as it would
979 * shorten the retry period and possibly cause failures.
980 * We should definitely go for a better scheme that is deadlock-free.
982 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
983 const char *name, const int namelen,
984 const char *context, const char *exten)
986 const char *msg = prev ? "deadlock" : "initial deadlock";
987 int retries;
988 struct ast_channel *c;
990 for (retries = 0; retries < 10; retries++) {
991 int done;
992 AST_LIST_LOCK(&channels);
993 AST_LIST_TRAVERSE(&channels, c, chan_list) {
994 if (prev) { /* look for next item */
995 if (c != prev) /* not this one */
996 continue;
997 /* found, prepare to return c->next */
998 c = AST_LIST_NEXT(c, chan_list);
1000 if (name) { /* want match by name */
1001 if ((!namelen && strcasecmp(c->name, name)) ||
1002 (namelen && strncasecmp(c->name, name, namelen)))
1003 continue; /* name match failed */
1004 } else if (exten) {
1005 if (context && strcasecmp(c->context, context) &&
1006 strcasecmp(c->macrocontext, context))
1007 continue; /* context match failed */
1008 if (strcasecmp(c->exten, exten) &&
1009 strcasecmp(c->macroexten, exten))
1010 continue; /* exten match failed */
1012 /* if we get here, c points to the desired record */
1013 break;
1015 /* exit if chan not found or mutex acquired successfully */
1016 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
1017 done = c == NULL || ast_channel_trylock(c) == 0;
1018 if (!done)
1019 if (option_debug)
1020 ast_log(LOG_DEBUG, "Avoiding %s for channel '%p'\n", msg, c);
1021 AST_LIST_UNLOCK(&channels);
1022 if (done)
1023 return c;
1024 usleep(1); /* give other threads a chance before retrying */
1027 * c is surely not null, but we don't have the lock so cannot
1028 * access c->name
1030 if (option_debug)
1031 ast_log(LOG_DEBUG, "Failure, could not lock '%p' after %d retries!\n",
1032 c, retries);
1034 return NULL;
1037 /*! \brief Browse channels in use */
1038 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
1040 return channel_find_locked(prev, NULL, 0, NULL, NULL);
1043 /*! \brief Get channel by name and lock it */
1044 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
1046 return channel_find_locked(NULL, name, 0, NULL, NULL);
1049 /*! \brief Get channel by name prefix and lock it */
1050 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
1052 return channel_find_locked(NULL, name, namelen, NULL, NULL);
1055 /*! \brief Get next channel by name prefix and lock it */
1056 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
1057 const int namelen)
1059 return channel_find_locked(chan, name, namelen, NULL, NULL);
1062 /*! \brief Get channel by exten (and optionally context) and lock it */
1063 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
1065 return channel_find_locked(NULL, NULL, 0, context, exten);
1068 /*! \brief Get next channel by exten (and optionally context) and lock it */
1069 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1070 const char *context)
1072 return channel_find_locked(chan, NULL, 0, context, exten);
1075 /*! \brief Wait, look for hangups and condition arg */
1076 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1078 struct ast_frame *f;
1080 while (ms > 0) {
1081 if (cond && ((*cond)(data) == 0))
1082 return 0;
1083 ms = ast_waitfor(chan, ms);
1084 if (ms < 0)
1085 return -1;
1086 if (ms > 0) {
1087 f = ast_read(chan);
1088 if (!f)
1089 return -1;
1090 ast_frfree(f);
1093 return 0;
1096 /*! \brief Wait, look for hangups */
1097 int ast_safe_sleep(struct ast_channel *chan, int ms)
1099 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1102 static void free_cid(struct ast_callerid *cid)
1104 if (cid->cid_dnid)
1105 free(cid->cid_dnid);
1106 if (cid->cid_num)
1107 free(cid->cid_num);
1108 if (cid->cid_name)
1109 free(cid->cid_name);
1110 if (cid->cid_ani)
1111 free(cid->cid_ani);
1112 if (cid->cid_rdnis)
1113 free(cid->cid_rdnis);
1116 /*! \brief Free a channel structure */
1117 void ast_channel_free(struct ast_channel *chan)
1119 int fd;
1120 struct ast_var_t *vardata;
1121 struct ast_frame *f;
1122 struct varshead *headp;
1123 struct ast_datastore *datastore = NULL;
1124 char name[AST_CHANNEL_NAME];
1126 headp=&chan->varshead;
1128 AST_LIST_LOCK(&channels);
1129 AST_LIST_REMOVE(&channels, chan, chan_list);
1130 /* Lock and unlock the channel just to be sure nobody
1131 has it locked still */
1132 ast_channel_lock(chan);
1133 ast_channel_unlock(chan);
1134 if (chan->tech_pvt) {
1135 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1136 free(chan->tech_pvt);
1139 if (chan->sched)
1140 sched_context_destroy(chan->sched);
1142 ast_copy_string(name, chan->name, sizeof(name));
1144 /* Stop monitoring */
1145 if (chan->monitor)
1146 chan->monitor->stop( chan, 0 );
1148 /* If there is native format music-on-hold state, free it */
1149 if (chan->music_state)
1150 ast_moh_cleanup(chan);
1152 /* if someone is whispering on the channel, stop them */
1153 if (chan->whisper)
1154 ast_channel_whisper_stop(chan);
1156 /* Free translators */
1157 if (chan->readtrans)
1158 ast_translator_free_path(chan->readtrans);
1159 if (chan->writetrans)
1160 ast_translator_free_path(chan->writetrans);
1161 if (chan->pbx)
1162 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1163 free_cid(&chan->cid);
1164 ast_mutex_destroy(&chan->lock);
1165 /* Close pipes if appropriate */
1166 if ((fd = chan->alertpipe[0]) > -1)
1167 close(fd);
1168 if ((fd = chan->alertpipe[1]) > -1)
1169 close(fd);
1170 if ((fd = chan->timingfd) > -1)
1171 close(fd);
1172 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1173 ast_frfree(f);
1175 /* Get rid of each of the data stores on the channel */
1176 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1177 /* Free the data store */
1178 ast_channel_datastore_free(datastore);
1179 AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1181 /* loop over the variables list, freeing all data and deleting list items */
1182 /* no need to lock the list, as the channel is already locked */
1184 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1185 ast_var_delete(vardata);
1187 /* Destroy the jitterbuffer */
1188 ast_jb_destroy(chan);
1190 ast_string_field_free_pools(chan);
1191 free(chan);
1192 AST_LIST_UNLOCK(&channels);
1194 ast_device_state_changed_literal(name);
1197 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
1199 struct ast_datastore *datastore = NULL;
1201 /* Make sure we at least have type so we can identify this */
1202 if (info == NULL) {
1203 return NULL;
1206 /* Allocate memory for datastore and clear it */
1207 datastore = ast_calloc(1, sizeof(*datastore));
1208 if (datastore == NULL) {
1209 return NULL;
1212 datastore->info = info;
1214 datastore->uid = ast_strdup(uid);
1216 return datastore;
1219 int ast_channel_datastore_free(struct ast_datastore *datastore)
1221 int res = 0;
1223 /* Using the destroy function (if present) destroy the data */
1224 if (datastore->info->destroy != NULL && datastore->data != NULL) {
1225 datastore->info->destroy(datastore->data);
1226 datastore->data = NULL;
1229 /* Free allocated UID memory */
1230 if (datastore->uid != NULL) {
1231 free(datastore->uid);
1232 datastore->uid = NULL;
1235 /* Finally free memory used by ourselves */
1236 free(datastore);
1238 return res;
1241 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1243 int res = 0;
1245 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1247 return res;
1250 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1252 struct ast_datastore *datastore2 = NULL;
1253 int res = -1;
1255 /* Find our position and remove ourselves */
1256 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1257 if (datastore2 == datastore) {
1258 AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1259 res = 0;
1260 break;
1263 AST_LIST_TRAVERSE_SAFE_END
1265 return res;
1268 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
1270 struct ast_datastore *datastore = NULL;
1272 if (info == NULL)
1273 return NULL;
1275 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1276 if (datastore->info == info) {
1277 if (uid != NULL && datastore->uid != NULL) {
1278 if (!strcasecmp(uid, datastore->uid)) {
1279 /* Matched by type AND uid */
1280 break;
1282 } else {
1283 /* Matched by type at least */
1284 break;
1288 AST_LIST_TRAVERSE_SAFE_END
1290 return datastore;
1293 int ast_channel_spy_add(struct ast_channel *chan, struct ast_channel_spy *spy)
1295 /* Link the owner channel to the spy */
1296 spy->chan = chan;
1298 if (!ast_test_flag(spy, CHANSPY_FORMAT_AUDIO)) {
1299 ast_log(LOG_WARNING, "Could not add channel spy '%s' to channel '%s', only audio format spies are supported.\n",
1300 spy->type, chan->name);
1301 return -1;
1304 if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST) && (spy->read_queue.format != AST_FORMAT_SLINEAR)) {
1305 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1306 ast_getformatname(spy->read_queue.format));
1307 return -1;
1310 if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST) && (spy->write_queue.format != AST_FORMAT_SLINEAR)) {
1311 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1312 ast_getformatname(spy->write_queue.format));
1313 return -1;
1316 if (ast_test_flag(spy, CHANSPY_MIXAUDIO) &&
1317 ((spy->read_queue.format != AST_FORMAT_SLINEAR) ||
1318 (spy->write_queue.format != AST_FORMAT_SLINEAR))) {
1319 ast_log(LOG_WARNING, "Cannot provide audio mixing on '%s'-'%s' format spies\n",
1320 ast_getformatname(spy->read_queue.format), ast_getformatname(spy->write_queue.format));
1321 return -1;
1324 if (!chan->spies) {
1325 if (!(chan->spies = ast_calloc(1, sizeof(*chan->spies)))) {
1326 return -1;
1329 AST_LIST_HEAD_INIT_NOLOCK(&chan->spies->list);
1330 AST_LIST_INSERT_HEAD(&chan->spies->list, spy, list);
1331 } else {
1332 AST_LIST_INSERT_TAIL(&chan->spies->list, spy, list);
1335 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1336 ast_cond_init(&spy->trigger, NULL);
1337 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1338 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1341 if (option_debug)
1342 ast_log(LOG_DEBUG, "Spy %s added to channel %s\n",
1343 spy->type, chan->name);
1345 return 0;
1348 /* Clean up a channel's spy information */
1349 static void spy_cleanup(struct ast_channel *chan)
1351 if (!AST_LIST_EMPTY(&chan->spies->list))
1352 return;
1353 if (chan->spies->read_translator.path)
1354 ast_translator_free_path(chan->spies->read_translator.path);
1355 if (chan->spies->write_translator.path)
1356 ast_translator_free_path(chan->spies->write_translator.path);
1357 free(chan->spies);
1358 chan->spies = NULL;
1359 return;
1362 /* Detach a spy from it's channel */
1363 static void spy_detach(struct ast_channel_spy *spy, struct ast_channel *chan)
1365 ast_mutex_lock(&spy->lock);
1367 /* We only need to poke them if they aren't already done */
1368 if (spy->status != CHANSPY_DONE) {
1369 /* Indicate to the spy to stop */
1370 spy->status = CHANSPY_STOP;
1371 spy->chan = NULL;
1372 /* Poke the spy if needed */
1373 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1374 ast_cond_signal(&spy->trigger);
1377 /* Print it out while we still have a lock so the structure can't go away (if signalled above) */
1378 if (option_debug)
1379 ast_log(LOG_DEBUG, "Spy %s removed from channel %s\n", spy->type, chan->name);
1381 ast_mutex_unlock(&spy->lock);
1383 return;
1386 void ast_channel_spy_stop_by_type(struct ast_channel *chan, const char *type)
1388 struct ast_channel_spy *spy = NULL;
1390 if (!chan->spies)
1391 return;
1393 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1394 ast_mutex_lock(&spy->lock);
1395 if ((spy->type == type) && (spy->status == CHANSPY_RUNNING)) {
1396 ast_mutex_unlock(&spy->lock);
1397 AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1398 spy_detach(spy, chan);
1399 } else
1400 ast_mutex_unlock(&spy->lock);
1402 AST_LIST_TRAVERSE_SAFE_END
1403 spy_cleanup(chan);
1406 void ast_channel_spy_trigger_wait(struct ast_channel_spy *spy)
1408 struct timeval tv;
1409 struct timespec ts;
1411 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
1412 ts.tv_sec = tv.tv_sec;
1413 ts.tv_nsec = tv.tv_usec * 1000;
1415 ast_cond_timedwait(&spy->trigger, &spy->lock, &ts);
1418 void ast_channel_spy_remove(struct ast_channel *chan, struct ast_channel_spy *spy)
1420 if (!chan->spies)
1421 return;
1423 AST_LIST_REMOVE(&chan->spies->list, spy, list);
1424 spy_detach(spy, chan);
1425 spy_cleanup(chan);
1428 void ast_channel_spy_free(struct ast_channel_spy *spy)
1430 struct ast_frame *f = NULL;
1432 if (spy->status == CHANSPY_DONE)
1433 return;
1435 /* Switch status to done in case we get called twice */
1436 spy->status = CHANSPY_DONE;
1438 /* Drop any frames in the queue */
1439 while ((f = AST_LIST_REMOVE_HEAD(&spy->write_queue.list, frame_list)))
1440 ast_frfree(f);
1441 while ((f = AST_LIST_REMOVE_HEAD(&spy->read_queue.list, frame_list)))
1442 ast_frfree(f);
1444 /* Destroy the condition if in use */
1445 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1446 ast_cond_destroy(&spy->trigger);
1448 /* Destroy our mutex since it is no longer in use */
1449 ast_mutex_destroy(&spy->lock);
1451 return;
1454 static void detach_spies(struct ast_channel *chan)
1456 struct ast_channel_spy *spy = NULL;
1458 if (!chan->spies)
1459 return;
1461 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1462 AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1463 spy_detach(spy, chan);
1465 AST_LIST_TRAVERSE_SAFE_END
1467 spy_cleanup(chan);
1470 /*! \brief Softly hangup a channel, don't lock */
1471 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1473 if (option_debug)
1474 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
1475 /* Inform channel driver that we need to be hung up, if it cares */
1476 chan->_softhangup |= cause;
1477 ast_queue_frame(chan, &ast_null_frame);
1478 /* Interrupt any poll call or such */
1479 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1480 pthread_kill(chan->blocker, SIGURG);
1481 return 0;
1484 /*! \brief Softly hangup a channel, lock */
1485 int ast_softhangup(struct ast_channel *chan, int cause)
1487 int res;
1488 ast_channel_lock(chan);
1489 res = ast_softhangup_nolock(chan, cause);
1490 ast_channel_unlock(chan);
1491 return res;
1494 enum spy_direction {
1495 SPY_READ,
1496 SPY_WRITE,
1499 #define SPY_QUEUE_SAMPLE_LIMIT 4000 /* half of one second */
1501 static void queue_frame_to_spies(struct ast_channel *chan, struct ast_frame *f, enum spy_direction dir)
1503 struct ast_frame *translated_frame = NULL;
1504 struct ast_channel_spy *spy;
1505 struct channel_spy_trans *trans;
1507 trans = (dir == SPY_READ) ? &chan->spies->read_translator : &chan->spies->write_translator;
1509 AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1510 struct ast_channel_spy_queue *queue;
1511 struct ast_frame *duped_fr;
1513 ast_mutex_lock(&spy->lock);
1515 queue = (dir == SPY_READ) ? &spy->read_queue : &spy->write_queue;
1517 if ((queue->format == AST_FORMAT_SLINEAR) && (f->subclass != AST_FORMAT_SLINEAR)) {
1518 if (!translated_frame) {
1519 if (trans->path && (trans->last_format != f->subclass)) {
1520 ast_translator_free_path(trans->path);
1521 trans->path = NULL;
1523 if (!trans->path) {
1524 if (option_debug)
1525 ast_log(LOG_DEBUG, "Building translator from %s to SLINEAR for spies on channel %s\n",
1526 ast_getformatname(f->subclass), chan->name);
1527 if ((trans->path = ast_translator_build_path(AST_FORMAT_SLINEAR, f->subclass)) == NULL) {
1528 ast_log(LOG_WARNING, "Cannot build a path from %s to %s\n",
1529 ast_getformatname(f->subclass), ast_getformatname(AST_FORMAT_SLINEAR));
1530 ast_mutex_unlock(&spy->lock);
1531 continue;
1532 } else {
1533 trans->last_format = f->subclass;
1536 if (!(translated_frame = ast_translate(trans->path, f, 0))) {
1537 ast_log(LOG_ERROR, "Translation to %s failed, dropping frame for spies\n",
1538 ast_getformatname(AST_FORMAT_SLINEAR));
1539 ast_mutex_unlock(&spy->lock);
1540 break;
1543 duped_fr = ast_frdup(translated_frame);
1544 } else if (f->subclass != queue->format) {
1545 ast_log(LOG_WARNING, "Spy '%s' on channel '%s' wants format '%s', but frame is '%s', dropping\n",
1546 spy->type, chan->name,
1547 ast_getformatname(queue->format), ast_getformatname(f->subclass));
1548 ast_mutex_unlock(&spy->lock);
1549 continue;
1550 } else
1551 duped_fr = ast_frdup(f);
1553 AST_LIST_INSERT_TAIL(&queue->list, duped_fr, frame_list);
1555 queue->samples += f->samples;
1557 if (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1558 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1559 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1560 case CHANSPY_TRIGGER_READ:
1561 if (dir == SPY_WRITE) {
1562 ast_set_flag(spy, CHANSPY_TRIGGER_WRITE);
1563 ast_clear_flag(spy, CHANSPY_TRIGGER_READ);
1564 if (option_debug)
1565 ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to write-trigger mode\n",
1566 spy->type, chan->name);
1568 break;
1569 case CHANSPY_TRIGGER_WRITE:
1570 if (dir == SPY_READ) {
1571 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1572 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1573 if (option_debug)
1574 ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to read-trigger mode\n",
1575 spy->type, chan->name);
1577 break;
1579 if (option_debug)
1580 ast_log(LOG_DEBUG, "Triggering queue flush for spy '%s' on '%s'\n",
1581 spy->type, chan->name);
1582 ast_set_flag(spy, CHANSPY_TRIGGER_FLUSH);
1583 ast_cond_signal(&spy->trigger);
1584 } else {
1585 if (option_debug)
1586 ast_log(LOG_DEBUG, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1587 spy->type, chan->name, (dir == SPY_READ) ? "read" : "write");
1588 while (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1589 struct ast_frame *drop = AST_LIST_REMOVE_HEAD(&queue->list, frame_list);
1590 queue->samples -= drop->samples;
1591 ast_frfree(drop);
1594 } else {
1595 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1596 case CHANSPY_TRIGGER_READ:
1597 if (dir == SPY_READ)
1598 ast_cond_signal(&spy->trigger);
1599 break;
1600 case CHANSPY_TRIGGER_WRITE:
1601 if (dir == SPY_WRITE)
1602 ast_cond_signal(&spy->trigger);
1603 break;
1607 ast_mutex_unlock(&spy->lock);
1610 if (translated_frame)
1611 ast_frfree(translated_frame);
1614 static void free_translation(struct ast_channel *clone)
1616 if (clone->writetrans)
1617 ast_translator_free_path(clone->writetrans);
1618 if (clone->readtrans)
1619 ast_translator_free_path(clone->readtrans);
1620 clone->writetrans = NULL;
1621 clone->readtrans = NULL;
1622 clone->rawwriteformat = clone->nativeformats;
1623 clone->rawreadformat = clone->nativeformats;
1626 /*! \brief Hangup a channel */
1627 int ast_hangup(struct ast_channel *chan)
1629 int res = 0;
1631 /* Don't actually hang up a channel that will masquerade as someone else, or
1632 if someone is going to masquerade as us */
1633 ast_channel_lock(chan);
1635 detach_spies(chan); /* get rid of spies */
1637 if (chan->masq) {
1638 if (ast_do_masquerade(chan))
1639 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1642 if (chan->masq) {
1643 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1644 ast_channel_unlock(chan);
1645 return 0;
1647 /* If this channel is one which will be masqueraded into something,
1648 mark it as a zombie already, so we know to free it later */
1649 if (chan->masqr) {
1650 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1651 ast_channel_unlock(chan);
1652 return 0;
1654 free_translation(chan);
1655 /* Close audio stream */
1656 if (chan->stream) {
1657 ast_closestream(chan->stream);
1658 chan->stream = NULL;
1660 /* Close video stream */
1661 if (chan->vstream) {
1662 ast_closestream(chan->vstream);
1663 chan->vstream = NULL;
1665 if (chan->sched) {
1666 sched_context_destroy(chan->sched);
1667 chan->sched = NULL;
1670 if (chan->generatordata) /* Clear any tone stuff remaining */
1671 chan->generator->release(chan, chan->generatordata);
1672 chan->generatordata = NULL;
1673 chan->generator = NULL;
1674 if (chan->cdr) { /* End the CDR if it hasn't already */
1675 ast_cdr_end(chan->cdr);
1676 ast_cdr_detach(chan->cdr); /* Post and Free the CDR */
1677 chan->cdr = NULL;
1679 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1680 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1681 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1682 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1683 CRASH;
1685 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1686 if (option_debug)
1687 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1688 if (chan->tech->hangup)
1689 res = chan->tech->hangup(chan);
1690 } else {
1691 if (option_debug)
1692 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1695 ast_channel_unlock(chan);
1696 manager_event(EVENT_FLAG_CALL, "Hangup",
1697 "Channel: %s\r\n"
1698 "Uniqueid: %s\r\n"
1699 "Cause: %d\r\n"
1700 "Cause-txt: %s\r\n",
1701 chan->name,
1702 chan->uniqueid,
1703 chan->hangupcause,
1704 ast_cause2str(chan->hangupcause)
1706 ast_channel_free(chan);
1707 return res;
1710 int ast_answer(struct ast_channel *chan)
1712 int res = 0;
1713 ast_channel_lock(chan);
1714 /* You can't answer an outbound call */
1715 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1716 ast_channel_unlock(chan);
1717 return 0;
1719 /* Stop if we're a zombie or need a soft hangup */
1720 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1721 ast_channel_unlock(chan);
1722 return -1;
1724 switch(chan->_state) {
1725 case AST_STATE_RINGING:
1726 case AST_STATE_RING:
1727 if (chan->tech->answer)
1728 res = chan->tech->answer(chan);
1729 ast_setstate(chan, AST_STATE_UP);
1730 ast_cdr_answer(chan->cdr);
1731 break;
1732 case AST_STATE_UP:
1733 ast_cdr_answer(chan->cdr);
1734 break;
1735 default:
1736 break;
1738 ast_channel_unlock(chan);
1739 return res;
1742 void ast_deactivate_generator(struct ast_channel *chan)
1744 ast_channel_lock(chan);
1745 if (chan->generatordata) {
1746 if (chan->generator && chan->generator->release)
1747 chan->generator->release(chan, chan->generatordata);
1748 chan->generatordata = NULL;
1749 chan->generator = NULL;
1750 chan->fds[AST_GENERATOR_FD] = -1;
1751 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1752 ast_settimeout(chan, 0, NULL, NULL);
1754 ast_channel_unlock(chan);
1757 static int generator_force(void *data)
1759 /* Called if generator doesn't have data */
1760 void *tmp;
1761 int res;
1762 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1763 struct ast_channel *chan = data;
1764 tmp = chan->generatordata;
1765 chan->generatordata = NULL;
1766 generate = chan->generator->generate;
1767 res = generate(chan, tmp, 0, 160);
1768 chan->generatordata = tmp;
1769 if (res) {
1770 if (option_debug)
1771 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1772 ast_deactivate_generator(chan);
1774 return 0;
1777 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1779 int res = 0;
1781 ast_channel_lock(chan);
1783 if (chan->generatordata) {
1784 if (chan->generator && chan->generator->release)
1785 chan->generator->release(chan, chan->generatordata);
1786 chan->generatordata = NULL;
1789 ast_prod(chan);
1790 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1791 res = -1;
1794 if (!res) {
1795 ast_settimeout(chan, 160, generator_force, chan);
1796 chan->generator = gen;
1799 ast_channel_unlock(chan);
1801 return res;
1804 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1805 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1807 int winner = -1;
1808 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1809 return winner;
1812 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1813 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1814 int *exception, int *outfd, int *ms)
1816 struct timeval start = { 0 , 0 };
1817 struct pollfd *pfds;
1818 int res;
1819 long rms;
1820 int x, y, max;
1821 int sz;
1822 time_t now = 0;
1823 long whentohangup = 0, diff;
1824 struct ast_channel *winner = NULL;
1825 struct fdmap {
1826 int chan;
1827 int fdno;
1828 } *fdmap;
1830 sz = n * AST_MAX_FDS + nfds;
1831 pfds = alloca(sizeof(*pfds) * sz);
1832 fdmap = alloca(sizeof(*fdmap) * sz);
1834 if (outfd)
1835 *outfd = -99999;
1836 if (exception)
1837 *exception = 0;
1839 /* Perform any pending masquerades */
1840 for (x=0; x < n; x++) {
1841 ast_channel_lock(c[x]);
1842 if (c[x]->masq) {
1843 if (ast_do_masquerade(c[x])) {
1844 ast_log(LOG_WARNING, "Masquerade failed\n");
1845 *ms = -1;
1846 ast_channel_unlock(c[x]);
1847 return NULL;
1850 if (c[x]->whentohangup) {
1851 if (!whentohangup)
1852 time(&now);
1853 diff = c[x]->whentohangup - now;
1854 if (diff < 1) {
1855 /* Should already be hungup */
1856 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1857 ast_channel_unlock(c[x]);
1858 return c[x];
1860 if (!whentohangup || (diff < whentohangup))
1861 whentohangup = diff;
1863 ast_channel_unlock(c[x]);
1865 /* Wait full interval */
1866 rms = *ms;
1867 if (whentohangup) {
1868 rms = whentohangup * 1000; /* timeout in milliseconds */
1869 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1870 rms = *ms;
1873 * Build the pollfd array, putting the channels' fds first,
1874 * followed by individual fds. Order is important because
1875 * individual fd's must have priority over channel fds.
1877 max = 0;
1878 for (x=0; x<n; x++) {
1879 for (y=0; y<AST_MAX_FDS; y++) {
1880 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1881 fdmap[max].chan = x; /* channel x is linked to this pfds */
1882 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1884 CHECK_BLOCKING(c[x]);
1886 /* Add the individual fds */
1887 for (x=0; x<nfds; x++) {
1888 fdmap[max].chan = -1;
1889 max += ast_add_fd(&pfds[max], fds[x]);
1892 if (*ms > 0)
1893 start = ast_tvnow();
1895 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1896 do {
1897 int kbrms = rms;
1898 if (kbrms > 600000)
1899 kbrms = 600000;
1900 res = poll(pfds, max, kbrms);
1901 if (!res)
1902 rms -= kbrms;
1903 } while (!res && (rms > 0));
1904 } else {
1905 res = poll(pfds, max, rms);
1907 for (x=0; x<n; x++)
1908 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1909 if (res < 0) { /* Simulate a timeout if we were interrupted */
1910 if (errno != EINTR)
1911 *ms = -1;
1912 return NULL;
1914 if (whentohangup) { /* if we have a timeout, check who expired */
1915 time(&now);
1916 for (x=0; x<n; x++) {
1917 if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1918 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1919 if (winner == NULL)
1920 winner = c[x];
1924 if (res == 0) { /* no fd ready, reset timeout and done */
1925 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1926 return winner;
1929 * Then check if any channel or fd has a pending event.
1930 * Remember to check channels first and fds last, as they
1931 * must have priority on setting 'winner'
1933 for (x = 0; x < max; x++) {
1934 res = pfds[x].revents;
1935 if (res == 0)
1936 continue;
1937 if (fdmap[x].chan >= 0) { /* this is a channel */
1938 winner = c[fdmap[x].chan]; /* override previous winners */
1939 if (res & POLLPRI)
1940 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1941 else
1942 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1943 winner->fdno = fdmap[x].fdno;
1944 } else { /* this is an fd */
1945 if (outfd)
1946 *outfd = pfds[x].fd;
1947 if (exception)
1948 *exception = (res & POLLPRI) ? -1 : 0;
1949 winner = NULL;
1952 if (*ms > 0) {
1953 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1954 if (*ms < 0)
1955 *ms = 0;
1957 return winner;
1960 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1962 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1965 int ast_waitfor(struct ast_channel *c, int ms)
1967 int oldms = ms; /* -1 if no timeout */
1969 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1970 if ((ms < 0) && (oldms < 0))
1971 ms = 0;
1972 return ms;
1975 /* XXX never to be called with ms = -1 */
1976 int ast_waitfordigit(struct ast_channel *c, int ms)
1978 return ast_waitfordigit_full(c, ms, -1, -1);
1981 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1983 int res = -1;
1984 #ifdef HAVE_ZAPTEL
1985 if (c->timingfd > -1) {
1986 if (!func) {
1987 samples = 0;
1988 data = 0;
1990 if (option_debug)
1991 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1992 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1993 c->timingfunc = func;
1994 c->timingdata = data;
1996 #endif
1997 return res;
2000 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
2003 /* Stop if we're a zombie or need a soft hangup */
2004 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2005 return -1;
2006 /* Wait for a digit, no more than ms milliseconds total. */
2007 while (ms) {
2008 struct ast_channel *rchan;
2009 int outfd;
2011 errno = 0;
2012 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2013 if (!rchan && outfd < 0 && ms) {
2014 if (errno == 0 || errno == EINTR)
2015 continue;
2016 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2017 return -1;
2018 } else if (outfd > -1) {
2019 /* The FD we were watching has something waiting */
2020 return 1;
2021 } else if (rchan) {
2022 int res;
2023 struct ast_frame *f = ast_read(c);
2024 if (!f)
2025 return -1;
2027 switch(f->frametype) {
2028 case AST_FRAME_DTMF:
2029 res = f->subclass;
2030 ast_frfree(f);
2031 return res;
2032 case AST_FRAME_CONTROL:
2033 switch(f->subclass) {
2034 case AST_CONTROL_HANGUP:
2035 ast_frfree(f);
2036 return -1;
2037 case AST_CONTROL_RINGING:
2038 case AST_CONTROL_ANSWER:
2039 /* Unimportant */
2040 break;
2041 default:
2042 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2043 break;
2045 break;
2046 case AST_FRAME_VOICE:
2047 /* Write audio if appropriate */
2048 if (audiofd > -1)
2049 write(audiofd, f->data, f->datalen);
2050 default:
2051 /* Ignore */
2052 break;
2054 ast_frfree(f);
2057 return 0; /* Time is up */
2060 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2062 struct ast_frame *f = NULL; /* the return value */
2063 int blah;
2064 int prestate;
2066 /* this function is very long so make sure there is only one return
2067 * point at the end (there is only one exception to this).
2069 ast_channel_lock(chan);
2070 if (chan->masq) {
2071 if (ast_do_masquerade(chan))
2072 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2073 else
2074 f = &ast_null_frame;
2075 goto done;
2078 /* Stop if we're a zombie or need a soft hangup */
2079 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2080 if (chan->generator)
2081 ast_deactivate_generator(chan);
2082 goto done;
2084 prestate = chan->_state;
2086 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) &&
2087 !ast_strlen_zero(chan->dtmfq)) {
2088 /* We have DTMF that has been deferred. Return it now */
2089 chan->dtmff.subclass = chan->dtmfq[0];
2090 /* Drop first digit from the buffer */
2091 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2092 f = &chan->dtmff;
2093 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY))
2094 chan->dtmff.frametype = AST_FRAME_DTMF_END;
2095 else {
2096 chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2097 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2098 chan->emulate_dtmf_digit = f->subclass;
2099 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2100 chan->dtmf_begin_tv = ast_tvnow();
2102 goto done;
2105 /* Read and ignore anything on the alertpipe, but read only
2106 one sizeof(blah) per frame that we send from it */
2107 if (chan->alertpipe[0] > -1)
2108 read(chan->alertpipe[0], &blah, sizeof(blah));
2110 #ifdef HAVE_ZAPTEL
2111 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2112 int res;
2114 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2115 blah = -1;
2116 /* IF we can't get event, assume it's an expired as-per the old interface */
2117 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
2118 if (res)
2119 blah = ZT_EVENT_TIMER_EXPIRED;
2121 if (blah == ZT_EVENT_TIMER_PING) {
2122 if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2123 /* Acknowledge PONG unless we need it again */
2124 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
2125 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2128 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
2129 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
2130 if (chan->timingfunc) {
2131 /* save a copy of func/data before unlocking the channel */
2132 int (*func)(void *) = chan->timingfunc;
2133 void *data = chan->timingdata;
2134 ast_channel_unlock(chan);
2135 func(data);
2136 } else {
2137 blah = 0;
2138 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
2139 chan->timingdata = NULL;
2140 ast_channel_unlock(chan);
2142 /* cannot 'goto done' because the channel is already unlocked */
2143 return &ast_null_frame;
2144 } else
2145 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2146 } else
2147 #endif
2148 if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2149 /* if the AST_GENERATOR_FD is set, call the generator with args
2150 * set to -1 so it can do whatever it needs to.
2152 void *tmp = chan->generatordata;
2153 chan->generatordata = NULL; /* reset to let ast_write get through */
2154 chan->generator->generate(chan, tmp, -1, -1);
2155 chan->generatordata = tmp;
2156 f = &ast_null_frame;
2157 goto done;
2160 /* Check for pending read queue */
2161 if (!AST_LIST_EMPTY(&chan->readq)) {
2162 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2163 /* Interpret hangup and return NULL */
2164 /* XXX why not the same for frames from the channel ? */
2165 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2166 ast_frfree(f);
2167 f = NULL;
2169 } else {
2170 chan->blocker = pthread_self();
2171 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2172 if (chan->tech->exception)
2173 f = chan->tech->exception(chan);
2174 else {
2175 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2176 f = &ast_null_frame;
2178 /* Clear the exception flag */
2179 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2180 } else if (chan->tech->read)
2181 f = chan->tech->read(chan);
2182 else
2183 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2186 if (f) {
2187 /* if the channel driver returned more than one frame, stuff the excess
2188 into the readq for the next ast_read call (note that we can safely assume
2189 that the readq is empty, because otherwise we would not have called into
2190 the channel driver and f would be only a single frame)
2192 if (AST_LIST_NEXT(f, frame_list)) {
2193 AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2194 AST_LIST_NEXT(f, frame_list) = NULL;
2197 switch (f->frametype) {
2198 case AST_FRAME_CONTROL:
2199 if (f->subclass == AST_CONTROL_ANSWER) {
2200 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2201 if (option_debug)
2202 ast_log(LOG_DEBUG, "Ignoring answer on an inbound call!\n");
2203 ast_frfree(f);
2204 f = &ast_null_frame;
2205 } else if (prestate == AST_STATE_UP) {
2206 if (option_debug)
2207 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
2208 ast_frfree(f);
2209 f = &ast_null_frame;
2210 } else {
2211 /* Answer the CDR */
2212 ast_setstate(chan, AST_STATE_UP);
2213 ast_cdr_answer(chan->cdr);
2216 break;
2217 case AST_FRAME_DTMF_END:
2218 ast_log(LOG_DTMF, "DTMF end '%c' received on %s\n", f->subclass, chan->name);
2219 /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2220 * However, only let emulation be forced if the other end cares about BEGIN frames */
2221 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2222 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2223 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
2224 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2225 else
2226 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2227 ast_frfree(f);
2228 f = &ast_null_frame;
2229 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2230 f->frametype = AST_FRAME_DTMF_BEGIN;
2231 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2232 chan->emulate_dtmf_digit = f->subclass;
2233 chan->dtmf_begin_tv = ast_tvnow();
2234 if (f->len)
2235 chan->emulate_dtmf_duration = f->len;
2236 else
2237 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2238 } else {
2239 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2240 if (!f->len)
2241 f->len = ast_tvdiff_ms(chan->dtmf_begin_tv, ast_tvnow());
2243 break;
2244 case AST_FRAME_DTMF_BEGIN:
2245 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2246 if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2247 ast_frfree(f);
2248 f = &ast_null_frame;
2249 } else {
2250 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2251 chan->dtmf_begin_tv = ast_tvnow();
2253 break;
2254 case AST_FRAME_VOICE:
2255 /* The EMULATE_DTMF flag must be cleared here as opposed to when the samples
2256 * first get to zero, because we want to make sure we pass at least one
2257 * voice frame through before starting the next digit, to ensure a gap
2258 * between DTMF digits. */
2259 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2260 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2261 chan->emulate_dtmf_digit = 0;
2264 if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2265 ast_frfree(f);
2266 f = &ast_null_frame;
2267 } else if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2268 if ((f->samples / 8) >= chan->emulate_dtmf_duration) { /* XXX 8kHz */
2269 chan->emulate_dtmf_duration = 0;
2270 f->frametype = AST_FRAME_DTMF_END;
2271 f->subclass = chan->emulate_dtmf_digit;
2272 } else {
2273 chan->emulate_dtmf_duration -= f->samples / 8; /* XXX 8kHz */
2274 ast_frfree(f);
2275 f = &ast_null_frame;
2277 } else if (!(f->subclass & chan->nativeformats)) {
2278 /* This frame can't be from the current native formats -- drop it on the
2279 floor */
2280 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2281 chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2282 ast_frfree(f);
2283 f = &ast_null_frame;
2284 } else {
2285 if (chan->spies)
2286 queue_frame_to_spies(chan, f, SPY_READ);
2288 if (chan->monitor && chan->monitor->read_stream ) {
2289 /* XXX what does this do ? */
2290 #ifndef MONITOR_CONSTANT_DELAY
2291 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2292 if (jump >= 0) {
2293 jump = chan->outsmpl - chan->insmpl;
2294 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2295 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2296 chan->insmpl += jump + f->samples;
2297 } else
2298 chan->insmpl+= f->samples;
2299 #else
2300 int jump = chan->outsmpl - chan->insmpl;
2301 if (jump - MONITOR_DELAY >= 0) {
2302 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2303 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2304 chan->insmpl += jump;
2305 } else
2306 chan->insmpl += f->samples;
2307 #endif
2308 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2309 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2310 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2314 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2315 f = &ast_null_frame;
2317 /* Run generator sitting on the line if timing device not available
2318 * and synchronous generation of outgoing frames is necessary */
2319 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
2320 void *tmp = chan->generatordata;
2321 int res;
2323 if (chan->timingfunc) {
2324 if (option_debug > 1)
2325 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2326 ast_settimeout(chan, 0, NULL, NULL);
2329 chan->generatordata = NULL; /* reset, to let writes go through */
2330 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2331 chan->generatordata = tmp;
2332 if (res) {
2333 if (option_debug > 1)
2334 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2335 ast_deactivate_generator(chan);
2338 } else if (f->frametype == AST_FRAME_CNG) {
2339 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2340 if (option_debug > 1)
2341 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2342 ast_settimeout(chan, 160, generator_force, chan);
2346 default:
2347 /* Just pass it on! */
2348 break;
2350 } else {
2351 /* Make sure we always return NULL in the future */
2352 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2353 if (chan->generator)
2354 ast_deactivate_generator(chan);
2355 /* End the CDR if appropriate */
2356 if (chan->cdr)
2357 ast_cdr_end(chan->cdr);
2360 /* High bit prints debugging */
2361 if (chan->fin & DEBUGCHAN_FLAG)
2362 ast_frame_dump(chan->name, f, "<<");
2363 chan->fin = FRAMECOUNT_INC(chan->fin);
2365 done:
2366 ast_channel_unlock(chan);
2367 return f;
2370 int ast_internal_timing_enabled(struct ast_channel *chan)
2372 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2373 if (option_debug > 4)
2374 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);
2375 return ret;
2378 struct ast_frame *ast_read(struct ast_channel *chan)
2380 return __ast_read(chan, 0);
2383 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2385 return __ast_read(chan, 1);
2388 int ast_indicate(struct ast_channel *chan, int condition)
2390 return ast_indicate_data(chan, condition, NULL, 0);
2393 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2395 int res = -1;
2397 ast_channel_lock(chan);
2398 /* Stop if we're a zombie or need a soft hangup */
2399 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2400 ast_channel_unlock(chan);
2401 return -1;
2403 if (chan->tech->indicate)
2404 res = chan->tech->indicate(chan, condition, data, datalen);
2405 ast_channel_unlock(chan);
2406 if (!chan->tech->indicate || res) {
2408 * Device does not support (that) indication, lets fake
2409 * it by doing our own tone generation. (PM2002)
2411 if (condition < 0)
2412 ast_playtones_stop(chan);
2413 else {
2414 const struct tone_zone_sound *ts = NULL;
2415 switch (condition) {
2416 case AST_CONTROL_RINGING:
2417 ts = ast_get_indication_tone(chan->zone, "ring");
2418 break;
2419 case AST_CONTROL_BUSY:
2420 ts = ast_get_indication_tone(chan->zone, "busy");
2421 break;
2422 case AST_CONTROL_CONGESTION:
2423 ts = ast_get_indication_tone(chan->zone, "congestion");
2424 break;
2426 if (ts && ts->data[0]) {
2427 if (option_debug)
2428 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2429 ast_playtones_start(chan,0,ts->data, 1);
2430 res = 0;
2431 } else if (condition == AST_CONTROL_PROGRESS) {
2432 /* ast_playtones_stop(chan); */
2433 } else if (condition == AST_CONTROL_PROCEEDING) {
2434 /* Do nothing, really */
2435 } else if (condition == AST_CONTROL_HOLD) {
2436 /* Do nothing.... */
2437 } else if (condition == AST_CONTROL_UNHOLD) {
2438 /* Do nothing.... */
2439 } else if (condition == AST_CONTROL_VIDUPDATE) {
2440 /* Do nothing.... */
2441 } else {
2442 /* not handled */
2443 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2444 res = -1;
2448 return res;
2451 int ast_recvchar(struct ast_channel *chan, int timeout)
2453 int c;
2454 char *buf = ast_recvtext(chan, timeout);
2455 if (buf == NULL)
2456 return -1; /* error or timeout */
2457 c = *(unsigned char *)buf;
2458 free(buf);
2459 return c;
2462 char *ast_recvtext(struct ast_channel *chan, int timeout)
2464 int res, done = 0;
2465 char *buf = NULL;
2467 while (!done) {
2468 struct ast_frame *f;
2469 if (ast_check_hangup(chan))
2470 break;
2471 res = ast_waitfor(chan, timeout);
2472 if (res <= 0) /* timeout or error */
2473 break;
2474 timeout = res; /* update timeout */
2475 f = ast_read(chan);
2476 if (f == NULL)
2477 break; /* no frame */
2478 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2479 done = 1; /* force a break */
2480 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2481 buf = ast_strndup((char *) f->data, f->datalen); /* dup and break */
2482 done = 1;
2484 ast_frfree(f);
2486 return buf;
2489 int ast_sendtext(struct ast_channel *chan, const char *text)
2491 int res = 0;
2492 /* Stop if we're a zombie or need a soft hangup */
2493 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2494 return -1;
2495 CHECK_BLOCKING(chan);
2496 if (chan->tech->send_text)
2497 res = chan->tech->send_text(chan, text);
2498 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2499 return res;
2502 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2504 int res = -1;
2506 if (chan->tech->send_digit_begin)
2507 res = chan->tech->send_digit_begin(chan, digit);
2509 if (res) {
2511 * Device does not support DTMF tones, lets fake
2512 * it by doing our own generation. (PM2002)
2514 static const char* dtmf_tones[] = {
2515 "!941+1336/100,!0/100", /* 0 */
2516 "!697+1209/100,!0/100", /* 1 */
2517 "!697+1336/100,!0/100", /* 2 */
2518 "!697+1477/100,!0/100", /* 3 */
2519 "!770+1209/100,!0/100", /* 4 */
2520 "!770+1336/100,!0/100", /* 5 */
2521 "!770+1477/100,!0/100", /* 6 */
2522 "!852+1209/100,!0/100", /* 7 */
2523 "!852+1336/100,!0/100", /* 8 */
2524 "!852+1477/100,!0/100", /* 9 */
2525 "!697+1633/100,!0/100", /* A */
2526 "!770+1633/100,!0/100", /* B */
2527 "!852+1633/100,!0/100", /* C */
2528 "!941+1633/100,!0/100", /* D */
2529 "!941+1209/100,!0/100", /* * */
2530 "!941+1477/100,!0/100" }; /* # */
2531 if (digit >= '0' && digit <='9')
2532 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2533 else if (digit >= 'A' && digit <= 'D')
2534 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2535 else if (digit == '*')
2536 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2537 else if (digit == '#')
2538 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2539 else {
2540 /* not handled */
2541 if (option_debug)
2542 ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2546 return 0;
2549 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2551 int res = -1;
2553 if (chan->tech->send_digit_end)
2554 res = chan->tech->send_digit_end(chan, digit, duration);
2556 if (res && chan->generator)
2557 ast_playtones_stop(chan);
2559 return 0;
2562 int ast_senddigit(struct ast_channel *chan, char digit)
2564 if (!ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2565 ast_senddigit_begin(chan, digit);
2566 ast_safe_sleep(chan, 100); /* XXX 100ms ... probably should be configurable */
2569 return ast_senddigit_end(chan, digit, 100);
2572 int ast_prod(struct ast_channel *chan)
2574 struct ast_frame a = { AST_FRAME_VOICE };
2575 char nothing[128];
2577 /* Send an empty audio frame to get things moving */
2578 if (chan->_state != AST_STATE_UP) {
2579 if (option_debug)
2580 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
2581 a.subclass = chan->rawwriteformat;
2582 a.data = nothing + AST_FRIENDLY_OFFSET;
2583 a.src = "ast_prod";
2584 if (ast_write(chan, &a))
2585 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2587 return 0;
2590 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2592 int res;
2593 if (!chan->tech->write_video)
2594 return 0;
2595 res = ast_write(chan, fr);
2596 if (!res)
2597 res = 1;
2598 return res;
2601 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2603 int res = -1;
2604 struct ast_frame *f = NULL;
2606 /* Stop if we're a zombie or need a soft hangup */
2607 ast_channel_lock(chan);
2608 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2609 goto done;
2611 /* Handle any pending masquerades */
2612 if (chan->masq && ast_do_masquerade(chan)) {
2613 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2614 goto done;
2616 if (chan->masqr) {
2617 res = 0; /* XXX explain, why 0 ? */
2618 goto done;
2620 if (chan->generatordata) {
2621 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2622 ast_deactivate_generator(chan);
2623 else {
2624 res = 0; /* XXX explain, why 0 ? */
2625 goto done;
2628 /* High bit prints debugging */
2629 if (chan->fout & DEBUGCHAN_FLAG)
2630 ast_frame_dump(chan->name, fr, ">>");
2631 CHECK_BLOCKING(chan);
2632 switch(fr->frametype) {
2633 case AST_FRAME_CONTROL:
2634 res = (chan->tech->indicate == NULL) ? 0 :
2635 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2636 break;
2637 case AST_FRAME_DTMF_BEGIN:
2638 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2639 ast_channel_unlock(chan);
2640 res = ast_senddigit_begin(chan, fr->subclass);
2641 ast_channel_lock(chan);
2642 CHECK_BLOCKING(chan);
2643 break;
2644 case AST_FRAME_DTMF_END:
2645 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2646 ast_channel_unlock(chan);
2647 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2648 ast_channel_lock(chan);
2649 CHECK_BLOCKING(chan);
2650 break;
2651 case AST_FRAME_TEXT:
2652 res = (chan->tech->send_text == NULL) ? 0 :
2653 chan->tech->send_text(chan, (char *) fr->data);
2654 break;
2655 case AST_FRAME_HTML:
2656 res = (chan->tech->send_html == NULL) ? 0 :
2657 chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2658 break;
2659 case AST_FRAME_VIDEO:
2660 /* XXX Handle translation of video codecs one day XXX */
2661 res = (chan->tech->write_video == NULL) ? 0 :
2662 chan->tech->write_video(chan, fr);
2663 break;
2664 case AST_FRAME_MODEM:
2665 res = (chan->tech->write == NULL) ? 0 :
2666 chan->tech->write(chan, fr);
2667 break;
2668 case AST_FRAME_VOICE:
2669 if (chan->tech->write == NULL)
2670 break; /*! \todo XXX should return 0 maybe ? */
2672 /* If someone is whispering on this channel then we must ensure that we are always getting signed linear frames */
2673 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2674 if (fr->subclass == AST_FORMAT_SLINEAR)
2675 f = fr;
2676 else {
2677 ast_mutex_lock(&chan->whisper->lock);
2678 if (chan->writeformat != AST_FORMAT_SLINEAR) {
2679 /* Rebuild the translation path and set our write format back to signed linear */
2680 chan->whisper->original_format = chan->writeformat;
2681 ast_set_write_format(chan, AST_FORMAT_SLINEAR);
2682 if (chan->whisper->path)
2683 ast_translator_free_path(chan->whisper->path);
2684 chan->whisper->path = ast_translator_build_path(AST_FORMAT_SLINEAR, chan->whisper->original_format);
2686 /* Translate frame using the above translation path */
2687 f = (chan->whisper->path) ? ast_translate(chan->whisper->path, fr, 0) : fr;
2688 ast_mutex_unlock(&chan->whisper->lock);
2690 } else {
2691 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2692 if (fr->subclass == chan->rawwriteformat)
2693 f = fr;
2694 else
2695 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2698 /* If we have no frame of audio, then we have to bail out */
2699 if (f == NULL) {
2700 res = 0;
2701 break;
2704 /* If spies are on the channel then queue the frame out to them */
2705 if (chan->spies)
2706 queue_frame_to_spies(chan, f, SPY_WRITE);
2708 /* If Monitor is running on this channel, then we have to write frames out there too */
2709 if (chan->monitor && chan->monitor->write_stream) {
2710 /* XXX must explain this code */
2711 #ifndef MONITOR_CONSTANT_DELAY
2712 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2713 if (jump >= 0) {
2714 jump = chan->insmpl - chan->outsmpl;
2715 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
2716 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2717 chan->outsmpl += jump + f->samples;
2718 } else
2719 chan->outsmpl += f->samples;
2720 #else
2721 int jump = chan->insmpl - chan->outsmpl;
2722 if (jump - MONITOR_DELAY >= 0) {
2723 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2724 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2725 chan->outsmpl += jump;
2726 } else
2727 chan->outsmpl += f->samples;
2728 #endif
2729 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2730 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2731 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2735 /* Finally the good part! Write this out to the channel */
2736 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2737 /* frame is assumed to be in SLINEAR, since that is
2738 required for whisper mode */
2739 ast_frame_adjust_volume(f, -2);
2740 if (ast_slinfactory_available(&chan->whisper->sf) >= f->samples) {
2741 short buf[f->samples];
2742 struct ast_frame whisper = {
2743 .frametype = AST_FRAME_VOICE,
2744 .subclass = AST_FORMAT_SLINEAR,
2745 .data = buf,
2746 .datalen = sizeof(buf),
2747 .samples = f->samples,
2750 ast_mutex_lock(&chan->whisper->lock);
2751 if (ast_slinfactory_read(&chan->whisper->sf, buf, f->samples))
2752 ast_frame_slinear_sum(f, &whisper);
2753 ast_mutex_unlock(&chan->whisper->lock);
2755 /* and now put it through the regular translator */
2756 f = (chan->writetrans) ? ast_translate(chan->writetrans, f, 0) : f;
2758 if (f)
2759 res = chan->tech->write(chan, f);
2760 else
2761 res = 0;
2762 break;
2763 case AST_FRAME_NULL:
2764 case AST_FRAME_IAX:
2765 /* Ignore these */
2766 res = 0;
2767 break;
2768 default:
2769 /* At this point, fr is the incoming frame and f is NULL. Channels do
2770 * not expect to get NULL as a frame pointer and will segfault. Hence,
2771 * we output the original frame passed in. */
2772 res = chan->tech->write(chan, fr);
2773 break;
2776 if (f && f != fr)
2777 ast_frfree(f);
2778 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2779 /* Consider a write failure to force a soft hangup */
2780 if (res < 0)
2781 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2782 else {
2783 chan->fout = FRAMECOUNT_INC(chan->fout);
2785 done:
2786 ast_channel_unlock(chan);
2787 return res;
2790 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2791 struct ast_trans_pvt **trans, const int direction)
2793 int native;
2794 int res;
2796 /* Make sure we only consider audio */
2797 fmt &= AST_FORMAT_AUDIO_MASK;
2799 native = chan->nativeformats;
2800 /* Find a translation path from the native format to one of the desired formats */
2801 if (!direction)
2802 /* reading */
2803 res = ast_translator_best_choice(&fmt, &native);
2804 else
2805 /* writing */
2806 res = ast_translator_best_choice(&native, &fmt);
2808 if (res < 0) {
2809 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2810 ast_getformatname(native), ast_getformatname(fmt));
2811 return -1;
2814 /* Now we have a good choice for both. */
2815 ast_channel_lock(chan);
2817 if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2818 /* the channel is already in these formats, so nothing to do */
2819 ast_channel_unlock(chan);
2820 return 0;
2823 *rawformat = native;
2824 /* User perspective is fmt */
2825 *format = fmt;
2826 /* Free any read translation we have right now */
2827 if (*trans)
2828 ast_translator_free_path(*trans);
2829 /* Build a translation path from the raw format to the desired format */
2830 if (!direction)
2831 /* reading */
2832 *trans = ast_translator_build_path(*format, *rawformat);
2833 else
2834 /* writing */
2835 *trans = ast_translator_build_path(*rawformat, *format);
2836 ast_channel_unlock(chan);
2837 if (option_debug)
2838 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2839 direction ? "write" : "read", ast_getformatname(fmt));
2840 return 0;
2843 int ast_set_read_format(struct ast_channel *chan, int fmt)
2845 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2846 &chan->readtrans, 0);
2849 int ast_set_write_format(struct ast_channel *chan, int fmt)
2851 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2852 &chan->writetrans, 1);
2855 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)
2857 int dummy_outstate;
2858 int cause = 0;
2859 struct ast_channel *chan;
2860 int res = 0;
2862 if (outstate)
2863 *outstate = 0;
2864 else
2865 outstate = &dummy_outstate; /* make outstate always a valid pointer */
2867 chan = ast_request(type, format, data, &cause);
2868 if (!chan) {
2869 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2870 /* compute error and return */
2871 if (cause == AST_CAUSE_BUSY)
2872 *outstate = AST_CONTROL_BUSY;
2873 else if (cause == AST_CAUSE_CONGESTION)
2874 *outstate = AST_CONTROL_CONGESTION;
2875 return NULL;
2878 if (oh) {
2879 if (oh->vars)
2880 ast_set_variables(chan, oh->vars);
2881 /* XXX why is this necessary, for the parent_channel perhaps ? */
2882 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2883 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2884 if (oh->parent_channel)
2885 ast_channel_inherit_variables(oh->parent_channel, chan);
2886 if (oh->account)
2887 ast_cdr_setaccount(chan, oh->account);
2889 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2891 if (ast_call(chan, data, 0)) { /* ast_call failed... */
2892 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2893 } else {
2894 res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
2895 while (timeout && chan->_state != AST_STATE_UP) {
2896 struct ast_frame *f;
2897 res = ast_waitfor(chan, timeout);
2898 if (res <= 0) /* error, timeout, or done */
2899 break;
2900 if (timeout > -1)
2901 timeout = res;
2902 f = ast_read(chan);
2903 if (!f) {
2904 *outstate = AST_CONTROL_HANGUP;
2905 res = 0;
2906 break;
2908 if (f->frametype == AST_FRAME_CONTROL) {
2909 switch (f->subclass) {
2910 case AST_CONTROL_RINGING: /* record but keep going */
2911 *outstate = f->subclass;
2912 break;
2914 case AST_CONTROL_BUSY:
2915 case AST_CONTROL_CONGESTION:
2916 case AST_CONTROL_ANSWER:
2917 *outstate = f->subclass;
2918 timeout = 0; /* trick to force exit from the while() */
2919 break;
2921 /* Ignore these */
2922 case AST_CONTROL_PROGRESS:
2923 case AST_CONTROL_PROCEEDING:
2924 case AST_CONTROL_HOLD:
2925 case AST_CONTROL_UNHOLD:
2926 case AST_CONTROL_VIDUPDATE:
2927 case -1: /* Ignore -- just stopping indications */
2928 break;
2930 default:
2931 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2934 ast_frfree(f);
2938 /* Final fixups */
2939 if (oh) {
2940 if (!ast_strlen_zero(oh->context))
2941 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2942 if (!ast_strlen_zero(oh->exten))
2943 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2944 if (oh->priority)
2945 chan->priority = oh->priority;
2947 if (chan->_state == AST_STATE_UP)
2948 *outstate = AST_CONTROL_ANSWER;
2950 if (res <= 0) {
2951 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
2952 ast_cdr_init(chan->cdr, chan);
2953 if (chan->cdr) {
2954 char tmp[256];
2955 snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
2956 ast_cdr_setapp(chan->cdr,"Dial",tmp);
2957 ast_cdr_update(chan);
2958 ast_cdr_start(chan->cdr);
2959 ast_cdr_end(chan->cdr);
2960 /* If the cause wasn't handled properly */
2961 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2962 ast_cdr_failed(chan->cdr);
2964 ast_hangup(chan);
2965 chan = NULL;
2967 return chan;
2970 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2972 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2975 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2977 struct chanlist *chan;
2978 struct ast_channel *c;
2979 int capabilities;
2980 int fmt;
2981 int res;
2982 int foo;
2983 int videoformat = format & AST_FORMAT_VIDEO_MASK;
2985 if (!cause)
2986 cause = &foo;
2987 *cause = AST_CAUSE_NOTDEFINED;
2989 if (AST_LIST_LOCK(&channels)) {
2990 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2991 return NULL;
2994 AST_LIST_TRAVERSE(&backends, chan, list) {
2995 if (strcasecmp(type, chan->tech->type))
2996 continue;
2998 capabilities = chan->tech->capabilities;
2999 fmt = format & AST_FORMAT_AUDIO_MASK;
3000 res = ast_translator_best_choice(&fmt, &capabilities);
3001 if (res < 0) {
3002 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
3003 AST_LIST_UNLOCK(&channels);
3004 return NULL;
3006 AST_LIST_UNLOCK(&channels);
3007 if (!chan->tech->requester)
3008 return NULL;
3010 if (!(c = chan->tech->requester(type, capabilities | videoformat, data, cause)))
3011 return NULL;
3013 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
3014 return c;
3017 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
3018 *cause = AST_CAUSE_NOSUCHDRIVER;
3019 AST_LIST_UNLOCK(&channels);
3021 return NULL;
3024 int ast_call(struct ast_channel *chan, char *addr, int timeout)
3026 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
3027 If the remote end does not answer within the timeout, then do NOT hang up, but
3028 return anyway. */
3029 int res = -1;
3030 /* Stop if we're a zombie or need a soft hangup */
3031 ast_channel_lock(chan);
3032 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3033 if (chan->tech->call)
3034 res = chan->tech->call(chan, addr, timeout);
3035 ast_set_flag(chan, AST_FLAG_OUTGOING);
3037 ast_channel_unlock(chan);
3038 return res;
3042 \brief Transfer a call to dest, if the channel supports transfer
3044 Called by:
3045 \arg app_transfer
3046 \arg the manager interface
3048 int ast_transfer(struct ast_channel *chan, char *dest)
3050 int res = -1;
3052 /* Stop if we're a zombie or need a soft hangup */
3053 ast_channel_lock(chan);
3054 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3055 if (chan->tech->transfer) {
3056 res = chan->tech->transfer(chan, dest);
3057 if (!res)
3058 res = 1;
3059 } else
3060 res = 0;
3062 ast_channel_unlock(chan);
3063 return res;
3066 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
3068 return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
3071 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
3073 int pos = 0; /* index in the buffer where we accumulate digits */
3074 int to = ftimeout;
3076 /* Stop if we're a zombie or need a soft hangup */
3077 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3078 return -1;
3079 if (!len)
3080 return -1;
3081 for (;;) {
3082 int d;
3083 if (c->stream) {
3084 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
3085 ast_stopstream(c);
3086 usleep(1000);
3087 if (!d)
3088 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3089 } else {
3090 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3092 if (d < 0)
3093 return -1;
3094 if (d == 0) {
3095 s[pos]='\0';
3096 return 1;
3098 if (d == 1) {
3099 s[pos]='\0';
3100 return 2;
3102 if (!strchr(enders, d))
3103 s[pos++] = d;
3104 if (strchr(enders, d) || (pos >= len)) {
3105 s[pos]='\0';
3106 return 0;
3108 to = timeout;
3110 /* Never reached */
3111 return 0;
3114 int ast_channel_supports_html(struct ast_channel *chan)
3116 return (chan->tech->send_html) ? 1 : 0;
3119 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3121 if (chan->tech->send_html)
3122 return chan->tech->send_html(chan, subclass, data, datalen);
3123 return -1;
3126 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
3128 return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
3131 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
3133 int src;
3134 int dst;
3136 /* Set up translation from the chan to the peer */
3137 src = chan->nativeformats;
3138 dst = peer->nativeformats;
3139 if (ast_translator_best_choice(&dst, &src) < 0) {
3140 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
3141 return -1;
3144 /* if the best path is not 'pass through', then
3145 transcoding is needed; if desired, force transcode path
3146 to use SLINEAR between channels, but only if there is
3147 no direct conversion available */
3148 if ((src != dst) && ast_opt_transcode_via_slin &&
3149 (ast_translate_path_steps(dst, src) != 1))
3150 dst = AST_FORMAT_SLINEAR;
3151 if (ast_set_read_format(chan, dst) < 0) {
3152 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
3153 return -1;
3155 if (ast_set_write_format(peer, dst) < 0) {
3156 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
3157 return -1;
3160 /* Set up translation from the peer to the chan */
3161 src = peer->nativeformats;
3162 dst = chan->nativeformats;
3163 if (ast_translator_best_choice(&dst, &src) < 0) {
3164 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
3165 return -1;
3168 /* if the best path is not 'pass through', then
3169 transcoding is needed; if desired, force transcode path
3170 to use SLINEAR between channels, but only if there is
3171 no direct conversion available */
3172 if ((src != dst) && ast_opt_transcode_via_slin &&
3173 (ast_translate_path_steps(dst, src) != 1))
3174 dst = AST_FORMAT_SLINEAR;
3175 if (ast_set_read_format(peer, dst) < 0) {
3176 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
3177 return -1;
3179 if (ast_set_write_format(chan, dst) < 0) {
3180 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
3181 return -1;
3183 return 0;
3186 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
3188 int res = -1;
3189 struct ast_channel *final_orig = original, *final_clone = clone;
3191 ast_channel_lock(original);
3192 while (ast_channel_trylock(clone)) {
3193 ast_channel_unlock(original);
3194 usleep(1);
3195 ast_channel_lock(original);
3198 /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
3199 and if so, we don't really want to masquerade it, but its proxy */
3200 if (original->_bridge && (original->_bridge != ast_bridged_channel(original)))
3201 final_orig = original->_bridge;
3203 if (clone->_bridge && (clone->_bridge != ast_bridged_channel(clone)))
3204 final_clone = clone->_bridge;
3206 if ((final_orig != original) || (final_clone != clone)) {
3207 ast_channel_lock(final_orig);
3208 while (ast_channel_trylock(final_clone)) {
3209 ast_channel_unlock(final_orig);
3210 usleep(1);
3211 ast_channel_lock(final_orig);
3213 ast_channel_unlock(clone);
3214 ast_channel_unlock(original);
3215 original = final_orig;
3216 clone = final_clone;
3219 if (original == clone) {
3220 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
3221 ast_channel_unlock(clone);
3222 ast_channel_unlock(original);
3223 return -1;
3226 if (option_debug)
3227 ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
3228 clone->name, original->name);
3229 if (original->masq) {
3230 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3231 original->masq->name, original->name);
3232 } else if (clone->masqr) {
3233 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3234 clone->name, clone->masqr->name);
3235 } else {
3236 original->masq = clone;
3237 clone->masqr = original;
3238 ast_queue_frame(original, &ast_null_frame);
3239 ast_queue_frame(clone, &ast_null_frame);
3240 if (option_debug)
3241 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
3242 res = 0;
3245 ast_channel_unlock(clone);
3246 ast_channel_unlock(original);
3248 return res;
3251 void ast_change_name(struct ast_channel *chan, char *newname)
3253 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
3254 ast_string_field_set(chan, name, newname);
3257 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
3259 struct ast_var_t *current, *newvar;
3260 const char *varname;
3262 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
3263 int vartype = 0;
3265 varname = ast_var_full_name(current);
3266 if (!varname)
3267 continue;
3269 if (varname[0] == '_') {
3270 vartype = 1;
3271 if (varname[1] == '_')
3272 vartype = 2;
3275 switch (vartype) {
3276 case 1:
3277 newvar = ast_var_assign(&varname[1], ast_var_value(current));
3278 if (newvar) {
3279 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3280 if (option_debug)
3281 ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
3283 break;
3284 case 2:
3285 newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
3286 if (newvar) {
3287 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3288 if (option_debug)
3289 ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
3291 break;
3292 default:
3293 if (option_debug)
3294 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
3295 break;
3301 \brief Clone channel variables from 'clone' channel into 'original' channel
3303 All variables except those related to app_groupcount are cloned.
3304 Variables are actually _removed_ from 'clone' channel, presumably
3305 because it will subsequently be destroyed.
3307 \note Assumes locks will be in place on both channels when called.
3309 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
3311 struct ast_var_t *varptr;
3313 /* we need to remove all app_groupcount related variables from the original
3314 channel before merging in the clone's variables; any groups assigned to the
3315 original channel should be released, only those assigned to the clone
3316 should remain
3319 AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
3320 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
3321 AST_LIST_REMOVE_CURRENT(&original->varshead, entries);
3322 ast_var_delete(varptr);
3325 AST_LIST_TRAVERSE_SAFE_END;
3327 /* Append variables from clone channel into original channel */
3328 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
3329 if (AST_LIST_FIRST(&clone->varshead))
3330 AST_LIST_APPEND_LIST(&original->varshead, &clone->varshead, entries);
3334 \brief Masquerade a channel
3336 \note Assumes channel will be locked when called
3338 int ast_do_masquerade(struct ast_channel *original)
3340 int x,i;
3341 int res=0;
3342 int origstate;
3343 struct ast_frame *cur;
3344 const struct ast_channel_tech *t;
3345 void *t_pvt;
3346 struct ast_callerid tmpcid;
3347 struct ast_channel *clone = original->masq;
3348 struct ast_channel_spy_list *spy_list = NULL;
3349 struct ast_channel_spy *spy = NULL;
3350 int rformat = original->readformat;
3351 int wformat = original->writeformat;
3352 char newn[100];
3353 char orig[100];
3354 char masqn[100];
3355 char zombn[100];
3357 if (option_debug > 3)
3358 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3359 clone->name, clone->_state, original->name, original->_state);
3361 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
3362 the clone channel into the original channel. Start by killing off the original
3363 channel's backend. I'm not sure we're going to keep this function, because
3364 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3366 /* We need the clone's lock, too */
3367 ast_channel_lock(clone);
3369 if (option_debug > 1)
3370 ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
3372 /* Having remembered the original read/write formats, we turn off any translation on either
3373 one */
3374 free_translation(clone);
3375 free_translation(original);
3378 /* Unlink the masquerade */
3379 original->masq = NULL;
3380 clone->masqr = NULL;
3382 /* Save the original name */
3383 ast_copy_string(orig, original->name, sizeof(orig));
3384 /* Save the new name */
3385 ast_copy_string(newn, clone->name, sizeof(newn));
3386 /* Create the masq name */
3387 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
3389 /* Copy the name from the clone channel */
3390 ast_string_field_set(original, name, newn);
3392 /* Mangle the name of the clone channel */
3393 ast_string_field_set(clone, name, masqn);
3395 /* Notify any managers of the change, first the masq then the other */
3396 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
3397 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
3399 /* Swap the technologies */
3400 t = original->tech;
3401 original->tech = clone->tech;
3402 clone->tech = t;
3404 t_pvt = original->tech_pvt;
3405 original->tech_pvt = clone->tech_pvt;
3406 clone->tech_pvt = t_pvt;
3408 /* Swap the readq's */
3409 cur = AST_LIST_FIRST(&original->readq);
3410 AST_LIST_HEAD_SET_NOLOCK(&original->readq, AST_LIST_FIRST(&clone->readq));
3411 AST_LIST_HEAD_SET_NOLOCK(&clone->readq, cur);
3413 /* Swap the alertpipes */
3414 for (i = 0; i < 2; i++) {
3415 x = original->alertpipe[i];
3416 original->alertpipe[i] = clone->alertpipe[i];
3417 clone->alertpipe[i] = x;
3420 /* Swap the raw formats */
3421 x = original->rawreadformat;
3422 original->rawreadformat = clone->rawreadformat;
3423 clone->rawreadformat = x;
3424 x = original->rawwriteformat;
3425 original->rawwriteformat = clone->rawwriteformat;
3426 clone->rawwriteformat = x;
3428 /* Swap the spies */
3429 spy_list = original->spies;
3430 original->spies = clone->spies;
3431 clone->spies = spy_list;
3433 /* Update channel on respective spy lists if present */
3434 if (original->spies) {
3435 AST_LIST_TRAVERSE(&original->spies->list, spy, list) {
3436 ast_mutex_lock(&spy->lock);
3437 spy->chan = original;
3438 ast_mutex_unlock(&spy->lock);
3441 if (clone->spies) {
3442 AST_LIST_TRAVERSE(&clone->spies->list, spy, list) {
3443 ast_mutex_lock(&spy->lock);
3444 spy->chan = clone;
3445 ast_mutex_unlock(&spy->lock);
3449 /* Save any pending frames on both sides. Start by counting
3450 * how many we're going to need... */
3451 x = 0;
3452 if (original->alertpipe[1] > -1) {
3453 AST_LIST_TRAVERSE(&clone->readq, cur, frame_list)
3454 x++;
3457 /* If we had any, prepend them to the ones already in the queue, and
3458 * load up the alertpipe */
3459 if (AST_LIST_FIRST(&clone->readq)) {
3460 AST_LIST_INSERT_TAIL(&clone->readq, AST_LIST_FIRST(&original->readq), frame_list);
3461 AST_LIST_HEAD_SET_NOLOCK(&original->readq, AST_LIST_FIRST(&clone->readq));
3462 AST_LIST_HEAD_SET_NOLOCK(&clone->readq, NULL);
3463 for (i = 0; i < x; i++)
3464 write(original->alertpipe[1], &x, sizeof(x));
3467 clone->_softhangup = AST_SOFTHANGUP_DEV;
3470 /* And of course, so does our current state. Note we need not
3471 call ast_setstate since the event manager doesn't really consider
3472 these separate. We do this early so that the clone has the proper
3473 state of the original channel. */
3474 origstate = original->_state;
3475 original->_state = clone->_state;
3476 clone->_state = origstate;
3478 if (clone->tech->fixup){
3479 res = clone->tech->fixup(original, clone);
3480 if (res)
3481 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
3484 /* Start by disconnecting the original's physical side */
3485 if (clone->tech->hangup)
3486 res = clone->tech->hangup(clone);
3487 if (res) {
3488 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
3489 ast_channel_unlock(clone);
3490 return -1;
3493 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
3494 /* Mangle the name of the clone channel */
3495 ast_string_field_set(clone, name, zombn);
3496 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
3498 /* Update the type. */
3499 t_pvt = original->monitor;
3500 original->monitor = clone->monitor;
3501 clone->monitor = t_pvt;
3503 /* Keep the same language. */
3504 ast_string_field_set(original, language, clone->language);
3505 /* Copy the FD's other than the generator fd */
3506 for (x = 0; x < AST_MAX_FDS; x++) {
3507 if (x != AST_GENERATOR_FD)
3508 original->fds[x] = clone->fds[x];
3511 /* move any whisperer over */
3512 ast_channel_whisper_stop(original);
3513 if (ast_test_flag(clone, AST_FLAG_WHISPER)) {
3514 original->whisper = clone->whisper;
3515 ast_set_flag(original, AST_FLAG_WHISPER);
3516 clone->whisper = NULL;
3517 ast_clear_flag(clone, AST_FLAG_WHISPER);
3520 /* Move data stores over */
3521 if (AST_LIST_FIRST(&clone->datastores))
3522 AST_LIST_INSERT_TAIL(&original->datastores, AST_LIST_FIRST(&clone->datastores), entry);
3523 AST_LIST_HEAD_INIT_NOLOCK(&clone->datastores);
3525 clone_variables(original, clone);
3526 AST_LIST_HEAD_INIT_NOLOCK(&clone->varshead);
3527 /* Presense of ADSI capable CPE follows clone */
3528 original->adsicpe = clone->adsicpe;
3529 /* Bridge remains the same */
3530 /* CDR fields remain the same */
3531 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3532 /* Application and data remain the same */
3533 /* Clone exception becomes real one, as with fdno */
3534 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
3535 original->fdno = clone->fdno;
3536 /* Schedule context remains the same */
3537 /* Stream stuff stays the same */
3538 /* Keep the original state. The fixup code will need to work with it most likely */
3540 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3541 out. */
3542 tmpcid = original->cid;
3543 original->cid = clone->cid;
3544 clone->cid = tmpcid;
3546 /* Restore original timing file descriptor */
3547 original->fds[AST_TIMING_FD] = original->timingfd;
3549 /* Our native formats are different now */
3550 original->nativeformats = clone->nativeformats;
3552 /* Context, extension, priority, app data, jump table, remain the same */
3553 /* pvt switches. pbx stays the same, as does next */
3555 /* Set the write format */
3556 ast_set_write_format(original, wformat);
3558 /* Set the read format */
3559 ast_set_read_format(original, rformat);
3561 /* Copy the music class */
3562 ast_string_field_set(original, musicclass, clone->musicclass);
3564 if (option_debug)
3565 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
3567 /* Okay. Last thing is to let the channel driver know about all this mess, so he
3568 can fix up everything as best as possible */
3569 if (original->tech->fixup) {
3570 res = original->tech->fixup(clone, original);
3571 if (res) {
3572 ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
3573 original->tech->type, original->name);
3574 ast_channel_unlock(clone);
3575 return -1;
3577 } else
3578 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
3579 original->tech->type, original->name);
3581 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
3582 a zombie so nothing tries to touch it. If it's already been marked as a
3583 zombie, then free it now (since it already is considered invalid). */
3584 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
3585 if (option_debug)
3586 ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
3587 ast_channel_unlock(clone);
3588 manager_event(EVENT_FLAG_CALL, "Hangup",
3589 "Channel: %s\r\n"
3590 "Uniqueid: %s\r\n"
3591 "Cause: %d\r\n"
3592 "Cause-txt: %s\r\n",
3593 clone->name,
3594 clone->uniqueid,
3595 clone->hangupcause,
3596 ast_cause2str(clone->hangupcause)
3598 ast_channel_free(clone);
3599 } else {
3600 if (option_debug)
3601 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
3602 ast_set_flag(clone, AST_FLAG_ZOMBIE);
3603 ast_queue_frame(clone, &ast_null_frame);
3604 ast_channel_unlock(clone);
3607 /* Signal any blocker */
3608 if (ast_test_flag(original, AST_FLAG_BLOCKING))
3609 pthread_kill(original->blocker, SIGURG);
3610 if (option_debug)
3611 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
3612 return 0;
3615 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
3617 if (callerid) {
3618 if (chan->cid.cid_num)
3619 free(chan->cid.cid_num);
3620 chan->cid.cid_num = ast_strdup(callerid);
3622 if (calleridname) {
3623 if (chan->cid.cid_name)
3624 free(chan->cid.cid_name);
3625 chan->cid.cid_name = ast_strdup(calleridname);
3627 if (ani) {
3628 if (chan->cid.cid_ani)
3629 free(chan->cid.cid_ani);
3630 chan->cid.cid_ani = ast_strdup(ani);
3632 if (chan->cdr)
3633 ast_cdr_setcid(chan->cdr, chan);
3634 manager_event(EVENT_FLAG_CALL, "Newcallerid",
3635 "Channel: %s\r\n"
3636 "CallerID: %s\r\n"
3637 "CallerIDName: %s\r\n"
3638 "Uniqueid: %s\r\n"
3639 "CID-CallingPres: %d (%s)\r\n",
3640 chan->name,
3641 S_OR(chan->cid.cid_num, "<Unknown>"),
3642 S_OR(chan->cid.cid_name, "<Unknown>"),
3643 chan->uniqueid,
3644 chan->cid.cid_pres,
3645 ast_describe_caller_presentation(chan->cid.cid_pres)
3649 int ast_setstate(struct ast_channel *chan, enum ast_channel_state state)
3651 int oldstate = chan->_state;
3653 if (oldstate == state)
3654 return 0;
3656 chan->_state = state;
3657 ast_device_state_changed_literal(chan->name);
3658 /* setstate used to conditionally report Newchannel; this is no more */
3659 manager_event(EVENT_FLAG_CALL,
3660 "Newstate",
3661 "Channel: %s\r\n"
3662 "State: %s\r\n"
3663 "CallerID: %s\r\n"
3664 "CallerIDName: %s\r\n"
3665 "Uniqueid: %s\r\n",
3666 chan->name, ast_state2str(chan->_state),
3667 S_OR(chan->cid.cid_num, "<unknown>"),
3668 S_OR(chan->cid.cid_name, "<unknown>"),
3669 chan->uniqueid);
3671 return 0;
3674 /*! \brief Find bridged channel */
3675 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
3677 struct ast_channel *bridged;
3678 bridged = chan->_bridge;
3679 if (bridged && bridged->tech->bridged_channel)
3680 bridged = bridged->tech->bridged_channel(chan, bridged);
3681 return bridged;
3684 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
3686 int min = 0, sec = 0, check;
3688 check = ast_autoservice_start(peer);
3689 if (check)
3690 return;
3692 if (remain > 0) {
3693 if (remain / 60 > 1) {
3694 min = remain / 60;
3695 sec = remain % 60;
3696 } else {
3697 sec = remain;
3701 if (!strcmp(sound,"timeleft")) { /* Queue support */
3702 ast_stream_and_wait(chan, "vm-youhave", chan->language, "");
3703 if (min) {
3704 ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, NULL);
3705 ast_stream_and_wait(chan, "queue-minutes", chan->language, "");
3707 if (sec) {
3708 ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, NULL);
3709 ast_stream_and_wait(chan, "queue-seconds", chan->language, "");
3711 } else {
3712 ast_stream_and_wait(chan, sound, chan->language, "");
3715 ast_autoservice_stop(peer);
3718 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
3719 struct ast_bridge_config *config, struct ast_frame **fo,
3720 struct ast_channel **rc, struct timeval bridge_end)
3722 /* Copy voice back and forth between the two channels. */
3723 struct ast_channel *cs[3];
3724 struct ast_frame *f;
3725 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3726 int o0nativeformats;
3727 int o1nativeformats;
3728 int watch_c0_dtmf;
3729 int watch_c1_dtmf;
3730 void *pvt0, *pvt1;
3731 /* Indicates whether a frame was queued into a jitterbuffer */
3732 int frame_put_in_jb = 0;
3733 int jb_in_use;
3734 int to;
3736 cs[0] = c0;
3737 cs[1] = c1;
3738 pvt0 = c0->tech_pvt;
3739 pvt1 = c1->tech_pvt;
3740 o0nativeformats = c0->nativeformats;
3741 o1nativeformats = c1->nativeformats;
3742 watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
3743 watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
3745 /* Check the need of a jitterbuffer for each channel */
3746 jb_in_use = ast_jb_do_usecheck(c0, c1);
3748 for (;;) {
3749 struct ast_channel *who, *other;
3751 if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
3752 (o0nativeformats != c0->nativeformats) ||
3753 (o1nativeformats != c1->nativeformats)) {
3754 /* Check for Masquerade, codec changes, etc */
3755 res = AST_BRIDGE_RETRY;
3756 break;
3758 if (bridge_end.tv_sec) {
3759 to = ast_tvdiff_ms(bridge_end, ast_tvnow());
3760 if (to <= 0) {
3761 if (config->timelimit)
3762 res = AST_BRIDGE_RETRY;
3763 else
3764 res = AST_BRIDGE_COMPLETE;
3765 break;
3767 } else
3768 to = -1;
3769 /* Calculate the appropriate max sleep interval - in general, this is the time,
3770 left to the closest jb delivery moment */
3771 if (jb_in_use)
3772 to = ast_jb_get_when_to_wakeup(c0, c1, to);
3773 who = ast_waitfor_n(cs, 2, &to);
3774 if (!who) {
3775 /* No frame received within the specified timeout - check if we have to deliver now */
3776 if (jb_in_use)
3777 ast_jb_get_and_deliver(c0, c1);
3778 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3779 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3780 c0->_softhangup = 0;
3781 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3782 c1->_softhangup = 0;
3783 c0->_bridge = c1;
3784 c1->_bridge = c0;
3786 continue;
3788 f = ast_read(who);
3789 if (!f) {
3790 *fo = NULL;
3791 *rc = who;
3792 if (option_debug)
3793 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
3794 break;
3797 other = (who == c0) ? c1 : c0; /* the 'other' channel */
3798 /* Try add the frame info the who's bridged channel jitterbuff */
3799 if (jb_in_use)
3800 frame_put_in_jb = !ast_jb_put(other, f);
3802 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
3803 int bridge_exit = 0;
3805 switch (f->subclass) {
3806 case AST_CONTROL_HOLD:
3807 case AST_CONTROL_UNHOLD:
3808 case AST_CONTROL_VIDUPDATE:
3809 ast_indicate_data(other, f->subclass, f->data, f->datalen);
3810 break;
3811 default:
3812 *fo = f;
3813 *rc = who;
3814 bridge_exit = 1;
3815 if (option_debug)
3816 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
3817 break;
3819 if (bridge_exit)
3820 break;
3822 if ((f->frametype == AST_FRAME_VOICE) ||
3823 (f->frametype == AST_FRAME_DTMF_BEGIN) ||
3824 (f->frametype == AST_FRAME_DTMF) ||
3825 (f->frametype == AST_FRAME_VIDEO) ||
3826 (f->frametype == AST_FRAME_IMAGE) ||
3827 (f->frametype == AST_FRAME_HTML) ||
3828 (f->frametype == AST_FRAME_MODEM) ||
3829 (f->frametype == AST_FRAME_TEXT)) {
3830 /* monitored dtmf causes exit from bridge */
3831 int monitored_source = (who == c0) ? watch_c0_dtmf : watch_c1_dtmf;
3833 if (monitored_source &&
3834 (f->frametype == AST_FRAME_DTMF_END ||
3835 f->frametype == AST_FRAME_DTMF_BEGIN)) {
3836 *fo = f;
3837 *rc = who;
3838 if (option_debug)
3839 ast_log(LOG_DEBUG, "Got DTMF %s on channel (%s)\n",
3840 f->frametype == AST_FRAME_DTMF_END ? "end" : "begin",
3841 who->name);
3842 break;
3844 /* Write immediately frames, not passed through jb */
3845 if (!frame_put_in_jb)
3846 ast_write(other, f);
3848 /* Check if we have to deliver now */
3849 if (jb_in_use)
3850 ast_jb_get_and_deliver(c0, c1);
3852 /* XXX do we want to pass on also frames not matched above ? */
3853 ast_frfree(f);
3855 /* Swap who gets priority */
3856 cs[2] = cs[0];
3857 cs[0] = cs[1];
3858 cs[1] = cs[2];
3860 return res;
3863 /*! \brief Bridge two channels together */
3864 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
3865 struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
3867 struct ast_channel *who = NULL;
3868 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3869 int nativefailed=0;
3870 int firstpass;
3871 int o0nativeformats;
3872 int o1nativeformats;
3873 long time_left_ms=0;
3874 struct timeval nexteventts = { 0, };
3875 char caller_warning = 0;
3876 char callee_warning = 0;
3878 if (c0->_bridge) {
3879 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3880 c0->name, c0->_bridge->name);
3881 return -1;
3883 if (c1->_bridge) {
3884 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3885 c1->name, c1->_bridge->name);
3886 return -1;
3889 /* Stop if we're a zombie or need a soft hangup */
3890 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3891 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
3892 return -1;
3894 *fo = NULL;
3895 firstpass = config->firstpass;
3896 config->firstpass = 0;
3898 if (ast_tvzero(config->start_time))
3899 config->start_time = ast_tvnow();
3900 time_left_ms = config->timelimit;
3902 caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
3903 callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
3905 if (config->start_sound && firstpass) {
3906 if (caller_warning)
3907 bridge_playfile(c0, c1, config->start_sound, time_left_ms / 1000);
3908 if (callee_warning)
3909 bridge_playfile(c1, c0, config->start_sound, time_left_ms / 1000);
3912 /* Keep track of bridge */
3913 c0->_bridge = c1;
3914 c1->_bridge = c0;
3916 /* \todo XXX here should check that cid_num is not NULL */
3917 manager_event(EVENT_FLAG_CALL, "Link",
3918 "Channel1: %s\r\n"
3919 "Channel2: %s\r\n"
3920 "Uniqueid1: %s\r\n"
3921 "Uniqueid2: %s\r\n"
3922 "CallerID1: %s\r\n"
3923 "CallerID2: %s\r\n",
3924 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3926 o0nativeformats = c0->nativeformats;
3927 o1nativeformats = c1->nativeformats;
3929 if (config->feature_timer) {
3930 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->feature_timer, 1000));
3931 } else if (config->timelimit) {
3932 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3933 if (caller_warning || callee_warning)
3934 nexteventts = ast_tvsub(nexteventts, ast_samp2tv(config->play_warning, 1000));
3937 if (!c0->tech->send_digit_begin)
3938 ast_set_flag(c1, AST_FLAG_END_DTMF_ONLY);
3939 if (!c1->tech->send_digit_begin)
3940 ast_set_flag(c0, AST_FLAG_END_DTMF_ONLY);
3942 for (/* ever */;;) {
3943 struct timeval now = { 0, };
3944 int to;
3946 to = -1;
3948 if (!ast_tvzero(nexteventts)) {
3949 now = ast_tvnow();
3950 to = ast_tvdiff_ms(nexteventts, now);
3951 if (to <= 0) {
3952 if (!config->timelimit) {
3953 res = AST_BRIDGE_COMPLETE;
3954 break;
3956 to = 0;
3960 if (config->timelimit) {
3961 time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
3962 if (time_left_ms < to)
3963 to = time_left_ms;
3965 if (time_left_ms <= 0) {
3966 if (caller_warning && config->end_sound)
3967 bridge_playfile(c0, c1, config->end_sound, 0);
3968 if (callee_warning && config->end_sound)
3969 bridge_playfile(c1, c0, config->end_sound, 0);
3970 *fo = NULL;
3971 if (who)
3972 *rc = who;
3973 res = 0;
3974 break;
3977 if (!to) {
3978 if (time_left_ms >= 5000 && config->warning_sound && config->play_warning) {
3979 int t = (time_left_ms + 500) / 1000; /* round to nearest second */
3980 if (caller_warning)
3981 bridge_playfile(c0, c1, config->warning_sound, t);
3982 if (callee_warning)
3983 bridge_playfile(c1, c0, config->warning_sound, t);
3985 if (config->warning_freq && (time_left_ms > (config->warning_freq + 5000)))
3986 nexteventts = ast_tvadd(nexteventts, ast_samp2tv(config->warning_freq, 1000));
3987 else
3988 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3992 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3993 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3994 c0->_softhangup = 0;
3995 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3996 c1->_softhangup = 0;
3997 c0->_bridge = c1;
3998 c1->_bridge = c0;
3999 if (option_debug)
4000 ast_log(LOG_DEBUG, "Unbridge signal received. Ending native bridge.\n");
4001 continue;
4004 /* Stop if we're a zombie or need a soft hangup */
4005 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
4006 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
4007 *fo = NULL;
4008 if (who)
4009 *rc = who;
4010 res = 0;
4011 if (option_debug)
4012 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",
4013 c0->name, c1->name,
4014 ast_test_flag(c0, AST_FLAG_ZOMBIE) ? "Yes" : "No",
4015 ast_check_hangup(c0) ? "Yes" : "No",
4016 ast_test_flag(c1, AST_FLAG_ZOMBIE) ? "Yes" : "No",
4017 ast_check_hangup(c1) ? "Yes" : "No");
4018 break;
4021 if (c0->tech->bridge &&
4022 (config->timelimit == 0) &&
4023 (c0->tech->bridge == c1->tech->bridge) &&
4024 !nativefailed && !c0->monitor && !c1->monitor &&
4025 !c0->spies && !c1->spies && !ast_test_flag(&(config->features_callee),AST_FEATURE_REDIRECT) &&
4026 !ast_test_flag(&(config->features_caller),AST_FEATURE_REDIRECT) ) {
4027 /* Looks like they share a bridge method and nothing else is in the way */
4028 ast_set_flag(c0, AST_FLAG_NBRIDGE);
4029 ast_set_flag(c1, AST_FLAG_NBRIDGE);
4030 if ((res = c0->tech->bridge(c0, c1, config->flags, fo, rc, to)) == AST_BRIDGE_COMPLETE) {
4031 /* \todo XXX here should check that cid_num is not NULL */
4032 manager_event(EVENT_FLAG_CALL, "Unlink",
4033 "Channel1: %s\r\n"
4034 "Channel2: %s\r\n"
4035 "Uniqueid1: %s\r\n"
4036 "Uniqueid2: %s\r\n"
4037 "CallerID1: %s\r\n"
4038 "CallerID2: %s\r\n",
4039 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
4040 if (option_debug)
4041 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n", c0->name, c1->name);
4043 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
4044 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
4046 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
4047 continue;
4049 c0->_bridge = NULL;
4050 c1->_bridge = NULL;
4052 return res;
4053 } else {
4054 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
4055 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
4057 switch (res) {
4058 case AST_BRIDGE_RETRY:
4059 continue;
4060 default:
4061 if (option_verbose > 2)
4062 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s ended\n",
4063 c0->name, c1->name);
4064 /* fallthrough */
4065 case AST_BRIDGE_FAILED_NOWARN:
4066 nativefailed++;
4067 break;
4071 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) ||
4072 (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
4073 !(c0->generator || c1->generator)) {
4074 if (ast_channel_make_compatible(c0, c1)) {
4075 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
4076 /* \todo XXX here should check that cid_num is not NULL */
4077 manager_event(EVENT_FLAG_CALL, "Unlink",
4078 "Channel1: %s\r\n"
4079 "Channel2: %s\r\n"
4080 "Uniqueid1: %s\r\n"
4081 "Uniqueid2: %s\r\n"
4082 "CallerID1: %s\r\n"
4083 "CallerID2: %s\r\n",
4084 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
4085 return AST_BRIDGE_FAILED;
4087 o0nativeformats = c0->nativeformats;
4088 o1nativeformats = c1->nativeformats;
4090 res = ast_generic_bridge(c0, c1, config, fo, rc, nexteventts);
4091 if (res != AST_BRIDGE_RETRY)
4092 break;
4095 ast_clear_flag(c0, AST_FLAG_END_DTMF_ONLY);
4096 ast_clear_flag(c1, AST_FLAG_END_DTMF_ONLY);
4098 c0->_bridge = NULL;
4099 c1->_bridge = NULL;
4101 /* \todo XXX here should check that cid_num is not NULL */
4102 manager_event(EVENT_FLAG_CALL, "Unlink",
4103 "Channel1: %s\r\n"
4104 "Channel2: %s\r\n"
4105 "Uniqueid1: %s\r\n"
4106 "Uniqueid2: %s\r\n"
4107 "CallerID1: %s\r\n"
4108 "CallerID2: %s\r\n",
4109 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
4110 if (option_debug)
4111 ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n", c0->name, c1->name);
4113 return res;
4116 /*! \brief Sets an option on a channel */
4117 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
4119 int res;
4121 if (chan->tech->setoption) {
4122 res = chan->tech->setoption(chan, option, data, datalen);
4123 if (res < 0)
4124 return res;
4125 } else {
4126 errno = ENOSYS;
4127 return -1;
4129 if (block) {
4130 /* XXX Implement blocking -- just wait for our option frame reply, discarding
4131 intermediate packets. XXX */
4132 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
4133 return -1;
4135 return 0;
4138 struct tonepair_def {
4139 int freq1;
4140 int freq2;
4141 int duration;
4142 int vol;
4145 struct tonepair_state {
4146 int fac1;
4147 int fac2;
4148 int v1_1;
4149 int v2_1;
4150 int v3_1;
4151 int v1_2;
4152 int v2_2;
4153 int v3_2;
4154 int origwfmt;
4155 int pos;
4156 int duration;
4157 int modulate;
4158 struct ast_frame f;
4159 unsigned char offset[AST_FRIENDLY_OFFSET];
4160 short data[4000];
4163 static void tonepair_release(struct ast_channel *chan, void *params)
4165 struct tonepair_state *ts = params;
4167 if (chan)
4168 ast_set_write_format(chan, ts->origwfmt);
4169 free(ts);
4172 static void *tonepair_alloc(struct ast_channel *chan, void *params)
4174 struct tonepair_state *ts;
4175 struct tonepair_def *td = params;
4177 if (!(ts = ast_calloc(1, sizeof(*ts))))
4178 return NULL;
4179 ts->origwfmt = chan->writeformat;
4180 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
4181 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
4182 tonepair_release(NULL, ts);
4183 ts = NULL;
4184 } else {
4185 ts->fac1 = 2.0 * cos(2.0 * M_PI * (td->freq1 / 8000.0)) * 32768.0;
4186 ts->v1_1 = 0;
4187 ts->v2_1 = sin(-4.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
4188 ts->v3_1 = sin(-2.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
4189 ts->v2_1 = 0;
4190 ts->fac2 = 2.0 * cos(2.0 * M_PI * (td->freq2 / 8000.0)) * 32768.0;
4191 ts->v2_2 = sin(-4.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
4192 ts->v3_2 = sin(-2.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
4193 ts->duration = td->duration;
4194 ts->modulate = 0;
4196 /* Let interrupts interrupt :) */
4197 ast_set_flag(chan, AST_FLAG_WRITE_INT);
4198 return ts;
4201 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
4203 struct tonepair_state *ts = data;
4204 int x;
4206 /* we need to prepare a frame with 16 * timelen samples as we're
4207 * generating SLIN audio
4209 len = samples * 2;
4211 if (len > sizeof(ts->data) / 2 - 1) {
4212 ast_log(LOG_WARNING, "Can't generate that much data!\n");
4213 return -1;
4215 memset(&ts->f, 0, sizeof(ts->f));
4216 for (x=0;x<len/2;x++) {
4217 ts->v1_1 = ts->v2_1;
4218 ts->v2_1 = ts->v3_1;
4219 ts->v3_1 = (ts->fac1 * ts->v2_1 >> 15) - ts->v1_1;
4221 ts->v1_2 = ts->v2_2;
4222 ts->v2_2 = ts->v3_2;
4223 ts->v3_2 = (ts->fac2 * ts->v2_2 >> 15) - ts->v1_2;
4224 if (ts->modulate) {
4225 int p;
4226 p = ts->v3_2 - 32768;
4227 if (p < 0) p = -p;
4228 p = ((p * 9) / 10) + 1;
4229 ts->data[x] = (ts->v3_1 * p) >> 15;
4230 } else
4231 ts->data[x] = ts->v3_1 + ts->v3_2;
4233 ts->f.frametype = AST_FRAME_VOICE;
4234 ts->f.subclass = AST_FORMAT_SLINEAR;
4235 ts->f.datalen = len;
4236 ts->f.samples = samples;
4237 ts->f.offset = AST_FRIENDLY_OFFSET;
4238 ts->f.data = ts->data;
4239 ast_write(chan, &ts->f);
4240 ts->pos += x;
4241 if (ts->duration > 0) {
4242 if (ts->pos >= ts->duration * 8)
4243 return -1;
4245 return 0;
4248 static struct ast_generator tonepair = {
4249 alloc: tonepair_alloc,
4250 release: tonepair_release,
4251 generate: tonepair_generator,
4254 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
4256 struct tonepair_def d = { 0, };
4258 d.freq1 = freq1;
4259 d.freq2 = freq2;
4260 d.duration = duration;
4261 d.vol = (vol < 1) ? 8192 : vol; /* force invalid to 8192 */
4262 if (ast_activate_generator(chan, &tonepair, &d))
4263 return -1;
4264 return 0;
4267 void ast_tonepair_stop(struct ast_channel *chan)
4269 ast_deactivate_generator(chan);
4272 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
4274 int res;
4276 if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
4277 return res;
4279 /* Give us some wiggle room */
4280 while (chan->generatordata && ast_waitfor(chan, 100) >= 0) {
4281 struct ast_frame *f = ast_read(chan);
4282 if (f)
4283 ast_frfree(f);
4284 else
4285 return -1;
4287 return 0;
4290 ast_group_t ast_get_group(const char *s)
4292 char *piece;
4293 char *c;
4294 int start=0, finish=0, x;
4295 ast_group_t group = 0;
4297 c = ast_strdupa(s);
4299 while ((piece = strsep(&c, ","))) {
4300 if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
4301 /* Range */
4302 } else if (sscanf(piece, "%d", &start)) {
4303 /* Just one */
4304 finish = start;
4305 } else {
4306 ast_log(LOG_ERROR, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s, piece);
4307 continue;
4309 for (x = start; x <= finish; x++) {
4310 if ((x > 63) || (x < 0)) {
4311 ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x);
4312 } else
4313 group |= ((ast_group_t) 1 << x);
4316 return group;
4319 static int (*ast_moh_start_ptr)(struct ast_channel *, const char *, const char *) = NULL;
4320 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
4321 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
4323 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, const char *, const char *),
4324 void (*stop_ptr)(struct ast_channel *),
4325 void (*cleanup_ptr)(struct ast_channel *))
4327 ast_moh_start_ptr = start_ptr;
4328 ast_moh_stop_ptr = stop_ptr;
4329 ast_moh_cleanup_ptr = cleanup_ptr;
4332 void ast_uninstall_music_functions(void)
4334 ast_moh_start_ptr = NULL;
4335 ast_moh_stop_ptr = NULL;
4336 ast_moh_cleanup_ptr = NULL;
4339 /*! \brief Turn on music on hold on a given channel */
4340 int ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
4342 if (ast_moh_start_ptr)
4343 return ast_moh_start_ptr(chan, mclass, interpclass);
4345 if (option_verbose > 2) {
4346 ast_verbose(VERBOSE_PREFIX_3 "Music class %s requested but no musiconhold loaded.\n",
4347 mclass ? mclass : (interpclass ? interpclass : "default"));
4350 return 0;
4353 /*! \brief Turn off music on hold on a given channel */
4354 void ast_moh_stop(struct ast_channel *chan)
4356 if (ast_moh_stop_ptr)
4357 ast_moh_stop_ptr(chan);
4360 void ast_moh_cleanup(struct ast_channel *chan)
4362 if (ast_moh_cleanup_ptr)
4363 ast_moh_cleanup_ptr(chan);
4366 void ast_channels_init(void)
4368 ast_cli_register_multiple(cli_channel, sizeof(cli_channel) / sizeof(struct ast_cli_entry));
4371 /*! \brief Print call group and pickup group ---*/
4372 char *ast_print_group(char *buf, int buflen, ast_group_t group)
4374 unsigned int i;
4375 int first=1;
4376 char num[3];
4378 buf[0] = '\0';
4380 if (!group) /* Return empty string if no group */
4381 return buf;
4383 for (i = 0; i <= 63; i++) { /* Max group is 63 */
4384 if (group & ((ast_group_t) 1 << i)) {
4385 if (!first) {
4386 strncat(buf, ", ", buflen);
4387 } else {
4388 first=0;
4390 snprintf(num, sizeof(num), "%u", i);
4391 strncat(buf, num, buflen);
4394 return buf;
4397 void ast_set_variables(struct ast_channel *chan, struct ast_variable *vars)
4399 struct ast_variable *cur;
4401 for (cur = vars; cur; cur = cur->next)
4402 pbx_builtin_setvar_helper(chan, cur->name, cur->value);
4405 static void copy_data_from_queue(struct ast_channel_spy_queue *queue, short *buf, unsigned int samples)
4407 struct ast_frame *f;
4408 int tocopy;
4409 int bytestocopy;
4411 while (samples) {
4412 if (!(f = AST_LIST_FIRST(&queue->list))) {
4413 ast_log(LOG_ERROR, "Ran out of frames before buffer filled!\n");
4414 break;
4417 tocopy = (f->samples > samples) ? samples : f->samples;
4418 bytestocopy = ast_codec_get_len(queue->format, tocopy);
4419 memcpy(buf, f->data, bytestocopy);
4420 samples -= tocopy;
4421 buf += tocopy;
4422 f->samples -= tocopy;
4423 f->data += bytestocopy;
4424 f->datalen -= bytestocopy;
4425 f->offset += bytestocopy;
4426 queue->samples -= tocopy;
4428 if (!f->samples)
4429 ast_frfree(AST_LIST_REMOVE_HEAD(&queue->list, frame_list));
4433 struct ast_frame *ast_channel_spy_read_frame(struct ast_channel_spy *spy, unsigned int samples)
4435 struct ast_frame *result;
4436 /* buffers are allocated to hold SLINEAR, which is the largest format */
4437 short read_buf[samples];
4438 short write_buf[samples];
4439 struct ast_frame *read_frame;
4440 struct ast_frame *write_frame;
4441 int need_dup;
4442 struct ast_frame stack_read_frame = { .frametype = AST_FRAME_VOICE,
4443 .subclass = spy->read_queue.format,
4444 .data = read_buf,
4445 .samples = samples,
4446 .datalen = ast_codec_get_len(spy->read_queue.format, samples),
4448 struct ast_frame stack_write_frame = { .frametype = AST_FRAME_VOICE,
4449 .subclass = spy->write_queue.format,
4450 .data = write_buf,
4451 .samples = samples,
4452 .datalen = ast_codec_get_len(spy->write_queue.format, samples),
4455 /* if a flush has been requested, dump everything in whichever queue is larger */
4456 if (ast_test_flag(spy, CHANSPY_TRIGGER_FLUSH)) {
4457 if (spy->read_queue.samples > spy->write_queue.samples) {
4458 if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST)) {
4459 AST_LIST_TRAVERSE(&spy->read_queue.list, result, frame_list)
4460 ast_frame_adjust_volume(result, spy->read_vol_adjustment);
4462 result = AST_LIST_FIRST(&spy->read_queue.list);
4463 AST_LIST_HEAD_SET_NOLOCK(&spy->read_queue.list, NULL);
4464 spy->read_queue.samples = 0;
4465 } else {
4466 if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST)) {
4467 AST_LIST_TRAVERSE(&spy->write_queue.list, result, frame_list)
4468 ast_frame_adjust_volume(result, spy->write_vol_adjustment);
4470 result = AST_LIST_FIRST(&spy->write_queue.list);
4471 AST_LIST_HEAD_SET_NOLOCK(&spy->write_queue.list, NULL);
4472 spy->write_queue.samples = 0;
4474 ast_clear_flag(spy, CHANSPY_TRIGGER_FLUSH);
4475 return result;
4478 if ((spy->read_queue.samples < samples) || (spy->write_queue.samples < samples))
4479 return NULL;
4481 /* short-circuit if both head frames have exactly what we want */
4482 if ((AST_LIST_FIRST(&spy->read_queue.list)->samples == samples) &&
4483 (AST_LIST_FIRST(&spy->write_queue.list)->samples == samples)) {
4484 read_frame = AST_LIST_REMOVE_HEAD(&spy->read_queue.list, frame_list);
4485 write_frame = AST_LIST_REMOVE_HEAD(&spy->write_queue.list, frame_list);
4487 spy->read_queue.samples -= samples;
4488 spy->write_queue.samples -= samples;
4490 need_dup = 0;
4491 } else {
4492 copy_data_from_queue(&spy->read_queue, read_buf, samples);
4493 copy_data_from_queue(&spy->write_queue, write_buf, samples);
4495 read_frame = &stack_read_frame;
4496 write_frame = &stack_write_frame;
4497 need_dup = 1;
4500 if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST))
4501 ast_frame_adjust_volume(read_frame, spy->read_vol_adjustment);
4503 if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST))
4504 ast_frame_adjust_volume(write_frame, spy->write_vol_adjustment);
4506 if (ast_test_flag(spy, CHANSPY_MIXAUDIO)) {
4507 ast_frame_slinear_sum(read_frame, write_frame);
4509 if (need_dup)
4510 result = ast_frdup(read_frame);
4511 else {
4512 result = read_frame;
4513 ast_frfree(write_frame);
4515 } else {
4516 if (need_dup) {
4517 result = ast_frdup(read_frame);
4518 AST_LIST_NEXT(result, frame_list) = ast_frdup(write_frame);
4519 } else {
4520 result = read_frame;
4521 AST_LIST_NEXT(result, frame_list) = write_frame;
4525 return result;
4528 static void *silence_generator_alloc(struct ast_channel *chan, void *data)
4530 /* just store the data pointer in the channel structure */
4531 return data;
4534 static void silence_generator_release(struct ast_channel *chan, void *data)
4536 /* nothing to do */
4539 static int silence_generator_generate(struct ast_channel *chan, void *data, int len, int samples)
4541 short buf[samples];
4542 struct ast_frame frame = {
4543 .frametype = AST_FRAME_VOICE,
4544 .subclass = AST_FORMAT_SLINEAR,
4545 .data = buf,
4546 .samples = samples,
4547 .datalen = sizeof(buf),
4549 memset(buf, 0, sizeof(buf));
4550 if (ast_write(chan, &frame))
4551 return -1;
4552 return 0;
4555 static struct ast_generator silence_generator = {
4556 .alloc = silence_generator_alloc,
4557 .release = silence_generator_release,
4558 .generate = silence_generator_generate,
4561 struct ast_silence_generator {
4562 int old_write_format;
4565 struct ast_silence_generator *ast_channel_start_silence_generator(struct ast_channel *chan)
4567 struct ast_silence_generator *state;
4569 if (!(state = ast_calloc(1, sizeof(*state)))) {
4570 return NULL;
4573 state->old_write_format = chan->writeformat;
4575 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
4576 ast_log(LOG_ERROR, "Could not set write format to SLINEAR\n");
4577 free(state);
4578 return NULL;
4581 ast_activate_generator(chan, &silence_generator, state);
4583 if (option_debug)
4584 ast_log(LOG_DEBUG, "Started silence generator on '%s'\n", chan->name);
4586 return state;
4589 void ast_channel_stop_silence_generator(struct ast_channel *chan, struct ast_silence_generator *state)
4591 if (!state)
4592 return;
4594 ast_deactivate_generator(chan);
4596 if (option_debug)
4597 ast_log(LOG_DEBUG, "Stopped silence generator on '%s'\n", chan->name);
4599 if (ast_set_write_format(chan, state->old_write_format) < 0)
4600 ast_log(LOG_ERROR, "Could not return write format to its original state\n");
4602 free(state);
4606 /*! \ brief Convert channel reloadreason (ENUM) to text string for manager event */
4607 const char *channelreloadreason2txt(enum channelreloadreason reason)
4609 switch (reason) {
4610 case CHANNEL_MODULE_LOAD:
4611 return "LOAD (Channel module load)";
4613 case CHANNEL_MODULE_RELOAD:
4614 return "RELOAD (Channel module reload)";
4616 case CHANNEL_CLI_RELOAD:
4617 return "CLIRELOAD (Channel module reload by CLI command)";
4619 default:
4620 return "MANAGERRELOAD (Channel module reload by manager)";
4624 #ifdef DEBUG_CHANNEL_LOCKS
4626 /*! \brief Unlock AST channel (and print debugging output)
4627 \note You need to enable DEBUG_CHANNEL_LOCKS for this function
4629 int ast_channel_unlock(struct ast_channel *chan)
4631 int res = 0;
4632 if (option_debug > 2)
4633 ast_log(LOG_DEBUG, "::::==== Unlocking AST channel %s\n", chan->name);
4635 if (!chan) {
4636 if (option_debug)
4637 ast_log(LOG_DEBUG, "::::==== Unlocking non-existing channel \n");
4638 return 0;
4641 res = ast_mutex_unlock(&chan->lock);
4643 if (option_debug > 2) {
4644 #ifdef DEBUG_THREADS
4645 int count = 0;
4646 if ((count = chan->lock.reentrancy))
4647 ast_log(LOG_DEBUG, ":::=== Still have %d locks (recursive)\n", count);
4648 #endif
4649 if (!res)
4650 if (option_debug)
4651 ast_log(LOG_DEBUG, "::::==== Channel %s was unlocked\n", chan->name);
4652 if (res == EINVAL) {
4653 if (option_debug)
4654 ast_log(LOG_DEBUG, "::::==== Channel %s had no lock by this thread. Failed unlocking\n", chan->name);
4657 if (res == EPERM) {
4658 /* We had no lock, so okay any way*/
4659 if (option_debug > 3)
4660 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked at all \n", chan->name);
4661 res = 0;
4663 return res;
4666 /*! \brief Lock AST channel (and print debugging output)
4667 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4668 int ast_channel_lock(struct ast_channel *chan)
4670 int res;
4672 if (option_debug > 3)
4673 ast_log(LOG_DEBUG, "====:::: Locking AST channel %s\n", chan->name);
4675 res = ast_mutex_lock(&chan->lock);
4677 if (option_debug > 3) {
4678 #ifdef DEBUG_THREADS
4679 int count = 0;
4680 if ((count = chan->lock.reentrancy))
4681 ast_log(LOG_DEBUG, ":::=== Now have %d locks (recursive)\n", count);
4682 #endif
4683 if (!res)
4684 ast_log(LOG_DEBUG, "::::==== Channel %s was locked\n", chan->name);
4685 if (res == EDEADLK) {
4686 /* We had no lock, so okey any way */
4687 if (option_debug > 3)
4688 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked by us. Lock would cause deadlock.\n", chan->name);
4690 if (res == EINVAL) {
4691 if (option_debug > 3)
4692 ast_log(LOG_DEBUG, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
4695 return res;
4698 /*! \brief Lock AST channel (and print debugging output)
4699 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4700 int ast_channel_trylock(struct ast_channel *chan)
4702 int res;
4704 if (option_debug > 2)
4705 ast_log(LOG_DEBUG, "====:::: Trying to lock AST channel %s\n", chan->name);
4707 res = ast_mutex_trylock(&chan->lock);
4709 if (option_debug > 2) {
4710 #ifdef DEBUG_THREADS
4711 int count = 0;
4712 if ((count = chan->lock.reentrancy))
4713 ast_log(LOG_DEBUG, ":::=== Now have %d locks (recursive)\n", count);
4714 #endif
4715 if (!res)
4716 ast_log(LOG_DEBUG, "::::==== Channel %s was locked\n", chan->name);
4717 if (res == EBUSY) {
4718 /* We failed to lock */
4719 if (option_debug > 2)
4720 ast_log(LOG_DEBUG, "::::==== Channel %s failed to lock. Not waiting around...\n", chan->name);
4722 if (res == EDEADLK) {
4723 /* We had no lock, so okey any way*/
4724 if (option_debug > 2)
4725 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked. Lock would cause deadlock.\n", chan->name);
4727 if (res == EINVAL && option_debug > 2)
4728 ast_log(LOG_DEBUG, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
4730 return res;
4733 #endif
4736 * Wrappers for various ast_say_*() functions that call the full version
4737 * of the same functions.
4738 * The proper place would be say.c, but that file is optional and one
4739 * must be able to build asterisk even without it (using a loadable 'say'
4740 * implementation that only supplies the 'full' version of the functions.
4743 int ast_say_number(struct ast_channel *chan, int num,
4744 const char *ints, const char *language, const char *options)
4746 return ast_say_number_full(chan, num, ints, language, options, -1, -1);
4749 int ast_say_enumeration(struct ast_channel *chan, int num,
4750 const char *ints, const char *language, const char *options)
4752 return ast_say_enumeration_full(chan, num, ints, language, options, -1, -1);
4755 int ast_say_digits(struct ast_channel *chan, int num,
4756 const char *ints, const char *lang)
4758 return ast_say_digits_full(chan, num, ints, lang, -1, -1);
4761 int ast_say_digit_str(struct ast_channel *chan, const char *str,
4762 const char *ints, const char *lang)
4764 return ast_say_digit_str_full(chan, str, ints, lang, -1, -1);
4767 int ast_say_character_str(struct ast_channel *chan, const char *str,
4768 const char *ints, const char *lang)
4770 return ast_say_character_str_full(chan, str, ints, lang, -1, -1);
4773 int ast_say_phonetic_str(struct ast_channel *chan, const char *str,
4774 const char *ints, const char *lang)
4776 return ast_say_phonetic_str_full(chan, str, ints, lang, -1, -1);
4779 int ast_say_digits_full(struct ast_channel *chan, int num,
4780 const char *ints, const char *lang, int audiofd, int ctrlfd)
4782 char buf[256];
4784 snprintf(buf, sizeof(buf), "%d", num);
4785 return ast_say_digit_str_full(chan, buf, ints, lang, audiofd, ctrlfd);
4788 int ast_channel_whisper_start(struct ast_channel *chan)
4790 if (chan->whisper)
4791 return -1;
4793 if (!(chan->whisper = ast_calloc(1, sizeof(*chan->whisper))))
4794 return -1;
4796 ast_mutex_init(&chan->whisper->lock);
4797 ast_slinfactory_init(&chan->whisper->sf);
4798 ast_set_flag(chan, AST_FLAG_WHISPER);
4800 return 0;
4803 int ast_channel_whisper_feed(struct ast_channel *chan, struct ast_frame *f)
4805 if (!chan->whisper)
4806 return -1;
4808 ast_mutex_lock(&chan->whisper->lock);
4809 ast_slinfactory_feed(&chan->whisper->sf, f);
4810 ast_mutex_unlock(&chan->whisper->lock);
4812 return 0;
4815 void ast_channel_whisper_stop(struct ast_channel *chan)
4817 if (!chan->whisper)
4818 return;
4820 ast_clear_flag(chan, AST_FLAG_WHISPER);
4821 if (chan->whisper->path)
4822 ast_translator_free_path(chan->whisper->path);
4823 if (chan->whisper->original_format && chan->writeformat == AST_FORMAT_SLINEAR)
4824 ast_set_write_format(chan, chan->whisper->original_format);
4825 ast_slinfactory_destroy(&chan->whisper->sf);
4826 ast_mutex_destroy(&chan->whisper->lock);
4827 free(chan->whisper);
4828 chan->whisper = NULL;