move extern declaration for this option to a header file where it belongs
[asterisk-bristuff.git] / main / channel.c
blob95293d6614a69c93e239918c4c78b3bf80deef3b
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 = 0;
100 static int uniqueint = 0;
102 unsigned long global_fin = 0, global_fout = 0;
104 AST_THREADSTORAGE(state2str_threadbuf, state2str_threadbuf_init);
105 #define STATE2STR_BUFSIZE 32
107 /* XXX 100ms ... this won't work with wideband support */
108 #define AST_DEFAULT_EMULATE_DTMF_SAMPLES 800
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(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 char *complete_channeltypes(const char *line, const char *word, int pos, int state)
272 struct chanlist *cl;
273 int which = 0;
274 int wordlen;
275 char *ret = NULL;
277 if (pos != 2)
278 return NULL;
280 wordlen = strlen(word);
282 AST_LIST_TRAVERSE(&backends, cl, list) {
283 if (!strncasecmp(word, cl->tech->type, wordlen) && ++which > state) {
284 ret = strdup(cl->tech->type);
285 break;
289 return ret;
292 static char show_channeltypes_usage[] =
293 "Usage: core show channeltypes\n"
294 " Lists available channel types registered in your Asterisk server.\n";
296 static char show_channeltype_usage[] =
297 "Usage: core show channeltype <name>\n"
298 " Show details about the specified channel type, <name>.\n";
300 static struct ast_cli_entry cli_show_channeltypes_deprecated = {
301 { "show", "channeltypes", NULL },
302 show_channeltypes, NULL,
303 NULL };
305 static struct ast_cli_entry cli_show_channeltype_deprecated = {
306 { "show", "channeltype", NULL },
307 show_channeltype, NULL,
308 NULL, complete_channeltypes };
310 static struct ast_cli_entry cli_channel[] = {
311 { { "core", "show", "channeltypes", NULL },
312 show_channeltypes, "List available channel types",
313 show_channeltypes_usage, NULL, &cli_show_channeltypes_deprecated },
315 { { "core", "show", "channeltype", NULL },
316 show_channeltype, "Give more details on that channel type",
317 show_channeltype_usage, complete_channeltypes, &cli_show_channeltype_deprecated },
320 /*! \brief Checks to see if a channel is needing hang up */
321 int ast_check_hangup(struct ast_channel *chan)
323 if (chan->_softhangup) /* yes if soft hangup flag set */
324 return 1;
325 if (!chan->tech_pvt) /* yes if no technology private data */
326 return 1;
327 if (!chan->whentohangup) /* no if no hangup scheduled */
328 return 0;
329 if (chan->whentohangup > time(NULL)) /* no if hangup time has not come yet. */
330 return 0;
331 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
332 return 1;
335 static int ast_check_hangup_locked(struct ast_channel *chan)
337 int res;
338 ast_channel_lock(chan);
339 res = ast_check_hangup(chan);
340 ast_channel_unlock(chan);
341 return res;
344 /*! \brief printf the string into a correctly sized mallocd buffer, and return the buffer */
345 char *ast_safe_string_alloc(const char *fmt, ...)
347 char *b2,buf[1];
348 int len;
350 va_list args;
351 va_start(args, fmt);
352 len = vsnprintf(buf, 1, fmt, args);
353 b2 = ast_malloc(len+1);
354 vsnprintf(b2, len+1, fmt, args);
355 va_end(args);
356 return b2;
359 /*! \brief Initiate system shutdown */
360 void ast_begin_shutdown(int hangup)
362 struct ast_channel *c;
363 shutting_down = 1;
364 if (hangup) {
365 AST_LIST_LOCK(&channels);
366 AST_LIST_TRAVERSE(&channels, c, chan_list)
367 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
368 AST_LIST_UNLOCK(&channels);
372 /*! \brief returns number of active/allocated channels */
373 int ast_active_channels(void)
375 struct ast_channel *c;
376 int cnt = 0;
377 AST_LIST_LOCK(&channels);
378 AST_LIST_TRAVERSE(&channels, c, chan_list)
379 cnt++;
380 AST_LIST_UNLOCK(&channels);
381 return cnt;
384 /*! \brief Cancel a shutdown in progress */
385 void ast_cancel_shutdown(void)
387 shutting_down = 0;
390 /*! \brief Returns non-zero if Asterisk is being shut down */
391 int ast_shutting_down(void)
393 return shutting_down;
396 /*! \brief Set when to hangup channel */
397 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
399 chan->whentohangup = offset ? time(NULL) + offset : 0;
400 ast_queue_frame(chan, &ast_null_frame);
401 return;
404 /*! \brief Compare a offset with when to hangup channel */
405 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
407 time_t whentohangup;
409 if (chan->whentohangup == 0) {
410 return (offset == 0) ? 0 : -1;
411 } else {
412 if (offset == 0) /* XXX why is this special ? */
413 return (1);
414 else {
415 whentohangup = offset + time (NULL);
416 if (chan->whentohangup < whentohangup)
417 return (1);
418 else if (chan->whentohangup == whentohangup)
419 return (0);
420 else
421 return (-1);
426 /*! \brief Register a new telephony channel in Asterisk */
427 int ast_channel_register(const struct ast_channel_tech *tech)
429 struct chanlist *chan;
431 AST_LIST_LOCK(&channels);
433 AST_LIST_TRAVERSE(&backends, chan, list) {
434 if (!strcasecmp(tech->type, chan->tech->type)) {
435 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
436 AST_LIST_UNLOCK(&channels);
437 return -1;
441 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
442 AST_LIST_UNLOCK(&channels);
443 return -1;
445 chan->tech = tech;
446 AST_LIST_INSERT_HEAD(&backends, chan, list);
448 if (option_debug)
449 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
451 if (option_verbose > 1)
452 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
453 chan->tech->description);
455 AST_LIST_UNLOCK(&channels);
456 return 0;
459 void ast_channel_unregister(const struct ast_channel_tech *tech)
461 struct chanlist *chan;
463 if (option_debug)
464 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
466 AST_LIST_LOCK(&channels);
468 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
469 if (chan->tech == tech) {
470 AST_LIST_REMOVE_CURRENT(&backends, list);
471 free(chan);
472 if (option_verbose > 1)
473 ast_verbose(VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
474 break;
477 AST_LIST_TRAVERSE_SAFE_END
479 AST_LIST_UNLOCK(&channels);
482 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
484 struct chanlist *chanls;
485 const struct ast_channel_tech *ret = NULL;
487 if (AST_LIST_LOCK(&channels)) {
488 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
489 return NULL;
492 AST_LIST_TRAVERSE(&backends, chanls, list) {
493 if (!strcasecmp(name, chanls->tech->type)) {
494 ret = chanls->tech;
495 break;
499 AST_LIST_UNLOCK(&channels);
501 return ret;
504 /*! \brief Gives the string form of a given hangup cause */
505 const char *ast_cause2str(int cause)
507 int x;
509 for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++) {
510 if (causes[x].cause == cause)
511 return causes[x].desc;
514 return "Unknown";
517 /*! \brief Convert a symbolic hangup cause to number */
518 int ast_str2cause(const char *name)
520 int x;
522 for (x = 0; x < sizeof(causes) / sizeof(causes[0]); x++)
523 if (strncasecmp(causes[x].name, name, strlen(causes[x].name)) == 0)
524 return causes[x].cause;
526 return -1;
529 /*! \brief Gives the string form of a given channel state */
530 char *ast_state2str(enum ast_channel_state state)
532 char *buf;
534 switch(state) {
535 case AST_STATE_DOWN:
536 return "Down";
537 case AST_STATE_RESERVED:
538 return "Rsrvd";
539 case AST_STATE_OFFHOOK:
540 return "OffHook";
541 case AST_STATE_DIALING:
542 return "Dialing";
543 case AST_STATE_RING:
544 return "Ring";
545 case AST_STATE_RINGING:
546 return "Ringing";
547 case AST_STATE_UP:
548 return "Up";
549 case AST_STATE_BUSY:
550 return "Busy";
551 case AST_STATE_DIALING_OFFHOOK:
552 return "Dialing Offhook";
553 case AST_STATE_PRERING:
554 return "Pre-ring";
555 default:
556 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
557 return "Unknown";
558 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
559 return buf;
563 /*! \brief Gives the string form of a given transfer capability */
564 char *ast_transfercapability2str(int transfercapability)
566 switch(transfercapability) {
567 case AST_TRANS_CAP_SPEECH:
568 return "SPEECH";
569 case AST_TRANS_CAP_DIGITAL:
570 return "DIGITAL";
571 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
572 return "RESTRICTED_DIGITAL";
573 case AST_TRANS_CAP_3_1K_AUDIO:
574 return "3K1AUDIO";
575 case AST_TRANS_CAP_DIGITAL_W_TONES:
576 return "DIGITAL_W_TONES";
577 case AST_TRANS_CAP_VIDEO:
578 return "VIDEO";
579 default:
580 return "UNKNOWN";
584 /*! \brief Pick the best audio codec */
585 int ast_best_codec(int fmts)
587 /* This just our opinion, expressed in code. We are asked to choose
588 the best codec to use, given no information */
589 int x;
590 static int prefs[] =
592 /*! Okay, ulaw is used by all telephony equipment, so start with it */
593 AST_FORMAT_ULAW,
594 /*! Unless of course, you're a silly European, so then prefer ALAW */
595 AST_FORMAT_ALAW,
596 /*! Okay, well, signed linear is easy to translate into other stuff */
597 AST_FORMAT_SLINEAR,
598 /*! G.726 is standard ADPCM, in RFC3551 packing order */
599 AST_FORMAT_G726,
600 /*! G.726 is standard ADPCM, in AAL2 packing order */
601 AST_FORMAT_G726_AAL2,
602 /*! ADPCM has great sound quality and is still pretty easy to translate */
603 AST_FORMAT_ADPCM,
604 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
605 translate and sounds pretty good */
606 AST_FORMAT_GSM,
607 /*! iLBC is not too bad */
608 AST_FORMAT_ILBC,
609 /*! Speex is free, but computationally more expensive than GSM */
610 AST_FORMAT_SPEEX,
611 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
612 to use it */
613 AST_FORMAT_LPC10,
614 /*! G.729a is faster than 723 and slightly less expensive */
615 AST_FORMAT_G729A,
616 /*! Down to G.723.1 which is proprietary but at least designed for voice */
617 AST_FORMAT_G723_1,
620 /* Strip out video */
621 fmts &= AST_FORMAT_AUDIO_MASK;
623 /* Find the first preferred codec in the format given */
624 for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
625 if (fmts & prefs[x])
626 return prefs[x];
627 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
628 return 0;
631 static const struct ast_channel_tech null_tech = {
632 .type = "NULL",
633 .description = "Null channel (should not see this)",
636 /*! \brief Create a new channel structure */
637 struct ast_channel *ast_channel_alloc(int needqueue, int state, const char *cid_num, const char *cid_name, const char *name_fmt, ...)
639 struct ast_channel *tmp;
640 int x;
641 int flags;
642 struct varshead *headp;
643 va_list ap1, ap2;
645 /* If shutting down, don't allocate any new channels */
646 if (shutting_down) {
647 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
648 return NULL;
651 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
652 return NULL;
654 if (!(tmp->sched = sched_context_create())) {
655 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
656 free(tmp);
657 return NULL;
660 ast_string_field_init(tmp, 128);
662 /* Don't bother initializing the last two FD here, because they
663 will *always* be set just a few lines down (AST_TIMING_FD,
664 AST_ALERT_FD). */
665 for (x = 0; x < AST_MAX_FDS - 2; x++)
666 tmp->fds[x] = -1;
668 #ifdef HAVE_ZAPTEL
669 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
670 if (tmp->timingfd > -1) {
671 /* Check if timing interface supports new
672 ping/pong scheme */
673 flags = 1;
674 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
675 needqueue = 0;
677 #else
678 tmp->timingfd = -1;
679 #endif
681 if (needqueue) {
682 if (pipe(tmp->alertpipe)) {
683 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
684 ast_string_field_free_pools(tmp);
685 free(tmp);
686 return NULL;
687 } else {
688 flags = fcntl(tmp->alertpipe[0], F_GETFL);
689 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
690 flags = fcntl(tmp->alertpipe[1], F_GETFL);
691 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
693 } else /* Make sure we've got it done right if they don't */
694 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
696 /* Always watch the alertpipe */
697 tmp->fds[AST_ALERT_FD] = tmp->alertpipe[0];
698 /* And timing pipe */
699 tmp->fds[AST_TIMING_FD] = tmp->timingfd;
700 ast_string_field_set(tmp, name, "**Unknown**");
702 /* Initial state */
703 tmp->_state = state;
705 tmp->streamid = -1;
707 tmp->fin = global_fin;
708 tmp->fout = global_fout;
710 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
711 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
712 ast_atomic_fetchadd_int(&uniqueint, 1));
713 } else {
714 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
715 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
718 if (!ast_strlen_zero(name_fmt)) {
719 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
720 * And they all use slightly different formats for their name string.
721 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
722 * This means, that the stringfields must have a routine that takes the va_lists directly, and
723 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
724 * This new function was written so this can be accomplished.
726 va_start(ap1, name_fmt);
727 va_start(ap2, name_fmt);
728 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
729 va_end(ap1);
730 va_end(ap2);
732 /* and now, since the channel structure is built, and has its name, let's call the
733 * manager event generator with this Newchannel event. This is the proper and correct
734 * place to make this call, but you sure do have to pass a lot of data into this func
735 * to do it here!
737 manager_event(EVENT_FLAG_CALL, "Newchannel",
738 "Channel: %s\r\n"
739 "State: %s\r\n"
740 "CallerIDNum: %s\r\n"
741 "CallerIDName: %s\r\n"
742 "Uniqueid: %s\r\n",
743 tmp->name, ast_state2str(state),
744 S_OR(cid_num, "<unknown>"),
745 S_OR(cid_name, "<unknown>"),
746 tmp->uniqueid);
749 headp = &tmp->varshead;
750 AST_LIST_HEAD_INIT_NOLOCK(headp);
752 ast_mutex_init(&tmp->lock);
754 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
756 strcpy(tmp->context, "default");
757 strcpy(tmp->exten, "s");
758 tmp->priority = 1;
760 ast_string_field_set(tmp, language, defaultlanguage);
761 tmp->amaflags = ast_default_amaflags;
762 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
764 tmp->tech = &null_tech;
766 AST_LIST_LOCK(&channels);
767 AST_LIST_INSERT_HEAD(&channels, tmp, chan_list);
768 AST_LIST_UNLOCK(&channels);
770 return tmp;
773 /*! \brief Queue an outgoing media frame */
774 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
776 struct ast_frame *f;
777 struct ast_frame *cur;
778 int blah = 1;
779 int qlen = 0;
781 /* Build us a copy and free the original one */
782 if (!(f = ast_frdup(fin))) {
783 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
784 return -1;
786 ast_channel_lock(chan);
788 /* See if the last frame on the queue is a hangup, if so don't queue anything */
789 if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
790 ast_frfree(f);
791 ast_channel_unlock(chan);
792 return 0;
795 /* Count how many frames exist on the queue */
796 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
797 qlen++;
800 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
801 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
802 if (fin->frametype != AST_FRAME_VOICE) {
803 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
804 CRASH;
805 } else {
806 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
807 ast_frfree(f);
808 ast_channel_unlock(chan);
809 return 0;
812 AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
813 if (chan->alertpipe[1] > -1) {
814 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
815 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
816 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
817 #ifdef HAVE_ZAPTEL
818 } else if (chan->timingfd > -1) {
819 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
820 #endif
821 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
822 pthread_kill(chan->blocker, SIGURG);
824 ast_channel_unlock(chan);
825 return 0;
828 /*! \brief Queue a hangup frame for channel */
829 int ast_queue_hangup(struct ast_channel *chan)
831 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
832 /* Yeah, let's not change a lock-critical value without locking */
833 if (!ast_channel_trylock(chan)) {
834 chan->_softhangup |= AST_SOFTHANGUP_DEV;
835 ast_channel_unlock(chan);
837 return ast_queue_frame(chan, &f);
840 /*! \brief Queue a control frame */
841 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
843 struct ast_frame f = { AST_FRAME_CONTROL, };
845 f.subclass = control;
847 return ast_queue_frame(chan, &f);
850 /*! \brief Queue a control frame with payload */
851 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
852 const void *data, size_t datalen)
854 struct ast_frame f = { AST_FRAME_CONTROL, };
856 f.subclass = control;
857 f.data = (void *) data;
858 f.datalen = datalen;
860 return ast_queue_frame(chan, &f);
863 /*! \brief Set defer DTMF flag on channel */
864 int ast_channel_defer_dtmf(struct ast_channel *chan)
866 int pre = 0;
868 if (chan) {
869 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
870 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
872 return pre;
875 /*! \brief Unset defer DTMF flag on channel */
876 void ast_channel_undefer_dtmf(struct ast_channel *chan)
878 if (chan)
879 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
883 * \brief Helper function to find channels.
885 * It supports these modes:
887 * prev != NULL : get channel next in list after prev
888 * name != NULL : get channel with matching name
889 * name != NULL && namelen != 0 : get channel whose name starts with prefix
890 * exten != NULL : get channel whose exten or macroexten matches
891 * context != NULL && exten != NULL : get channel whose context or macrocontext
893 * It returns with the channel's lock held. If getting the individual lock fails,
894 * unlock and retry quickly up to 10 times, then give up.
896 * \note XXX Note that this code has cost O(N) because of the need to verify
897 * that the object is still on the global list.
899 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
900 * can only be done with the lock held or someone could delete the
901 * object while we work on it. This causes some ugliness in the code.
902 * Note that removing the first ast_log() may be harmful, as it would
903 * shorten the retry period and possibly cause failures.
904 * We should definitely go for a better scheme that is deadlock-free.
906 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
907 const char *name, const int namelen,
908 const char *context, const char *exten)
910 const char *msg = prev ? "deadlock" : "initial deadlock";
911 int retries;
912 struct ast_channel *c;
914 for (retries = 0; retries < 10; retries++) {
915 int done;
916 AST_LIST_LOCK(&channels);
917 AST_LIST_TRAVERSE(&channels, c, chan_list) {
918 if (prev) { /* look for next item */
919 if (c != prev) /* not this one */
920 continue;
921 /* found, prepare to return c->next */
922 c = AST_LIST_NEXT(c, chan_list);
924 if (name) { /* want match by name */
925 if ((!namelen && strcasecmp(c->name, name)) ||
926 (namelen && strncasecmp(c->name, name, namelen)))
927 continue; /* name match failed */
928 } else if (exten) {
929 if (context && strcasecmp(c->context, context) &&
930 strcasecmp(c->macrocontext, context))
931 continue; /* context match failed */
932 if (strcasecmp(c->exten, exten) &&
933 strcasecmp(c->macroexten, exten))
934 continue; /* exten match failed */
936 /* if we get here, c points to the desired record */
937 break;
939 /* exit if chan not found or mutex acquired successfully */
940 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
941 done = c == NULL || ast_channel_trylock(c) == 0;
942 if (!done)
943 ast_log(LOG_DEBUG, "Avoiding %s for channel '%p'\n", msg, c);
944 AST_LIST_UNLOCK(&channels);
945 if (done)
946 return c;
947 usleep(1); /* give other threads a chance before retrying */
950 * c is surely not null, but we don't have the lock so cannot
951 * access c->name
953 ast_log(LOG_DEBUG, "Failure, could not lock '%p' after %d retries!\n",
954 c, retries);
956 return NULL;
959 /*! \brief Browse channels in use */
960 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
962 return channel_find_locked(prev, NULL, 0, NULL, NULL);
965 /*! \brief Get channel by name and lock it */
966 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
968 return channel_find_locked(NULL, name, 0, NULL, NULL);
971 /*! \brief Get channel by name prefix and lock it */
972 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
974 return channel_find_locked(NULL, name, namelen, NULL, NULL);
977 /*! \brief Get next channel by name prefix and lock it */
978 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
979 const int namelen)
981 return channel_find_locked(chan, name, namelen, NULL, NULL);
984 /*! \brief Get channel by exten (and optionally context) and lock it */
985 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
987 return channel_find_locked(NULL, NULL, 0, context, exten);
990 /*! \brief Get next channel by exten (and optionally context) and lock it */
991 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
992 const char *context)
994 return channel_find_locked(chan, NULL, 0, context, exten);
997 /*! \brief Wait, look for hangups and condition arg */
998 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1000 struct ast_frame *f;
1002 while (ms > 0) {
1003 if (cond && ((*cond)(data) == 0))
1004 return 0;
1005 ms = ast_waitfor(chan, ms);
1006 if (ms < 0)
1007 return -1;
1008 if (ms > 0) {
1009 f = ast_read(chan);
1010 if (!f)
1011 return -1;
1012 ast_frfree(f);
1015 return 0;
1018 /*! \brief Wait, look for hangups */
1019 int ast_safe_sleep(struct ast_channel *chan, int ms)
1021 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1024 static void free_cid(struct ast_callerid *cid)
1026 if (cid->cid_dnid)
1027 free(cid->cid_dnid);
1028 if (cid->cid_num)
1029 free(cid->cid_num);
1030 if (cid->cid_name)
1031 free(cid->cid_name);
1032 if (cid->cid_ani)
1033 free(cid->cid_ani);
1034 if (cid->cid_rdnis)
1035 free(cid->cid_rdnis);
1038 /*! \brief Free a channel structure */
1039 void ast_channel_free(struct ast_channel *chan)
1041 int fd;
1042 struct ast_var_t *vardata;
1043 struct ast_frame *f;
1044 struct varshead *headp;
1045 struct ast_datastore *datastore = NULL;
1046 char name[AST_CHANNEL_NAME];
1048 headp=&chan->varshead;
1050 AST_LIST_LOCK(&channels);
1051 AST_LIST_REMOVE(&channels, chan, chan_list);
1052 /* Lock and unlock the channel just to be sure nobody
1053 has it locked still */
1054 ast_channel_lock(chan);
1055 ast_channel_unlock(chan);
1056 if (chan->tech_pvt) {
1057 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1058 free(chan->tech_pvt);
1061 if (chan->sched)
1062 sched_context_destroy(chan->sched);
1064 ast_copy_string(name, chan->name, sizeof(name));
1066 /* Stop monitoring */
1067 if (chan->monitor)
1068 chan->monitor->stop( chan, 0 );
1070 /* If there is native format music-on-hold state, free it */
1071 if (chan->music_state)
1072 ast_moh_cleanup(chan);
1074 /* if someone is whispering on the channel, stop them */
1075 if (chan->whisper)
1076 ast_channel_whisper_stop(chan);
1078 /* Free translators */
1079 if (chan->readtrans)
1080 ast_translator_free_path(chan->readtrans);
1081 if (chan->writetrans)
1082 ast_translator_free_path(chan->writetrans);
1083 if (chan->pbx)
1084 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1085 free_cid(&chan->cid);
1086 ast_mutex_destroy(&chan->lock);
1087 /* Close pipes if appropriate */
1088 if ((fd = chan->alertpipe[0]) > -1)
1089 close(fd);
1090 if ((fd = chan->alertpipe[1]) > -1)
1091 close(fd);
1092 if ((fd = chan->timingfd) > -1)
1093 close(fd);
1094 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1095 ast_frfree(f);
1097 /* Get rid of each of the data stores on the channel */
1098 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1099 /* Free the data store */
1100 ast_channel_datastore_free(datastore);
1101 AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1103 /* loop over the variables list, freeing all data and deleting list items */
1104 /* no need to lock the list, as the channel is already locked */
1106 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1107 ast_var_delete(vardata);
1109 /* Destroy the jitterbuffer */
1110 ast_jb_destroy(chan);
1112 ast_string_field_free_pools(chan);
1113 free(chan);
1114 AST_LIST_UNLOCK(&channels);
1116 ast_device_state_changed_literal(name);
1119 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
1121 struct ast_datastore *datastore = NULL;
1123 /* Make sure we at least have type so we can identify this */
1124 if (info == NULL) {
1125 return NULL;
1128 /* Allocate memory for datastore and clear it */
1129 datastore = ast_calloc(1, sizeof(*datastore));
1130 if (datastore == NULL) {
1131 return NULL;
1134 datastore->info = info;
1136 datastore->uid = ast_strdup(uid);
1138 return datastore;
1141 int ast_channel_datastore_free(struct ast_datastore *datastore)
1143 int res = 0;
1145 /* Using the destroy function (if present) destroy the data */
1146 if (datastore->info->destroy != NULL && datastore->data != NULL) {
1147 datastore->info->destroy(datastore->data);
1148 datastore->data = NULL;
1151 /* Free allocated UID memory */
1152 if (datastore->uid != NULL) {
1153 free(datastore->uid);
1154 datastore->uid = NULL;
1157 /* Finally free memory used by ourselves */
1158 free(datastore);
1160 return res;
1163 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1165 int res = 0;
1167 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1169 return res;
1172 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1174 struct ast_datastore *datastore2 = NULL;
1175 int res = -1;
1177 /* Find our position and remove ourselves */
1178 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1179 if (datastore2 == datastore) {
1180 AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1181 res = 0;
1182 break;
1185 AST_LIST_TRAVERSE_SAFE_END
1187 return res;
1190 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
1192 struct ast_datastore *datastore = NULL;
1194 if (info == NULL)
1195 return NULL;
1197 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1198 if (datastore->info == info) {
1199 if (uid != NULL && datastore->uid != NULL) {
1200 if (!strcasecmp(uid, datastore->uid)) {
1201 /* Matched by type AND uid */
1202 break;
1204 } else {
1205 /* Matched by type at least */
1206 break;
1210 AST_LIST_TRAVERSE_SAFE_END
1212 return datastore;
1215 int ast_channel_spy_add(struct ast_channel *chan, struct ast_channel_spy *spy)
1217 /* Link the owner channel to the spy */
1218 spy->chan = chan;
1220 if (!ast_test_flag(spy, CHANSPY_FORMAT_AUDIO)) {
1221 ast_log(LOG_WARNING, "Could not add channel spy '%s' to channel '%s', only audio format spies are supported.\n",
1222 spy->type, chan->name);
1223 return -1;
1226 if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST) && (spy->read_queue.format != AST_FORMAT_SLINEAR)) {
1227 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1228 ast_getformatname(spy->read_queue.format));
1229 return -1;
1232 if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST) && (spy->write_queue.format != AST_FORMAT_SLINEAR)) {
1233 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1234 ast_getformatname(spy->write_queue.format));
1235 return -1;
1238 if (ast_test_flag(spy, CHANSPY_MIXAUDIO) &&
1239 ((spy->read_queue.format != AST_FORMAT_SLINEAR) ||
1240 (spy->write_queue.format != AST_FORMAT_SLINEAR))) {
1241 ast_log(LOG_WARNING, "Cannot provide audio mixing on '%s'-'%s' format spies\n",
1242 ast_getformatname(spy->read_queue.format), ast_getformatname(spy->write_queue.format));
1243 return -1;
1246 if (!chan->spies) {
1247 if (!(chan->spies = ast_calloc(1, sizeof(*chan->spies)))) {
1248 return -1;
1251 AST_LIST_HEAD_INIT_NOLOCK(&chan->spies->list);
1252 AST_LIST_INSERT_HEAD(&chan->spies->list, spy, list);
1253 } else {
1254 AST_LIST_INSERT_TAIL(&chan->spies->list, spy, list);
1257 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1258 ast_cond_init(&spy->trigger, NULL);
1259 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1260 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1263 ast_log(LOG_DEBUG, "Spy %s added to channel %s\n",
1264 spy->type, chan->name);
1266 return 0;
1269 /* Clean up a channel's spy information */
1270 static void spy_cleanup(struct ast_channel *chan)
1272 if (!AST_LIST_EMPTY(&chan->spies->list))
1273 return;
1274 if (chan->spies->read_translator.path)
1275 ast_translator_free_path(chan->spies->read_translator.path);
1276 if (chan->spies->write_translator.path)
1277 ast_translator_free_path(chan->spies->write_translator.path);
1278 free(chan->spies);
1279 chan->spies = NULL;
1280 return;
1283 /* Detach a spy from it's channel */
1284 static void spy_detach(struct ast_channel_spy *spy, struct ast_channel *chan)
1286 ast_mutex_lock(&spy->lock);
1288 /* We only need to poke them if they aren't already done */
1289 if (spy->status != CHANSPY_DONE) {
1290 /* Indicate to the spy to stop */
1291 spy->status = CHANSPY_STOP;
1292 spy->chan = NULL;
1293 /* Poke the spy if needed */
1294 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1295 ast_cond_signal(&spy->trigger);
1298 /* Print it out while we still have a lock so the structure can't go away (if signalled above) */
1299 ast_log(LOG_DEBUG, "Spy %s removed from channel %s\n", spy->type, chan->name);
1301 ast_mutex_unlock(&spy->lock);
1303 return;
1306 void ast_channel_spy_stop_by_type(struct ast_channel *chan, const char *type)
1308 struct ast_channel_spy *spy = NULL;
1310 if (!chan->spies)
1311 return;
1313 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1314 ast_mutex_lock(&spy->lock);
1315 if ((spy->type == type) && (spy->status == CHANSPY_RUNNING)) {
1316 ast_mutex_unlock(&spy->lock);
1317 AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1318 spy_detach(spy, chan);
1319 } else
1320 ast_mutex_unlock(&spy->lock);
1322 AST_LIST_TRAVERSE_SAFE_END
1323 spy_cleanup(chan);
1326 void ast_channel_spy_trigger_wait(struct ast_channel_spy *spy)
1328 struct timeval tv;
1329 struct timespec ts;
1331 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
1332 ts.tv_sec = tv.tv_sec;
1333 ts.tv_nsec = tv.tv_usec * 1000;
1335 ast_cond_timedwait(&spy->trigger, &spy->lock, &ts);
1338 void ast_channel_spy_remove(struct ast_channel *chan, struct ast_channel_spy *spy)
1340 if (!chan->spies)
1341 return;
1343 AST_LIST_REMOVE(&chan->spies->list, spy, list);
1344 spy_detach(spy, chan);
1345 spy_cleanup(chan);
1348 void ast_channel_spy_free(struct ast_channel_spy *spy)
1350 struct ast_frame *f = NULL;
1352 if (spy->status == CHANSPY_DONE)
1353 return;
1355 /* Switch status to done in case we get called twice */
1356 spy->status = CHANSPY_DONE;
1358 /* Drop any frames in the queue */
1359 while ((f = AST_LIST_REMOVE_HEAD(&spy->write_queue.list, frame_list)))
1360 ast_frfree(f);
1361 while ((f = AST_LIST_REMOVE_HEAD(&spy->read_queue.list, frame_list)))
1362 ast_frfree(f);
1364 /* Destroy the condition if in use */
1365 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1366 ast_cond_destroy(&spy->trigger);
1368 /* Destroy our mutex since it is no longer in use */
1369 ast_mutex_destroy(&spy->lock);
1371 return;
1374 static void detach_spies(struct ast_channel *chan)
1376 struct ast_channel_spy *spy = NULL;
1378 if (!chan->spies)
1379 return;
1381 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1382 AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1383 spy_detach(spy, chan);
1385 AST_LIST_TRAVERSE_SAFE_END
1387 spy_cleanup(chan);
1390 /*! \brief Softly hangup a channel, don't lock */
1391 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1393 if (option_debug)
1394 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
1395 /* Inform channel driver that we need to be hung up, if it cares */
1396 chan->_softhangup |= cause;
1397 ast_queue_frame(chan, &ast_null_frame);
1398 /* Interrupt any poll call or such */
1399 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1400 pthread_kill(chan->blocker, SIGURG);
1401 return 0;
1404 /*! \brief Softly hangup a channel, lock */
1405 int ast_softhangup(struct ast_channel *chan, int cause)
1407 int res;
1408 ast_channel_lock(chan);
1409 res = ast_softhangup_nolock(chan, cause);
1410 ast_channel_unlock(chan);
1411 return res;
1414 enum spy_direction {
1415 SPY_READ,
1416 SPY_WRITE,
1419 #define SPY_QUEUE_SAMPLE_LIMIT 4000 /* half of one second */
1421 static void queue_frame_to_spies(struct ast_channel *chan, struct ast_frame *f, enum spy_direction dir)
1423 struct ast_frame *translated_frame = NULL;
1424 struct ast_channel_spy *spy;
1425 struct channel_spy_trans *trans;
1427 trans = (dir == SPY_READ) ? &chan->spies->read_translator : &chan->spies->write_translator;
1429 AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1430 struct ast_channel_spy_queue *queue;
1431 struct ast_frame *duped_fr;
1433 ast_mutex_lock(&spy->lock);
1435 queue = (dir == SPY_READ) ? &spy->read_queue : &spy->write_queue;
1437 if ((queue->format == AST_FORMAT_SLINEAR) && (f->subclass != AST_FORMAT_SLINEAR)) {
1438 if (!translated_frame) {
1439 if (trans->path && (trans->last_format != f->subclass)) {
1440 ast_translator_free_path(trans->path);
1441 trans->path = NULL;
1443 if (!trans->path) {
1444 ast_log(LOG_DEBUG, "Building translator from %s to SLINEAR for spies on channel %s\n",
1445 ast_getformatname(f->subclass), chan->name);
1446 if ((trans->path = ast_translator_build_path(AST_FORMAT_SLINEAR, f->subclass)) == NULL) {
1447 ast_log(LOG_WARNING, "Cannot build a path from %s to %s\n",
1448 ast_getformatname(f->subclass), ast_getformatname(AST_FORMAT_SLINEAR));
1449 ast_mutex_unlock(&spy->lock);
1450 continue;
1451 } else {
1452 trans->last_format = f->subclass;
1455 if (!(translated_frame = ast_translate(trans->path, f, 0))) {
1456 ast_log(LOG_ERROR, "Translation to %s failed, dropping frame for spies\n",
1457 ast_getformatname(AST_FORMAT_SLINEAR));
1458 ast_mutex_unlock(&spy->lock);
1459 break;
1462 duped_fr = ast_frdup(translated_frame);
1463 } else if (f->subclass != queue->format) {
1464 ast_log(LOG_WARNING, "Spy '%s' on channel '%s' wants format '%s', but frame is '%s', dropping\n",
1465 spy->type, chan->name,
1466 ast_getformatname(queue->format), ast_getformatname(f->subclass));
1467 ast_mutex_unlock(&spy->lock);
1468 continue;
1469 } else
1470 duped_fr = ast_frdup(f);
1472 AST_LIST_INSERT_TAIL(&queue->list, duped_fr, frame_list);
1474 queue->samples += f->samples;
1476 if (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1477 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1478 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1479 case CHANSPY_TRIGGER_READ:
1480 if (dir == SPY_WRITE) {
1481 ast_set_flag(spy, CHANSPY_TRIGGER_WRITE);
1482 ast_clear_flag(spy, CHANSPY_TRIGGER_READ);
1483 if (option_debug)
1484 ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to write-trigger mode\n",
1485 spy->type, chan->name);
1487 break;
1488 case CHANSPY_TRIGGER_WRITE:
1489 if (dir == SPY_READ) {
1490 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1491 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1492 if (option_debug)
1493 ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to read-trigger mode\n",
1494 spy->type, chan->name);
1496 break;
1498 if (option_debug)
1499 ast_log(LOG_DEBUG, "Triggering queue flush for spy '%s' on '%s'\n",
1500 spy->type, chan->name);
1501 ast_set_flag(spy, CHANSPY_TRIGGER_FLUSH);
1502 ast_cond_signal(&spy->trigger);
1503 } else {
1504 if (option_debug)
1505 ast_log(LOG_DEBUG, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1506 spy->type, chan->name, (dir == SPY_READ) ? "read" : "write");
1507 while (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1508 struct ast_frame *drop = AST_LIST_REMOVE_HEAD(&queue->list, frame_list);
1509 queue->samples -= drop->samples;
1510 ast_frfree(drop);
1513 } else {
1514 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1515 case CHANSPY_TRIGGER_READ:
1516 if (dir == SPY_READ)
1517 ast_cond_signal(&spy->trigger);
1518 break;
1519 case CHANSPY_TRIGGER_WRITE:
1520 if (dir == SPY_WRITE)
1521 ast_cond_signal(&spy->trigger);
1522 break;
1526 ast_mutex_unlock(&spy->lock);
1529 if (translated_frame)
1530 ast_frfree(translated_frame);
1533 static void free_translation(struct ast_channel *clone)
1535 if (clone->writetrans)
1536 ast_translator_free_path(clone->writetrans);
1537 if (clone->readtrans)
1538 ast_translator_free_path(clone->readtrans);
1539 clone->writetrans = NULL;
1540 clone->readtrans = NULL;
1541 clone->rawwriteformat = clone->nativeformats;
1542 clone->rawreadformat = clone->nativeformats;
1545 /*! \brief Hangup a channel */
1546 int ast_hangup(struct ast_channel *chan)
1548 int res = 0;
1550 /* Don't actually hang up a channel that will masquerade as someone else, or
1551 if someone is going to masquerade as us */
1552 ast_channel_lock(chan);
1554 detach_spies(chan); /* get rid of spies */
1556 if (chan->masq) {
1557 if (ast_do_masquerade(chan))
1558 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1561 if (chan->masq) {
1562 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1563 ast_channel_unlock(chan);
1564 return 0;
1566 /* If this channel is one which will be masqueraded into something,
1567 mark it as a zombie already, so we know to free it later */
1568 if (chan->masqr) {
1569 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1570 ast_channel_unlock(chan);
1571 return 0;
1573 free_translation(chan);
1574 /* Close audio stream */
1575 if (chan->stream) {
1576 ast_closestream(chan->stream);
1577 chan->stream = NULL;
1579 /* Close video stream */
1580 if (chan->vstream) {
1581 ast_closestream(chan->vstream);
1582 chan->vstream = NULL;
1584 if (chan->sched) {
1585 sched_context_destroy(chan->sched);
1586 chan->sched = NULL;
1589 if (chan->generatordata) /* Clear any tone stuff remaining */
1590 chan->generator->release(chan, chan->generatordata);
1591 chan->generatordata = NULL;
1592 chan->generator = NULL;
1593 if (chan->cdr) { /* End the CDR if it hasn't already */
1594 ast_cdr_end(chan->cdr);
1595 ast_cdr_detach(chan->cdr); /* Post and Free the CDR */
1596 chan->cdr = NULL;
1598 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1599 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1600 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1601 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1602 CRASH;
1604 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1605 if (option_debug)
1606 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1607 if (chan->tech->hangup)
1608 res = chan->tech->hangup(chan);
1609 } else {
1610 if (option_debug)
1611 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1614 ast_channel_unlock(chan);
1615 manager_event(EVENT_FLAG_CALL, "Hangup",
1616 "Channel: %s\r\n"
1617 "Uniqueid: %s\r\n"
1618 "Cause: %d\r\n"
1619 "Cause-txt: %s\r\n",
1620 chan->name,
1621 chan->uniqueid,
1622 chan->hangupcause,
1623 ast_cause2str(chan->hangupcause)
1625 ast_channel_free(chan);
1626 return res;
1629 int ast_answer(struct ast_channel *chan)
1631 int res = 0;
1632 ast_channel_lock(chan);
1633 /* You can't answer an outbound call */
1634 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1635 ast_channel_unlock(chan);
1636 return 0;
1638 /* Stop if we're a zombie or need a soft hangup */
1639 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1640 ast_channel_unlock(chan);
1641 return -1;
1643 switch(chan->_state) {
1644 case AST_STATE_RINGING:
1645 case AST_STATE_RING:
1646 if (chan->tech->answer)
1647 res = chan->tech->answer(chan);
1648 ast_setstate(chan, AST_STATE_UP);
1649 ast_cdr_answer(chan->cdr);
1650 break;
1651 case AST_STATE_UP:
1652 ast_cdr_answer(chan->cdr);
1653 break;
1654 default:
1655 break;
1657 ast_channel_unlock(chan);
1658 return res;
1661 void ast_deactivate_generator(struct ast_channel *chan)
1663 ast_channel_lock(chan);
1664 if (chan->generatordata) {
1665 if (chan->generator && chan->generator->release)
1666 chan->generator->release(chan, chan->generatordata);
1667 chan->generatordata = NULL;
1668 chan->generator = NULL;
1669 chan->fds[AST_GENERATOR_FD] = -1;
1670 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1671 ast_settimeout(chan, 0, NULL, NULL);
1673 ast_channel_unlock(chan);
1676 static int generator_force(void *data)
1678 /* Called if generator doesn't have data */
1679 void *tmp;
1680 int res;
1681 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1682 struct ast_channel *chan = data;
1683 tmp = chan->generatordata;
1684 chan->generatordata = NULL;
1685 generate = chan->generator->generate;
1686 res = generate(chan, tmp, 0, 160);
1687 chan->generatordata = tmp;
1688 if (res) {
1689 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1690 ast_deactivate_generator(chan);
1692 return 0;
1695 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1697 int res = 0;
1699 ast_channel_lock(chan);
1701 if (chan->generatordata) {
1702 if (chan->generator && chan->generator->release)
1703 chan->generator->release(chan, chan->generatordata);
1704 chan->generatordata = NULL;
1707 ast_prod(chan);
1708 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1709 res = -1;
1712 if (!res) {
1713 ast_settimeout(chan, 160, generator_force, chan);
1714 chan->generator = gen;
1717 ast_channel_unlock(chan);
1719 return res;
1722 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1723 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1725 int winner = -1;
1726 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1727 return winner;
1730 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1731 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1732 int *exception, int *outfd, int *ms)
1734 struct timeval start = { 0 , 0 };
1735 struct pollfd *pfds;
1736 int res;
1737 long rms;
1738 int x, y, max;
1739 int sz;
1740 time_t now = 0;
1741 long whentohangup = 0, diff;
1742 struct ast_channel *winner = NULL;
1743 struct fdmap {
1744 int chan;
1745 int fdno;
1746 } *fdmap;
1748 sz = n * AST_MAX_FDS + nfds;
1749 pfds = alloca(sizeof(*pfds) * sz);
1750 fdmap = alloca(sizeof(*fdmap) * sz);
1752 if (outfd)
1753 *outfd = -99999;
1754 if (exception)
1755 *exception = 0;
1757 /* Perform any pending masquerades */
1758 for (x=0; x < n; x++) {
1759 ast_channel_lock(c[x]);
1760 if (c[x]->masq) {
1761 if (ast_do_masquerade(c[x])) {
1762 ast_log(LOG_WARNING, "Masquerade failed\n");
1763 *ms = -1;
1764 ast_channel_unlock(c[x]);
1765 return NULL;
1768 if (c[x]->whentohangup) {
1769 if (!whentohangup)
1770 time(&now);
1771 diff = c[x]->whentohangup - now;
1772 if (diff < 1) {
1773 /* Should already be hungup */
1774 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1775 ast_channel_unlock(c[x]);
1776 return c[x];
1778 if (!whentohangup || (diff < whentohangup))
1779 whentohangup = diff;
1781 ast_channel_unlock(c[x]);
1783 /* Wait full interval */
1784 rms = *ms;
1785 if (whentohangup) {
1786 rms = whentohangup * 1000; /* timeout in milliseconds */
1787 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1788 rms = *ms;
1791 * Build the pollfd array, putting the channels' fds first,
1792 * followed by individual fds. Order is important because
1793 * individual fd's must have priority over channel fds.
1795 max = 0;
1796 for (x=0; x<n; x++) {
1797 for (y=0; y<AST_MAX_FDS; y++) {
1798 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1799 fdmap[max].chan = x; /* channel x is linked to this pfds */
1800 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1802 CHECK_BLOCKING(c[x]);
1804 /* Add the individual fds */
1805 for (x=0; x<nfds; x++) {
1806 fdmap[max].chan = -1;
1807 max += ast_add_fd(&pfds[max], fds[x]);
1810 if (*ms > 0)
1811 start = ast_tvnow();
1813 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1814 do {
1815 int kbrms = rms;
1816 if (kbrms > 600000)
1817 kbrms = 600000;
1818 res = poll(pfds, max, kbrms);
1819 if (!res)
1820 rms -= kbrms;
1821 } while (!res && (rms > 0));
1822 } else {
1823 res = poll(pfds, max, rms);
1825 for (x=0; x<n; x++)
1826 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1827 if (res < 0) { /* Simulate a timeout if we were interrupted */
1828 if (errno != EINTR)
1829 *ms = -1;
1830 return NULL;
1832 if (whentohangup) { /* if we have a timeout, check who expired */
1833 time(&now);
1834 for (x=0; x<n; x++) {
1835 if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1836 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1837 if (winner == NULL)
1838 winner = c[x];
1842 if (res == 0) { /* no fd ready, reset timeout and done */
1843 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1844 return winner;
1847 * Then check if any channel or fd has a pending event.
1848 * Remember to check channels first and fds last, as they
1849 * must have priority on setting 'winner'
1851 for (x = 0; x < max; x++) {
1852 res = pfds[x].revents;
1853 if (res == 0)
1854 continue;
1855 if (fdmap[x].chan >= 0) { /* this is a channel */
1856 winner = c[fdmap[x].chan]; /* override previous winners */
1857 if (res & POLLPRI)
1858 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1859 else
1860 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1861 winner->fdno = fdmap[x].fdno;
1862 } else { /* this is an fd */
1863 if (outfd)
1864 *outfd = pfds[x].fd;
1865 if (exception)
1866 *exception = (res & POLLPRI) ? -1 : 0;
1867 winner = NULL;
1870 if (*ms > 0) {
1871 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1872 if (*ms < 0)
1873 *ms = 0;
1875 return winner;
1878 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1880 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1883 int ast_waitfor(struct ast_channel *c, int ms)
1885 int oldms = ms; /* -1 if no timeout */
1887 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1888 if ((ms < 0) && (oldms < 0))
1889 ms = 0;
1890 return ms;
1893 /* XXX never to be called with ms = -1 */
1894 int ast_waitfordigit(struct ast_channel *c, int ms)
1896 return ast_waitfordigit_full(c, ms, -1, -1);
1899 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1901 int res = -1;
1902 #ifdef HAVE_ZAPTEL
1903 if (c->timingfd > -1) {
1904 if (!func) {
1905 samples = 0;
1906 data = 0;
1908 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1909 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1910 c->timingfunc = func;
1911 c->timingdata = data;
1913 #endif
1914 return res;
1917 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1920 /* Stop if we're a zombie or need a soft hangup */
1921 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1922 return -1;
1923 /* Wait for a digit, no more than ms milliseconds total. */
1924 while (ms) {
1925 struct ast_channel *rchan;
1926 int outfd;
1928 errno = 0;
1929 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1930 if (!rchan && outfd < 0 && ms) {
1931 if (errno == 0 || errno == EINTR)
1932 continue;
1933 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1934 return -1;
1935 } else if (outfd > -1) {
1936 /* The FD we were watching has something waiting */
1937 return 1;
1938 } else if (rchan) {
1939 int res;
1940 struct ast_frame *f = ast_read(c);
1941 if (!f)
1942 return -1;
1944 switch(f->frametype) {
1945 case AST_FRAME_DTMF:
1946 res = f->subclass;
1947 ast_frfree(f);
1948 return res;
1949 case AST_FRAME_CONTROL:
1950 switch(f->subclass) {
1951 case AST_CONTROL_HANGUP:
1952 ast_frfree(f);
1953 return -1;
1954 case AST_CONTROL_RINGING:
1955 case AST_CONTROL_ANSWER:
1956 /* Unimportant */
1957 break;
1958 default:
1959 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1960 break;
1962 break;
1963 case AST_FRAME_VOICE:
1964 /* Write audio if appropriate */
1965 if (audiofd > -1)
1966 write(audiofd, f->data, f->datalen);
1967 default:
1968 /* Ignore */
1969 break;
1971 ast_frfree(f);
1974 return 0; /* Time is up */
1977 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
1979 struct ast_frame *f = NULL; /* the return value */
1980 int blah;
1981 int prestate;
1983 /* this function is very long so make sure there is only one return
1984 * point at the end (there is only one exception to this).
1986 ast_channel_lock(chan);
1987 if (chan->masq) {
1988 if (ast_do_masquerade(chan))
1989 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1990 else
1991 f = &ast_null_frame;
1992 goto done;
1995 /* Stop if we're a zombie or need a soft hangup */
1996 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1997 if (chan->generator)
1998 ast_deactivate_generator(chan);
1999 goto done;
2001 prestate = chan->_state;
2003 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) &&
2004 !ast_strlen_zero(chan->dtmfq)) {
2005 /* We have DTMF that has been deferred. Return it now */
2006 chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2007 chan->dtmff.subclass = chan->dtmfq[0];
2008 /* Drop first digit from the buffer */
2009 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2010 f = &chan->dtmff;
2011 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2012 chan->emulate_dtmf_digit = f->subclass;
2013 chan->emulate_dtmf_samples = AST_DEFAULT_EMULATE_DTMF_SAMPLES;
2014 goto done;
2017 /* Read and ignore anything on the alertpipe, but read only
2018 one sizeof(blah) per frame that we send from it */
2019 if (chan->alertpipe[0] > -1)
2020 read(chan->alertpipe[0], &blah, sizeof(blah));
2022 #ifdef HAVE_ZAPTEL
2023 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2024 int res;
2026 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2027 blah = -1;
2028 /* IF we can't get event, assume it's an expired as-per the old interface */
2029 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
2030 if (res)
2031 blah = ZT_EVENT_TIMER_EXPIRED;
2033 if (blah == ZT_EVENT_TIMER_PING) {
2034 if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2035 /* Acknowledge PONG unless we need it again */
2036 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
2037 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2040 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
2041 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
2042 if (chan->timingfunc) {
2043 /* save a copy of func/data before unlocking the channel */
2044 int (*func)(void *) = chan->timingfunc;
2045 void *data = chan->timingdata;
2046 ast_channel_unlock(chan);
2047 func(data);
2048 } else {
2049 blah = 0;
2050 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
2051 chan->timingdata = NULL;
2052 ast_channel_unlock(chan);
2054 /* cannot 'goto done' because the channel is already unlocked */
2055 return &ast_null_frame;
2056 } else
2057 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2058 } else
2059 #endif
2060 if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2061 /* if the AST_GENERATOR_FD is set, call the generator with args
2062 * set to -1 so it can do whatever it needs to.
2064 void *tmp = chan->generatordata;
2065 chan->generatordata = NULL; /* reset to let ast_write get through */
2066 chan->generator->generate(chan, tmp, -1, -1);
2067 chan->generatordata = tmp;
2068 f = &ast_null_frame;
2069 goto done;
2072 /* Check for pending read queue */
2073 if (!AST_LIST_EMPTY(&chan->readq)) {
2074 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2075 /* Interpret hangup and return NULL */
2076 /* XXX why not the same for frames from the channel ? */
2077 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2078 ast_frfree(f);
2079 f = NULL;
2081 } else {
2082 chan->blocker = pthread_self();
2083 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2084 if (chan->tech->exception)
2085 f = chan->tech->exception(chan);
2086 else {
2087 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2088 f = &ast_null_frame;
2090 /* Clear the exception flag */
2091 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2092 } else if (chan->tech->read)
2093 f = chan->tech->read(chan);
2094 else
2095 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2098 if (f) {
2099 /* if the channel driver returned more than one frame, stuff the excess
2100 into the readq for the next ast_read call (note that we can safely assume
2101 that the readq is empty, because otherwise we would not have called into
2102 the channel driver and f would be only a single frame)
2104 if (AST_LIST_NEXT(f, frame_list)) {
2105 AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2106 AST_LIST_NEXT(f, frame_list) = NULL;
2109 switch (f->frametype) {
2110 case AST_FRAME_CONTROL:
2111 if (f->subclass == AST_CONTROL_ANSWER) {
2112 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2113 ast_log(LOG_DEBUG, "Ignoring answer on an inbound call!\n");
2114 ast_frfree(f);
2115 f = &ast_null_frame;
2116 } else if (prestate == AST_STATE_UP) {
2117 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
2118 ast_frfree(f);
2119 f = &ast_null_frame;
2120 } else {
2121 /* Answer the CDR */
2122 ast_setstate(chan, AST_STATE_UP);
2123 ast_cdr_answer(chan->cdr);
2126 break;
2127 case AST_FRAME_DTMF_END:
2128 ast_log(LOG_DTMF, "DTMF end '%c' received on %s\n", f->subclass, chan->name);
2129 if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
2130 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
2131 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2132 else
2133 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2134 ast_frfree(f);
2135 f = &ast_null_frame;
2136 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2137 f->frametype = AST_FRAME_DTMF_BEGIN;
2138 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2139 chan->emulate_dtmf_digit = f->subclass;
2140 if (f->samples)
2141 chan->emulate_dtmf_samples = f->samples;
2142 else
2143 chan->emulate_dtmf_samples = AST_DEFAULT_EMULATE_DTMF_SAMPLES;
2144 } else
2145 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2146 break;
2147 case AST_FRAME_DTMF_BEGIN:
2148 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2149 if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF)) {
2150 ast_frfree(f);
2151 f = &ast_null_frame;
2152 } else
2153 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2154 break;
2155 case AST_FRAME_VOICE:
2156 /* The EMULATE_DTMF flag must be cleared here as opposed to when the samples
2157 * first get to zero, because we want to make sure we pass at least one
2158 * voice frame through before starting the next digit, to ensure a gap
2159 * between DTMF digits. */
2160 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_samples) {
2161 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2162 chan->emulate_dtmf_digit = 0;
2165 if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2166 ast_frfree(f);
2167 f = &ast_null_frame;
2168 } else if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2169 if (f->samples >= chan->emulate_dtmf_samples) {
2170 chan->emulate_dtmf_samples = 0;
2171 f->frametype = AST_FRAME_DTMF_END;
2172 f->subclass = chan->emulate_dtmf_digit;
2173 } else {
2174 chan->emulate_dtmf_samples -= f->samples;
2175 ast_frfree(f);
2176 f = &ast_null_frame;
2178 } else if (!(f->subclass & chan->nativeformats)) {
2179 /* This frame can't be from the current native formats -- drop it on the
2180 floor */
2181 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2182 chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2183 ast_frfree(f);
2184 f = &ast_null_frame;
2185 } else {
2186 if (chan->spies)
2187 queue_frame_to_spies(chan, f, SPY_READ);
2189 if (chan->monitor && chan->monitor->read_stream ) {
2190 /* XXX what does this do ? */
2191 #ifndef MONITOR_CONSTANT_DELAY
2192 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2193 if (jump >= 0) {
2194 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2195 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2196 chan->insmpl += jump + 4 * f->samples;
2197 } else
2198 chan->insmpl+= f->samples;
2199 #else
2200 int jump = chan->outsmpl - chan->insmpl;
2201 if (jump - MONITOR_DELAY >= 0) {
2202 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2203 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2204 chan->insmpl += jump;
2205 } else
2206 chan->insmpl += f->samples;
2207 #endif
2208 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2209 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2210 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2214 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2215 f = &ast_null_frame;
2217 /* Run generator sitting on the line if timing device not available
2218 * and synchronous generation of outgoing frames is necessary */
2219 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
2220 void *tmp = chan->generatordata;
2221 int res;
2223 if (chan->timingfunc) {
2224 if (option_debug > 1)
2225 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2226 ast_settimeout(chan, 0, NULL, NULL);
2229 chan->generatordata = NULL; /* reset, to let writes go through */
2230 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2231 chan->generatordata = tmp;
2232 if (res) {
2233 if (option_debug > 1)
2234 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2235 ast_deactivate_generator(chan);
2238 } else if (f->frametype == AST_FRAME_CNG) {
2239 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2240 if (option_debug > 1)
2241 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2242 ast_settimeout(chan, 160, generator_force, chan);
2246 default:
2247 /* Just pass it on! */
2248 break;
2250 } else {
2251 /* Make sure we always return NULL in the future */
2252 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2253 if (chan->generator)
2254 ast_deactivate_generator(chan);
2255 /* End the CDR if appropriate */
2256 if (chan->cdr)
2257 ast_cdr_end(chan->cdr);
2260 /* High bit prints debugging */
2261 if (chan->fin & DEBUGCHAN_FLAG)
2262 ast_frame_dump(chan->name, f, "<<");
2263 chan->fin = FRAMECOUNT_INC(chan->fin);
2265 done:
2266 ast_channel_unlock(chan);
2267 return f;
2270 int ast_internal_timing_enabled(struct ast_channel *chan)
2272 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2273 if (option_debug > 4)
2274 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);
2275 return ret;
2278 struct ast_frame *ast_read(struct ast_channel *chan)
2280 return __ast_read(chan, 0);
2283 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2285 return __ast_read(chan, 1);
2288 int ast_indicate(struct ast_channel *chan, int condition)
2290 return ast_indicate_data(chan, condition, NULL, 0);
2293 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2295 int res = -1;
2297 ast_channel_lock(chan);
2298 /* Stop if we're a zombie or need a soft hangup */
2299 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2300 ast_channel_unlock(chan);
2301 return -1;
2303 if (chan->tech->indicate)
2304 res = chan->tech->indicate(chan, condition, data, datalen);
2305 ast_channel_unlock(chan);
2306 if (!chan->tech->indicate || res) {
2308 * Device does not support (that) indication, lets fake
2309 * it by doing our own tone generation. (PM2002)
2311 if (condition < 0)
2312 ast_playtones_stop(chan);
2313 else {
2314 const struct tone_zone_sound *ts = NULL;
2315 switch (condition) {
2316 case AST_CONTROL_RINGING:
2317 ts = ast_get_indication_tone(chan->zone, "ring");
2318 break;
2319 case AST_CONTROL_BUSY:
2320 ts = ast_get_indication_tone(chan->zone, "busy");
2321 break;
2322 case AST_CONTROL_CONGESTION:
2323 ts = ast_get_indication_tone(chan->zone, "congestion");
2324 break;
2326 if (ts && ts->data[0]) {
2327 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2328 ast_playtones_start(chan,0,ts->data, 1);
2329 res = 0;
2330 } else if (condition == AST_CONTROL_PROGRESS) {
2331 /* ast_playtones_stop(chan); */
2332 } else if (condition == AST_CONTROL_PROCEEDING) {
2333 /* Do nothing, really */
2334 } else if (condition == AST_CONTROL_HOLD) {
2335 /* Do nothing.... */
2336 } else if (condition == AST_CONTROL_UNHOLD) {
2337 /* Do nothing.... */
2338 } else if (condition == AST_CONTROL_VIDUPDATE) {
2339 /* Do nothing.... */
2340 } else {
2341 /* not handled */
2342 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2343 res = -1;
2347 return res;
2350 int ast_recvchar(struct ast_channel *chan, int timeout)
2352 int c;
2353 char *buf = ast_recvtext(chan, timeout);
2354 if (buf == NULL)
2355 return -1; /* error or timeout */
2356 c = *(unsigned char *)buf;
2357 free(buf);
2358 return c;
2361 char *ast_recvtext(struct ast_channel *chan, int timeout)
2363 int res, done = 0;
2364 char *buf = NULL;
2366 while (!done) {
2367 struct ast_frame *f;
2368 if (ast_check_hangup(chan))
2369 break;
2370 res = ast_waitfor(chan, timeout);
2371 if (res <= 0) /* timeout or error */
2372 break;
2373 timeout = res; /* update timeout */
2374 f = ast_read(chan);
2375 if (f == NULL)
2376 break; /* no frame */
2377 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2378 done = 1; /* force a break */
2379 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2380 buf = ast_strndup((char *) f->data, f->datalen); /* dup and break */
2381 done = 1;
2383 ast_frfree(f);
2385 return buf;
2388 int ast_sendtext(struct ast_channel *chan, const char *text)
2390 int res = 0;
2391 /* Stop if we're a zombie or need a soft hangup */
2392 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2393 return -1;
2394 CHECK_BLOCKING(chan);
2395 if (chan->tech->send_text)
2396 res = chan->tech->send_text(chan, text);
2397 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2398 return res;
2401 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2403 int res = -1;
2405 if (chan->tech->send_digit_begin)
2406 res = chan->tech->send_digit_begin(chan, digit);
2408 if (res) {
2410 * Device does not support DTMF tones, lets fake
2411 * it by doing our own generation. (PM2002)
2413 static const char* dtmf_tones[] = {
2414 "!941+1336/100,!0/100", /* 0 */
2415 "!697+1209/100,!0/100", /* 1 */
2416 "!697+1336/100,!0/100", /* 2 */
2417 "!697+1477/100,!0/100", /* 3 */
2418 "!770+1209/100,!0/100", /* 4 */
2419 "!770+1336/100,!0/100", /* 5 */
2420 "!770+1477/100,!0/100", /* 6 */
2421 "!852+1209/100,!0/100", /* 7 */
2422 "!852+1336/100,!0/100", /* 8 */
2423 "!852+1477/100,!0/100", /* 9 */
2424 "!697+1633/100,!0/100", /* A */
2425 "!770+1633/100,!0/100", /* B */
2426 "!852+1633/100,!0/100", /* C */
2427 "!941+1633/100,!0/100", /* D */
2428 "!941+1209/100,!0/100", /* * */
2429 "!941+1477/100,!0/100" }; /* # */
2430 if (digit >= '0' && digit <='9')
2431 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2432 else if (digit >= 'A' && digit <= 'D')
2433 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2434 else if (digit == '*')
2435 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2436 else if (digit == '#')
2437 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2438 else {
2439 /* not handled */
2440 ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2444 return 0;
2447 int ast_senddigit_end(struct ast_channel *chan, char digit)
2449 int res = -1;
2451 if (chan->tech->send_digit_end)
2452 res = chan->tech->send_digit_end(chan, digit);
2454 if (res && chan->generator)
2455 ast_playtones_stop(chan);
2457 return 0;
2460 int ast_senddigit(struct ast_channel *chan, char digit)
2462 ast_senddigit_begin(chan, digit);
2464 ast_safe_sleep(chan, 100); /* XXX 100ms ... probably should be configurable */
2466 return ast_senddigit_end(chan, digit);
2469 int ast_prod(struct ast_channel *chan)
2471 struct ast_frame a = { AST_FRAME_VOICE };
2472 char nothing[128];
2474 /* Send an empty audio frame to get things moving */
2475 if (chan->_state != AST_STATE_UP) {
2476 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
2477 a.subclass = chan->rawwriteformat;
2478 a.data = nothing + AST_FRIENDLY_OFFSET;
2479 a.src = "ast_prod";
2480 if (ast_write(chan, &a))
2481 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2483 return 0;
2486 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2488 int res;
2489 if (!chan->tech->write_video)
2490 return 0;
2491 res = ast_write(chan, fr);
2492 if (!res)
2493 res = 1;
2494 return res;
2497 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2499 int res = -1;
2500 struct ast_frame *f = NULL;
2502 /* Stop if we're a zombie or need a soft hangup */
2503 ast_channel_lock(chan);
2504 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2505 goto done;
2507 /* Handle any pending masquerades */
2508 if (chan->masq && ast_do_masquerade(chan)) {
2509 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2510 goto done;
2512 if (chan->masqr) {
2513 res = 0; /* XXX explain, why 0 ? */
2514 goto done;
2516 if (chan->generatordata) {
2517 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2518 ast_deactivate_generator(chan);
2519 else {
2520 res = 0; /* XXX explain, why 0 ? */
2521 goto done;
2524 /* High bit prints debugging */
2525 if (chan->fout & DEBUGCHAN_FLAG)
2526 ast_frame_dump(chan->name, fr, ">>");
2527 CHECK_BLOCKING(chan);
2528 switch(fr->frametype) {
2529 case AST_FRAME_CONTROL:
2530 res = (chan->tech->indicate == NULL) ? 0 :
2531 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2532 break;
2533 case AST_FRAME_DTMF_BEGIN:
2534 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2535 ast_channel_unlock(chan);
2536 res = ast_senddigit_begin(chan, fr->subclass);
2537 ast_channel_lock(chan);
2538 CHECK_BLOCKING(chan);
2539 break;
2540 case AST_FRAME_DTMF_END:
2541 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2542 ast_channel_unlock(chan);
2543 res = ast_senddigit_end(chan, fr->subclass);
2544 ast_channel_lock(chan);
2545 CHECK_BLOCKING(chan);
2546 break;
2547 case AST_FRAME_TEXT:
2548 res = (chan->tech->send_text == NULL) ? 0 :
2549 chan->tech->send_text(chan, (char *) fr->data);
2550 break;
2551 case AST_FRAME_HTML:
2552 res = (chan->tech->send_html == NULL) ? 0 :
2553 chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2554 break;
2555 case AST_FRAME_VIDEO:
2556 /* XXX Handle translation of video codecs one day XXX */
2557 res = (chan->tech->write_video == NULL) ? 0 :
2558 chan->tech->write_video(chan, fr);
2559 break;
2560 case AST_FRAME_MODEM:
2561 res = (chan->tech->write == NULL) ? 0 :
2562 chan->tech->write(chan, fr);
2563 break;
2564 case AST_FRAME_VOICE:
2565 if (chan->tech->write == NULL)
2566 break; /*! \todo XXX should return 0 maybe ? */
2568 /* If someone is whispering on this channel then we must ensure that we are always getting signed linear frames */
2569 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2570 if (fr->subclass == AST_FORMAT_SLINEAR)
2571 f = fr;
2572 else {
2573 ast_mutex_lock(&chan->whisper->lock);
2574 if (chan->writeformat != AST_FORMAT_SLINEAR) {
2575 /* Rebuild the translation path and set our write format back to signed linear */
2576 chan->whisper->original_format = chan->writeformat;
2577 ast_set_write_format(chan, AST_FORMAT_SLINEAR);
2578 if (chan->whisper->path)
2579 ast_translator_free_path(chan->whisper->path);
2580 chan->whisper->path = ast_translator_build_path(AST_FORMAT_SLINEAR, chan->whisper->original_format);
2582 /* Translate frame using the above translation path */
2583 f = (chan->whisper->path) ? ast_translate(chan->whisper->path, fr, 0) : fr;
2584 ast_mutex_unlock(&chan->whisper->lock);
2586 } else {
2587 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2588 if (fr->subclass == chan->rawwriteformat)
2589 f = fr;
2590 else
2591 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2594 /* If we have no frame of audio, then we have to bail out */
2595 if (f == NULL) {
2596 res = 0;
2597 break;
2600 /* If spies are on the channel then queue the frame out to them */
2601 if (chan->spies)
2602 queue_frame_to_spies(chan, f, SPY_WRITE);
2604 /* If Monitor is running on this channel, then we have to write frames out there too */
2605 if (chan->monitor && chan->monitor->write_stream) {
2606 /* XXX must explain this code */
2607 #ifndef MONITOR_CONSTANT_DELAY
2608 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2609 if (jump >= 0) {
2610 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2611 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2612 chan->outsmpl += jump + 4 * f->samples;
2613 } else
2614 chan->outsmpl += f->samples;
2615 #else
2616 int jump = chan->insmpl - chan->outsmpl;
2617 if (jump - MONITOR_DELAY >= 0) {
2618 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2619 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2620 chan->outsmpl += jump;
2621 } else
2622 chan->outsmpl += f->samples;
2623 #endif
2624 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2625 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2626 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2630 /* Finally the good part! Write this out to the channel */
2631 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2632 /* frame is assumed to be in SLINEAR, since that is
2633 required for whisper mode */
2634 ast_frame_adjust_volume(f, -2);
2635 if (ast_slinfactory_available(&chan->whisper->sf) >= f->samples) {
2636 short buf[f->samples];
2637 struct ast_frame whisper = {
2638 .frametype = AST_FRAME_VOICE,
2639 .subclass = AST_FORMAT_SLINEAR,
2640 .data = buf,
2641 .datalen = sizeof(buf),
2642 .samples = f->samples,
2645 ast_mutex_lock(&chan->whisper->lock);
2646 if (ast_slinfactory_read(&chan->whisper->sf, buf, f->samples))
2647 ast_frame_slinear_sum(f, &whisper);
2648 ast_mutex_unlock(&chan->whisper->lock);
2650 /* and now put it through the regular translator */
2651 f = (chan->writetrans) ? ast_translate(chan->writetrans, f, 0) : f;
2654 res = chan->tech->write(chan, f);
2655 break;
2656 case AST_FRAME_NULL:
2657 case AST_FRAME_IAX:
2658 /* Ignore these */
2659 res = 0;
2660 break;
2661 default:
2662 /* At this point, fr is the incoming frame and f is NULL. Channels do
2663 * not expect to get NULL as a frame pointer and will segfault. Hence,
2664 * we output the original frame passed in. */
2665 res = chan->tech->write(chan, fr);
2666 break;
2669 if (f && f != fr)
2670 ast_frfree(f);
2671 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2672 /* Consider a write failure to force a soft hangup */
2673 if (res < 0)
2674 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2675 else {
2676 chan->fout = FRAMECOUNT_INC(chan->fout);
2678 done:
2679 ast_channel_unlock(chan);
2680 return res;
2683 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2684 struct ast_trans_pvt **trans, const int direction)
2686 int native;
2687 int res;
2689 /* Make sure we only consider audio */
2690 fmt &= AST_FORMAT_AUDIO_MASK;
2692 native = chan->nativeformats;
2693 /* Find a translation path from the native format to one of the desired formats */
2694 if (!direction)
2695 /* reading */
2696 res = ast_translator_best_choice(&fmt, &native);
2697 else
2698 /* writing */
2699 res = ast_translator_best_choice(&native, &fmt);
2701 if (res < 0) {
2702 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2703 ast_getformatname(native), ast_getformatname(fmt));
2704 return -1;
2707 /* Now we have a good choice for both. */
2708 ast_channel_lock(chan);
2710 if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2711 /* the channel is already in these formats, so nothing to do */
2712 ast_channel_unlock(chan);
2713 return 0;
2716 *rawformat = native;
2717 /* User perspective is fmt */
2718 *format = fmt;
2719 /* Free any read translation we have right now */
2720 if (*trans)
2721 ast_translator_free_path(*trans);
2722 /* Build a translation path from the raw format to the desired format */
2723 if (!direction)
2724 /* reading */
2725 *trans = ast_translator_build_path(*format, *rawformat);
2726 else
2727 /* writing */
2728 *trans = ast_translator_build_path(*rawformat, *format);
2729 ast_channel_unlock(chan);
2730 if (option_debug)
2731 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2732 direction ? "write" : "read", ast_getformatname(fmt));
2733 return 0;
2736 int ast_set_read_format(struct ast_channel *chan, int fmt)
2738 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2739 &chan->readtrans, 0);
2742 int ast_set_write_format(struct ast_channel *chan, int fmt)
2744 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2745 &chan->writetrans, 1);
2748 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)
2750 int dummy_outstate;
2751 int cause = 0;
2752 struct ast_channel *chan;
2753 int res = 0;
2755 if (outstate)
2756 *outstate = 0;
2757 else
2758 outstate = &dummy_outstate; /* make outstate always a valid pointer */
2760 chan = ast_request(type, format, data, &cause);
2761 if (!chan) {
2762 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2763 /* compute error and return */
2764 if (cause == AST_CAUSE_BUSY)
2765 *outstate = AST_CONTROL_BUSY;
2766 else if (cause == AST_CAUSE_CONGESTION)
2767 *outstate = AST_CONTROL_CONGESTION;
2768 return NULL;
2771 if (oh) {
2772 if (oh->vars)
2773 ast_set_variables(chan, oh->vars);
2774 /* XXX why is this necessary, for the parent_channel perhaps ? */
2775 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2776 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2777 if (oh->parent_channel)
2778 ast_channel_inherit_variables(oh->parent_channel, chan);
2779 if (oh->account)
2780 ast_cdr_setaccount(chan, oh->account);
2782 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2784 if (ast_call(chan, data, 0)) { /* ast_call failed... */
2785 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2786 } else {
2787 res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
2788 while (timeout && chan->_state != AST_STATE_UP) {
2789 struct ast_frame *f;
2790 res = ast_waitfor(chan, timeout);
2791 if (res <= 0) /* error, timeout, or done */
2792 break;
2793 if (timeout > -1)
2794 timeout = res;
2795 f = ast_read(chan);
2796 if (!f) {
2797 *outstate = AST_CONTROL_HANGUP;
2798 res = 0;
2799 break;
2801 if (f->frametype == AST_FRAME_CONTROL) {
2802 switch (f->subclass) {
2803 case AST_CONTROL_RINGING: /* record but keep going */
2804 *outstate = f->subclass;
2805 break;
2807 case AST_CONTROL_BUSY:
2808 case AST_CONTROL_CONGESTION:
2809 case AST_CONTROL_ANSWER:
2810 *outstate = f->subclass;
2811 timeout = 0; /* trick to force exit from the while() */
2812 break;
2814 /* Ignore these */
2815 case AST_CONTROL_PROGRESS:
2816 case AST_CONTROL_PROCEEDING:
2817 case AST_CONTROL_HOLD:
2818 case AST_CONTROL_UNHOLD:
2819 case AST_CONTROL_VIDUPDATE:
2820 case -1: /* Ignore -- just stopping indications */
2821 break;
2823 default:
2824 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2827 ast_frfree(f);
2831 /* Final fixups */
2832 if (oh) {
2833 if (!ast_strlen_zero(oh->context))
2834 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2835 if (!ast_strlen_zero(oh->exten))
2836 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2837 if (oh->priority)
2838 chan->priority = oh->priority;
2840 if (chan->_state == AST_STATE_UP)
2841 *outstate = AST_CONTROL_ANSWER;
2843 if (res <= 0) {
2844 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
2845 ast_cdr_init(chan->cdr, chan);
2846 if (chan->cdr) {
2847 char tmp[256];
2848 snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
2849 ast_cdr_setapp(chan->cdr,"Dial",tmp);
2850 ast_cdr_update(chan);
2851 ast_cdr_start(chan->cdr);
2852 ast_cdr_end(chan->cdr);
2853 /* If the cause wasn't handled properly */
2854 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2855 ast_cdr_failed(chan->cdr);
2857 ast_hangup(chan);
2858 chan = NULL;
2860 return chan;
2863 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2865 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2868 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2870 struct chanlist *chan;
2871 struct ast_channel *c;
2872 int capabilities;
2873 int fmt;
2874 int res;
2875 int foo;
2876 int videoformat = format & AST_FORMAT_VIDEO_MASK;
2878 if (!cause)
2879 cause = &foo;
2880 *cause = AST_CAUSE_NOTDEFINED;
2882 if (AST_LIST_LOCK(&channels)) {
2883 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2884 return NULL;
2887 AST_LIST_TRAVERSE(&backends, chan, list) {
2888 if (strcasecmp(type, chan->tech->type))
2889 continue;
2891 capabilities = chan->tech->capabilities;
2892 fmt = format & AST_FORMAT_AUDIO_MASK;
2893 res = ast_translator_best_choice(&fmt, &capabilities);
2894 if (res < 0) {
2895 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2896 AST_LIST_UNLOCK(&channels);
2897 return NULL;
2899 AST_LIST_UNLOCK(&channels);
2900 if (!chan->tech->requester)
2901 return NULL;
2903 if (!(c = chan->tech->requester(type, capabilities | videoformat, data, cause)))
2904 return NULL;
2906 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
2907 return c;
2910 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2911 *cause = AST_CAUSE_NOSUCHDRIVER;
2912 AST_LIST_UNLOCK(&channels);
2914 return NULL;
2917 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2919 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2920 If the remote end does not answer within the timeout, then do NOT hang up, but
2921 return anyway. */
2922 int res = -1;
2923 /* Stop if we're a zombie or need a soft hangup */
2924 ast_channel_lock(chan);
2925 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2926 if (chan->tech->call)
2927 res = chan->tech->call(chan, addr, timeout);
2928 ast_set_flag(chan, AST_FLAG_OUTGOING);
2930 ast_channel_unlock(chan);
2931 return res;
2935 \brief Transfer a call to dest, if the channel supports transfer
2937 Called by:
2938 \arg app_transfer
2939 \arg the manager interface
2941 int ast_transfer(struct ast_channel *chan, char *dest)
2943 int res = -1;
2945 /* Stop if we're a zombie or need a soft hangup */
2946 ast_channel_lock(chan);
2947 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2948 if (chan->tech->transfer) {
2949 res = chan->tech->transfer(chan, dest);
2950 if (!res)
2951 res = 1;
2952 } else
2953 res = 0;
2955 ast_channel_unlock(chan);
2956 return res;
2959 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2961 return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
2964 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2966 int pos = 0; /* index in the buffer where we accumulate digits */
2967 int to = ftimeout;
2969 /* Stop if we're a zombie or need a soft hangup */
2970 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2971 return -1;
2972 if (!len)
2973 return -1;
2974 for (;;) {
2975 int d;
2976 if (c->stream) {
2977 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2978 ast_stopstream(c);
2979 usleep(1000);
2980 if (!d)
2981 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2982 } else {
2983 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2985 if (d < 0)
2986 return -1;
2987 if (d == 0) {
2988 s[pos]='\0';
2989 return 1;
2991 if (d == 1) {
2992 s[pos]='\0';
2993 return 2;
2995 if (!strchr(enders, d))
2996 s[pos++] = d;
2997 if (strchr(enders, d) || (pos >= len)) {
2998 s[pos]='\0';
2999 return 0;
3001 to = timeout;
3003 /* Never reached */
3004 return 0;
3007 int ast_channel_supports_html(struct ast_channel *chan)
3009 return (chan->tech->send_html) ? 1 : 0;
3012 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3014 if (chan->tech->send_html)
3015 return chan->tech->send_html(chan, subclass, data, datalen);
3016 return -1;
3019 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
3021 return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
3024 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
3026 int src;
3027 int dst;
3029 /* Set up translation from the chan to the peer */
3030 src = chan->nativeformats;
3031 dst = peer->nativeformats;
3032 if (ast_translator_best_choice(&dst, &src) < 0) {
3033 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
3034 return -1;
3037 /* if the best path is not 'pass through', then
3038 transcoding is needed; if desired, force transcode path
3039 to use SLINEAR between channels, but only if there is
3040 no direct conversion available */
3041 if ((src != dst) && ast_opt_transcode_via_slin &&
3042 (ast_translate_path_steps(dst, src) != 1))
3043 dst = AST_FORMAT_SLINEAR;
3044 if (ast_set_read_format(chan, dst) < 0) {
3045 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
3046 return -1;
3048 if (ast_set_write_format(peer, dst) < 0) {
3049 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
3050 return -1;
3053 /* Set up translation from the peer to the chan */
3054 src = peer->nativeformats;
3055 dst = chan->nativeformats;
3056 if (ast_translator_best_choice(&dst, &src) < 0) {
3057 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
3058 return -1;
3061 /* if the best path is not 'pass through', then
3062 transcoding is needed; if desired, force transcode path
3063 to use SLINEAR between channels, but only if there is
3064 no direct conversion available */
3065 if ((src != dst) && ast_opt_transcode_via_slin &&
3066 (ast_translate_path_steps(dst, src) != 1))
3067 dst = AST_FORMAT_SLINEAR;
3068 if (ast_set_read_format(peer, dst) < 0) {
3069 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
3070 return -1;
3072 if (ast_set_write_format(chan, dst) < 0) {
3073 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
3074 return -1;
3076 return 0;
3079 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
3081 int res = -1;
3082 struct ast_channel *final_orig = original, *final_clone = clone;
3084 ast_channel_lock(original);
3085 while (ast_channel_trylock(clone)) {
3086 ast_channel_unlock(original);
3087 usleep(1);
3088 ast_channel_lock(original);
3091 /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
3092 and if so, we don't really want to masquerade it, but its proxy */
3093 if (original->_bridge && (original->_bridge != ast_bridged_channel(original)))
3094 final_orig = original->_bridge;
3096 if (clone->_bridge && (clone->_bridge != ast_bridged_channel(clone)))
3097 final_clone = clone->_bridge;
3099 if ((final_orig != original) || (final_clone != clone)) {
3100 ast_channel_lock(final_orig);
3101 while (ast_channel_trylock(final_clone)) {
3102 ast_channel_unlock(final_orig);
3103 usleep(1);
3104 ast_channel_lock(final_orig);
3106 ast_channel_unlock(clone);
3107 ast_channel_unlock(original);
3108 original = final_orig;
3109 clone = final_clone;
3112 if (original == clone) {
3113 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
3114 ast_channel_unlock(clone);
3115 ast_channel_unlock(original);
3116 return -1;
3119 ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
3120 clone->name, original->name);
3121 if (original->masq) {
3122 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3123 original->masq->name, original->name);
3124 } else if (clone->masqr) {
3125 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3126 clone->name, clone->masqr->name);
3127 } else {
3128 original->masq = clone;
3129 clone->masqr = original;
3130 ast_queue_frame(original, &ast_null_frame);
3131 ast_queue_frame(clone, &ast_null_frame);
3132 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
3133 res = 0;
3136 ast_channel_unlock(clone);
3137 ast_channel_unlock(original);
3139 return res;
3142 void ast_change_name(struct ast_channel *chan, char *newname)
3144 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
3145 ast_string_field_set(chan, name, newname);
3148 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
3150 struct ast_var_t *current, *newvar;
3151 const char *varname;
3153 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
3154 int vartype = 0;
3156 varname = ast_var_full_name(current);
3157 if (!varname)
3158 continue;
3160 if (varname[0] == '_') {
3161 vartype = 1;
3162 if (varname[1] == '_')
3163 vartype = 2;
3166 switch (vartype) {
3167 case 1:
3168 newvar = ast_var_assign(&varname[1], ast_var_value(current));
3169 if (newvar) {
3170 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3171 if (option_debug)
3172 ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
3174 break;
3175 case 2:
3176 newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
3177 if (newvar) {
3178 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3179 if (option_debug)
3180 ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
3182 break;
3183 default:
3184 if (option_debug)
3185 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
3186 break;
3192 \brief Clone channel variables from 'clone' channel into 'original' channel
3194 All variables except those related to app_groupcount are cloned.
3195 Variables are actually _removed_ from 'clone' channel, presumably
3196 because it will subsequently be destroyed.
3198 \note Assumes locks will be in place on both channels when called.
3200 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
3202 struct ast_var_t *varptr;
3204 /* we need to remove all app_groupcount related variables from the original
3205 channel before merging in the clone's variables; any groups assigned to the
3206 original channel should be released, only those assigned to the clone
3207 should remain
3210 AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
3211 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
3212 AST_LIST_REMOVE_CURRENT(&original->varshead, entries);
3213 ast_var_delete(varptr);
3216 AST_LIST_TRAVERSE_SAFE_END;
3218 /* Append variables from clone channel into original channel */
3219 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
3220 if (AST_LIST_FIRST(&clone->varshead))
3221 AST_LIST_APPEND_LIST(&original->varshead, &clone->varshead, entries);
3225 \brief Masquerade a channel
3227 \note Assumes channel will be locked when called
3229 int ast_do_masquerade(struct ast_channel *original)
3231 int x,i;
3232 int res=0;
3233 int origstate;
3234 struct ast_frame *cur;
3235 const struct ast_channel_tech *t;
3236 void *t_pvt;
3237 struct ast_callerid tmpcid;
3238 struct ast_channel *clone = original->masq;
3239 struct ast_channel_spy_list *spy_list = NULL;
3240 struct ast_channel_spy *spy = NULL;
3241 int rformat = original->readformat;
3242 int wformat = original->writeformat;
3243 char newn[100];
3244 char orig[100];
3245 char masqn[100];
3246 char zombn[100];
3248 if (option_debug > 3)
3249 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3250 clone->name, clone->_state, original->name, original->_state);
3252 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
3253 the clone channel into the original channel. Start by killing off the original
3254 channel's backend. I'm not sure we're going to keep this function, because
3255 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3257 /* We need the clone's lock, too */
3258 ast_channel_lock(clone);
3260 if (option_debug > 1)
3261 ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
3263 /* Having remembered the original read/write formats, we turn off any translation on either
3264 one */
3265 free_translation(clone);
3266 free_translation(original);
3269 /* Unlink the masquerade */
3270 original->masq = NULL;
3271 clone->masqr = NULL;
3273 /* Save the original name */
3274 ast_copy_string(orig, original->name, sizeof(orig));
3275 /* Save the new name */
3276 ast_copy_string(newn, clone->name, sizeof(newn));
3277 /* Create the masq name */
3278 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
3280 /* Copy the name from the clone channel */
3281 ast_string_field_set(original, name, newn);
3283 /* Mangle the name of the clone channel */
3284 ast_string_field_set(clone, name, masqn);
3286 /* Notify any managers of the change, first the masq then the other */
3287 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
3288 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
3290 /* Swap the technologies */
3291 t = original->tech;
3292 original->tech = clone->tech;
3293 clone->tech = t;
3295 t_pvt = original->tech_pvt;
3296 original->tech_pvt = clone->tech_pvt;
3297 clone->tech_pvt = t_pvt;
3299 /* Swap the readq's */
3300 cur = AST_LIST_FIRST(&original->readq);
3301 AST_LIST_HEAD_SET_NOLOCK(&original->readq, AST_LIST_FIRST(&clone->readq));
3302 AST_LIST_HEAD_SET_NOLOCK(&clone->readq, cur);
3304 /* Swap the alertpipes */
3305 for (i = 0; i < 2; i++) {
3306 x = original->alertpipe[i];
3307 original->alertpipe[i] = clone->alertpipe[i];
3308 clone->alertpipe[i] = x;
3311 /* Swap the raw formats */
3312 x = original->rawreadformat;
3313 original->rawreadformat = clone->rawreadformat;
3314 clone->rawreadformat = x;
3315 x = original->rawwriteformat;
3316 original->rawwriteformat = clone->rawwriteformat;
3317 clone->rawwriteformat = x;
3319 /* Swap the spies */
3320 spy_list = original->spies;
3321 original->spies = clone->spies;
3322 clone->spies = spy_list;
3324 /* Update channel on respective spy lists if present */
3325 if (original->spies) {
3326 AST_LIST_TRAVERSE(&original->spies->list, spy, list) {
3327 ast_mutex_lock(&spy->lock);
3328 spy->chan = original;
3329 ast_mutex_unlock(&spy->lock);
3332 if (clone->spies) {
3333 AST_LIST_TRAVERSE(&clone->spies->list, spy, list) {
3334 ast_mutex_lock(&spy->lock);
3335 spy->chan = clone;
3336 ast_mutex_unlock(&spy->lock);
3340 /* Save any pending frames on both sides. Start by counting
3341 * how many we're going to need... */
3342 x = 0;
3343 if (original->alertpipe[1] > -1) {
3344 AST_LIST_TRAVERSE(&clone->readq, cur, frame_list)
3345 x++;
3348 /* If we had any, prepend them to the ones already in the queue, and
3349 * load up the alertpipe */
3350 if (AST_LIST_FIRST(&clone->readq)) {
3351 AST_LIST_INSERT_TAIL(&clone->readq, AST_LIST_FIRST(&original->readq), frame_list);
3352 AST_LIST_HEAD_SET_NOLOCK(&original->readq, AST_LIST_FIRST(&clone->readq));
3353 AST_LIST_HEAD_SET_NOLOCK(&clone->readq, NULL);
3354 for (i = 0; i < x; i++)
3355 write(original->alertpipe[1], &x, sizeof(x));
3358 clone->_softhangup = AST_SOFTHANGUP_DEV;
3361 /* And of course, so does our current state. Note we need not
3362 call ast_setstate since the event manager doesn't really consider
3363 these separate. We do this early so that the clone has the proper
3364 state of the original channel. */
3365 origstate = original->_state;
3366 original->_state = clone->_state;
3367 clone->_state = origstate;
3369 if (clone->tech->fixup){
3370 res = clone->tech->fixup(original, clone);
3371 if (res)
3372 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
3375 /* Start by disconnecting the original's physical side */
3376 if (clone->tech->hangup)
3377 res = clone->tech->hangup(clone);
3378 if (res) {
3379 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
3380 ast_channel_unlock(clone);
3381 return -1;
3384 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
3385 /* Mangle the name of the clone channel */
3386 ast_string_field_set(clone, name, zombn);
3387 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
3389 /* Update the type. */
3390 t_pvt = original->monitor;
3391 original->monitor = clone->monitor;
3392 clone->monitor = t_pvt;
3394 /* Keep the same language. */
3395 ast_string_field_set(original, language, clone->language);
3396 /* Copy the FD's other than the generator fd */
3397 for (x = 0; x < AST_MAX_FDS; x++) {
3398 if (x != AST_GENERATOR_FD)
3399 original->fds[x] = clone->fds[x];
3402 /* move any whisperer over */
3403 ast_channel_whisper_stop(original);
3404 if (ast_test_flag(clone, AST_FLAG_WHISPER)) {
3405 original->whisper = clone->whisper;
3406 ast_set_flag(original, AST_FLAG_WHISPER);
3407 clone->whisper = NULL;
3408 ast_clear_flag(clone, AST_FLAG_WHISPER);
3411 /* Move data stores over */
3412 if (AST_LIST_FIRST(&clone->datastores))
3413 AST_LIST_INSERT_TAIL(&original->datastores, AST_LIST_FIRST(&clone->datastores), entry);
3414 AST_LIST_HEAD_INIT_NOLOCK(&clone->datastores);
3416 clone_variables(original, clone);
3417 AST_LIST_HEAD_INIT_NOLOCK(&clone->varshead);
3418 /* Presense of ADSI capable CPE follows clone */
3419 original->adsicpe = clone->adsicpe;
3420 /* Bridge remains the same */
3421 /* CDR fields remain the same */
3422 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3423 /* Application and data remain the same */
3424 /* Clone exception becomes real one, as with fdno */
3425 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
3426 original->fdno = clone->fdno;
3427 /* Schedule context remains the same */
3428 /* Stream stuff stays the same */
3429 /* Keep the original state. The fixup code will need to work with it most likely */
3431 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3432 out. */
3433 tmpcid = original->cid;
3434 original->cid = clone->cid;
3435 clone->cid = tmpcid;
3437 /* Restore original timing file descriptor */
3438 original->fds[AST_TIMING_FD] = original->timingfd;
3440 /* Our native formats are different now */
3441 original->nativeformats = clone->nativeformats;
3443 /* Context, extension, priority, app data, jump table, remain the same */
3444 /* pvt switches. pbx stays the same, as does next */
3446 /* Set the write format */
3447 ast_set_write_format(original, wformat);
3449 /* Set the read format */
3450 ast_set_read_format(original, rformat);
3452 /* Copy the music class */
3453 ast_string_field_set(original, musicclass, clone->musicclass);
3455 if (option_debug)
3456 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
3458 /* Okay. Last thing is to let the channel driver know about all this mess, so he
3459 can fix up everything as best as possible */
3460 if (original->tech->fixup) {
3461 res = original->tech->fixup(clone, original);
3462 if (res) {
3463 ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
3464 original->tech->type, original->name);
3465 ast_channel_unlock(clone);
3466 return -1;
3468 } else
3469 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
3470 original->tech->type, original->name);
3472 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
3473 a zombie so nothing tries to touch it. If it's already been marked as a
3474 zombie, then free it now (since it already is considered invalid). */
3475 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
3476 if (option_debug)
3477 ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
3478 ast_channel_unlock(clone);
3479 manager_event(EVENT_FLAG_CALL, "Hangup",
3480 "Channel: %s\r\n"
3481 "Uniqueid: %s\r\n"
3482 "Cause: %d\r\n"
3483 "Cause-txt: %s\r\n",
3484 clone->name,
3485 clone->uniqueid,
3486 clone->hangupcause,
3487 ast_cause2str(clone->hangupcause)
3489 ast_channel_free(clone);
3490 } else {
3491 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
3492 ast_set_flag(clone, AST_FLAG_ZOMBIE);
3493 ast_queue_frame(clone, &ast_null_frame);
3494 ast_channel_unlock(clone);
3497 /* Signal any blocker */
3498 if (ast_test_flag(original, AST_FLAG_BLOCKING))
3499 pthread_kill(original->blocker, SIGURG);
3500 if (option_debug)
3501 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
3502 return 0;
3505 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
3507 if (callerid) {
3508 if (chan->cid.cid_num)
3509 free(chan->cid.cid_num);
3510 chan->cid.cid_num = ast_strdup(callerid);
3512 if (calleridname) {
3513 if (chan->cid.cid_name)
3514 free(chan->cid.cid_name);
3515 chan->cid.cid_name = ast_strdup(calleridname);
3517 if (ani) {
3518 if (chan->cid.cid_ani)
3519 free(chan->cid.cid_ani);
3520 chan->cid.cid_ani = ast_strdup(ani);
3522 if (chan->cdr)
3523 ast_cdr_setcid(chan->cdr, chan);
3524 manager_event(EVENT_FLAG_CALL, "Newcallerid",
3525 "Channel: %s\r\n"
3526 "CallerID: %s\r\n"
3527 "CallerIDName: %s\r\n"
3528 "Uniqueid: %s\r\n"
3529 "CID-CallingPres: %d (%s)\r\n",
3530 chan->name,
3531 S_OR(chan->cid.cid_num, "<Unknown>"),
3532 S_OR(chan->cid.cid_name, "<Unknown>"),
3533 chan->uniqueid,
3534 chan->cid.cid_pres,
3535 ast_describe_caller_presentation(chan->cid.cid_pres)
3539 int ast_setstate(struct ast_channel *chan, enum ast_channel_state state)
3541 int oldstate = chan->_state;
3543 if (oldstate == state)
3544 return 0;
3546 chan->_state = state;
3547 ast_device_state_changed_literal(chan->name);
3548 /* setstate used to conditionally report Newchannel; this is no more */
3549 manager_event(EVENT_FLAG_CALL,
3550 "Newstate",
3551 "Channel: %s\r\n"
3552 "State: %s\r\n"
3553 "CallerID: %s\r\n"
3554 "CallerIDName: %s\r\n"
3555 "Uniqueid: %s\r\n",
3556 chan->name, ast_state2str(chan->_state),
3557 S_OR(chan->cid.cid_num, "<unknown>"),
3558 S_OR(chan->cid.cid_name, "<unknown>"),
3559 chan->uniqueid);
3561 return 0;
3564 /*! \brief Find bridged channel */
3565 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
3567 struct ast_channel *bridged;
3568 bridged = chan->_bridge;
3569 if (bridged && bridged->tech->bridged_channel)
3570 bridged = bridged->tech->bridged_channel(chan, bridged);
3571 return bridged;
3574 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
3576 int min = 0, sec = 0, check;
3578 check = ast_autoservice_start(peer);
3579 if (check)
3580 return;
3582 if (remain > 0) {
3583 if (remain / 60 > 1) {
3584 min = remain / 60;
3585 sec = remain % 60;
3586 } else {
3587 sec = remain;
3591 if (!strcmp(sound,"timeleft")) { /* Queue support */
3592 ast_stream_and_wait(chan, "vm-youhave", chan->language, "");
3593 if (min) {
3594 ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, NULL);
3595 ast_stream_and_wait(chan, "queue-minutes", chan->language, "");
3597 if (sec) {
3598 ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, NULL);
3599 ast_stream_and_wait(chan, "queue-seconds", chan->language, "");
3601 } else {
3602 ast_stream_and_wait(chan, sound, chan->language, "");
3605 ast_autoservice_stop(peer);
3608 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
3609 struct ast_bridge_config *config, struct ast_frame **fo,
3610 struct ast_channel **rc, struct timeval bridge_end)
3612 /* Copy voice back and forth between the two channels. */
3613 struct ast_channel *cs[3];
3614 struct ast_frame *f;
3615 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3616 int o0nativeformats;
3617 int o1nativeformats;
3618 int watch_c0_dtmf;
3619 int watch_c1_dtmf;
3620 void *pvt0, *pvt1;
3621 /* Indicates whether a frame was queued into a jitterbuffer */
3622 int frame_put_in_jb = 0;
3623 int jb_in_use;
3624 int to;
3626 cs[0] = c0;
3627 cs[1] = c1;
3628 pvt0 = c0->tech_pvt;
3629 pvt1 = c1->tech_pvt;
3630 o0nativeformats = c0->nativeformats;
3631 o1nativeformats = c1->nativeformats;
3632 watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
3633 watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
3635 /* Check the need of a jitterbuffer for each channel */
3636 jb_in_use = ast_jb_do_usecheck(c0, c1);
3638 for (;;) {
3639 struct ast_channel *who, *other;
3641 if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
3642 (o0nativeformats != c0->nativeformats) ||
3643 (o1nativeformats != c1->nativeformats)) {
3644 /* Check for Masquerade, codec changes, etc */
3645 res = AST_BRIDGE_RETRY;
3646 break;
3648 if (bridge_end.tv_sec) {
3649 to = ast_tvdiff_ms(bridge_end, ast_tvnow());
3650 if (to <= 0) {
3651 if (config->timelimit)
3652 res = AST_BRIDGE_RETRY;
3653 else
3654 res = AST_BRIDGE_COMPLETE;
3655 break;
3657 } else
3658 to = -1;
3659 /* Calculate the appropriate max sleep interval - in general, this is the time,
3660 left to the closest jb delivery moment */
3661 if (jb_in_use)
3662 to = ast_jb_get_when_to_wakeup(c0, c1, to);
3663 who = ast_waitfor_n(cs, 2, &to);
3664 if (!who) {
3665 /* No frame received within the specified timeout - check if we have to deliver now */
3666 if (jb_in_use)
3667 ast_jb_get_and_deliver(c0, c1);
3668 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3669 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3670 c0->_softhangup = 0;
3671 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3672 c1->_softhangup = 0;
3673 c0->_bridge = c1;
3674 c1->_bridge = c0;
3676 continue;
3678 f = ast_read(who);
3679 if (!f) {
3680 *fo = NULL;
3681 *rc = who;
3682 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
3683 break;
3686 other = (who == c0) ? c1 : c0; /* the 'other' channel */
3687 /* Try add the frame info the who's bridged channel jitterbuff */
3688 if (jb_in_use)
3689 frame_put_in_jb = !ast_jb_put(other, f);
3691 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
3692 int bridge_exit = 0;
3694 switch (f->subclass) {
3695 case AST_CONTROL_HOLD:
3696 case AST_CONTROL_UNHOLD:
3697 case AST_CONTROL_VIDUPDATE:
3698 ast_indicate_data(other, f->subclass, f->data, f->datalen);
3699 break;
3700 default:
3701 *fo = f;
3702 *rc = who;
3703 bridge_exit = 1;
3704 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
3705 break;
3707 if (bridge_exit)
3708 break;
3710 if ((f->frametype == AST_FRAME_VOICE) ||
3711 (f->frametype == AST_FRAME_DTMF_BEGIN) ||
3712 (f->frametype == AST_FRAME_DTMF) ||
3713 (f->frametype == AST_FRAME_VIDEO) ||
3714 (f->frametype == AST_FRAME_IMAGE) ||
3715 (f->frametype == AST_FRAME_HTML) ||
3716 (f->frametype == AST_FRAME_MODEM) ||
3717 (f->frametype == AST_FRAME_TEXT)) {
3718 /* monitored dtmf causes exit from bridge */
3719 int monitored_source = (who == c0) ? watch_c0_dtmf : watch_c1_dtmf;
3721 if (monitored_source &&
3722 (f->frametype == AST_FRAME_DTMF_END ||
3723 f->frametype == AST_FRAME_DTMF_BEGIN)) {
3724 *fo = f;
3725 *rc = who;
3726 ast_log(LOG_DEBUG, "Got DTMF %s on channel (%s)\n",
3727 f->frametype == AST_FRAME_DTMF_END ? "end" : "begin",
3728 who->name);
3729 break;
3731 /* Write immediately frames, not passed through jb */
3732 if (!frame_put_in_jb)
3733 ast_write(other, f);
3735 /* Check if we have to deliver now */
3736 if (jb_in_use)
3737 ast_jb_get_and_deliver(c0, c1);
3739 /* XXX do we want to pass on also frames not matched above ? */
3740 ast_frfree(f);
3742 /* Swap who gets priority */
3743 cs[2] = cs[0];
3744 cs[0] = cs[1];
3745 cs[1] = cs[2];
3747 return res;
3750 /*! \brief Bridge two channels together */
3751 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
3752 struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
3754 struct ast_channel *who = NULL;
3755 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3756 int nativefailed=0;
3757 int firstpass;
3758 int o0nativeformats;
3759 int o1nativeformats;
3760 long time_left_ms=0;
3761 struct timeval nexteventts = { 0, };
3762 char caller_warning = 0;
3763 char callee_warning = 0;
3765 if (c0->_bridge) {
3766 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3767 c0->name, c0->_bridge->name);
3768 return -1;
3770 if (c1->_bridge) {
3771 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3772 c1->name, c1->_bridge->name);
3773 return -1;
3776 /* Stop if we're a zombie or need a soft hangup */
3777 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3778 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
3779 return -1;
3781 *fo = NULL;
3782 firstpass = config->firstpass;
3783 config->firstpass = 0;
3785 if (ast_tvzero(config->start_time))
3786 config->start_time = ast_tvnow();
3787 time_left_ms = config->timelimit;
3789 caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
3790 callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
3792 if (config->start_sound && firstpass) {
3793 if (caller_warning)
3794 bridge_playfile(c0, c1, config->start_sound, time_left_ms / 1000);
3795 if (callee_warning)
3796 bridge_playfile(c1, c0, config->start_sound, time_left_ms / 1000);
3799 /* Keep track of bridge */
3800 c0->_bridge = c1;
3801 c1->_bridge = c0;
3803 /* \todo XXX here should check that cid_num is not NULL */
3804 manager_event(EVENT_FLAG_CALL, "Link",
3805 "Channel1: %s\r\n"
3806 "Channel2: %s\r\n"
3807 "Uniqueid1: %s\r\n"
3808 "Uniqueid2: %s\r\n"
3809 "CallerID1: %s\r\n"
3810 "CallerID2: %s\r\n",
3811 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3813 o0nativeformats = c0->nativeformats;
3814 o1nativeformats = c1->nativeformats;
3816 if (config->feature_timer) {
3817 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->feature_timer, 1000));
3818 } else if (config->timelimit) {
3819 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3820 if (caller_warning || callee_warning)
3821 nexteventts = ast_tvsub(nexteventts, ast_samp2tv(config->play_warning, 1000));
3824 for (/* ever */;;) {
3825 struct timeval now = { 0, };
3826 int to;
3828 to = -1;
3830 if (!ast_tvzero(nexteventts)) {
3831 now = ast_tvnow();
3832 to = ast_tvdiff_ms(nexteventts, now);
3833 if (to <= 0) {
3834 if (!config->timelimit) {
3835 res = AST_BRIDGE_COMPLETE;
3836 break;
3838 to = 0;
3842 if (config->timelimit) {
3843 time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
3844 if (time_left_ms < to)
3845 to = time_left_ms;
3847 if (time_left_ms <= 0) {
3848 if (caller_warning && config->end_sound)
3849 bridge_playfile(c0, c1, config->end_sound, 0);
3850 if (callee_warning && config->end_sound)
3851 bridge_playfile(c1, c0, config->end_sound, 0);
3852 *fo = NULL;
3853 if (who)
3854 *rc = who;
3855 res = 0;
3856 break;
3859 if (!to) {
3860 if (time_left_ms >= 5000 && config->warning_sound && config->play_warning) {
3861 int t = (time_left_ms + 500) / 1000; /* round to nearest second */
3862 if (caller_warning)
3863 bridge_playfile(c0, c1, config->warning_sound, t);
3864 if (callee_warning)
3865 bridge_playfile(c1, c0, config->warning_sound, t);
3867 if (config->warning_freq) {
3869 if (time_left_ms > (config->warning_freq + 5000)) {
3870 nexteventts = ast_tvadd(nexteventts, ast_samp2tv(config->warning_freq, 1000));
3873 } else
3874 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3878 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3879 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3880 c0->_softhangup = 0;
3881 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3882 c1->_softhangup = 0;
3883 c0->_bridge = c1;
3884 c1->_bridge = c0;
3885 ast_log(LOG_DEBUG, "Unbridge signal received. Ending native bridge.\n");
3886 continue;
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 *fo = NULL;
3893 if (who)
3894 *rc = who;
3895 res = 0;
3896 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",
3897 c0->name, c1->name,
3898 ast_test_flag(c0, AST_FLAG_ZOMBIE) ? "Yes" : "No",
3899 ast_check_hangup(c0) ? "Yes" : "No",
3900 ast_test_flag(c1, AST_FLAG_ZOMBIE) ? "Yes" : "No",
3901 ast_check_hangup(c1) ? "Yes" : "No");
3902 break;
3905 if (c0->tech->bridge &&
3906 (config->timelimit == 0) &&
3907 (c0->tech->bridge == c1->tech->bridge) &&
3908 !nativefailed && !c0->monitor && !c1->monitor &&
3909 !c0->spies && !c1->spies && !ast_test_flag(&(config->features_callee),AST_FEATURE_REDIRECT) &&
3910 !ast_test_flag(&(config->features_caller),AST_FEATURE_REDIRECT) ) {
3911 /* Looks like they share a bridge method and nothing else is in the way */
3912 ast_set_flag(c0, AST_FLAG_NBRIDGE);
3913 ast_set_flag(c1, AST_FLAG_NBRIDGE);
3914 if ((res = c0->tech->bridge(c0, c1, config->flags, fo, rc, to)) == AST_BRIDGE_COMPLETE) {
3915 /* \todo XXX here should check that cid_num is not NULL */
3916 manager_event(EVENT_FLAG_CALL, "Unlink",
3917 "Channel1: %s\r\n"
3918 "Channel2: %s\r\n"
3919 "Uniqueid1: %s\r\n"
3920 "Uniqueid2: %s\r\n"
3921 "CallerID1: %s\r\n"
3922 "CallerID2: %s\r\n",
3923 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3924 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n", c0->name, c1->name);
3926 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
3927 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
3929 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3930 continue;
3932 c0->_bridge = NULL;
3933 c1->_bridge = NULL;
3935 return res;
3936 } else {
3937 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
3938 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
3940 switch (res) {
3941 case AST_BRIDGE_RETRY:
3942 continue;
3943 default:
3944 if (option_verbose > 2)
3945 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s ended\n",
3946 c0->name, c1->name);
3947 /* fallthrough */
3948 case AST_BRIDGE_FAILED_NOWARN:
3949 nativefailed++;
3950 break;
3954 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) ||
3955 (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
3956 !(c0->generator || c1->generator)) {
3957 if (ast_channel_make_compatible(c0, c1)) {
3958 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
3959 /* \todo XXX here should check that cid_num is not NULL */
3960 manager_event(EVENT_FLAG_CALL, "Unlink",
3961 "Channel1: %s\r\n"
3962 "Channel2: %s\r\n"
3963 "Uniqueid1: %s\r\n"
3964 "Uniqueid2: %s\r\n"
3965 "CallerID1: %s\r\n"
3966 "CallerID2: %s\r\n",
3967 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3968 return AST_BRIDGE_FAILED;
3970 o0nativeformats = c0->nativeformats;
3971 o1nativeformats = c1->nativeformats;
3973 res = ast_generic_bridge(c0, c1, config, fo, rc, nexteventts);
3974 if (res != AST_BRIDGE_RETRY)
3975 break;
3978 c0->_bridge = NULL;
3979 c1->_bridge = NULL;
3981 /* \todo XXX here should check that cid_num is not NULL */
3982 manager_event(EVENT_FLAG_CALL, "Unlink",
3983 "Channel1: %s\r\n"
3984 "Channel2: %s\r\n"
3985 "Uniqueid1: %s\r\n"
3986 "Uniqueid2: %s\r\n"
3987 "CallerID1: %s\r\n"
3988 "CallerID2: %s\r\n",
3989 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3990 ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n", c0->name, c1->name);
3992 return res;
3995 /*! \brief Sets an option on a channel */
3996 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
3998 int res;
4000 if (chan->tech->setoption) {
4001 res = chan->tech->setoption(chan, option, data, datalen);
4002 if (res < 0)
4003 return res;
4004 } else {
4005 errno = ENOSYS;
4006 return -1;
4008 if (block) {
4009 /* XXX Implement blocking -- just wait for our option frame reply, discarding
4010 intermediate packets. XXX */
4011 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
4012 return -1;
4014 return 0;
4017 struct tonepair_def {
4018 int freq1;
4019 int freq2;
4020 int duration;
4021 int vol;
4024 struct tonepair_state {
4025 int fac1;
4026 int fac2;
4027 int v1_1;
4028 int v2_1;
4029 int v3_1;
4030 int v1_2;
4031 int v2_2;
4032 int v3_2;
4033 int origwfmt;
4034 int pos;
4035 int duration;
4036 int modulate;
4037 struct ast_frame f;
4038 unsigned char offset[AST_FRIENDLY_OFFSET];
4039 short data[4000];
4042 static void tonepair_release(struct ast_channel *chan, void *params)
4044 struct tonepair_state *ts = params;
4046 if (chan)
4047 ast_set_write_format(chan, ts->origwfmt);
4048 free(ts);
4051 static void *tonepair_alloc(struct ast_channel *chan, void *params)
4053 struct tonepair_state *ts;
4054 struct tonepair_def *td = params;
4056 if (!(ts = ast_calloc(1, sizeof(*ts))))
4057 return NULL;
4058 ts->origwfmt = chan->writeformat;
4059 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
4060 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
4061 tonepair_release(NULL, ts);
4062 ts = NULL;
4063 } else {
4064 ts->fac1 = 2.0 * cos(2.0 * M_PI * (td->freq1 / 8000.0)) * 32768.0;
4065 ts->v1_1 = 0;
4066 ts->v2_1 = sin(-4.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
4067 ts->v3_1 = sin(-2.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
4068 ts->v2_1 = 0;
4069 ts->fac2 = 2.0 * cos(2.0 * M_PI * (td->freq2 / 8000.0)) * 32768.0;
4070 ts->v2_2 = sin(-4.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
4071 ts->v3_2 = sin(-2.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
4072 ts->duration = td->duration;
4073 ts->modulate = 0;
4075 /* Let interrupts interrupt :) */
4076 ast_set_flag(chan, AST_FLAG_WRITE_INT);
4077 return ts;
4080 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
4082 struct tonepair_state *ts = data;
4083 int x;
4085 /* we need to prepare a frame with 16 * timelen samples as we're
4086 * generating SLIN audio
4088 len = samples * 2;
4090 if (len > sizeof(ts->data) / 2 - 1) {
4091 ast_log(LOG_WARNING, "Can't generate that much data!\n");
4092 return -1;
4094 memset(&ts->f, 0, sizeof(ts->f));
4095 for (x=0;x<len/2;x++) {
4096 ts->v1_1 = ts->v2_1;
4097 ts->v2_1 = ts->v3_1;
4098 ts->v3_1 = (ts->fac1 * ts->v2_1 >> 15) - ts->v1_1;
4100 ts->v1_2 = ts->v2_2;
4101 ts->v2_2 = ts->v3_2;
4102 ts->v3_2 = (ts->fac2 * ts->v2_2 >> 15) - ts->v1_2;
4103 if (ts->modulate) {
4104 int p;
4105 p = ts->v3_2 - 32768;
4106 if (p < 0) p = -p;
4107 p = ((p * 9) / 10) + 1;
4108 ts->data[x] = (ts->v3_1 * p) >> 15;
4109 } else
4110 ts->data[x] = ts->v3_1 + ts->v3_2;
4112 ts->f.frametype = AST_FRAME_VOICE;
4113 ts->f.subclass = AST_FORMAT_SLINEAR;
4114 ts->f.datalen = len;
4115 ts->f.samples = samples;
4116 ts->f.offset = AST_FRIENDLY_OFFSET;
4117 ts->f.data = ts->data;
4118 ast_write(chan, &ts->f);
4119 ts->pos += x;
4120 if (ts->duration > 0) {
4121 if (ts->pos >= ts->duration * 8)
4122 return -1;
4124 return 0;
4127 static struct ast_generator tonepair = {
4128 alloc: tonepair_alloc,
4129 release: tonepair_release,
4130 generate: tonepair_generator,
4133 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
4135 struct tonepair_def d = { 0, };
4137 d.freq1 = freq1;
4138 d.freq2 = freq2;
4139 d.duration = duration;
4140 d.vol = (vol < 1) ? 8192 : vol; /* force invalid to 8192 */
4141 if (ast_activate_generator(chan, &tonepair, &d))
4142 return -1;
4143 return 0;
4146 void ast_tonepair_stop(struct ast_channel *chan)
4148 ast_deactivate_generator(chan);
4151 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
4153 int res;
4155 if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
4156 return res;
4158 /* Give us some wiggle room */
4159 while (chan->generatordata && ast_waitfor(chan, 100) >= 0) {
4160 struct ast_frame *f = ast_read(chan);
4161 if (f)
4162 ast_frfree(f);
4163 else
4164 return -1;
4166 return 0;
4169 ast_group_t ast_get_group(const char *s)
4171 char *piece;
4172 char *c;
4173 int start=0, finish=0, x;
4174 ast_group_t group = 0;
4176 c = ast_strdupa(s);
4178 while ((piece = strsep(&c, ","))) {
4179 if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
4180 /* Range */
4181 } else if (sscanf(piece, "%d", &start)) {
4182 /* Just one */
4183 finish = start;
4184 } else {
4185 ast_log(LOG_ERROR, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s, piece);
4186 continue;
4188 for (x = start; x <= finish; x++) {
4189 if ((x > 63) || (x < 0)) {
4190 ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x);
4191 } else
4192 group |= ((ast_group_t) 1 << x);
4195 return group;
4198 static int (*ast_moh_start_ptr)(struct ast_channel *, const char *, const char *) = NULL;
4199 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
4200 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
4202 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, const char *, const char *),
4203 void (*stop_ptr)(struct ast_channel *),
4204 void (*cleanup_ptr)(struct ast_channel *))
4206 ast_moh_start_ptr = start_ptr;
4207 ast_moh_stop_ptr = stop_ptr;
4208 ast_moh_cleanup_ptr = cleanup_ptr;
4211 void ast_uninstall_music_functions(void)
4213 ast_moh_start_ptr = NULL;
4214 ast_moh_stop_ptr = NULL;
4215 ast_moh_cleanup_ptr = NULL;
4218 /*! \brief Turn on music on hold on a given channel */
4219 int ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
4221 if (ast_moh_start_ptr)
4222 return ast_moh_start_ptr(chan, mclass, interpclass);
4224 if (option_verbose > 2) {
4225 ast_verbose(VERBOSE_PREFIX_3 "Music class %s requested but no musiconhold loaded.\n",
4226 mclass ? mclass : (interpclass ? interpclass : "default"));
4229 return 0;
4232 /*! \brief Turn off music on hold on a given channel */
4233 void ast_moh_stop(struct ast_channel *chan)
4235 if (ast_moh_stop_ptr)
4236 ast_moh_stop_ptr(chan);
4239 void ast_moh_cleanup(struct ast_channel *chan)
4241 if (ast_moh_cleanup_ptr)
4242 ast_moh_cleanup_ptr(chan);
4245 void ast_channels_init(void)
4247 ast_cli_register_multiple(cli_channel, sizeof(cli_channel) / sizeof(struct ast_cli_entry));
4250 /*! \brief Print call group and pickup group ---*/
4251 char *ast_print_group(char *buf, int buflen, ast_group_t group)
4253 unsigned int i;
4254 int first=1;
4255 char num[3];
4257 buf[0] = '\0';
4259 if (!group) /* Return empty string if no group */
4260 return buf;
4262 for (i = 0; i <= 63; i++) { /* Max group is 63 */
4263 if (group & ((ast_group_t) 1 << i)) {
4264 if (!first) {
4265 strncat(buf, ", ", buflen);
4266 } else {
4267 first=0;
4269 snprintf(num, sizeof(num), "%u", i);
4270 strncat(buf, num, buflen);
4273 return buf;
4276 void ast_set_variables(struct ast_channel *chan, struct ast_variable *vars)
4278 struct ast_variable *cur;
4280 for (cur = vars; cur; cur = cur->next)
4281 pbx_builtin_setvar_helper(chan, cur->name, cur->value);
4284 static void copy_data_from_queue(struct ast_channel_spy_queue *queue, short *buf, unsigned int samples)
4286 struct ast_frame *f;
4287 int tocopy;
4288 int bytestocopy;
4290 while (samples) {
4291 if (!(f = AST_LIST_FIRST(&queue->list))) {
4292 ast_log(LOG_ERROR, "Ran out of frames before buffer filled!\n");
4293 break;
4296 tocopy = (f->samples > samples) ? samples : f->samples;
4297 bytestocopy = ast_codec_get_len(queue->format, tocopy);
4298 memcpy(buf, f->data, bytestocopy);
4299 samples -= tocopy;
4300 buf += tocopy;
4301 f->samples -= tocopy;
4302 f->data += bytestocopy;
4303 f->datalen -= bytestocopy;
4304 f->offset += bytestocopy;
4305 queue->samples -= tocopy;
4307 if (!f->samples)
4308 ast_frfree(AST_LIST_REMOVE_HEAD(&queue->list, frame_list));
4312 struct ast_frame *ast_channel_spy_read_frame(struct ast_channel_spy *spy, unsigned int samples)
4314 struct ast_frame *result;
4315 /* buffers are allocated to hold SLINEAR, which is the largest format */
4316 short read_buf[samples];
4317 short write_buf[samples];
4318 struct ast_frame *read_frame;
4319 struct ast_frame *write_frame;
4320 int need_dup;
4321 struct ast_frame stack_read_frame = { .frametype = AST_FRAME_VOICE,
4322 .subclass = spy->read_queue.format,
4323 .data = read_buf,
4324 .samples = samples,
4325 .datalen = ast_codec_get_len(spy->read_queue.format, samples),
4327 struct ast_frame stack_write_frame = { .frametype = AST_FRAME_VOICE,
4328 .subclass = spy->write_queue.format,
4329 .data = write_buf,
4330 .samples = samples,
4331 .datalen = ast_codec_get_len(spy->write_queue.format, samples),
4334 /* if a flush has been requested, dump everything in whichever queue is larger */
4335 if (ast_test_flag(spy, CHANSPY_TRIGGER_FLUSH)) {
4336 if (spy->read_queue.samples > spy->write_queue.samples) {
4337 if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST)) {
4338 AST_LIST_TRAVERSE(&spy->read_queue.list, result, frame_list)
4339 ast_frame_adjust_volume(result, spy->read_vol_adjustment);
4341 result = AST_LIST_FIRST(&spy->read_queue.list);
4342 AST_LIST_HEAD_SET_NOLOCK(&spy->read_queue.list, NULL);
4343 spy->read_queue.samples = 0;
4344 } else {
4345 if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST)) {
4346 AST_LIST_TRAVERSE(&spy->write_queue.list, result, frame_list)
4347 ast_frame_adjust_volume(result, spy->write_vol_adjustment);
4349 result = AST_LIST_FIRST(&spy->write_queue.list);
4350 AST_LIST_HEAD_SET_NOLOCK(&spy->write_queue.list, NULL);
4351 spy->write_queue.samples = 0;
4353 ast_clear_flag(spy, CHANSPY_TRIGGER_FLUSH);
4354 return result;
4357 if ((spy->read_queue.samples < samples) || (spy->write_queue.samples < samples))
4358 return NULL;
4360 /* short-circuit if both head frames have exactly what we want */
4361 if ((AST_LIST_FIRST(&spy->read_queue.list)->samples == samples) &&
4362 (AST_LIST_FIRST(&spy->write_queue.list)->samples == samples)) {
4363 read_frame = AST_LIST_REMOVE_HEAD(&spy->read_queue.list, frame_list);
4364 write_frame = AST_LIST_REMOVE_HEAD(&spy->write_queue.list, frame_list);
4366 spy->read_queue.samples -= samples;
4367 spy->write_queue.samples -= samples;
4369 need_dup = 0;
4370 } else {
4371 copy_data_from_queue(&spy->read_queue, read_buf, samples);
4372 copy_data_from_queue(&spy->write_queue, write_buf, samples);
4374 read_frame = &stack_read_frame;
4375 write_frame = &stack_write_frame;
4376 need_dup = 1;
4379 if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST))
4380 ast_frame_adjust_volume(read_frame, spy->read_vol_adjustment);
4382 if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST))
4383 ast_frame_adjust_volume(write_frame, spy->write_vol_adjustment);
4385 if (ast_test_flag(spy, CHANSPY_MIXAUDIO)) {
4386 ast_frame_slinear_sum(read_frame, write_frame);
4388 if (need_dup)
4389 result = ast_frdup(read_frame);
4390 else {
4391 result = read_frame;
4392 ast_frfree(write_frame);
4394 } else {
4395 if (need_dup) {
4396 result = ast_frdup(read_frame);
4397 AST_LIST_NEXT(result, frame_list) = ast_frdup(write_frame);
4398 } else {
4399 result = read_frame;
4400 AST_LIST_NEXT(result, frame_list) = write_frame;
4404 return result;
4407 static void *silence_generator_alloc(struct ast_channel *chan, void *data)
4409 /* just store the data pointer in the channel structure */
4410 return data;
4413 static void silence_generator_release(struct ast_channel *chan, void *data)
4415 /* nothing to do */
4418 static int silence_generator_generate(struct ast_channel *chan, void *data, int len, int samples)
4420 short buf[samples];
4421 struct ast_frame frame = {
4422 .frametype = AST_FRAME_VOICE,
4423 .subclass = AST_FORMAT_SLINEAR,
4424 .data = buf,
4425 .samples = samples,
4426 .datalen = sizeof(buf),
4428 memset(buf, 0, sizeof(buf));
4429 if (ast_write(chan, &frame))
4430 return -1;
4431 return 0;
4434 static struct ast_generator silence_generator = {
4435 .alloc = silence_generator_alloc,
4436 .release = silence_generator_release,
4437 .generate = silence_generator_generate,
4440 struct ast_silence_generator {
4441 int old_write_format;
4444 struct ast_silence_generator *ast_channel_start_silence_generator(struct ast_channel *chan)
4446 struct ast_silence_generator *state;
4448 if (!(state = ast_calloc(1, sizeof(*state)))) {
4449 return NULL;
4452 state->old_write_format = chan->writeformat;
4454 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
4455 ast_log(LOG_ERROR, "Could not set write format to SLINEAR\n");
4456 free(state);
4457 return NULL;
4460 ast_activate_generator(chan, &silence_generator, state);
4462 if (option_debug)
4463 ast_log(LOG_DEBUG, "Started silence generator on '%s'\n", chan->name);
4465 return state;
4468 void ast_channel_stop_silence_generator(struct ast_channel *chan, struct ast_silence_generator *state)
4470 if (!state)
4471 return;
4473 ast_deactivate_generator(chan);
4475 if (option_debug)
4476 ast_log(LOG_DEBUG, "Stopped silence generator on '%s'\n", chan->name);
4478 if (ast_set_write_format(chan, state->old_write_format) < 0)
4479 ast_log(LOG_ERROR, "Could not return write format to its original state\n");
4481 free(state);
4485 /*! \ brief Convert channel reloadreason (ENUM) to text string for manager event */
4486 const char *channelreloadreason2txt(enum channelreloadreason reason)
4488 switch (reason) {
4489 case CHANNEL_MODULE_LOAD:
4490 return "LOAD (Channel module load)";
4492 case CHANNEL_MODULE_RELOAD:
4493 return "RELOAD (Channel module reload)";
4495 case CHANNEL_CLI_RELOAD:
4496 return "CLIRELOAD (Channel module reload by CLI command)";
4498 default:
4499 return "MANAGERRELOAD (Channel module reload by manager)";
4503 #ifdef DEBUG_CHANNEL_LOCKS
4505 /*! \brief Unlock AST channel (and print debugging output)
4506 \note You need to enable DEBUG_CHANNEL_LOCKS for this function
4508 int ast_channel_unlock(struct ast_channel *chan)
4510 int res = 0;
4511 if (option_debug > 2)
4512 ast_log(LOG_DEBUG, "::::==== Unlocking AST channel %s\n", chan->name);
4514 if (!chan) {
4515 ast_log(LOG_DEBUG, "::::==== Unlocking non-existing channel \n");
4516 return 0;
4519 res = ast_mutex_unlock(&chan->lock);
4521 if (option_debug > 2) {
4522 #ifdef DEBUG_THREADS
4523 int count = 0;
4524 if ((count = chan->lock.reentrancy))
4525 ast_log(LOG_DEBUG, ":::=== Still have %d locks (recursive)\n", count);
4526 #endif
4527 if (!res)
4528 ast_log(LOG_DEBUG, "::::==== Channel %s was unlocked\n", chan->name);
4529 if (res == EINVAL) {
4530 ast_log(LOG_DEBUG, "::::==== Channel %s had no lock by this thread. Failed unlocking\n", chan->name);
4533 if (res == EPERM) {
4534 /* We had no lock, so okay any way*/
4535 if (option_debug > 3)
4536 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked at all \n", chan->name);
4537 res = 0;
4539 return res;
4542 /*! \brief Lock AST channel (and print debugging output)
4543 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4544 int ast_channel_lock(struct ast_channel *chan)
4546 int res;
4548 if (option_debug > 3)
4549 ast_log(LOG_DEBUG, "====:::: Locking AST channel %s\n", chan->name);
4551 res = ast_mutex_lock(&chan->lock);
4553 if (option_debug > 3) {
4554 #ifdef DEBUG_THREADS
4555 int count = 0;
4556 if ((count = chan->lock.reentrancy))
4557 ast_log(LOG_DEBUG, ":::=== Now have %d locks (recursive)\n", count);
4558 #endif
4559 if (!res)
4560 ast_log(LOG_DEBUG, "::::==== Channel %s was locked\n", chan->name);
4561 if (res == EDEADLK) {
4562 /* We had no lock, so okey any way */
4563 if (option_debug > 3)
4564 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked by us. Lock would cause deadlock.\n", chan->name);
4566 if (res == EINVAL) {
4567 if (option_debug > 3)
4568 ast_log(LOG_DEBUG, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
4571 return res;
4574 /*! \brief Lock AST channel (and print debugging output)
4575 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4576 int ast_channel_trylock(struct ast_channel *chan)
4578 int res;
4580 if (option_debug > 2)
4581 ast_log(LOG_DEBUG, "====:::: Trying to lock AST channel %s\n", chan->name);
4583 res = ast_mutex_trylock(&chan->lock);
4585 if (option_debug > 2) {
4586 #ifdef DEBUG_THREADS
4587 int count = 0;
4588 if ((count = chan->lock.reentrancy))
4589 ast_log(LOG_DEBUG, ":::=== Now have %d locks (recursive)\n", count);
4590 #endif
4591 if (!res)
4592 ast_log(LOG_DEBUG, "::::==== Channel %s was locked\n", chan->name);
4593 if (res == EBUSY) {
4594 /* We failed to lock */
4595 if (option_debug > 2)
4596 ast_log(LOG_DEBUG, "::::==== Channel %s failed to lock. Not waiting around...\n", chan->name);
4598 if (res == EDEADLK) {
4599 /* We had no lock, so okey any way*/
4600 if (option_debug > 2)
4601 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked. Lock would cause deadlock.\n", chan->name);
4603 if (res == EINVAL && option_debug > 2)
4604 ast_log(LOG_DEBUG, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
4606 return res;
4609 #endif
4612 * Wrappers for various ast_say_*() functions that call the full version
4613 * of the same functions.
4614 * The proper place would be say.c, but that file is optional and one
4615 * must be able to build asterisk even without it (using a loadable 'say'
4616 * implementation that only supplies the 'full' version of the functions.
4619 int ast_say_number(struct ast_channel *chan, int num,
4620 const char *ints, const char *language, const char *options)
4622 return ast_say_number_full(chan, num, ints, language, options, -1, -1);
4625 int ast_say_enumeration(struct ast_channel *chan, int num,
4626 const char *ints, const char *language, const char *options)
4628 return ast_say_enumeration_full(chan, num, ints, language, options, -1, -1);
4631 int ast_say_digits(struct ast_channel *chan, int num,
4632 const char *ints, const char *lang)
4634 return ast_say_digits_full(chan, num, ints, lang, -1, -1);
4637 int ast_say_digit_str(struct ast_channel *chan, const char *str,
4638 const char *ints, const char *lang)
4640 return ast_say_digit_str_full(chan, str, ints, lang, -1, -1);
4643 int ast_say_character_str(struct ast_channel *chan, const char *str,
4644 const char *ints, const char *lang)
4646 return ast_say_character_str_full(chan, str, ints, lang, -1, -1);
4649 int ast_say_phonetic_str(struct ast_channel *chan, const char *str,
4650 const char *ints, const char *lang)
4652 return ast_say_phonetic_str_full(chan, str, ints, lang, -1, -1);
4655 int ast_say_digits_full(struct ast_channel *chan, int num,
4656 const char *ints, const char *lang, int audiofd, int ctrlfd)
4658 char buf[256];
4660 snprintf(buf, sizeof(buf), "%d", num);
4661 return ast_say_digit_str_full(chan, buf, ints, lang, audiofd, ctrlfd);
4664 int ast_channel_whisper_start(struct ast_channel *chan)
4666 if (chan->whisper)
4667 return -1;
4669 if (!(chan->whisper = ast_calloc(1, sizeof(*chan->whisper))))
4670 return -1;
4672 ast_mutex_init(&chan->whisper->lock);
4673 ast_slinfactory_init(&chan->whisper->sf);
4674 ast_set_flag(chan, AST_FLAG_WHISPER);
4676 return 0;
4679 int ast_channel_whisper_feed(struct ast_channel *chan, struct ast_frame *f)
4681 if (!chan->whisper)
4682 return -1;
4684 ast_mutex_lock(&chan->whisper->lock);
4685 ast_slinfactory_feed(&chan->whisper->sf, f);
4686 ast_mutex_unlock(&chan->whisper->lock);
4688 return 0;
4691 void ast_channel_whisper_stop(struct ast_channel *chan)
4693 if (!chan->whisper)
4694 return;
4696 ast_clear_flag(chan, AST_FLAG_WHISPER);
4697 if (chan->whisper->path)
4698 ast_translator_free_path(chan->whisper->path);
4699 if (chan->whisper->original_format && chan->writeformat == AST_FORMAT_SLINEAR)
4700 ast_set_write_format(chan, chan->whisper->original_format);
4701 ast_slinfactory_destroy(&chan->whisper->sf);
4702 ast_mutex_destroy(&chan->whisper->lock);
4703 free(chan->whisper);
4704 chan->whisper = NULL;