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.
21 * \brief Channel Management
23 * \author Mark Spencer <markster@digium.com>
28 ASTERISK_FILE_VERSION(__FILE__
, "$Revision$")
41 #include <sys/ioctl.h>
42 #include <zaptel/zaptel.h>
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/audiohook.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 /* uncomment if you have problems with 'monitoring' synchronized files */
75 #define MONITOR_CONSTANT_DELAY
76 #define MONITOR_DELAY 150 * 8 /* 150 ms of MONITORING DELAY */
79 /*! Prevent new channel allocation if shutting down. */
80 static int shutting_down
;
84 unsigned long global_fin
, global_fout
;
86 AST_THREADSTORAGE(state2str_threadbuf
, state2str_threadbuf_init
);
87 #define STATE2STR_BUFSIZE 32
89 /*! Default amount of time to use when emulating a digit as a begin and end
91 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
93 /*! Minimum allowed digit length - 80ms */
94 #define AST_MIN_DTMF_DURATION 80
96 /*! Minimum amount of time between the end of the last digit and the beginning
97 * of a new one - 45ms */
98 #define AST_MIN_DTMF_GAP 45
101 const struct ast_channel_tech
*tech
;
102 AST_LIST_ENTRY(chanlist
) list
;
105 /*! the list of registered channel types */
106 static AST_LIST_HEAD_NOLOCK_STATIC(backends
, chanlist
);
108 /*! the list of channels we have. Note that the lock for this list is used for
109 both the channels list and the backends list. */
110 static AST_LIST_HEAD_STATIC(channels
, ast_channel
);
112 /*! map AST_CAUSE's to readable string representations */
113 const struct ast_cause
{
118 { AST_CAUSE_UNALLOCATED
, "UNALLOCATED", "Unallocated (unassigned) number" },
119 { AST_CAUSE_NO_ROUTE_TRANSIT_NET
, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
120 { AST_CAUSE_NO_ROUTE_DESTINATION
, "NO_ROUTE_DESTINATION", "No route to destination" },
121 { AST_CAUSE_CHANNEL_UNACCEPTABLE
, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
122 { AST_CAUSE_CALL_AWARDED_DELIVERED
, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
123 { AST_CAUSE_NORMAL_CLEARING
, "NORMAL_CLEARING", "Normal Clearing" },
124 { AST_CAUSE_USER_BUSY
, "USER_BUSY", "User busy" },
125 { AST_CAUSE_NO_USER_RESPONSE
, "NO_USER_RESPONSE", "No user responding" },
126 { AST_CAUSE_NO_ANSWER
, "NO_ANSWER", "User alerting, no answer" },
127 { AST_CAUSE_CALL_REJECTED
, "CALL_REJECTED", "Call Rejected" },
128 { AST_CAUSE_NUMBER_CHANGED
, "NUMBER_CHANGED", "Number changed" },
129 { AST_CAUSE_DESTINATION_OUT_OF_ORDER
, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
130 { AST_CAUSE_INVALID_NUMBER_FORMAT
, "INVALID_NUMBER_FORMAT", "Invalid number format" },
131 { AST_CAUSE_FACILITY_REJECTED
, "FACILITY_REJECTED", "Facility rejected" },
132 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY
, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
133 { AST_CAUSE_NORMAL_UNSPECIFIED
, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
134 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION
, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
135 { AST_CAUSE_NETWORK_OUT_OF_ORDER
, "NETWORK_OUT_OF_ORDER", "Network out of order" },
136 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE
, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
137 { AST_CAUSE_SWITCH_CONGESTION
, "SWITCH_CONGESTION", "Switching equipment congestion" },
138 { AST_CAUSE_ACCESS_INFO_DISCARDED
, "ACCESS_INFO_DISCARDED", "Access information discarded" },
139 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL
, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
140 { AST_CAUSE_PRE_EMPTED
, "PRE_EMPTED", "Pre-empted" },
141 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED
, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
142 { AST_CAUSE_OUTGOING_CALL_BARRED
, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
143 { AST_CAUSE_INCOMING_CALL_BARRED
, "INCOMING_CALL_BARRED", "Incoming call barred" },
144 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH
, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
145 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
146 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL
, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
147 { AST_CAUSE_CHAN_NOT_IMPLEMENTED
, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
148 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED
, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
149 { AST_CAUSE_INVALID_CALL_REFERENCE
, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
150 { AST_CAUSE_INCOMPATIBLE_DESTINATION
, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
151 { AST_CAUSE_INVALID_MSG_UNSPECIFIED
, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
152 { AST_CAUSE_MANDATORY_IE_MISSING
, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
153 { AST_CAUSE_MESSAGE_TYPE_NONEXIST
, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
154 { AST_CAUSE_WRONG_MESSAGE
, "WRONG_MESSAGE", "Wrong message" },
155 { AST_CAUSE_IE_NONEXIST
, "IE_NONEXIST", "Info. element nonexist or not implemented" },
156 { AST_CAUSE_INVALID_IE_CONTENTS
, "INVALID_IE_CONTENTS", "Invalid information element contents" },
157 { AST_CAUSE_WRONG_CALL_STATE
, "WRONG_CALL_STATE", "Message not compatible with call state" },
158 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE
, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
159 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR
, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
160 { AST_CAUSE_PROTOCOL_ERROR
, "PROTOCOL_ERROR", "Protocol error, unspecified" },
161 { AST_CAUSE_INTERWORKING
, "INTERWORKING", "Interworking, unspecified" },
164 struct ast_variable
*ast_channeltype_list(void)
167 struct ast_variable
*var
=NULL
, *prev
= NULL
;
168 AST_LIST_TRAVERSE(&backends
, cl
, list
) {
170 if ((prev
->next
= ast_variable_new(cl
->tech
->type
, cl
->tech
->description
)))
173 var
= ast_variable_new(cl
->tech
->type
, cl
->tech
->description
);
180 static int show_channeltypes(int fd
, int argc
, char *argv
[])
182 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
186 ast_cli(fd
, FORMAT
, "Type", "Description", "Devicestate", "Indications", "Transfer");
187 ast_cli(fd
, FORMAT
, "----------", "-----------", "-----------", "-----------", "--------");
188 if (AST_LIST_LOCK(&channels
)) {
189 ast_log(LOG_WARNING
, "Unable to lock channel list\n");
192 AST_LIST_TRAVERSE(&backends
, cl
, list
) {
193 ast_cli(fd
, FORMAT
, cl
->tech
->type
, cl
->tech
->description
,
194 (cl
->tech
->devicestate
) ? "yes" : "no",
195 (cl
->tech
->indicate
) ? "yes" : "no",
196 (cl
->tech
->transfer
) ? "yes" : "no");
199 AST_LIST_UNLOCK(&channels
);
200 ast_cli(fd
, "----------\n%d channel drivers registered.\n", count_chan
);
201 return RESULT_SUCCESS
;
207 static int show_channeltype_deprecated(int fd
, int argc
, char *argv
[])
209 struct chanlist
*cl
= NULL
;
212 return RESULT_SHOWUSAGE
;
214 if (AST_LIST_LOCK(&channels
)) {
215 ast_log(LOG_WARNING
, "Unable to lock channel list\n");
216 return RESULT_FAILURE
;
219 AST_LIST_TRAVERSE(&backends
, cl
, list
) {
220 if (!strncasecmp(cl
->tech
->type
, argv
[2], strlen(cl
->tech
->type
))) {
227 ast_cli(fd
, "\n%s is not a registered channel driver.\n", argv
[2]);
228 AST_LIST_UNLOCK(&channels
);
229 return RESULT_FAILURE
;
233 "-- Info about channel driver: %s --\n"
234 " Device State: %s\n"
237 " Capabilities: %d\n"
241 " Image Support: %s\n"
242 " Text Support: %s\n",
244 (cl
->tech
->devicestate
) ? "yes" : "no",
245 (cl
->tech
->indicate
) ? "yes" : "no",
246 (cl
->tech
->transfer
) ? "yes" : "no",
247 (cl
->tech
->capabilities
) ? cl
->tech
->capabilities
: -1,
248 (cl
->tech
->send_digit_begin
) ? "yes" : "no",
249 (cl
->tech
->send_digit_end
) ? "yes" : "no",
250 (cl
->tech
->send_html
) ? "yes" : "no",
251 (cl
->tech
->send_image
) ? "yes" : "no",
252 (cl
->tech
->send_text
) ? "yes" : "no"
256 AST_LIST_UNLOCK(&channels
);
257 return RESULT_SUCCESS
;
260 static int show_channeltype(int fd
, int argc
, char *argv
[])
262 struct chanlist
*cl
= NULL
;
265 return RESULT_SHOWUSAGE
;
267 if (AST_LIST_LOCK(&channels
)) {
268 ast_log(LOG_WARNING
, "Unable to lock channel list\n");
269 return RESULT_FAILURE
;
272 AST_LIST_TRAVERSE(&backends
, cl
, list
) {
273 if (!strncasecmp(cl
->tech
->type
, argv
[3], strlen(cl
->tech
->type
))) {
280 ast_cli(fd
, "\n%s is not a registered channel driver.\n", argv
[3]);
281 AST_LIST_UNLOCK(&channels
);
282 return RESULT_FAILURE
;
286 "-- Info about channel driver: %s --\n"
287 " Device State: %s\n"
290 " Capabilities: %d\n"
294 " Image Support: %s\n"
295 " Text Support: %s\n",
297 (cl
->tech
->devicestate
) ? "yes" : "no",
298 (cl
->tech
->indicate
) ? "yes" : "no",
299 (cl
->tech
->transfer
) ? "yes" : "no",
300 (cl
->tech
->capabilities
) ? cl
->tech
->capabilities
: -1,
301 (cl
->tech
->send_digit_begin
) ? "yes" : "no",
302 (cl
->tech
->send_digit_end
) ? "yes" : "no",
303 (cl
->tech
->send_html
) ? "yes" : "no",
304 (cl
->tech
->send_image
) ? "yes" : "no",
305 (cl
->tech
->send_text
) ? "yes" : "no"
309 AST_LIST_UNLOCK(&channels
);
310 return RESULT_SUCCESS
;
313 static char *complete_channeltypes_deprecated(const char *line
, const char *word
, int pos
, int state
)
323 wordlen
= strlen(word
);
325 AST_LIST_TRAVERSE(&backends
, cl
, list
) {
326 if (!strncasecmp(word
, cl
->tech
->type
, wordlen
) && ++which
> state
) {
327 ret
= strdup(cl
->tech
->type
);
335 static char *complete_channeltypes(const char *line
, const char *word
, int pos
, int state
)
345 wordlen
= strlen(word
);
347 AST_LIST_TRAVERSE(&backends
, cl
, list
) {
348 if (!strncasecmp(word
, cl
->tech
->type
, wordlen
) && ++which
> state
) {
349 ret
= strdup(cl
->tech
->type
);
357 static char show_channeltypes_usage
[] =
358 "Usage: core show channeltypes\n"
359 " Lists available channel types registered in your Asterisk server.\n";
361 static char show_channeltype_usage
[] =
362 "Usage: core show channeltype <name>\n"
363 " Show details about the specified channel type, <name>.\n";
365 static struct ast_cli_entry cli_show_channeltypes_deprecated
= {
366 { "show", "channeltypes", NULL
},
367 show_channeltypes
, NULL
,
370 static struct ast_cli_entry cli_show_channeltype_deprecated
= {
371 { "show", "channeltype", NULL
},
372 show_channeltype_deprecated
, NULL
,
373 NULL
, complete_channeltypes_deprecated
};
375 static struct ast_cli_entry cli_channel
[] = {
376 { { "core", "show", "channeltypes", NULL
},
377 show_channeltypes
, "List available channel types",
378 show_channeltypes_usage
, NULL
, &cli_show_channeltypes_deprecated
},
380 { { "core", "show", "channeltype", NULL
},
381 show_channeltype
, "Give more details on that channel type",
382 show_channeltype_usage
, complete_channeltypes
, &cli_show_channeltype_deprecated
},
385 /*! \brief Checks to see if a channel is needing hang up */
386 int ast_check_hangup(struct ast_channel
*chan
)
388 if (chan
->_softhangup
) /* yes if soft hangup flag set */
390 if (!chan
->tech_pvt
) /* yes if no technology private data */
392 if (!chan
->whentohangup
) /* no if no hangup scheduled */
394 if (chan
->whentohangup
> time(NULL
)) /* no if hangup time has not come yet. */
396 chan
->_softhangup
|= AST_SOFTHANGUP_TIMEOUT
; /* record event */
400 static int ast_check_hangup_locked(struct ast_channel
*chan
)
403 ast_channel_lock(chan
);
404 res
= ast_check_hangup(chan
);
405 ast_channel_unlock(chan
);
409 /*! \brief printf the string into a correctly sized mallocd buffer, and return the buffer */
410 char *ast_safe_string_alloc(const char *fmt
, ...)
417 len
= vsnprintf(buf
, 1, fmt
, args
);
420 if (!(b2
= ast_malloc(len
+ 1)))
424 vsnprintf(b2
, len
+ 1, fmt
, args
);
430 /*! \brief Initiate system shutdown */
431 void ast_begin_shutdown(int hangup
)
433 struct ast_channel
*c
;
436 AST_LIST_LOCK(&channels
);
437 AST_LIST_TRAVERSE(&channels
, c
, chan_list
)
438 ast_softhangup(c
, AST_SOFTHANGUP_SHUTDOWN
);
439 AST_LIST_UNLOCK(&channels
);
443 /*! \brief returns number of active/allocated channels */
444 int ast_active_channels(void)
446 struct ast_channel
*c
;
448 AST_LIST_LOCK(&channels
);
449 AST_LIST_TRAVERSE(&channels
, c
, chan_list
)
451 AST_LIST_UNLOCK(&channels
);
455 /*! \brief Cancel a shutdown in progress */
456 void ast_cancel_shutdown(void)
461 /*! \brief Returns non-zero if Asterisk is being shut down */
462 int ast_shutting_down(void)
464 return shutting_down
;
467 /*! \brief Set when to hangup channel */
468 void ast_channel_setwhentohangup(struct ast_channel
*chan
, time_t offset
)
470 chan
->whentohangup
= offset
? time(NULL
) + offset
: 0;
471 ast_queue_frame(chan
, &ast_null_frame
);
475 /*! \brief Compare a offset with when to hangup channel */
476 int ast_channel_cmpwhentohangup(struct ast_channel
*chan
, time_t offset
)
480 if (chan
->whentohangup
== 0) {
481 return (offset
== 0) ? 0 : -1;
483 if (offset
== 0) /* XXX why is this special ? */
486 whentohangup
= offset
+ time (NULL
);
487 if (chan
->whentohangup
< whentohangup
)
489 else if (chan
->whentohangup
== whentohangup
)
497 /*! \brief Register a new telephony channel in Asterisk */
498 int ast_channel_register(const struct ast_channel_tech
*tech
)
500 struct chanlist
*chan
;
502 AST_LIST_LOCK(&channels
);
504 AST_LIST_TRAVERSE(&backends
, chan
, list
) {
505 if (!strcasecmp(tech
->type
, chan
->tech
->type
)) {
506 ast_log(LOG_WARNING
, "Already have a handler for type '%s'\n", tech
->type
);
507 AST_LIST_UNLOCK(&channels
);
512 if (!(chan
= ast_calloc(1, sizeof(*chan
)))) {
513 AST_LIST_UNLOCK(&channels
);
517 AST_LIST_INSERT_HEAD(&backends
, chan
, list
);
520 ast_log(LOG_DEBUG
, "Registered handler for '%s' (%s)\n", chan
->tech
->type
, chan
->tech
->description
);
522 if (option_verbose
> 1)
523 ast_verbose(VERBOSE_PREFIX_2
"Registered channel type '%s' (%s)\n", chan
->tech
->type
,
524 chan
->tech
->description
);
526 AST_LIST_UNLOCK(&channels
);
530 void ast_channel_unregister(const struct ast_channel_tech
*tech
)
532 struct chanlist
*chan
;
535 ast_log(LOG_DEBUG
, "Unregistering channel type '%s'\n", tech
->type
);
537 AST_LIST_LOCK(&channels
);
539 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends
, chan
, list
) {
540 if (chan
->tech
== tech
) {
541 AST_LIST_REMOVE_CURRENT(&backends
, list
);
543 if (option_verbose
> 1)
544 ast_verbose(VERBOSE_PREFIX_2
"Unregistered channel type '%s'\n", tech
->type
);
548 AST_LIST_TRAVERSE_SAFE_END
550 AST_LIST_UNLOCK(&channels
);
553 const struct ast_channel_tech
*ast_get_channel_tech(const char *name
)
555 struct chanlist
*chanls
;
556 const struct ast_channel_tech
*ret
= NULL
;
558 if (AST_LIST_LOCK(&channels
)) {
559 ast_log(LOG_WARNING
, "Unable to lock channel tech list\n");
563 AST_LIST_TRAVERSE(&backends
, chanls
, list
) {
564 if (!strcasecmp(name
, chanls
->tech
->type
)) {
570 AST_LIST_UNLOCK(&channels
);
575 /*! \brief Gives the string form of a given hangup cause */
576 const char *ast_cause2str(int cause
)
580 for (x
=0; x
< sizeof(causes
) / sizeof(causes
[0]); x
++) {
581 if (causes
[x
].cause
== cause
)
582 return causes
[x
].desc
;
588 /*! \brief Convert a symbolic hangup cause to number */
589 int ast_str2cause(const char *name
)
593 for (x
= 0; x
< sizeof(causes
) / sizeof(causes
[0]); x
++)
594 if (strncasecmp(causes
[x
].name
, name
, strlen(causes
[x
].name
)) == 0)
595 return causes
[x
].cause
;
600 /*! \brief Gives the string form of a given channel state */
601 char *ast_state2str(enum ast_channel_state state
)
608 case AST_STATE_RESERVED
:
610 case AST_STATE_OFFHOOK
:
612 case AST_STATE_DIALING
:
616 case AST_STATE_RINGING
:
622 case AST_STATE_DIALING_OFFHOOK
:
623 return "Dialing Offhook";
624 case AST_STATE_PRERING
:
627 if (!(buf
= ast_threadstorage_get(&state2str_threadbuf
, STATE2STR_BUFSIZE
)))
629 snprintf(buf
, STATE2STR_BUFSIZE
, "Unknown (%d)", state
);
634 /*! \brief Gives the string form of a given transfer capability */
635 char *ast_transfercapability2str(int transfercapability
)
637 switch(transfercapability
) {
638 case AST_TRANS_CAP_SPEECH
:
640 case AST_TRANS_CAP_DIGITAL
:
642 case AST_TRANS_CAP_RESTRICTED_DIGITAL
:
643 return "RESTRICTED_DIGITAL";
644 case AST_TRANS_CAP_3_1K_AUDIO
:
646 case AST_TRANS_CAP_DIGITAL_W_TONES
:
647 return "DIGITAL_W_TONES";
648 case AST_TRANS_CAP_VIDEO
:
655 /*! \brief Pick the best audio codec */
656 int ast_best_codec(int fmts
)
658 /* This just our opinion, expressed in code. We are asked to choose
659 the best codec to use, given no information */
663 /*! Okay, ulaw is used by all telephony equipment, so start with it */
665 /*! Unless of course, you're a silly European, so then prefer ALAW */
667 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
669 /*! Okay, well, signed linear is easy to translate into other stuff */
671 /*! G.726 is standard ADPCM, in RFC3551 packing order */
673 /*! G.726 is standard ADPCM, in AAL2 packing order */
674 AST_FORMAT_G726_AAL2
,
675 /*! ADPCM has great sound quality and is still pretty easy to translate */
677 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
678 translate and sounds pretty good */
680 /*! iLBC is not too bad */
682 /*! Speex is free, but computationally more expensive than GSM */
684 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
687 /*! G.729a is faster than 723 and slightly less expensive */
689 /*! Down to G.723.1 which is proprietary but at least designed for voice */
693 /* Strip out video */
694 fmts
&= AST_FORMAT_AUDIO_MASK
;
696 /* Find the first preferred codec in the format given */
697 for (x
=0; x
< (sizeof(prefs
) / sizeof(prefs
[0]) ); x
++)
700 ast_log(LOG_WARNING
, "Don't know any of 0x%x formats\n", fmts
);
704 static const struct ast_channel_tech null_tech
= {
706 .description
= "Null channel (should not see this)",
709 /*! \brief Create a new channel structure */
710 struct ast_channel
*ast_channel_alloc(int needqueue
, int state
, const char *cid_num
, const char *cid_name
, const char *acctcode
, const char *exten
, const char *context
, const int amaflag
, const char *name_fmt
, ...)
712 struct ast_channel
*tmp
;
715 struct varshead
*headp
;
718 /* If shutting down, don't allocate any new channels */
720 ast_log(LOG_WARNING
, "Channel allocation failed: Refusing due to active shutdown\n");
724 if (!(tmp
= ast_calloc(1, sizeof(*tmp
))))
727 if (!(tmp
->sched
= sched_context_create())) {
728 ast_log(LOG_WARNING
, "Channel allocation failed: Unable to create schedule context\n");
733 if ((ast_string_field_init(tmp
, 128))) {
734 sched_context_destroy(tmp
->sched
);
739 /* Don't bother initializing the last two FD here, because they
740 will *always* be set just a few lines down (AST_TIMING_FD,
742 for (x
= 0; x
< AST_MAX_FDS
- 2; x
++)
746 tmp
->timingfd
= open("/dev/zap/timer", O_RDWR
);
747 if (tmp
->timingfd
> -1) {
748 /* Check if timing interface supports new
751 if (!ioctl(tmp
->timingfd
, ZT_TIMERPONG
, &flags
))
759 if (pipe(tmp
->alertpipe
)) {
760 ast_log(LOG_WARNING
, "Channel allocation failed: Can't create alert pipe!\n");
762 if (tmp
->timingfd
> -1)
763 close(tmp
->timingfd
);
765 sched_context_destroy(tmp
->sched
);
766 ast_string_field_free_memory(tmp
);
770 flags
= fcntl(tmp
->alertpipe
[0], F_GETFL
);
771 fcntl(tmp
->alertpipe
[0], F_SETFL
, flags
| O_NONBLOCK
);
772 flags
= fcntl(tmp
->alertpipe
[1], F_GETFL
);
773 fcntl(tmp
->alertpipe
[1], F_SETFL
, flags
| O_NONBLOCK
);
775 } else /* Make sure we've got it done right if they don't */
776 tmp
->alertpipe
[0] = tmp
->alertpipe
[1] = -1;
778 /* Always watch the alertpipe */
779 tmp
->fds
[AST_ALERT_FD
] = tmp
->alertpipe
[0];
780 /* And timing pipe */
781 tmp
->fds
[AST_TIMING_FD
] = tmp
->timingfd
;
782 ast_string_field_set(tmp
, name
, "**Unknown**");
789 tmp
->fin
= global_fin
;
790 tmp
->fout
= global_fout
;
792 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME
)) {
793 ast_string_field_build(tmp
, uniqueid
, "%li.%d", (long) time(NULL
),
794 ast_atomic_fetchadd_int(&uniqueint
, 1));
796 ast_string_field_build(tmp
, uniqueid
, "%s-%li.%d", ast_config_AST_SYSTEM_NAME
,
797 (long) time(NULL
), ast_atomic_fetchadd_int(&uniqueint
, 1));
800 tmp
->cid
.cid_name
= ast_strdup(cid_name
);
801 tmp
->cid
.cid_num
= ast_strdup(cid_num
);
803 if (!ast_strlen_zero(name_fmt
)) {
804 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
805 * And they all use slightly different formats for their name string.
806 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
807 * This means, that the stringfields must have a routine that takes the va_lists directly, and
808 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
809 * This new function was written so this can be accomplished.
811 va_start(ap1
, name_fmt
);
812 va_start(ap2
, name_fmt
);
813 ast_string_field_build_va(tmp
, name
, name_fmt
, ap1
, ap2
);
818 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
820 /* These 4 variables need to be set up for the cdr_init() to work right */
822 tmp
->amaflags
= amaflag
;
824 tmp
->amaflags
= ast_default_amaflags
;
826 if (!ast_strlen_zero(acctcode
))
827 ast_string_field_set(tmp
, accountcode
, acctcode
);
829 ast_string_field_set(tmp
, accountcode
, ast_default_accountcode
);
831 if (!ast_strlen_zero(context
))
832 ast_copy_string(tmp
->context
, context
, sizeof(tmp
->context
));
834 strcpy(tmp
->context
, "default");
836 if (!ast_strlen_zero(exten
))
837 ast_copy_string(tmp
->exten
, exten
, sizeof(tmp
->exten
));
839 strcpy(tmp
->exten
, "s");
843 tmp
->cdr
= ast_cdr_alloc();
844 ast_cdr_init(tmp
->cdr
, tmp
);
845 ast_cdr_start(tmp
->cdr
);
847 headp
= &tmp
->varshead
;
848 AST_LIST_HEAD_INIT_NOLOCK(headp
);
850 ast_mutex_init(&tmp
->lock
);
852 AST_LIST_HEAD_INIT_NOLOCK(&tmp
->datastores
);
854 ast_string_field_set(tmp
, language
, defaultlanguage
);
856 tmp
->tech
= &null_tech
;
858 AST_LIST_LOCK(&channels
);
859 AST_LIST_INSERT_HEAD(&channels
, tmp
, chan_list
);
860 AST_LIST_UNLOCK(&channels
);
863 * and now, since the channel structure is built, and has its name, let's
864 * call the manager event generator with this Newchannel event. This is the
865 * proper and correct place to make this call, but you sure do have to pass
866 * a lot of data into this func to do it here!
868 if (!ast_strlen_zero(name_fmt
)) {
869 manager_event(EVENT_FLAG_CALL
, "Newchannel",
872 "CallerIDNum: %s\r\n"
873 "CallerIDName: %s\r\n"
875 tmp
->name
, ast_state2str(state
),
876 S_OR(cid_num
, "<unknown>"),
877 S_OR(cid_name
, "<unknown>"),
884 /*! \brief Queue an outgoing media frame */
885 int ast_queue_frame(struct ast_channel
*chan
, struct ast_frame
*fin
)
888 struct ast_frame
*cur
;
892 /* Build us a copy and free the original one */
893 if (!(f
= ast_frdup(fin
))) {
894 ast_log(LOG_WARNING
, "Unable to duplicate frame\n");
897 ast_channel_lock(chan
);
899 /* See if the last frame on the queue is a hangup, if so don't queue anything */
900 if ((cur
= AST_LIST_LAST(&chan
->readq
)) && (cur
->frametype
== AST_FRAME_CONTROL
) && (cur
->subclass
== AST_CONTROL_HANGUP
)) {
902 ast_channel_unlock(chan
);
906 /* Count how many frames exist on the queue */
907 AST_LIST_TRAVERSE(&chan
->readq
, cur
, frame_list
) {
911 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
912 if (((fin
->frametype
== AST_FRAME_VOICE
) && (qlen
> 96)) || (qlen
> 128)) {
913 if (fin
->frametype
!= AST_FRAME_VOICE
) {
914 ast_log(LOG_WARNING
, "Exceptionally long queue length queuing to %s\n", chan
->name
);
918 ast_log(LOG_DEBUG
, "Dropping voice to exceptionally long queue on %s\n", chan
->name
);
920 ast_channel_unlock(chan
);
924 AST_LIST_INSERT_TAIL(&chan
->readq
, f
, frame_list
);
925 if (chan
->alertpipe
[1] > -1) {
926 if (write(chan
->alertpipe
[1], &blah
, sizeof(blah
)) != sizeof(blah
))
927 ast_log(LOG_WARNING
, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
928 chan
->name
, f
->frametype
, f
->subclass
, qlen
, strerror(errno
));
930 } else if (chan
->timingfd
> -1) {
931 ioctl(chan
->timingfd
, ZT_TIMERPING
, &blah
);
933 } else if (ast_test_flag(chan
, AST_FLAG_BLOCKING
)) {
934 pthread_kill(chan
->blocker
, SIGURG
);
936 ast_channel_unlock(chan
);
940 /*! \brief Queue a hangup frame for channel */
941 int ast_queue_hangup(struct ast_channel
*chan
)
943 struct ast_frame f
= { AST_FRAME_CONTROL
, AST_CONTROL_HANGUP
};
944 /* Yeah, let's not change a lock-critical value without locking */
945 if (!ast_channel_trylock(chan
)) {
946 chan
->_softhangup
|= AST_SOFTHANGUP_DEV
;
947 ast_channel_unlock(chan
);
949 return ast_queue_frame(chan
, &f
);
952 /*! \brief Queue a control frame */
953 int ast_queue_control(struct ast_channel
*chan
, enum ast_control_frame_type control
)
955 struct ast_frame f
= { AST_FRAME_CONTROL
, };
957 f
.subclass
= control
;
959 return ast_queue_frame(chan
, &f
);
962 /*! \brief Queue a control frame with payload */
963 int ast_queue_control_data(struct ast_channel
*chan
, enum ast_control_frame_type control
,
964 const void *data
, size_t datalen
)
966 struct ast_frame f
= { AST_FRAME_CONTROL
, };
968 f
.subclass
= control
;
969 f
.data
= (void *) data
;
972 return ast_queue_frame(chan
, &f
);
975 /*! \brief Set defer DTMF flag on channel */
976 int ast_channel_defer_dtmf(struct ast_channel
*chan
)
981 pre
= ast_test_flag(chan
, AST_FLAG_DEFER_DTMF
);
982 ast_set_flag(chan
, AST_FLAG_DEFER_DTMF
);
987 /*! \brief Unset defer DTMF flag on channel */
988 void ast_channel_undefer_dtmf(struct ast_channel
*chan
)
991 ast_clear_flag(chan
, AST_FLAG_DEFER_DTMF
);
995 * \brief Helper function to find channels.
997 * It supports these modes:
999 * prev != NULL : get channel next in list after prev
1000 * name != NULL : get channel with matching name
1001 * name != NULL && namelen != 0 : get channel whose name starts with prefix
1002 * exten != NULL : get channel whose exten or macroexten matches
1003 * context != NULL && exten != NULL : get channel whose context or macrocontext
1005 * It returns with the channel's lock held. If getting the individual lock fails,
1006 * unlock and retry quickly up to 10 times, then give up.
1008 * \note XXX Note that this code has cost O(N) because of the need to verify
1009 * that the object is still on the global list.
1011 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
1012 * can only be done with the lock held or someone could delete the
1013 * object while we work on it. This causes some ugliness in the code.
1014 * Note that removing the first ast_log() may be harmful, as it would
1015 * shorten the retry period and possibly cause failures.
1016 * We should definitely go for a better scheme that is deadlock-free.
1018 static struct ast_channel
*channel_find_locked(const struct ast_channel
*prev
,
1019 const char *name
, const int namelen
,
1020 const char *context
, const char *exten
)
1022 const char *msg
= prev
? "deadlock" : "initial deadlock";
1024 struct ast_channel
*c
;
1025 const struct ast_channel
*_prev
= prev
;
1027 for (retries
= 0; retries
< 200; retries
++) {
1029 AST_LIST_LOCK(&channels
);
1030 AST_LIST_TRAVERSE(&channels
, c
, chan_list
) {
1032 if (prev
) { /* look for next item */
1033 if (c
!= prev
) /* not this one */
1035 /* found, prepare to return c->next */
1036 if ((c
= AST_LIST_NEXT(c
, chan_list
)) == NULL
) break;
1037 /* If prev was the last item on the channel list, then we just
1038 * want to return NULL, instead of trying to deref NULL in the
1042 /* We want prev to be NULL in case we end up doing more searching through
1043 * the channel list to find the channel (ie: name searching). If we didn't
1044 * set this to NULL the logic would just blow up
1045 * XXX Need a better explanation for this ...
1048 if (name
) { /* want match by name */
1049 if ((!namelen
&& strcasecmp(c
->name
, name
)) ||
1050 (namelen
&& strncasecmp(c
->name
, name
, namelen
)))
1051 continue; /* name match failed */
1053 if (context
&& strcasecmp(c
->context
, context
) &&
1054 strcasecmp(c
->macrocontext
, context
))
1055 continue; /* context match failed */
1056 if (strcasecmp(c
->exten
, exten
) &&
1057 strcasecmp(c
->macroexten
, exten
))
1058 continue; /* exten match failed */
1060 /* if we get here, c points to the desired record */
1063 /* exit if chan not found or mutex acquired successfully */
1064 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
1065 done
= c
== NULL
|| ast_channel_trylock(c
) == 0;
1068 ast_log(LOG_DEBUG
, "Avoiding %s for channel '%p'\n", msg
, c
);
1069 if (retries
== 199) {
1070 /* We are about to fail due to a deadlock, so report this
1071 * while we still have the list lock.
1074 ast_log(LOG_DEBUG
, "Failure, could not lock '%p' after %d retries!\n", c
, retries
);
1075 /* As we have deadlocked, we will skip this channel and
1076 * see if there is another match.
1077 * NOTE: No point doing this for a full-name match,
1078 * as there can be no more matches.
1080 if (!(name
&& !namelen
)) {
1086 AST_LIST_UNLOCK(&channels
);
1089 /* If we reach this point we basically tried to lock a channel and failed. Instead of
1090 * starting from the beginning of the list we can restore our saved pointer to the previous
1091 * channel and start from there.
1094 usleep(1); /* give other threads a chance before retrying */
1100 /*! \brief Browse channels in use */
1101 struct ast_channel
*ast_channel_walk_locked(const struct ast_channel
*prev
)
1103 return channel_find_locked(prev
, NULL
, 0, NULL
, NULL
);
1106 /*! \brief Get channel by name and lock it */
1107 struct ast_channel
*ast_get_channel_by_name_locked(const char *name
)
1109 return channel_find_locked(NULL
, name
, 0, NULL
, NULL
);
1112 /*! \brief Get channel by name prefix and lock it */
1113 struct ast_channel
*ast_get_channel_by_name_prefix_locked(const char *name
, const int namelen
)
1115 return channel_find_locked(NULL
, name
, namelen
, NULL
, NULL
);
1118 /*! \brief Get next channel by name prefix and lock it */
1119 struct ast_channel
*ast_walk_channel_by_name_prefix_locked(const struct ast_channel
*chan
, const char *name
,
1122 return channel_find_locked(chan
, name
, namelen
, NULL
, NULL
);
1125 /*! \brief Get channel by exten (and optionally context) and lock it */
1126 struct ast_channel
*ast_get_channel_by_exten_locked(const char *exten
, const char *context
)
1128 return channel_find_locked(NULL
, NULL
, 0, context
, exten
);
1131 /*! \brief Get next channel by exten (and optionally context) and lock it */
1132 struct ast_channel
*ast_walk_channel_by_exten_locked(const struct ast_channel
*chan
, const char *exten
,
1133 const char *context
)
1135 return channel_find_locked(chan
, NULL
, 0, context
, exten
);
1138 /*! \brief Wait, look for hangups and condition arg */
1139 int ast_safe_sleep_conditional(struct ast_channel
*chan
, int ms
, int (*cond
)(void*), void *data
)
1141 struct ast_frame
*f
;
1144 if (cond
&& ((*cond
)(data
) == 0))
1146 ms
= ast_waitfor(chan
, ms
);
1159 /*! \brief Wait, look for hangups */
1160 int ast_safe_sleep(struct ast_channel
*chan
, int ms
)
1162 return ast_safe_sleep_conditional(chan
, ms
, NULL
, NULL
);
1165 static void free_cid(struct ast_callerid
*cid
)
1168 free(cid
->cid_dnid
);
1172 free(cid
->cid_name
);
1176 free(cid
->cid_rdnis
);
1179 /*! \brief Free a channel structure */
1180 void ast_channel_free(struct ast_channel
*chan
)
1183 struct ast_var_t
*vardata
;
1184 struct ast_frame
*f
;
1185 struct varshead
*headp
;
1186 struct ast_datastore
*datastore
= NULL
;
1187 char name
[AST_CHANNEL_NAME
];
1189 headp
=&chan
->varshead
;
1191 AST_LIST_LOCK(&channels
);
1192 if (!AST_LIST_REMOVE(&channels
, chan
, chan_list
)) {
1193 AST_LIST_UNLOCK(&channels
);
1194 ast_log(LOG_ERROR
, "Unable to find channel in list to free. Assuming it has already been done.\n");
1196 /* Lock and unlock the channel just to be sure nobody has it locked still
1197 due to a reference retrieved from the channel list. */
1198 ast_channel_lock(chan
);
1199 ast_channel_unlock(chan
);
1201 /* Get rid of each of the data stores on the channel */
1202 while ((datastore
= AST_LIST_REMOVE_HEAD(&chan
->datastores
, entry
)))
1203 /* Free the data store */
1204 ast_channel_datastore_free(datastore
);
1206 /* Lock and unlock the channel just to be sure nobody has it locked still
1207 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
1208 ast_channel_lock(chan
);
1209 ast_channel_unlock(chan
);
1211 if (chan
->tech_pvt
) {
1212 ast_log(LOG_WARNING
, "Channel '%s' may not have been hung up properly\n", chan
->name
);
1213 free(chan
->tech_pvt
);
1217 sched_context_destroy(chan
->sched
);
1219 ast_copy_string(name
, chan
->name
, sizeof(name
));
1221 /* Stop monitoring */
1223 chan
->monitor
->stop( chan
, 0 );
1225 /* If there is native format music-on-hold state, free it */
1226 if (chan
->music_state
)
1227 ast_moh_cleanup(chan
);
1229 /* Free translators */
1230 if (chan
->readtrans
)
1231 ast_translator_free_path(chan
->readtrans
);
1232 if (chan
->writetrans
)
1233 ast_translator_free_path(chan
->writetrans
);
1235 ast_log(LOG_WARNING
, "PBX may not have been terminated properly on '%s'\n", chan
->name
);
1236 free_cid(&chan
->cid
);
1237 /* Close pipes if appropriate */
1238 if ((fd
= chan
->alertpipe
[0]) > -1)
1240 if ((fd
= chan
->alertpipe
[1]) > -1)
1242 if ((fd
= chan
->timingfd
) > -1)
1244 while ((f
= AST_LIST_REMOVE_HEAD(&chan
->readq
, frame_list
)))
1247 /* loop over the variables list, freeing all data and deleting list items */
1248 /* no need to lock the list, as the channel is already locked */
1250 while ((vardata
= AST_LIST_REMOVE_HEAD(headp
, entries
)))
1251 ast_var_delete(vardata
);
1253 ast_app_group_discard(chan
);
1255 /* Destroy the jitterbuffer */
1256 ast_jb_destroy(chan
);
1258 ast_mutex_destroy(&chan
->lock
);
1260 ast_string_field_free_memory(chan
);
1262 AST_LIST_UNLOCK(&channels
);
1264 ast_device_state_changed_literal(name
);
1267 struct ast_datastore
*ast_channel_datastore_alloc(const struct ast_datastore_info
*info
, char *uid
)
1269 struct ast_datastore
*datastore
= NULL
;
1271 /* Make sure we at least have type so we can identify this */
1276 /* Allocate memory for datastore and clear it */
1277 datastore
= ast_calloc(1, sizeof(*datastore
));
1278 if (datastore
== NULL
) {
1282 datastore
->info
= info
;
1284 datastore
->uid
= ast_strdup(uid
);
1289 int ast_channel_datastore_free(struct ast_datastore
*datastore
)
1293 /* Using the destroy function (if present) destroy the data */
1294 if (datastore
->info
->destroy
!= NULL
&& datastore
->data
!= NULL
) {
1295 datastore
->info
->destroy(datastore
->data
);
1296 datastore
->data
= NULL
;
1299 /* Free allocated UID memory */
1300 if (datastore
->uid
!= NULL
) {
1301 free(datastore
->uid
);
1302 datastore
->uid
= NULL
;
1305 /* Finally free memory used by ourselves */
1311 int ast_channel_datastore_inherit(struct ast_channel
*from
, struct ast_channel
*to
)
1313 struct ast_datastore
*datastore
= NULL
, *datastore2
;
1315 AST_LIST_TRAVERSE(&from
->datastores
, datastore
, entry
) {
1316 if (datastore
->inheritance
> 0) {
1317 datastore2
= ast_channel_datastore_alloc(datastore
->info
, datastore
->uid
);
1319 datastore2
->data
= datastore
->info
->duplicate(datastore
->data
);
1320 datastore2
->inheritance
= datastore
->inheritance
== DATASTORE_INHERIT_FOREVER
? DATASTORE_INHERIT_FOREVER
: datastore
->inheritance
- 1;
1321 AST_LIST_INSERT_TAIL(&to
->datastores
, datastore2
, entry
);
1328 int ast_channel_datastore_add(struct ast_channel
*chan
, struct ast_datastore
*datastore
)
1332 AST_LIST_INSERT_HEAD(&chan
->datastores
, datastore
, entry
);
1337 int ast_channel_datastore_remove(struct ast_channel
*chan
, struct ast_datastore
*datastore
)
1339 struct ast_datastore
*datastore2
= NULL
;
1342 /* Find our position and remove ourselves */
1343 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan
->datastores
, datastore2
, entry
) {
1344 if (datastore2
== datastore
) {
1345 AST_LIST_REMOVE_CURRENT(&chan
->datastores
, entry
);
1350 AST_LIST_TRAVERSE_SAFE_END
1355 struct ast_datastore
*ast_channel_datastore_find(struct ast_channel
*chan
, const struct ast_datastore_info
*info
, char *uid
)
1357 struct ast_datastore
*datastore
= NULL
;
1362 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan
->datastores
, datastore
, entry
) {
1363 if (datastore
->info
== info
) {
1364 if (uid
!= NULL
&& datastore
->uid
!= NULL
) {
1365 if (!strcasecmp(uid
, datastore
->uid
)) {
1366 /* Matched by type AND uid */
1370 /* Matched by type at least */
1375 AST_LIST_TRAVERSE_SAFE_END
1380 /*! \brief Softly hangup a channel, don't lock */
1381 int ast_softhangup_nolock(struct ast_channel
*chan
, int cause
)
1384 ast_log(LOG_DEBUG
, "Soft-Hanging up channel '%s'\n", chan
->name
);
1385 /* Inform channel driver that we need to be hung up, if it cares */
1386 chan
->_softhangup
|= cause
;
1387 ast_queue_frame(chan
, &ast_null_frame
);
1388 /* Interrupt any poll call or such */
1389 if (ast_test_flag(chan
, AST_FLAG_BLOCKING
))
1390 pthread_kill(chan
->blocker
, SIGURG
);
1394 /*! \brief Softly hangup a channel, lock */
1395 int ast_softhangup(struct ast_channel
*chan
, int cause
)
1398 ast_channel_lock(chan
);
1399 res
= ast_softhangup_nolock(chan
, cause
);
1400 ast_channel_unlock(chan
);
1404 static void free_translation(struct ast_channel
*clone
)
1406 if (clone
->writetrans
)
1407 ast_translator_free_path(clone
->writetrans
);
1408 if (clone
->readtrans
)
1409 ast_translator_free_path(clone
->readtrans
);
1410 clone
->writetrans
= NULL
;
1411 clone
->readtrans
= NULL
;
1412 clone
->rawwriteformat
= clone
->nativeformats
;
1413 clone
->rawreadformat
= clone
->nativeformats
;
1416 /*! \brief Hangup a channel */
1417 int ast_hangup(struct ast_channel
*chan
)
1420 struct ast_cdr
*cdr
= NULL
;
1422 /* Don't actually hang up a channel that will masquerade as someone else, or
1423 if someone is going to masquerade as us */
1424 ast_channel_lock(chan
);
1426 if (chan
->audiohooks
) {
1427 ast_audiohook_detach_list(chan
->audiohooks
);
1428 chan
->audiohooks
= NULL
;
1431 ast_autoservice_stop(chan
);
1434 if (ast_do_masquerade(chan
))
1435 ast_log(LOG_WARNING
, "Failed to perform masquerade\n");
1439 ast_log(LOG_WARNING
, "%s getting hung up, but someone is trying to masq into us?!?\n", chan
->name
);
1440 ast_channel_unlock(chan
);
1443 /* If this channel is one which will be masqueraded into something,
1444 mark it as a zombie already, so we know to free it later */
1446 ast_set_flag(chan
, AST_FLAG_ZOMBIE
);
1447 ast_channel_unlock(chan
);
1450 free_translation(chan
);
1451 /* Close audio stream */
1453 ast_closestream(chan
->stream
);
1454 chan
->stream
= NULL
;
1456 /* Close video stream */
1457 if (chan
->vstream
) {
1458 ast_closestream(chan
->vstream
);
1459 chan
->vstream
= NULL
;
1462 sched_context_destroy(chan
->sched
);
1466 if (chan
->generatordata
) /* Clear any tone stuff remaining */
1467 chan
->generator
->release(chan
, chan
->generatordata
);
1468 chan
->generatordata
= NULL
;
1469 chan
->generator
= NULL
;
1470 if (chan
->cdr
) { /* End the CDR if it hasn't already */
1471 ast_cdr_end(chan
->cdr
);
1475 if (ast_test_flag(chan
, AST_FLAG_BLOCKING
)) {
1476 ast_log(LOG_WARNING
, "Hard hangup called by thread %ld on %s, while fd "
1477 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1478 (long)pthread_self(), chan
->name
, (long)chan
->blocker
, chan
->blockproc
);
1481 if (!ast_test_flag(chan
, AST_FLAG_ZOMBIE
)) {
1483 ast_log(LOG_DEBUG
, "Hanging up channel '%s'\n", chan
->name
);
1484 if (chan
->tech
->hangup
)
1485 res
= chan
->tech
->hangup(chan
);
1488 ast_log(LOG_DEBUG
, "Hanging up zombie '%s'\n", chan
->name
);
1491 ast_channel_unlock(chan
);
1492 manager_event(EVENT_FLAG_CALL
, "Hangup",
1496 "Cause-txt: %s\r\n",
1500 ast_cause2str(chan
->hangupcause
)
1502 ast_channel_free(chan
);
1505 ast_cdr_detach(cdr
);
1510 int ast_answer(struct ast_channel
*chan
)
1513 ast_channel_lock(chan
);
1514 /* You can't answer an outbound call */
1515 if (ast_test_flag(chan
, AST_FLAG_OUTGOING
)) {
1516 ast_channel_unlock(chan
);
1519 /* Stop if we're a zombie or need a soft hangup */
1520 if (ast_test_flag(chan
, AST_FLAG_ZOMBIE
) || ast_check_hangup(chan
)) {
1521 ast_channel_unlock(chan
);
1524 switch(chan
->_state
) {
1525 case AST_STATE_RINGING
:
1526 case AST_STATE_RING
:
1527 if (chan
->tech
->answer
)
1528 res
= chan
->tech
->answer(chan
);
1529 ast_setstate(chan
, AST_STATE_UP
);
1530 ast_cdr_answer(chan
->cdr
);
1533 ast_cdr_answer(chan
->cdr
);
1538 chan
->visible_indication
= 0;
1539 ast_channel_unlock(chan
);
1543 void ast_deactivate_generator(struct ast_channel
*chan
)
1545 ast_channel_lock(chan
);
1546 if (chan
->generatordata
) {
1547 if (chan
->generator
&& chan
->generator
->release
)
1548 chan
->generator
->release(chan
, chan
->generatordata
);
1549 chan
->generatordata
= NULL
;
1550 chan
->generator
= NULL
;
1551 chan
->fds
[AST_GENERATOR_FD
] = -1;
1552 ast_clear_flag(chan
, AST_FLAG_WRITE_INT
);
1553 ast_settimeout(chan
, 0, NULL
, NULL
);
1555 ast_channel_unlock(chan
);
1558 static int generator_force(const void *data
)
1560 /* Called if generator doesn't have data */
1563 int (*generate
)(struct ast_channel
*chan
, void *tmp
, int datalen
, int samples
) = NULL
;
1564 struct ast_channel
*chan
= (struct ast_channel
*)data
;
1566 ast_channel_lock(chan
);
1567 tmp
= chan
->generatordata
;
1568 chan
->generatordata
= NULL
;
1569 if (chan
->generator
)
1570 generate
= chan
->generator
->generate
;
1571 ast_channel_unlock(chan
);
1573 if (!tmp
|| !generate
)
1576 res
= generate(chan
, tmp
, 0, ast_format_rate(chan
->writeformat
& AST_FORMAT_AUDIO_MASK
) / 50);
1578 chan
->generatordata
= tmp
;
1582 ast_log(LOG_DEBUG
, "Auto-deactivating generator\n");
1583 ast_deactivate_generator(chan
);
1589 int ast_activate_generator(struct ast_channel
*chan
, struct ast_generator
*gen
, void *params
)
1593 ast_channel_lock(chan
);
1595 if (chan
->generatordata
) {
1596 if (chan
->generator
&& chan
->generator
->release
)
1597 chan
->generator
->release(chan
, chan
->generatordata
);
1598 chan
->generatordata
= NULL
;
1602 if (gen
->alloc
&& !(chan
->generatordata
= gen
->alloc(chan
, params
))) {
1607 ast_settimeout(chan
, 160, generator_force
, chan
);
1608 chan
->generator
= gen
;
1611 ast_channel_unlock(chan
);
1616 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1617 int ast_waitfor_n_fd(int *fds
, int n
, int *ms
, int *exception
)
1620 ast_waitfor_nandfds(NULL
, 0, fds
, n
, exception
, &winner
, ms
);
1624 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1625 struct ast_channel
*ast_waitfor_nandfds(struct ast_channel
**c
, int n
, int *fds
, int nfds
,
1626 int *exception
, int *outfd
, int *ms
)
1628 struct timeval start
= { 0 , 0 };
1629 struct pollfd
*pfds
= NULL
;
1635 long whentohangup
= 0, diff
;
1636 struct ast_channel
*winner
= NULL
;
1642 if ((sz
= n
* AST_MAX_FDS
+ nfds
)) {
1643 pfds
= alloca(sizeof(*pfds
) * sz
);
1644 fdmap
= alloca(sizeof(*fdmap
) * sz
);
1652 /* Perform any pending masquerades */
1653 for (x
=0; x
< n
; x
++) {
1654 ast_channel_lock(c
[x
]);
1656 if (ast_do_masquerade(c
[x
])) {
1657 ast_log(LOG_WARNING
, "Masquerade failed\n");
1659 ast_channel_unlock(c
[x
]);
1663 if (c
[x
]->whentohangup
) {
1666 diff
= c
[x
]->whentohangup
- now
;
1668 /* Should already be hungup */
1669 c
[x
]->_softhangup
|= AST_SOFTHANGUP_TIMEOUT
;
1670 ast_channel_unlock(c
[x
]);
1673 if (!whentohangup
|| (diff
< whentohangup
))
1674 whentohangup
= diff
;
1676 ast_channel_unlock(c
[x
]);
1678 /* Wait full interval */
1681 rms
= whentohangup
* 1000; /* timeout in milliseconds */
1682 if (*ms
>= 0 && *ms
< rms
) /* original *ms still smaller */
1686 * Build the pollfd array, putting the channels' fds first,
1687 * followed by individual fds. Order is important because
1688 * individual fd's must have priority over channel fds.
1691 for (x
=0; x
<n
; x
++) {
1692 for (y
=0; y
<AST_MAX_FDS
; y
++) {
1693 fdmap
[max
].fdno
= y
; /* fd y is linked to this pfds */
1694 fdmap
[max
].chan
= x
; /* channel x is linked to this pfds */
1695 max
+= ast_add_fd(&pfds
[max
], c
[x
]->fds
[y
]);
1697 CHECK_BLOCKING(c
[x
]);
1699 /* Add the individual fds */
1700 for (x
=0; x
<nfds
; x
++) {
1701 fdmap
[max
].chan
= -1;
1702 max
+= ast_add_fd(&pfds
[max
], fds
[x
]);
1706 start
= ast_tvnow();
1708 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1713 res
= poll(pfds
, max
, kbrms
);
1716 } while (!res
&& (rms
> 0));
1718 res
= poll(pfds
, max
, rms
);
1721 ast_clear_flag(c
[x
], AST_FLAG_BLOCKING
);
1722 if (res
< 0) { /* Simulate a timeout if we were interrupted */
1727 if (whentohangup
) { /* if we have a timeout, check who expired */
1729 for (x
=0; x
<n
; x
++) {
1730 if (c
[x
]->whentohangup
&& now
>= c
[x
]->whentohangup
) {
1731 c
[x
]->_softhangup
|= AST_SOFTHANGUP_TIMEOUT
;
1737 if (res
== 0) { /* no fd ready, reset timeout and done */
1738 *ms
= 0; /* XXX use 0 since we may not have an exact timeout. */
1742 * Then check if any channel or fd has a pending event.
1743 * Remember to check channels first and fds last, as they
1744 * must have priority on setting 'winner'
1746 for (x
= 0; x
< max
; x
++) {
1747 res
= pfds
[x
].revents
;
1750 if (fdmap
[x
].chan
>= 0) { /* this is a channel */
1751 winner
= c
[fdmap
[x
].chan
]; /* override previous winners */
1753 ast_set_flag(winner
, AST_FLAG_EXCEPTION
);
1755 ast_clear_flag(winner
, AST_FLAG_EXCEPTION
);
1756 winner
->fdno
= fdmap
[x
].fdno
;
1757 } else { /* this is an fd */
1759 *outfd
= pfds
[x
].fd
;
1761 *exception
= (res
& POLLPRI
) ? -1 : 0;
1766 *ms
-= ast_tvdiff_ms(ast_tvnow(), start
);
1773 struct ast_channel
*ast_waitfor_n(struct ast_channel
**c
, int n
, int *ms
)
1775 return ast_waitfor_nandfds(c
, n
, NULL
, 0, NULL
, NULL
, ms
);
1778 int ast_waitfor(struct ast_channel
*c
, int ms
)
1780 int oldms
= ms
; /* -1 if no timeout */
1782 ast_waitfor_nandfds(&c
, 1, NULL
, 0, NULL
, NULL
, &ms
);
1783 if ((ms
< 0) && (oldms
< 0))
1788 /* XXX never to be called with ms = -1 */
1789 int ast_waitfordigit(struct ast_channel
*c
, int ms
)
1791 return ast_waitfordigit_full(c
, ms
, -1, -1);
1794 int ast_settimeout(struct ast_channel
*c
, int samples
, int (*func
)(const void *data
), void *data
)
1798 if (c
->timingfd
> -1) {
1804 ast_log(LOG_DEBUG
, "Scheduling timer at %d sample intervals\n", samples
);
1805 res
= ioctl(c
->timingfd
, ZT_TIMERCONFIG
, &samples
);
1806 c
->timingfunc
= func
;
1807 c
->timingdata
= data
;
1813 int ast_waitfordigit_full(struct ast_channel
*c
, int ms
, int audiofd
, int cmdfd
)
1815 /* Stop if we're a zombie or need a soft hangup */
1816 if (ast_test_flag(c
, AST_FLAG_ZOMBIE
) || ast_check_hangup(c
))
1819 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
1820 ast_set_flag(c
, AST_FLAG_END_DTMF_ONLY
);
1822 /* Wait for a digit, no more than ms milliseconds total. */
1824 struct ast_channel
*rchan
;
1828 rchan
= ast_waitfor_nandfds(&c
, 1, &cmdfd
, (cmdfd
> -1) ? 1 : 0, NULL
, &outfd
, &ms
);
1829 if (!rchan
&& outfd
< 0 && ms
) {
1830 if (errno
== 0 || errno
== EINTR
)
1832 ast_log(LOG_WARNING
, "Wait failed (%s)\n", strerror(errno
));
1833 ast_clear_flag(c
, AST_FLAG_END_DTMF_ONLY
);
1835 } else if (outfd
> -1) {
1836 /* The FD we were watching has something waiting */
1837 ast_clear_flag(c
, AST_FLAG_END_DTMF_ONLY
);
1841 struct ast_frame
*f
= ast_read(c
);
1845 switch(f
->frametype
) {
1846 case AST_FRAME_DTMF_BEGIN
:
1848 case AST_FRAME_DTMF_END
:
1851 ast_clear_flag(c
, AST_FLAG_END_DTMF_ONLY
);
1853 case AST_FRAME_CONTROL
:
1854 switch(f
->subclass
) {
1855 case AST_CONTROL_HANGUP
:
1857 ast_clear_flag(c
, AST_FLAG_END_DTMF_ONLY
);
1859 case AST_CONTROL_RINGING
:
1860 case AST_CONTROL_ANSWER
:
1861 case AST_CONTROL_SRCUPDATE
:
1865 ast_log(LOG_WARNING
, "Unexpected control subclass '%d'\n", f
->subclass
);
1869 case AST_FRAME_VOICE
:
1870 /* Write audio if appropriate */
1872 write(audiofd
, f
->data
, f
->datalen
);
1881 ast_clear_flag(c
, AST_FLAG_END_DTMF_ONLY
);
1883 return 0; /* Time is up */
1886 static void ast_read_generator_actions(struct ast_channel
*chan
, struct ast_frame
*f
)
1888 if (chan
->generatordata
&& !ast_internal_timing_enabled(chan
)) {
1889 void *tmp
= chan
->generatordata
;
1890 int (*generate
)(struct ast_channel
*chan
, void *tmp
, int datalen
, int samples
) = NULL
;
1894 if (chan
->timingfunc
) {
1895 if (option_debug
> 1)
1896 ast_log(LOG_DEBUG
, "Generator got voice, switching to phase locked mode\n");
1897 ast_settimeout(chan
, 0, NULL
, NULL
);
1900 chan
->generatordata
= NULL
; /* reset, to let writes go through */
1902 if (f
->subclass
!= chan
->writeformat
) {
1904 factor
= ((float) ast_format_rate(chan
->writeformat
)) / ((float) ast_format_rate(f
->subclass
));
1905 samples
= (int) ( ((float) f
->samples
) * factor
);
1907 samples
= f
->samples
;
1910 if (chan
->generator
->generate
) {
1911 generate
= chan
->generator
->generate
;
1913 /* This unlock is here based on two assumptions that hold true at this point in the
1914 * code. 1) this function is only called from within __ast_read() and 2) all generators
1915 * call ast_write() in their generate callback.
1917 * The reason this is added is so that when ast_write is called, the lock that occurs
1918 * there will not recursively lock the channel. Doing this will cause intended deadlock
1919 * avoidance not to work in deeper functions
1921 ast_channel_unlock(chan
);
1922 res
= generate(chan
, tmp
, f
->datalen
, samples
);
1923 ast_channel_lock(chan
);
1924 chan
->generatordata
= tmp
;
1926 if (option_debug
> 1)
1927 ast_log(LOG_DEBUG
, "Auto-deactivating generator\n");
1928 ast_deactivate_generator(chan
);
1931 } else if (f
->frametype
== AST_FRAME_CNG
) {
1932 if (chan
->generator
&& !chan
->timingfunc
&& (chan
->timingfd
> -1)) {
1933 if (option_debug
> 1)
1934 ast_log(LOG_DEBUG
, "Generator got CNG, switching to timed mode\n");
1935 ast_settimeout(chan
, 160, generator_force
, chan
);
1940 static struct ast_frame
*__ast_read(struct ast_channel
*chan
, int dropaudio
)
1942 struct ast_frame
*f
= NULL
; /* the return value */
1947 /* this function is very long so make sure there is only one return
1948 * point at the end (there are only two exceptions to this).
1950 while(ast_channel_trylock(chan
)) {
1952 /*cannot goto done since the channel is not locked*/
1953 return &ast_null_frame
;
1958 if (ast_do_masquerade(chan
))
1959 ast_log(LOG_WARNING
, "Failed to perform masquerade\n");
1961 f
= &ast_null_frame
;
1965 /* Stop if we're a zombie or need a soft hangup */
1966 if (ast_test_flag(chan
, AST_FLAG_ZOMBIE
) || ast_check_hangup(chan
)) {
1967 if (chan
->generator
)
1968 ast_deactivate_generator(chan
);
1971 prestate
= chan
->_state
;
1973 if (!ast_test_flag(chan
, AST_FLAG_DEFER_DTMF
| AST_FLAG_EMULATE_DTMF
| AST_FLAG_IN_DTMF
) &&
1974 !ast_strlen_zero(chan
->dtmfq
) &&
1975 (ast_tvzero(chan
->dtmf_tv
) || ast_tvdiff_ms(ast_tvnow(), chan
->dtmf_tv
) > AST_MIN_DTMF_GAP
) ) {
1976 /* We have DTMF that has been deferred. Return it now */
1977 chan
->dtmff
.subclass
= chan
->dtmfq
[0];
1978 /* Drop first digit from the buffer */
1979 memmove(chan
->dtmfq
, chan
->dtmfq
+ 1, sizeof(chan
->dtmfq
) - 1);
1981 if (ast_test_flag(chan
, AST_FLAG_END_DTMF_ONLY
)) {
1982 ast_log(LOG_DTMF
, "DTMF end emulation of '%c' queued on %s\n", f
->subclass
, chan
->name
);
1983 chan
->dtmff
.frametype
= AST_FRAME_DTMF_END
;
1985 ast_log(LOG_DTMF
, "DTMF begin emulation of '%c' with duration %d queued on %s\n", f
->subclass
, AST_DEFAULT_EMULATE_DTMF_DURATION
, chan
->name
);
1986 chan
->dtmff
.frametype
= AST_FRAME_DTMF_BEGIN
;
1987 ast_set_flag(chan
, AST_FLAG_EMULATE_DTMF
);
1988 chan
->emulate_dtmf_digit
= f
->subclass
;
1989 chan
->emulate_dtmf_duration
= AST_DEFAULT_EMULATE_DTMF_DURATION
;
1991 chan
->dtmf_tv
= ast_tvnow();
1995 /* Read and ignore anything on the alertpipe, but read only
1996 one sizeof(blah) per frame that we send from it */
1997 if (chan
->alertpipe
[0] > -1)
1998 read(chan
->alertpipe
[0], &blah
, sizeof(blah
));
2001 if (chan
->timingfd
> -1 && chan
->fdno
== AST_TIMING_FD
&& ast_test_flag(chan
, AST_FLAG_EXCEPTION
)) {
2004 ast_clear_flag(chan
, AST_FLAG_EXCEPTION
);
2006 /* IF we can't get event, assume it's an expired as-per the old interface */
2007 res
= ioctl(chan
->timingfd
, ZT_GETEVENT
, &blah
);
2009 blah
= ZT_EVENT_TIMER_EXPIRED
;
2011 if (blah
== ZT_EVENT_TIMER_PING
) {
2012 if (AST_LIST_EMPTY(&chan
->readq
) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan
->readq
), frame_list
)) {
2013 /* Acknowledge PONG unless we need it again */
2014 if (ioctl(chan
->timingfd
, ZT_TIMERPONG
, &blah
)) {
2015 ast_log(LOG_WARNING
, "Failed to pong timer on '%s': %s\n", chan
->name
, strerror(errno
));
2018 } else if (blah
== ZT_EVENT_TIMER_EXPIRED
) {
2019 ioctl(chan
->timingfd
, ZT_TIMERACK
, &blah
);
2020 if (chan
->timingfunc
) {
2021 /* save a copy of func/data before unlocking the channel */
2022 int (*func
)(const void *) = chan
->timingfunc
;
2023 void *data
= chan
->timingdata
;
2024 ast_channel_unlock(chan
);
2028 ioctl(chan
->timingfd
, ZT_TIMERCONFIG
, &blah
);
2029 chan
->timingdata
= NULL
;
2030 ast_channel_unlock(chan
);
2032 /* cannot 'goto done' because the channel is already unlocked */
2033 return &ast_null_frame
;
2035 ast_log(LOG_NOTICE
, "No/unknown event '%d' on timer for '%s'?\n", blah
, chan
->name
);
2038 if (chan
->fds
[AST_GENERATOR_FD
] > -1 && chan
->fdno
== AST_GENERATOR_FD
) {
2039 /* if the AST_GENERATOR_FD is set, call the generator with args
2040 * set to -1 so it can do whatever it needs to.
2042 void *tmp
= chan
->generatordata
;
2043 chan
->generatordata
= NULL
; /* reset to let ast_write get through */
2044 chan
->generator
->generate(chan
, tmp
, -1, -1);
2045 chan
->generatordata
= tmp
;
2046 f
= &ast_null_frame
;
2050 /* Check for pending read queue */
2051 if (!AST_LIST_EMPTY(&chan
->readq
)) {
2052 f
= AST_LIST_REMOVE_HEAD(&chan
->readq
, frame_list
);
2053 /* Interpret hangup and return NULL */
2054 /* XXX why not the same for frames from the channel ? */
2055 if (f
->frametype
== AST_FRAME_CONTROL
&& f
->subclass
== AST_CONTROL_HANGUP
) {
2060 chan
->blocker
= pthread_self();
2061 if (ast_test_flag(chan
, AST_FLAG_EXCEPTION
)) {
2062 if (chan
->tech
->exception
)
2063 f
= chan
->tech
->exception(chan
);
2065 ast_log(LOG_WARNING
, "Exception flag set on '%s', but no exception handler\n", chan
->name
);
2066 f
= &ast_null_frame
;
2068 /* Clear the exception flag */
2069 ast_clear_flag(chan
, AST_FLAG_EXCEPTION
);
2070 } else if (chan
->tech
->read
)
2071 f
= chan
->tech
->read(chan
);
2073 ast_log(LOG_WARNING
, "No read routine on channel %s\n", chan
->name
);
2077 /* if the channel driver returned more than one frame, stuff the excess
2078 into the readq for the next ast_read call (note that we can safely assume
2079 that the readq is empty, because otherwise we would not have called into
2080 the channel driver and f would be only a single frame)
2082 if (AST_LIST_NEXT(f
, frame_list
)) {
2083 AST_LIST_HEAD_SET_NOLOCK(&chan
->readq
, AST_LIST_NEXT(f
, frame_list
));
2084 AST_LIST_NEXT(f
, frame_list
) = NULL
;
2087 switch (f
->frametype
) {
2088 case AST_FRAME_CONTROL
:
2089 if (f
->subclass
== AST_CONTROL_ANSWER
) {
2090 if (!ast_test_flag(chan
, AST_FLAG_OUTGOING
)) {
2092 ast_log(LOG_DEBUG
, "Ignoring answer on an inbound call!\n");
2094 f
= &ast_null_frame
;
2095 } else if (prestate
== AST_STATE_UP
) {
2097 ast_log(LOG_DEBUG
, "Dropping duplicate answer!\n");
2099 f
= &ast_null_frame
;
2101 /* Answer the CDR */
2102 ast_setstate(chan
, AST_STATE_UP
);
2103 if (!chan
->cdr
) { /* up till now, this insertion hasn't been done. Therefore,
2104 to keep from throwing off the basic order of the universe,
2105 we will try to keep this cdr from getting posted. */
2106 chan
->cdr
= ast_cdr_alloc();
2107 ast_cdr_init(chan
->cdr
, chan
);
2108 ast_cdr_start(chan
->cdr
);
2111 ast_cdr_answer(chan
->cdr
);
2115 case AST_FRAME_DTMF_END
:
2116 ast_log(LOG_DTMF
, "DTMF end '%c' received on %s, duration %ld ms\n", f
->subclass
, chan
->name
, f
->len
);
2117 /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2118 * However, only let emulation be forced if the other end cares about BEGIN frames */
2119 if ( ast_test_flag(chan
, AST_FLAG_DEFER_DTMF
) ||
2120 (ast_test_flag(chan
, AST_FLAG_EMULATE_DTMF
) && !ast_test_flag(chan
, AST_FLAG_END_DTMF_ONLY
)) ) {
2121 if (strlen(chan
->dtmfq
) < sizeof(chan
->dtmfq
) - 2) {
2122 ast_log(LOG_DTMF
, "DTMF end '%c' put into dtmf queue on %s\n", f
->subclass
, chan
->name
);
2123 chan
->dtmfq
[strlen(chan
->dtmfq
)] = f
->subclass
;
2125 ast_log(LOG_WARNING
, "Dropping deferred DTMF digits on %s\n", chan
->name
);
2127 f
= &ast_null_frame
;
2128 } else if (!ast_test_flag(chan
, AST_FLAG_IN_DTMF
| AST_FLAG_END_DTMF_ONLY
)) {
2129 if (!ast_tvzero(chan
->dtmf_tv
) &&
2130 ast_tvdiff_ms(ast_tvnow(), chan
->dtmf_tv
) < AST_MIN_DTMF_GAP
) {
2131 /* If it hasn't been long enough, defer this digit */
2132 if (strlen(chan
->dtmfq
) < sizeof(chan
->dtmfq
) - 2) {
2133 ast_log(LOG_DTMF
, "DTMF end '%c' put into dtmf queue on %s\n", f
->subclass
, chan
->name
);
2134 chan
->dtmfq
[strlen(chan
->dtmfq
)] = f
->subclass
;
2136 ast_log(LOG_WARNING
, "Dropping deferred DTMF digits on %s\n", chan
->name
);
2138 f
= &ast_null_frame
;
2140 /* There was no begin, turn this into a begin and send the end later */
2141 f
->frametype
= AST_FRAME_DTMF_BEGIN
;
2142 ast_set_flag(chan
, AST_FLAG_EMULATE_DTMF
);
2143 chan
->emulate_dtmf_digit
= f
->subclass
;
2144 chan
->dtmf_tv
= ast_tvnow();
2146 if (f
->len
> AST_MIN_DTMF_DURATION
)
2147 chan
->emulate_dtmf_duration
= f
->len
;
2149 chan
->emulate_dtmf_duration
= AST_MIN_DTMF_DURATION
;
2151 chan
->emulate_dtmf_duration
= AST_DEFAULT_EMULATE_DTMF_DURATION
;
2152 ast_log(LOG_DTMF
, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f
->subclass
, chan
->emulate_dtmf_duration
, chan
->name
);
2154 if (chan
->audiohooks
) {
2155 struct ast_frame
*old_frame
= f
;
2156 f
= ast_audiohook_write_list(chan
, chan
->audiohooks
, AST_AUDIOHOOK_DIRECTION_READ
, f
);
2158 ast_frfree(old_frame
);
2161 struct timeval now
= ast_tvnow();
2162 if (ast_test_flag(chan
, AST_FLAG_IN_DTMF
)) {
2163 ast_log(LOG_DTMF
, "DTMF end accepted with begin '%c' on %s\n", f
->subclass
, chan
->name
);
2164 ast_clear_flag(chan
, AST_FLAG_IN_DTMF
);
2166 f
->len
= ast_tvdiff_ms(now
, chan
->dtmf_tv
);
2167 } else if (!f
->len
) {
2168 ast_log(LOG_DTMF
, "DTMF end accepted without begin '%c' on %s\n", f
->subclass
, chan
->name
);
2169 f
->len
= AST_MIN_DTMF_DURATION
;
2171 if (f
->len
< AST_MIN_DTMF_DURATION
) {
2172 ast_log(LOG_DTMF
, "DTMF end '%c' has duration %ld but want minimum %d, emulating on %s\n", f
->subclass
, f
->len
, AST_MIN_DTMF_DURATION
, chan
->name
);
2173 ast_set_flag(chan
, AST_FLAG_EMULATE_DTMF
);
2174 chan
->emulate_dtmf_digit
= f
->subclass
;
2175 chan
->emulate_dtmf_duration
= AST_MIN_DTMF_DURATION
- f
->len
;
2177 f
= &ast_null_frame
;
2179 ast_log(LOG_DTMF
, "DTMF end passthrough '%c' on %s\n", f
->subclass
, chan
->name
);
2180 chan
->dtmf_tv
= now
;
2182 if (chan
->audiohooks
) {
2183 struct ast_frame
*old_frame
= f
;
2184 f
= ast_audiohook_write_list(chan
, chan
->audiohooks
, AST_AUDIOHOOK_DIRECTION_READ
, f
);
2186 ast_frfree(old_frame
);
2190 case AST_FRAME_DTMF_BEGIN
:
2191 ast_log(LOG_DTMF
, "DTMF begin '%c' received on %s\n", f
->subclass
, chan
->name
);
2192 if ( ast_test_flag(chan
, AST_FLAG_DEFER_DTMF
| AST_FLAG_END_DTMF_ONLY
| AST_FLAG_EMULATE_DTMF
) ||
2193 (!ast_tvzero(chan
->dtmf_tv
) &&
2194 ast_tvdiff_ms(ast_tvnow(), chan
->dtmf_tv
) < AST_MIN_DTMF_GAP
) ) {
2195 ast_log(LOG_DTMF
, "DTMF begin ignored '%c' on %s\n", f
->subclass
, chan
->name
);
2197 f
= &ast_null_frame
;
2199 ast_set_flag(chan
, AST_FLAG_IN_DTMF
);
2200 chan
->dtmf_tv
= ast_tvnow();
2201 ast_log(LOG_DTMF
, "DTMF begin passthrough '%c' on %s\n", f
->subclass
, chan
->name
);
2204 case AST_FRAME_NULL
:
2205 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2206 * is reached , because we want to make sure we pass at least one
2207 * voice frame through before starting the next digit, to ensure a gap
2208 * between DTMF digits. */
2209 if (ast_test_flag(chan
, AST_FLAG_EMULATE_DTMF
)) {
2210 struct timeval now
= ast_tvnow();
2211 if (!chan
->emulate_dtmf_duration
) {
2212 ast_clear_flag(chan
, AST_FLAG_EMULATE_DTMF
);
2213 chan
->emulate_dtmf_digit
= 0;
2214 } else if (ast_tvdiff_ms(now
, chan
->dtmf_tv
) >= chan
->emulate_dtmf_duration
) {
2215 chan
->emulate_dtmf_duration
= 0;
2218 f
->frametype
= AST_FRAME_DTMF_END
;
2219 f
->subclass
= chan
->emulate_dtmf_digit
;
2220 f
->len
= ast_tvdiff_ms(now
, chan
->dtmf_tv
);
2221 chan
->dtmf_tv
= now
;
2222 ast_clear_flag(chan
, AST_FLAG_EMULATE_DTMF
);
2223 chan
->emulate_dtmf_digit
= 0;
2224 ast_log(LOG_DTMF
, "DTMF end emulation of '%c' queued on %s\n", f
->subclass
, chan
->name
);
2228 case AST_FRAME_VOICE
:
2229 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2230 * is reached , because we want to make sure we pass at least one
2231 * voice frame through before starting the next digit, to ensure a gap
2232 * between DTMF digits. */
2233 if (ast_test_flag(chan
, AST_FLAG_EMULATE_DTMF
) && !chan
->emulate_dtmf_duration
) {
2234 ast_clear_flag(chan
, AST_FLAG_EMULATE_DTMF
);
2235 chan
->emulate_dtmf_digit
= 0;
2238 if (dropaudio
|| ast_test_flag(chan
, AST_FLAG_IN_DTMF
)) {
2240 ast_read_generator_actions(chan
, f
);
2242 f
= &ast_null_frame
;
2245 if (ast_test_flag(chan
, AST_FLAG_EMULATE_DTMF
) && !ast_test_flag(chan
, AST_FLAG_IN_DTMF
)) {
2246 struct timeval now
= ast_tvnow();
2247 if (ast_tvdiff_ms(now
, chan
->dtmf_tv
) >= chan
->emulate_dtmf_duration
) {
2248 chan
->emulate_dtmf_duration
= 0;
2251 f
->frametype
= AST_FRAME_DTMF_END
;
2252 f
->subclass
= chan
->emulate_dtmf_digit
;
2253 f
->len
= ast_tvdiff_ms(now
, chan
->dtmf_tv
);
2254 chan
->dtmf_tv
= now
;
2255 if (chan
->audiohooks
) {
2256 struct ast_frame
*old_frame
= f
;
2257 f
= ast_audiohook_write_list(chan
, chan
->audiohooks
, AST_AUDIOHOOK_DIRECTION_READ
, f
);
2259 ast_frfree(old_frame
);
2261 ast_log(LOG_DTMF
, "DTMF end emulation of '%c' queued on %s\n", f
->subclass
, chan
->name
);
2263 /* Drop voice frames while we're still in the middle of the digit */
2265 f
= &ast_null_frame
;
2267 } else if ((f
->frametype
== AST_FRAME_VOICE
) && !(f
->subclass
& chan
->nativeformats
)) {
2268 /* This frame can't be from the current native formats -- drop it on the
2270 ast_log(LOG_NOTICE
, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2271 chan
->name
, ast_getformatname(f
->subclass
), ast_getformatname(chan
->nativeformats
));
2273 f
= &ast_null_frame
;
2274 } else if ((f
->frametype
== AST_FRAME_VOICE
)) {
2275 if (chan
->audiohooks
) {
2276 struct ast_frame
*old_frame
= f
;
2277 f
= ast_audiohook_write_list(chan
, chan
->audiohooks
, AST_AUDIOHOOK_DIRECTION_READ
, f
);
2279 ast_frfree(old_frame
);
2281 if (chan
->monitor
&& chan
->monitor
->read_stream
) {
2282 /* XXX what does this do ? */
2283 #ifndef MONITOR_CONSTANT_DELAY
2284 int jump
= chan
->outsmpl
- chan
->insmpl
- 4 * f
->samples
;
2286 jump
= chan
->outsmpl
- chan
->insmpl
;
2287 if (ast_seekstream(chan
->monitor
->read_stream
, jump
, SEEK_FORCECUR
) == -1)
2288 ast_log(LOG_WARNING
, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2289 chan
->insmpl
+= jump
+ f
->samples
;
2291 chan
->insmpl
+= f
->samples
;
2293 int jump
= chan
->outsmpl
- chan
->insmpl
;
2294 if (jump
- MONITOR_DELAY
>= 0) {
2295 if (ast_seekstream(chan
->monitor
->read_stream
, jump
- f
->samples
, SEEK_FORCECUR
) == -1)
2296 ast_log(LOG_WARNING
, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2297 chan
->insmpl
+= jump
;
2299 chan
->insmpl
+= f
->samples
;
2301 if (chan
->monitor
->state
== AST_MONITOR_RUNNING
) {
2302 if (ast_writestream(chan
->monitor
->read_stream
, f
) < 0)
2303 ast_log(LOG_WARNING
, "Failed to write data to channel monitor read stream\n");
2307 if (chan
->readtrans
&& (f
= ast_translate(chan
->readtrans
, f
, 1)) == NULL
)
2308 f
= &ast_null_frame
;
2310 /* Run generator sitting on the line if timing device not available
2311 * and synchronous generation of outgoing frames is necessary */
2312 ast_read_generator_actions(chan
, f
);
2315 /* Just pass it on! */
2319 /* Make sure we always return NULL in the future */
2320 chan
->_softhangup
|= AST_SOFTHANGUP_DEV
;
2321 if (chan
->generator
)
2322 ast_deactivate_generator(chan
);
2323 /* End the CDR if appropriate */
2325 ast_cdr_end(chan
->cdr
);
2328 /* High bit prints debugging */
2329 if (chan
->fin
& DEBUGCHAN_FLAG
)
2330 ast_frame_dump(chan
->name
, f
, "<<");
2331 chan
->fin
= FRAMECOUNT_INC(chan
->fin
);
2334 ast_channel_unlock(chan
);
2338 int ast_internal_timing_enabled(struct ast_channel
*chan
)
2340 int ret
= ast_opt_internal_timing
&& chan
->timingfd
> -1;
2341 if (option_debug
> 4)
2342 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
);
2346 struct ast_frame
*ast_read(struct ast_channel
*chan
)
2348 return __ast_read(chan
, 0);
2351 struct ast_frame
*ast_read_noaudio(struct ast_channel
*chan
)
2353 return __ast_read(chan
, 1);
2356 int ast_indicate(struct ast_channel
*chan
, int condition
)
2358 return ast_indicate_data(chan
, condition
, NULL
, 0);
2361 int ast_indicate_data(struct ast_channel
*chan
, int condition
, const void *data
, size_t datalen
)
2365 ast_channel_lock(chan
);
2366 /* Stop if we're a zombie or need a soft hangup */
2367 if (ast_test_flag(chan
, AST_FLAG_ZOMBIE
) || ast_check_hangup(chan
)) {
2368 ast_channel_unlock(chan
);
2371 if (chan
->tech
->indicate
)
2372 res
= chan
->tech
->indicate(chan
, condition
, data
, datalen
);
2373 ast_channel_unlock(chan
);
2374 if (!chan
->tech
->indicate
|| res
) {
2376 * Device does not support (that) indication, lets fake
2377 * it by doing our own tone generation. (PM2002)
2380 ast_playtones_stop(chan
);
2382 const struct tone_zone_sound
*ts
= NULL
;
2383 switch (condition
) {
2384 case AST_CONTROL_RINGING
:
2385 ts
= ast_get_indication_tone(chan
->zone
, "ring");
2387 case AST_CONTROL_BUSY
:
2388 ts
= ast_get_indication_tone(chan
->zone
, "busy");
2390 case AST_CONTROL_CONGESTION
:
2391 ts
= ast_get_indication_tone(chan
->zone
, "congestion");
2394 if (ts
&& ts
->data
[0]) {
2396 ast_log(LOG_DEBUG
, "Driver for channel '%s' does not support indication %d, emulating it\n", chan
->name
, condition
);
2397 ast_playtones_start(chan
,0,ts
->data
, 1);
2399 chan
->visible_indication
= condition
;
2400 } else if (condition
== AST_CONTROL_PROGRESS
) {
2401 /* ast_playtones_stop(chan); */
2402 } else if (condition
== AST_CONTROL_PROCEEDING
) {
2403 /* Do nothing, really */
2404 } else if (condition
== AST_CONTROL_HOLD
) {
2405 /* Do nothing.... */
2406 } else if (condition
== AST_CONTROL_UNHOLD
) {
2407 /* Do nothing.... */
2408 } else if (condition
== AST_CONTROL_VIDUPDATE
) {
2409 /* Do nothing.... */
2410 } else if (condition
== AST_CONTROL_SRCUPDATE
) {
2414 ast_log(LOG_WARNING
, "Unable to handle indication %d for '%s'\n", condition
, chan
->name
);
2419 chan
->visible_indication
= condition
;
2424 int ast_recvchar(struct ast_channel
*chan
, int timeout
)
2427 char *buf
= ast_recvtext(chan
, timeout
);
2429 return -1; /* error or timeout */
2430 c
= *(unsigned char *)buf
;
2435 char *ast_recvtext(struct ast_channel
*chan
, int timeout
)
2441 struct ast_frame
*f
;
2442 if (ast_check_hangup(chan
))
2444 res
= ast_waitfor(chan
, timeout
);
2445 if (res
<= 0) /* timeout or error */
2447 timeout
= res
; /* update timeout */
2450 break; /* no frame */
2451 if (f
->frametype
== AST_FRAME_CONTROL
&& f
->subclass
== AST_CONTROL_HANGUP
)
2452 done
= 1; /* force a break */
2453 else if (f
->frametype
== AST_FRAME_TEXT
) { /* what we want */
2454 buf
= ast_strndup((char *) f
->data
, f
->datalen
); /* dup and break */
2462 int ast_sendtext(struct ast_channel
*chan
, const char *text
)
2465 /* Stop if we're a zombie or need a soft hangup */
2466 if (ast_test_flag(chan
, AST_FLAG_ZOMBIE
) || ast_check_hangup(chan
))
2468 CHECK_BLOCKING(chan
);
2469 if (chan
->tech
->send_text
)
2470 res
= chan
->tech
->send_text(chan
, text
);
2471 ast_clear_flag(chan
, AST_FLAG_BLOCKING
);
2475 int ast_senddigit_begin(struct ast_channel
*chan
, char digit
)
2477 /* Device does not support DTMF tones, lets fake
2478 * it by doing our own generation. */
2479 static const char* dtmf_tones
[] = {
2498 if (!chan
->tech
->send_digit_begin
)
2501 if (!chan
->tech
->send_digit_begin(chan
, digit
))
2504 if (digit
>= '0' && digit
<='9')
2505 ast_playtones_start(chan
, 0, dtmf_tones
[digit
-'0'], 0);
2506 else if (digit
>= 'A' && digit
<= 'D')
2507 ast_playtones_start(chan
, 0, dtmf_tones
[digit
-'A'+10], 0);
2508 else if (digit
== '*')
2509 ast_playtones_start(chan
, 0, dtmf_tones
[14], 0);
2510 else if (digit
== '#')
2511 ast_playtones_start(chan
, 0, dtmf_tones
[15], 0);
2515 ast_log(LOG_DEBUG
, "Unable to generate DTMF tone '%c' for '%s'\n", digit
, chan
->name
);
2521 int ast_senddigit_end(struct ast_channel
*chan
, char digit
, unsigned int duration
)
2525 if (chan
->tech
->send_digit_end
)
2526 res
= chan
->tech
->send_digit_end(chan
, digit
, duration
);
2528 if (res
&& chan
->generator
)
2529 ast_playtones_stop(chan
);
2534 int ast_senddigit(struct ast_channel
*chan
, char digit
)
2536 if (chan
->tech
->send_digit_begin
) {
2537 ast_senddigit_begin(chan
, digit
);
2538 ast_safe_sleep(chan
, AST_DEFAULT_EMULATE_DTMF_DURATION
);
2541 return ast_senddigit_end(chan
, digit
, AST_DEFAULT_EMULATE_DTMF_DURATION
);
2544 int ast_prod(struct ast_channel
*chan
)
2546 struct ast_frame a
= { AST_FRAME_VOICE
};
2549 /* Send an empty audio frame to get things moving */
2550 if (chan
->_state
!= AST_STATE_UP
) {
2552 ast_log(LOG_DEBUG
, "Prodding channel '%s'\n", chan
->name
);
2553 a
.subclass
= chan
->rawwriteformat
;
2554 a
.data
= nothing
+ AST_FRIENDLY_OFFSET
;
2556 if (ast_write(chan
, &a
))
2557 ast_log(LOG_WARNING
, "Prodding channel '%s' failed\n", chan
->name
);
2562 int ast_write_video(struct ast_channel
*chan
, struct ast_frame
*fr
)
2565 if (!chan
->tech
->write_video
)
2567 res
= ast_write(chan
, fr
);
2573 int ast_write(struct ast_channel
*chan
, struct ast_frame
*fr
)
2577 struct ast_frame
*f
= NULL
, *f2
= NULL
;
2579 /*Deadlock avoidance*/
2580 while(ast_channel_trylock(chan
)) {
2581 /*cannot goto done since the channel is not locked*/
2584 ast_log(LOG_DEBUG
, "Deadlock avoided for write to channel '%s'\n", chan
->name
);
2589 /* Stop if we're a zombie or need a soft hangup */
2590 if (ast_test_flag(chan
, AST_FLAG_ZOMBIE
) || ast_check_hangup(chan
))
2593 /* Handle any pending masquerades */
2594 if (chan
->masq
&& ast_do_masquerade(chan
)) {
2595 ast_log(LOG_WARNING
, "Failed to perform masquerade\n");
2599 res
= 0; /* XXX explain, why 0 ? */
2602 if (chan
->generatordata
) {
2603 if (ast_test_flag(chan
, AST_FLAG_WRITE_INT
))
2604 ast_deactivate_generator(chan
);
2606 if (fr
->frametype
== AST_FRAME_DTMF_END
) {
2607 /* There is a generator running while we're in the middle of a digit.
2608 * It's probably inband DTMF, so go ahead and pass it so it can
2609 * stop the generator */
2610 ast_clear_flag(chan
, AST_FLAG_BLOCKING
);
2611 ast_channel_unlock(chan
);
2612 res
= ast_senddigit_end(chan
, fr
->subclass
, fr
->len
);
2613 ast_channel_lock(chan
);
2614 CHECK_BLOCKING(chan
);
2615 } else if (fr
->frametype
== AST_FRAME_CONTROL
&& fr
->subclass
== AST_CONTROL_UNHOLD
) {
2616 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
2617 res
= (chan
->tech
->indicate
== NULL
) ? 0 :
2618 chan
->tech
->indicate(chan
, fr
->subclass
, fr
->data
, fr
->datalen
);
2620 res
= 0; /* XXX explain, why 0 ? */
2624 /* High bit prints debugging */
2625 if (chan
->fout
& DEBUGCHAN_FLAG
)
2626 ast_frame_dump(chan
->name
, fr
, ">>");
2627 CHECK_BLOCKING(chan
);
2628 switch(fr
->frametype
) {
2629 case AST_FRAME_CONTROL
:
2630 res
= (chan
->tech
->indicate
== NULL
) ? 0 :
2631 chan
->tech
->indicate(chan
, fr
->subclass
, fr
->data
, fr
->datalen
);
2633 case AST_FRAME_DTMF_BEGIN
:
2634 if (chan
->audiohooks
) {
2635 struct ast_frame
*old_frame
= fr
;
2636 fr
= ast_audiohook_write_list(chan
, chan
->audiohooks
, AST_AUDIOHOOK_DIRECTION_WRITE
, fr
);
2637 if (old_frame
!= fr
)
2640 ast_clear_flag(chan
, AST_FLAG_BLOCKING
);
2641 ast_channel_unlock(chan
);
2642 res
= ast_senddigit_begin(chan
, fr
->subclass
);
2643 ast_channel_lock(chan
);
2644 CHECK_BLOCKING(chan
);
2646 case AST_FRAME_DTMF_END
:
2647 if (chan
->audiohooks
) {
2648 struct ast_frame
*old_frame
= fr
;
2649 fr
= ast_audiohook_write_list(chan
, chan
->audiohooks
, AST_AUDIOHOOK_DIRECTION_WRITE
, fr
);
2650 if (old_frame
!= fr
)
2653 ast_clear_flag(chan
, AST_FLAG_BLOCKING
);
2654 ast_channel_unlock(chan
);
2655 res
= ast_senddigit_end(chan
, fr
->subclass
, fr
->len
);
2656 ast_channel_lock(chan
);
2657 CHECK_BLOCKING(chan
);
2659 case AST_FRAME_TEXT
:
2660 res
= (chan
->tech
->send_text
== NULL
) ? 0 :
2661 chan
->tech
->send_text(chan
, (char *) fr
->data
);
2663 case AST_FRAME_HTML
:
2664 res
= (chan
->tech
->send_html
== NULL
) ? 0 :
2665 chan
->tech
->send_html(chan
, fr
->subclass
, (char *) fr
->data
, fr
->datalen
);
2667 case AST_FRAME_VIDEO
:
2668 /* XXX Handle translation of video codecs one day XXX */
2669 res
= (chan
->tech
->write_video
== NULL
) ? 0 :
2670 chan
->tech
->write_video(chan
, fr
);
2672 case AST_FRAME_MODEM
:
2673 res
= (chan
->tech
->write
== NULL
) ? 0 :
2674 chan
->tech
->write(chan
, fr
);
2676 case AST_FRAME_VOICE
:
2677 if (chan
->tech
->write
== NULL
)
2678 break; /*! \todo XXX should return 0 maybe ? */
2680 if (chan
->audiohooks
) {
2681 struct ast_frame
*old_frame
= fr
;
2682 fr
= ast_audiohook_write_list(chan
, chan
->audiohooks
, AST_AUDIOHOOK_DIRECTION_WRITE
, fr
);
2683 if (old_frame
!= fr
)
2687 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2688 if (fr
->subclass
== chan
->rawwriteformat
)
2691 f
= (chan
->writetrans
) ? ast_translate(chan
->writetrans
, fr
, 0) : fr
;
2693 /* If we have no frame of audio, then we have to bail out */
2699 /* If Monitor is running on this channel, then we have to write frames out there too */
2700 if (chan
->monitor
&& chan
->monitor
->write_stream
) {
2701 /* XXX must explain this code */
2702 #ifndef MONITOR_CONSTANT_DELAY
2703 int jump
= chan
->insmpl
- chan
->outsmpl
- 4 * f
->samples
;
2705 jump
= chan
->insmpl
- chan
->outsmpl
;
2706 if (ast_seekstream(chan
->monitor
->write_stream
, jump
, SEEK_FORCECUR
) == -1)
2707 ast_log(LOG_WARNING
, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2708 chan
->outsmpl
+= jump
+ f
->samples
;
2710 chan
->outsmpl
+= f
->samples
;
2712 int jump
= chan
->insmpl
- chan
->outsmpl
;
2713 if (jump
- MONITOR_DELAY
>= 0) {
2714 if (ast_seekstream(chan
->monitor
->write_stream
, jump
- f
->samples
, SEEK_FORCECUR
) == -1)
2715 ast_log(LOG_WARNING
, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2716 chan
->outsmpl
+= jump
;
2718 chan
->outsmpl
+= f
->samples
;
2720 if (chan
->monitor
->state
== AST_MONITOR_RUNNING
) {
2721 if (ast_writestream(chan
->monitor
->write_stream
, f
) < 0)
2722 ast_log(LOG_WARNING
, "Failed to write data to channel monitor write stream\n");
2727 res
= chan
->tech
->write(chan
,f
);
2731 case AST_FRAME_NULL
:
2737 /* At this point, fr is the incoming frame and f is NULL. Channels do
2738 * not expect to get NULL as a frame pointer and will segfault. Hence,
2739 * we output the original frame passed in. */
2740 res
= chan
->tech
->write(chan
, fr
);
2748 ast_clear_flag(chan
, AST_FLAG_BLOCKING
);
2749 /* Consider a write failure to force a soft hangup */
2751 chan
->_softhangup
|= AST_SOFTHANGUP_DEV
;
2753 chan
->fout
= FRAMECOUNT_INC(chan
->fout
);
2756 ast_channel_unlock(chan
);
2760 static int set_format(struct ast_channel
*chan
, int fmt
, int *rawformat
, int *format
,
2761 struct ast_trans_pvt
**trans
, const int direction
)
2766 /* Make sure we only consider audio */
2767 fmt
&= AST_FORMAT_AUDIO_MASK
;
2769 native
= chan
->nativeformats
;
2770 /* Find a translation path from the native format to one of the desired formats */
2773 res
= ast_translator_best_choice(&fmt
, &native
);
2776 res
= ast_translator_best_choice(&native
, &fmt
);
2779 ast_log(LOG_WARNING
, "Unable to find a codec translation path from %s to %s\n",
2780 ast_getformatname(native
), ast_getformatname(fmt
));
2784 /* Now we have a good choice for both. */
2785 ast_channel_lock(chan
);
2787 if ((*rawformat
== native
) && (*format
== fmt
) && ((*rawformat
== *format
) || (*trans
))) {
2788 /* the channel is already in these formats, so nothing to do */
2789 ast_channel_unlock(chan
);
2793 *rawformat
= native
;
2794 /* User perspective is fmt */
2796 /* Free any read translation we have right now */
2798 ast_translator_free_path(*trans
);
2799 /* Build a translation path from the raw format to the desired format */
2802 *trans
= ast_translator_build_path(*format
, *rawformat
);
2805 *trans
= ast_translator_build_path(*rawformat
, *format
);
2806 ast_channel_unlock(chan
);
2808 ast_log(LOG_DEBUG
, "Set channel %s to %s format %s\n", chan
->name
,
2809 direction
? "write" : "read", ast_getformatname(fmt
));
2813 int ast_set_read_format(struct ast_channel
*chan
, int fmt
)
2815 return set_format(chan
, fmt
, &chan
->rawreadformat
, &chan
->readformat
,
2816 &chan
->readtrans
, 0);
2819 int ast_set_write_format(struct ast_channel
*chan
, int fmt
)
2821 return set_format(chan
, fmt
, &chan
->rawwriteformat
, &chan
->writeformat
,
2822 &chan
->writetrans
, 1);
2825 char *ast_channel_reason2str(int reason
)
2827 switch (reason
) /* the following appear to be the only ones actually returned by request_and_dial */
2830 return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
2831 case AST_CONTROL_HANGUP
:
2833 case AST_CONTROL_RING
:
2834 return "Local Ring";
2835 case AST_CONTROL_RINGING
:
2836 return "Remote end Ringing";
2837 case AST_CONTROL_ANSWER
:
2838 return "Remote end has Answered";
2839 case AST_CONTROL_BUSY
:
2840 return "Remote end is Busy";
2841 case AST_CONTROL_CONGESTION
:
2842 return "Congestion (circuits busy)";
2844 return "Unknown Reason!!";
2848 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
)
2852 struct ast_channel
*chan
;
2854 int last_subclass
= 0;
2859 outstate
= &dummy_outstate
; /* make outstate always a valid pointer */
2861 chan
= ast_request(type
, format
, data
, &cause
);
2863 ast_log(LOG_NOTICE
, "Unable to request channel %s/%s\n", type
, (char *)data
);
2864 /* compute error and return */
2865 if (cause
== AST_CAUSE_BUSY
)
2866 *outstate
= AST_CONTROL_BUSY
;
2867 else if (cause
== AST_CAUSE_CONGESTION
)
2868 *outstate
= AST_CONTROL_CONGESTION
;
2874 ast_set_variables(chan
, oh
->vars
);
2875 /* XXX why is this necessary, for the parent_channel perhaps ? */
2876 if (!ast_strlen_zero(oh
->cid_num
) && !ast_strlen_zero(oh
->cid_name
))
2877 ast_set_callerid(chan
, oh
->cid_num
, oh
->cid_name
, oh
->cid_num
);
2878 if (oh
->parent_channel
)
2879 ast_channel_inherit_variables(oh
->parent_channel
, chan
);
2881 ast_cdr_setaccount(chan
, oh
->account
);
2883 ast_set_callerid(chan
, cid_num
, cid_name
, cid_num
);
2887 if (!chan
->cdr
) { /* up till now, this insertion hasn't been done. Therefore,
2888 to keep from throwing off the basic order of the universe,
2889 we will try to keep this cdr from getting posted. */
2890 chan
->cdr
= ast_cdr_alloc();
2891 ast_cdr_init(chan
->cdr
, chan
);
2892 ast_cdr_start(chan
->cdr
);
2894 if (ast_call(chan
, data
, 0)) { /* ast_call failed... */
2895 ast_log(LOG_NOTICE
, "Unable to call channel %s/%s\n", type
, (char *)data
);
2897 res
= 1; /* mark success in case chan->_state is already AST_STATE_UP */
2898 while (timeout
&& chan
->_state
!= AST_STATE_UP
) {
2899 struct ast_frame
*f
;
2900 res
= ast_waitfor(chan
, timeout
);
2901 if (res
<= 0) /* error, timeout, or done */
2907 *outstate
= AST_CONTROL_HANGUP
;
2911 if (f
->frametype
== AST_FRAME_CONTROL
) {
2912 switch (f
->subclass
) {
2913 case AST_CONTROL_RINGING
: /* record but keep going */
2914 *outstate
= f
->subclass
;
2917 case AST_CONTROL_BUSY
:
2918 case AST_CONTROL_CONGESTION
:
2919 case AST_CONTROL_ANSWER
:
2920 *outstate
= f
->subclass
;
2921 timeout
= 0; /* trick to force exit from the while() */
2925 case AST_CONTROL_PROGRESS
:
2926 case AST_CONTROL_PROCEEDING
:
2927 case AST_CONTROL_HOLD
:
2928 case AST_CONTROL_UNHOLD
:
2929 case AST_CONTROL_VIDUPDATE
:
2930 case AST_CONTROL_SRCUPDATE
:
2931 case -1: /* Ignore -- just stopping indications */
2935 ast_log(LOG_NOTICE
, "Don't know what to do with control frame %d\n", f
->subclass
);
2937 last_subclass
= f
->subclass
;
2945 if (!ast_strlen_zero(oh
->context
))
2946 ast_copy_string(chan
->context
, oh
->context
, sizeof(chan
->context
));
2947 if (!ast_strlen_zero(oh
->exten
))
2948 ast_copy_string(chan
->exten
, oh
->exten
, sizeof(chan
->exten
));
2950 chan
->priority
= oh
->priority
;
2952 if (chan
->_state
== AST_STATE_UP
)
2953 *outstate
= AST_CONTROL_ANSWER
;
2956 if ( AST_CONTROL_RINGING
== last_subclass
)
2957 chan
->hangupcause
= AST_CAUSE_NO_ANSWER
;
2958 if (!chan
->cdr
&& (chan
->cdr
= ast_cdr_alloc()))
2959 ast_cdr_init(chan
->cdr
, chan
);
2962 snprintf(tmp
, sizeof(tmp
), "%s/%s", type
, (char *)data
);
2963 ast_cdr_setapp(chan
->cdr
,"Dial",tmp
);
2964 ast_cdr_update(chan
);
2965 ast_cdr_start(chan
->cdr
);
2966 ast_cdr_end(chan
->cdr
);
2967 /* If the cause wasn't handled properly */
2968 if (ast_cdr_disposition(chan
->cdr
,chan
->hangupcause
))
2969 ast_cdr_failed(chan
->cdr
);
2977 struct ast_channel
*ast_request_and_dial(const char *type
, int format
, void *data
, int timeout
, int *outstate
, const char *cidnum
, const char *cidname
)
2979 return __ast_request_and_dial(type
, format
, data
, timeout
, outstate
, cidnum
, cidname
, NULL
);
2982 struct ast_channel
*ast_request(const char *type
, int format
, void *data
, int *cause
)
2984 struct chanlist
*chan
;
2985 struct ast_channel
*c
;
2990 int videoformat
= format
& AST_FORMAT_VIDEO_MASK
;
2994 *cause
= AST_CAUSE_NOTDEFINED
;
2996 if (AST_LIST_LOCK(&channels
)) {
2997 ast_log(LOG_WARNING
, "Unable to lock channel list\n");
3001 AST_LIST_TRAVERSE(&backends
, chan
, list
) {
3002 if (strcasecmp(type
, chan
->tech
->type
))
3005 capabilities
= chan
->tech
->capabilities
;
3006 fmt
= format
& AST_FORMAT_AUDIO_MASK
;
3007 res
= ast_translator_best_choice(&fmt
, &capabilities
);
3009 ast_log(LOG_WARNING
, "No translator path exists for channel type %s (native %d) to %d\n", type
, chan
->tech
->capabilities
, format
);
3010 *cause
= AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
;
3011 AST_LIST_UNLOCK(&channels
);
3014 AST_LIST_UNLOCK(&channels
);
3015 if (!chan
->tech
->requester
)
3018 if (!(c
= chan
->tech
->requester(type
, capabilities
| videoformat
, data
, cause
)))
3021 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
3025 ast_log(LOG_WARNING
, "No channel type registered for '%s'\n", type
);
3026 *cause
= AST_CAUSE_NOSUCHDRIVER
;
3027 AST_LIST_UNLOCK(&channels
);
3032 int ast_call(struct ast_channel
*chan
, char *addr
, int timeout
)
3034 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
3035 If the remote end does not answer within the timeout, then do NOT hang up, but
3038 /* Stop if we're a zombie or need a soft hangup */
3039 ast_channel_lock(chan
);
3040 if (!ast_test_flag(chan
, AST_FLAG_ZOMBIE
) && !ast_check_hangup(chan
)) {
3041 if (chan
->tech
->call
)
3042 res
= chan
->tech
->call(chan
, addr
, timeout
);
3043 ast_set_flag(chan
, AST_FLAG_OUTGOING
);
3045 ast_channel_unlock(chan
);
3050 \brief Transfer a call to dest, if the channel supports transfer
3054 \arg the manager interface
3056 int ast_transfer(struct ast_channel
*chan
, char *dest
)
3060 /* Stop if we're a zombie or need a soft hangup */
3061 ast_channel_lock(chan
);
3062 if (!ast_test_flag(chan
, AST_FLAG_ZOMBIE
) && !ast_check_hangup(chan
)) {
3063 if (chan
->tech
->transfer
) {
3064 res
= chan
->tech
->transfer(chan
, dest
);
3070 ast_channel_unlock(chan
);
3074 int ast_readstring(struct ast_channel
*c
, char *s
, int len
, int timeout
, int ftimeout
, char *enders
)
3076 return ast_readstring_full(c
, s
, len
, timeout
, ftimeout
, enders
, -1, -1);
3079 int ast_readstring_full(struct ast_channel
*c
, char *s
, int len
, int timeout
, int ftimeout
, char *enders
, int audiofd
, int ctrlfd
)
3081 int pos
= 0; /* index in the buffer where we accumulate digits */
3084 /* Stop if we're a zombie or need a soft hangup */
3085 if (ast_test_flag(c
, AST_FLAG_ZOMBIE
) || ast_check_hangup(c
))
3092 d
= ast_waitstream_full(c
, AST_DIGIT_ANY
, audiofd
, ctrlfd
);
3096 d
= ast_waitfordigit_full(c
, to
, audiofd
, ctrlfd
);
3098 d
= ast_waitfordigit_full(c
, to
, audiofd
, ctrlfd
);
3110 if (!strchr(enders
, d
))
3112 if (strchr(enders
, d
) || (pos
>= len
)) {
3122 int ast_channel_supports_html(struct ast_channel
*chan
)
3124 return (chan
->tech
->send_html
) ? 1 : 0;
3127 int ast_channel_sendhtml(struct ast_channel
*chan
, int subclass
, const char *data
, int datalen
)
3129 if (chan
->tech
->send_html
)
3130 return chan
->tech
->send_html(chan
, subclass
, data
, datalen
);
3134 int ast_channel_sendurl(struct ast_channel
*chan
, const char *url
)
3136 return ast_channel_sendhtml(chan
, AST_HTML_URL
, url
, strlen(url
) + 1);
3139 int ast_channel_make_compatible(struct ast_channel
*chan
, struct ast_channel
*peer
)
3144 if (chan
->readformat
== peer
->writeformat
&& chan
->writeformat
== peer
->readformat
) {
3145 /* Already compatible! Moving on ... */
3149 /* Set up translation from the chan to the peer */
3150 src
= chan
->nativeformats
;
3151 dst
= peer
->nativeformats
;
3152 if (ast_translator_best_choice(&dst
, &src
) < 0) {
3153 ast_log(LOG_WARNING
, "No path to translate from %s(%d) to %s(%d)\n", chan
->name
, src
, peer
->name
, dst
);
3157 /* if the best path is not 'pass through', then
3158 transcoding is needed; if desired, force transcode path
3159 to use SLINEAR between channels, but only if there is
3160 no direct conversion available */
3161 if ((src
!= dst
) && ast_opt_transcode_via_slin
&&
3162 (ast_translate_path_steps(dst
, src
) != 1))
3163 dst
= AST_FORMAT_SLINEAR
;
3164 if (ast_set_read_format(chan
, dst
) < 0) {
3165 ast_log(LOG_WARNING
, "Unable to set read format on channel %s to %d\n", chan
->name
, dst
);
3168 if (ast_set_write_format(peer
, dst
) < 0) {
3169 ast_log(LOG_WARNING
, "Unable to set write format on channel %s to %d\n", peer
->name
, dst
);
3173 /* Set up translation from the peer to the chan */
3174 src
= peer
->nativeformats
;
3175 dst
= chan
->nativeformats
;
3176 if (ast_translator_best_choice(&dst
, &src
) < 0) {
3177 ast_log(LOG_WARNING
, "No path to translate from %s(%d) to %s(%d)\n", peer
->name
, src
, chan
->name
, dst
);
3181 /* if the best path is not 'pass through', then
3182 transcoding is needed; if desired, force transcode path
3183 to use SLINEAR between channels, but only if there is
3184 no direct conversion available */
3185 if ((src
!= dst
) && ast_opt_transcode_via_slin
&&
3186 (ast_translate_path_steps(dst
, src
) != 1))
3187 dst
= AST_FORMAT_SLINEAR
;
3188 if (ast_set_read_format(peer
, dst
) < 0) {
3189 ast_log(LOG_WARNING
, "Unable to set read format on channel %s to %d\n", peer
->name
, dst
);
3192 if (ast_set_write_format(chan
, dst
) < 0) {
3193 ast_log(LOG_WARNING
, "Unable to set write format on channel %s to %d\n", chan
->name
, dst
);
3199 int ast_channel_masquerade(struct ast_channel
*original
, struct ast_channel
*clone
)
3202 struct ast_channel
*final_orig
, *final_clone
, *base
;
3205 final_orig
= original
;
3206 final_clone
= clone
;
3208 ast_channel_lock(original
);
3209 while (ast_channel_trylock(clone
)) {
3210 ast_channel_unlock(original
);
3212 ast_channel_lock(original
);
3215 /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
3216 and if so, we don't really want to masquerade it, but its proxy */
3217 if (original
->_bridge
&& (original
->_bridge
!= ast_bridged_channel(original
)) && (original
->_bridge
->_bridge
!= original
))
3218 final_orig
= original
->_bridge
;
3220 if (clone
->_bridge
&& (clone
->_bridge
!= ast_bridged_channel(clone
)) && (clone
->_bridge
->_bridge
!= clone
))
3221 final_clone
= clone
->_bridge
;
3223 if (final_clone
->tech
->get_base_channel
&& (base
= final_clone
->tech
->get_base_channel(final_clone
))) {
3227 if ((final_orig
!= original
) || (final_clone
!= clone
)) {
3228 /* Lots and lots of deadlock avoidance. The main one we're competing with
3229 * is ast_write(), which locks channels recursively, when working with a
3231 if (ast_channel_trylock(final_orig
)) {
3232 ast_channel_unlock(clone
);
3233 ast_channel_unlock(original
);
3236 if (ast_channel_trylock(final_clone
)) {
3237 ast_channel_unlock(final_orig
);
3238 ast_channel_unlock(clone
);
3239 ast_channel_unlock(original
);
3242 ast_channel_unlock(clone
);
3243 ast_channel_unlock(original
);
3244 original
= final_orig
;
3245 clone
= final_clone
;
3248 if (original
== clone
) {
3249 ast_log(LOG_WARNING
, "Can't masquerade channel '%s' into itself!\n", original
->name
);
3250 ast_channel_unlock(clone
);
3251 ast_channel_unlock(original
);
3256 ast_log(LOG_DEBUG
, "Planning to masquerade channel %s into the structure of %s\n",
3257 clone
->name
, original
->name
);
3258 if (original
->masq
) {
3259 ast_log(LOG_WARNING
, "%s is already going to masquerade as %s\n",
3260 original
->masq
->name
, original
->name
);
3261 } else if (clone
->masqr
) {
3262 ast_log(LOG_WARNING
, "%s is already going to masquerade as %s\n",
3263 clone
->name
, clone
->masqr
->name
);
3265 original
->masq
= clone
;
3266 clone
->masqr
= original
;
3267 ast_queue_frame(original
, &ast_null_frame
);
3268 ast_queue_frame(clone
, &ast_null_frame
);
3270 ast_log(LOG_DEBUG
, "Done planning to masquerade channel %s into the structure of %s\n", clone
->name
, original
->name
);
3274 ast_channel_unlock(clone
);
3275 ast_channel_unlock(original
);
3280 void ast_change_name(struct ast_channel
*chan
, char *newname
)
3282 manager_event(EVENT_FLAG_CALL
, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan
->name
, newname
, chan
->uniqueid
);
3283 ast_string_field_set(chan
, name
, newname
);
3286 void ast_channel_inherit_variables(const struct ast_channel
*parent
, struct ast_channel
*child
)
3288 struct ast_var_t
*current
, *newvar
;
3289 const char *varname
;
3291 AST_LIST_TRAVERSE(&parent
->varshead
, current
, entries
) {
3294 varname
= ast_var_full_name(current
);
3298 if (varname
[0] == '_') {
3300 if (varname
[1] == '_')
3306 newvar
= ast_var_assign(&varname
[1], ast_var_value(current
));
3308 AST_LIST_INSERT_TAIL(&child
->varshead
, newvar
, entries
);
3310 ast_log(LOG_DEBUG
, "Copying soft-transferable variable %s.\n", ast_var_name(newvar
));
3314 newvar
= ast_var_assign(ast_var_full_name(current
), ast_var_value(current
));
3316 AST_LIST_INSERT_TAIL(&child
->varshead
, newvar
, entries
);
3318 ast_log(LOG_DEBUG
, "Copying hard-transferable variable %s.\n", ast_var_name(newvar
));
3323 ast_log(LOG_DEBUG
, "Not copying variable %s.\n", ast_var_name(current
));
3330 \brief Clone channel variables from 'clone' channel into 'original' channel
3332 All variables except those related to app_groupcount are cloned.
3333 Variables are actually _removed_ from 'clone' channel, presumably
3334 because it will subsequently be destroyed.
3336 \note Assumes locks will be in place on both channels when called.
3338 static void clone_variables(struct ast_channel
*original
, struct ast_channel
*clone
)
3340 struct ast_var_t
*current
, *newvar
;
3341 /* Append variables from clone channel into original channel */
3342 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
3343 if (AST_LIST_FIRST(&clone
->varshead
))
3344 AST_LIST_APPEND_LIST(&original
->varshead
, &clone
->varshead
, entries
);
3346 /* then, dup the varshead list into the clone */
3348 AST_LIST_TRAVERSE(&original
->varshead
, current
, entries
) {
3349 newvar
= ast_var_assign(current
->name
, current
->value
);
3351 AST_LIST_INSERT_TAIL(&clone
->varshead
, newvar
, entries
);
3356 \brief Masquerade a channel
3358 \note Assumes channel will be locked when called
3360 int ast_do_masquerade(struct ast_channel
*original
)
3365 struct ast_frame
*cur
;
3366 const struct ast_channel_tech
*t
;
3368 struct ast_callerid tmpcid
;
3369 struct ast_channel
*clone
= original
->masq
;
3370 struct ast_cdr
*cdr
;
3371 int rformat
= original
->readformat
;
3372 int wformat
= original
->writeformat
;
3378 if (option_debug
> 3)
3379 ast_log(LOG_DEBUG
, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3380 clone
->name
, clone
->_state
, original
->name
, original
->_state
);
3382 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
3383 the clone channel into the original channel. Start by killing off the original
3384 channel's backend. I'm not sure we're going to keep this function, because
3385 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3387 /* We need the clone's lock, too */
3388 ast_channel_lock(clone
);
3390 if (option_debug
> 1)
3391 ast_log(LOG_DEBUG
, "Got clone lock for masquerade on '%s' at %p\n", clone
->name
, &clone
->lock
);
3393 /* Having remembered the original read/write formats, we turn off any translation on either
3395 free_translation(clone
);
3396 free_translation(original
);
3399 /* Unlink the masquerade */
3400 original
->masq
= NULL
;
3401 clone
->masqr
= NULL
;
3403 /* Save the original name */
3404 ast_copy_string(orig
, original
->name
, sizeof(orig
));
3405 /* Save the new name */
3406 ast_copy_string(newn
, clone
->name
, sizeof(newn
));
3407 /* Create the masq name */
3408 snprintf(masqn
, sizeof(masqn
), "%s<MASQ>", newn
);
3410 /* Copy the name from the clone channel */
3411 ast_string_field_set(original
, name
, newn
);
3413 /* Mangle the name of the clone channel */
3414 ast_string_field_set(clone
, name
, masqn
);
3416 /* Notify any managers of the change, first the masq then the other */
3417 manager_event(EVENT_FLAG_CALL
, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn
, masqn
, clone
->uniqueid
);
3418 manager_event(EVENT_FLAG_CALL
, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig
, newn
, original
->uniqueid
);
3420 /* Swap the technologies */
3422 original
->tech
= clone
->tech
;
3426 cdr
= original
->cdr
;
3427 original
->cdr
= clone
->cdr
;
3430 t_pvt
= original
->tech_pvt
;
3431 original
->tech_pvt
= clone
->tech_pvt
;
3432 clone
->tech_pvt
= t_pvt
;
3434 /* Swap the alertpipes */
3435 for (i
= 0; i
< 2; i
++) {
3436 x
= original
->alertpipe
[i
];
3437 original
->alertpipe
[i
] = clone
->alertpipe
[i
];
3438 clone
->alertpipe
[i
] = x
;
3442 * Swap the readq's. The end result should be this:
3444 * 1) All frames should be on the new (original) channel.
3445 * 2) Any frames that were already on the new channel before this
3446 * masquerade need to be at the end of the readq, after all of the
3447 * frames on the old (clone) channel.
3448 * 3) The alertpipe needs to get poked for every frame that was already
3449 * on the new channel, since we are now using the alert pipe from the
3450 * old (clone) channel.
3453 AST_LIST_HEAD_NOLOCK(, ast_frame
) tmp_readq
;
3454 AST_LIST_HEAD_SET_NOLOCK(&tmp_readq
, NULL
);
3456 AST_LIST_APPEND_LIST(&tmp_readq
, &original
->readq
, frame_list
);
3457 AST_LIST_APPEND_LIST(&original
->readq
, &clone
->readq
, frame_list
);
3459 while ((cur
= AST_LIST_REMOVE_HEAD(&tmp_readq
, frame_list
))) {
3460 AST_LIST_INSERT_TAIL(&original
->readq
, cur
, frame_list
);
3461 if (original
->alertpipe
[1] > -1) {
3463 write(original
->alertpipe
[1], &poke
, sizeof(poke
));
3468 /* Swap the raw formats */
3469 x
= original
->rawreadformat
;
3470 original
->rawreadformat
= clone
->rawreadformat
;
3471 clone
->rawreadformat
= x
;
3472 x
= original
->rawwriteformat
;
3473 original
->rawwriteformat
= clone
->rawwriteformat
;
3474 clone
->rawwriteformat
= x
;
3476 clone
->_softhangup
= AST_SOFTHANGUP_DEV
;
3478 /* And of course, so does our current state. Note we need not
3479 call ast_setstate since the event manager doesn't really consider
3480 these separate. We do this early so that the clone has the proper
3481 state of the original channel. */
3482 origstate
= original
->_state
;
3483 original
->_state
= clone
->_state
;
3484 clone
->_state
= origstate
;
3486 if (clone
->tech
->fixup
){
3487 res
= clone
->tech
->fixup(original
, clone
);
3489 ast_log(LOG_WARNING
, "Fixup failed on channel %s, strange things may happen.\n", clone
->name
);
3492 /* Start by disconnecting the original's physical side */
3493 if (clone
->tech
->hangup
)
3494 res
= clone
->tech
->hangup(clone
);
3496 ast_log(LOG_WARNING
, "Hangup failed! Strange things may happen!\n");
3497 ast_channel_unlock(clone
);
3501 snprintf(zombn
, sizeof(zombn
), "%s<ZOMBIE>", orig
);
3502 /* Mangle the name of the clone channel */
3503 ast_string_field_set(clone
, name
, zombn
);
3504 manager_event(EVENT_FLAG_CALL
, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn
, zombn
, clone
->uniqueid
);
3506 /* Update the type. */
3507 t_pvt
= original
->monitor
;
3508 original
->monitor
= clone
->monitor
;
3509 clone
->monitor
= t_pvt
;
3511 /* Keep the same language. */
3512 ast_string_field_set(original
, language
, clone
->language
);
3513 /* Copy the FD's other than the generator fd */
3514 for (x
= 0; x
< AST_MAX_FDS
; x
++) {
3515 if (x
!= AST_GENERATOR_FD
)
3516 original
->fds
[x
] = clone
->fds
[x
];
3519 ast_app_group_update(clone
, original
);
3520 /* Move data stores over */
3521 if (AST_LIST_FIRST(&clone
->datastores
)) {
3522 struct ast_datastore
*ds
;
3523 AST_LIST_APPEND_LIST(&original
->datastores
, &clone
->datastores
, entry
);
3524 AST_LIST_TRAVERSE(&original
->datastores
, ds
, entry
) {
3525 if (ds
->info
->chan_fixup
)
3526 ds
->info
->chan_fixup(ds
->data
, clone
, original
);
3530 clone_variables(original
, clone
);
3531 /* Presense of ADSI capable CPE follows clone */
3532 original
->adsicpe
= clone
->adsicpe
;
3533 /* Bridge remains the same */
3534 /* CDR fields remain the same */
3535 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3536 /* Application and data remain the same */
3537 /* Clone exception becomes real one, as with fdno */
3538 ast_copy_flags(original
, clone
, AST_FLAG_EXCEPTION
);
3539 original
->fdno
= clone
->fdno
;
3540 /* Schedule context remains the same */
3541 /* Stream stuff stays the same */
3542 /* Keep the original state. The fixup code will need to work with it most likely */
3544 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3546 tmpcid
= original
->cid
;
3547 original
->cid
= clone
->cid
;
3548 clone
->cid
= tmpcid
;
3550 /* Restore original timing file descriptor */
3551 original
->fds
[AST_TIMING_FD
] = original
->timingfd
;
3553 /* Our native formats are different now */
3554 original
->nativeformats
= clone
->nativeformats
;
3556 /* Context, extension, priority, app data, jump table, remain the same */
3557 /* pvt switches. pbx stays the same, as does next */
3559 /* Set the write format */
3560 ast_set_write_format(original
, wformat
);
3562 /* Set the read format */
3563 ast_set_read_format(original
, rformat
);
3565 /* Copy the music class */
3566 ast_string_field_set(original
, musicclass
, clone
->musicclass
);
3569 ast_log(LOG_DEBUG
, "Putting channel %s in %d/%d formats\n", original
->name
, wformat
, rformat
);
3571 /* Okay. Last thing is to let the channel driver know about all this mess, so he
3572 can fix up everything as best as possible */
3573 if (original
->tech
->fixup
) {
3574 res
= original
->tech
->fixup(clone
, original
);
3576 ast_log(LOG_WARNING
, "Channel for type '%s' could not fixup channel %s\n",
3577 original
->tech
->type
, original
->name
);
3578 ast_channel_unlock(clone
);
3582 ast_log(LOG_WARNING
, "Channel type '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
3583 original
->tech
->type
, original
->name
);
3585 /* If an indication is currently playing maintain it on the channel that is taking the place of original */
3586 if (original
->visible_indication
)
3587 ast_indicate(original
, original
->visible_indication
);
3589 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
3590 a zombie so nothing tries to touch it. If it's already been marked as a
3591 zombie, then free it now (since it already is considered invalid). */
3592 if (ast_test_flag(clone
, AST_FLAG_ZOMBIE
)) {
3594 ast_log(LOG_DEBUG
, "Destroying channel clone '%s'\n", clone
->name
);
3595 ast_channel_unlock(clone
);
3596 manager_event(EVENT_FLAG_CALL
, "Hangup",
3600 "Cause-txt: %s\r\n",
3604 ast_cause2str(clone
->hangupcause
)
3606 ast_channel_free(clone
);
3609 ast_log(LOG_DEBUG
, "Released clone lock on '%s'\n", clone
->name
);
3610 ast_set_flag(clone
, AST_FLAG_ZOMBIE
);
3611 ast_queue_frame(clone
, &ast_null_frame
);
3612 ast_channel_unlock(clone
);
3615 /* Signal any blocker */
3616 if (ast_test_flag(original
, AST_FLAG_BLOCKING
))
3617 pthread_kill(original
->blocker
, SIGURG
);
3619 ast_log(LOG_DEBUG
, "Done Masquerading %s (%d)\n", original
->name
, original
->_state
);
3623 void ast_set_callerid(struct ast_channel
*chan
, const char *callerid
, const char *calleridname
, const char *ani
)
3625 ast_channel_lock(chan
);
3628 if (chan
->cid
.cid_num
)
3629 free(chan
->cid
.cid_num
);
3630 chan
->cid
.cid_num
= ast_strdup(callerid
);
3633 if (chan
->cid
.cid_name
)
3634 free(chan
->cid
.cid_name
);
3635 chan
->cid
.cid_name
= ast_strdup(calleridname
);
3638 if (chan
->cid
.cid_ani
)
3639 free(chan
->cid
.cid_ani
);
3640 chan
->cid
.cid_ani
= ast_strdup(ani
);
3643 ast_cdr_setcid(chan
->cdr
, chan
);
3644 manager_event(EVENT_FLAG_CALL
, "Newcallerid",
3647 "CallerIDName: %s\r\n"
3649 "CID-CallingPres: %d (%s)\r\n",
3651 S_OR(chan
->cid
.cid_num
, "<Unknown>"),
3652 S_OR(chan
->cid
.cid_name
, "<Unknown>"),
3655 ast_describe_caller_presentation(chan
->cid
.cid_pres
)
3658 ast_channel_unlock(chan
);
3661 int ast_setstate(struct ast_channel
*chan
, enum ast_channel_state state
)
3663 int oldstate
= chan
->_state
;
3665 if (oldstate
== state
)
3668 chan
->_state
= state
;
3669 ast_device_state_changed_literal(chan
->name
);
3670 /* setstate used to conditionally report Newchannel; this is no more */
3671 manager_event(EVENT_FLAG_CALL
,
3676 "CallerIDName: %s\r\n"
3678 chan
->name
, ast_state2str(chan
->_state
),
3679 S_OR(chan
->cid
.cid_num
, "<unknown>"),
3680 S_OR(chan
->cid
.cid_name
, "<unknown>"),
3686 /*! \brief Find bridged channel */
3687 struct ast_channel
*ast_bridged_channel(struct ast_channel
*chan
)
3689 struct ast_channel
*bridged
;
3690 bridged
= chan
->_bridge
;
3691 if (bridged
&& bridged
->tech
->bridged_channel
)
3692 bridged
= bridged
->tech
->bridged_channel(chan
, bridged
);
3696 static void bridge_playfile(struct ast_channel
*chan
, struct ast_channel
*peer
, const char *sound
, int remain
)
3698 int min
= 0, sec
= 0, check
;
3700 check
= ast_autoservice_start(peer
);
3705 if (remain
/ 60 > 1) {
3713 if (!strcmp(sound
,"timeleft")) { /* Queue support */
3714 ast_stream_and_wait(chan
, "vm-youhave", chan
->language
, "");
3716 ast_say_number(chan
, min
, AST_DIGIT_ANY
, chan
->language
, NULL
);
3717 ast_stream_and_wait(chan
, "queue-minutes", chan
->language
, "");
3720 ast_say_number(chan
, sec
, AST_DIGIT_ANY
, chan
->language
, NULL
);
3721 ast_stream_and_wait(chan
, "queue-seconds", chan
->language
, "");
3724 ast_stream_and_wait(chan
, sound
, chan
->language
, "");
3727 ast_autoservice_stop(peer
);
3730 static enum ast_bridge_result
ast_generic_bridge(struct ast_channel
*c0
, struct ast_channel
*c1
,
3731 struct ast_bridge_config
*config
, struct ast_frame
**fo
,
3732 struct ast_channel
**rc
, struct timeval bridge_end
)
3734 /* Copy voice back and forth between the two channels. */
3735 struct ast_channel
*cs
[3];
3736 struct ast_frame
*f
;
3737 enum ast_bridge_result res
= AST_BRIDGE_COMPLETE
;
3738 int o0nativeformats
;
3739 int o1nativeformats
;
3743 /* Indicates whether a frame was queued into a jitterbuffer */
3744 int frame_put_in_jb
= 0;
3750 pvt0
= c0
->tech_pvt
;
3751 pvt1
= c1
->tech_pvt
;
3752 o0nativeformats
= c0
->nativeformats
;
3753 o1nativeformats
= c1
->nativeformats
;
3754 watch_c0_dtmf
= config
->flags
& AST_BRIDGE_DTMF_CHANNEL_0
;
3755 watch_c1_dtmf
= config
->flags
& AST_BRIDGE_DTMF_CHANNEL_1
;
3757 /* Check the need of a jitterbuffer for each channel */
3758 jb_in_use
= ast_jb_do_usecheck(c0
, c1
);
3761 struct ast_channel
*who
, *other
;
3763 if ((c0
->tech_pvt
!= pvt0
) || (c1
->tech_pvt
!= pvt1
) ||
3764 (o0nativeformats
!= c0
->nativeformats
) ||
3765 (o1nativeformats
!= c1
->nativeformats
)) {
3766 /* Check for Masquerade, codec changes, etc */
3767 res
= AST_BRIDGE_RETRY
;
3770 if (bridge_end
.tv_sec
) {
3771 to
= ast_tvdiff_ms(bridge_end
, ast_tvnow());
3773 if (config
->timelimit
)
3774 res
= AST_BRIDGE_RETRY
;
3776 res
= AST_BRIDGE_COMPLETE
;
3781 /* Calculate the appropriate max sleep interval - in general, this is the time,
3782 left to the closest jb delivery moment */
3784 to
= ast_jb_get_when_to_wakeup(c0
, c1
, to
);
3785 who
= ast_waitfor_n(cs
, 2, &to
);
3787 /* No frame received within the specified timeout - check if we have to deliver now */
3789 ast_jb_get_and_deliver(c0
, c1
);
3790 if (c0
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
|| c1
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
) {
3791 if (c0
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
)
3792 c0
->_softhangup
= 0;
3793 if (c1
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
)
3794 c1
->_softhangup
= 0;
3805 ast_log(LOG_DEBUG
, "Didn't get a frame from channel: %s\n",who
->name
);
3809 other
= (who
== c0
) ? c1
: c0
; /* the 'other' channel */
3810 /* Try add the frame info the who's bridged channel jitterbuff */
3812 frame_put_in_jb
= !ast_jb_put(other
, f
);
3814 if ((f
->frametype
== AST_FRAME_CONTROL
) && !(config
->flags
& AST_BRIDGE_IGNORE_SIGS
)) {
3815 int bridge_exit
= 0;
3817 switch (f
->subclass
) {
3818 case AST_CONTROL_HOLD
:
3819 case AST_CONTROL_UNHOLD
:
3820 case AST_CONTROL_VIDUPDATE
:
3821 case AST_CONTROL_SRCUPDATE
:
3822 ast_indicate_data(other
, f
->subclass
, f
->data
, f
->datalen
);
3829 ast_log(LOG_DEBUG
, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f
->subclass
, who
->name
);
3835 if ((f
->frametype
== AST_FRAME_VOICE
) ||
3836 (f
->frametype
== AST_FRAME_DTMF_BEGIN
) ||
3837 (f
->frametype
== AST_FRAME_DTMF
) ||
3838 (f
->frametype
== AST_FRAME_VIDEO
) ||
3839 (f
->frametype
== AST_FRAME_IMAGE
) ||
3840 (f
->frametype
== AST_FRAME_HTML
) ||
3841 (f
->frametype
== AST_FRAME_MODEM
) ||
3842 (f
->frametype
== AST_FRAME_TEXT
)) {
3843 /* monitored dtmf causes exit from bridge */
3844 int monitored_source
= (who
== c0
) ? watch_c0_dtmf
: watch_c1_dtmf
;
3846 if (monitored_source
&&
3847 (f
->frametype
== AST_FRAME_DTMF_END
||
3848 f
->frametype
== AST_FRAME_DTMF_BEGIN
)) {
3852 ast_log(LOG_DEBUG
, "Got DTMF %s on channel (%s)\n",
3853 f
->frametype
== AST_FRAME_DTMF_END
? "end" : "begin",
3857 /* Write immediately frames, not passed through jb */
3858 if (!frame_put_in_jb
)
3859 ast_write(other
, f
);
3861 /* Check if we have to deliver now */
3863 ast_jb_get_and_deliver(c0
, c1
);
3865 /* XXX do we want to pass on also frames not matched above ? */
3868 /* Swap who gets priority */
3876 /*! \brief Bridge two channels together */
3877 enum ast_bridge_result
ast_channel_bridge(struct ast_channel
*c0
, struct ast_channel
*c1
,
3878 struct ast_bridge_config
*config
, struct ast_frame
**fo
, struct ast_channel
**rc
)
3880 struct ast_channel
*who
= NULL
;
3881 enum ast_bridge_result res
= AST_BRIDGE_COMPLETE
;
3884 int o0nativeformats
;
3885 int o1nativeformats
;
3886 long time_left_ms
=0;
3887 struct timeval nexteventts
= { 0, };
3888 char caller_warning
= 0;
3889 char callee_warning
= 0;
3892 ast_log(LOG_WARNING
, "%s is already in a bridge with %s\n",
3893 c0
->name
, c0
->_bridge
->name
);
3897 ast_log(LOG_WARNING
, "%s is already in a bridge with %s\n",
3898 c1
->name
, c1
->_bridge
->name
);
3902 /* Stop if we're a zombie or need a soft hangup */
3903 if (ast_test_flag(c0
, AST_FLAG_ZOMBIE
) || ast_check_hangup_locked(c0
) ||
3904 ast_test_flag(c1
, AST_FLAG_ZOMBIE
) || ast_check_hangup_locked(c1
))
3908 firstpass
= config
->firstpass
;
3909 config
->firstpass
= 0;
3911 if (ast_tvzero(config
->start_time
))
3912 config
->start_time
= ast_tvnow();
3913 time_left_ms
= config
->timelimit
;
3915 caller_warning
= ast_test_flag(&config
->features_caller
, AST_FEATURE_PLAY_WARNING
);
3916 callee_warning
= ast_test_flag(&config
->features_callee
, AST_FEATURE_PLAY_WARNING
);
3918 if (config
->start_sound
&& firstpass
) {
3920 bridge_playfile(c0
, c1
, config
->start_sound
, time_left_ms
/ 1000);
3922 bridge_playfile(c1
, c0
, config
->start_sound
, time_left_ms
/ 1000);
3925 /* Keep track of bridge */
3929 /* \todo XXX here should check that cid_num is not NULL */
3930 manager_event(EVENT_FLAG_CALL
, "Link",
3936 "CallerID2: %s\r\n",
3937 c0
->name
, c1
->name
, c0
->uniqueid
, c1
->uniqueid
, c0
->cid
.cid_num
, c1
->cid
.cid_num
);
3939 o0nativeformats
= c0
->nativeformats
;
3940 o1nativeformats
= c1
->nativeformats
;
3942 if (config
->feature_timer
) {
3943 nexteventts
= ast_tvadd(config
->start_time
, ast_samp2tv(config
->feature_timer
, 1000));
3944 } else if (config
->timelimit
) {
3945 nexteventts
= ast_tvadd(config
->start_time
, ast_samp2tv(config
->timelimit
, 1000));
3946 if (caller_warning
|| callee_warning
)
3947 nexteventts
= ast_tvsub(nexteventts
, ast_samp2tv(config
->play_warning
, 1000));
3950 if (!c0
->tech
->send_digit_begin
)
3951 ast_set_flag(c1
, AST_FLAG_END_DTMF_ONLY
);
3952 if (!c1
->tech
->send_digit_begin
)
3953 ast_set_flag(c0
, AST_FLAG_END_DTMF_ONLY
);
3955 /* Before we enter in and bridge these two together tell them both the source of audio has changed */
3956 ast_indicate(c0
, AST_CONTROL_SRCUPDATE
);
3957 ast_indicate(c1
, AST_CONTROL_SRCUPDATE
);
3959 for (/* ever */;;) {
3960 struct timeval now
= { 0, };
3965 if (!ast_tvzero(nexteventts
)) {
3967 to
= ast_tvdiff_ms(nexteventts
, now
);
3969 if (!config
->timelimit
) {
3970 res
= AST_BRIDGE_COMPLETE
;
3977 if (config
->timelimit
) {
3978 time_left_ms
= config
->timelimit
- ast_tvdiff_ms(now
, config
->start_time
);
3979 if (time_left_ms
< to
)
3982 if (time_left_ms
<= 0) {
3983 if (caller_warning
&& config
->end_sound
)
3984 bridge_playfile(c0
, c1
, config
->end_sound
, 0);
3985 if (callee_warning
&& config
->end_sound
)
3986 bridge_playfile(c1
, c0
, config
->end_sound
, 0);
3995 if (time_left_ms
>= 5000 && config
->warning_sound
&& config
->play_warning
) {
3996 int t
= (time_left_ms
+ 500) / 1000; /* round to nearest second */
3998 bridge_playfile(c0
, c1
, config
->warning_sound
, t
);
4000 bridge_playfile(c1
, c0
, config
->warning_sound
, t
);
4002 if (config
->warning_freq
&& (time_left_ms
> (config
->warning_freq
+ 5000)))
4003 nexteventts
= ast_tvadd(nexteventts
, ast_samp2tv(config
->warning_freq
, 1000));
4005 nexteventts
= ast_tvadd(config
->start_time
, ast_samp2tv(config
->timelimit
, 1000));
4009 if (c0
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
|| c1
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
) {
4010 if (c0
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
)
4011 c0
->_softhangup
= 0;
4012 if (c1
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
)
4013 c1
->_softhangup
= 0;
4017 ast_log(LOG_DEBUG
, "Unbridge signal received. Ending native bridge.\n");
4021 /* Stop if we're a zombie or need a soft hangup */
4022 if (ast_test_flag(c0
, AST_FLAG_ZOMBIE
) || ast_check_hangup_locked(c0
) ||
4023 ast_test_flag(c1
, AST_FLAG_ZOMBIE
) || ast_check_hangup_locked(c1
)) {
4029 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",
4031 ast_test_flag(c0
, AST_FLAG_ZOMBIE
) ? "Yes" : "No",
4032 ast_check_hangup(c0
) ? "Yes" : "No",
4033 ast_test_flag(c1
, AST_FLAG_ZOMBIE
) ? "Yes" : "No",
4034 ast_check_hangup(c1
) ? "Yes" : "No");
4038 /* See if the BRIDGEPEER variable needs to be updated */
4039 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c0
, "BRIDGEPEER")))
4040 pbx_builtin_setvar_helper(c0
, "BRIDGEPEER", c1
->name
);
4041 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c1
, "BRIDGEPEER")))
4042 pbx_builtin_setvar_helper(c1
, "BRIDGEPEER", c0
->name
);
4044 if (c0
->tech
->bridge
&&
4045 (config
->timelimit
== 0) &&
4046 (c0
->tech
->bridge
== c1
->tech
->bridge
) &&
4047 !nativefailed
&& !c0
->monitor
&& !c1
->monitor
&&
4048 !c0
->audiohooks
&& !c1
->audiohooks
&& !ast_test_flag(&(config
->features_callee
),AST_FEATURE_REDIRECT
) &&
4049 !ast_test_flag(&(config
->features_caller
),AST_FEATURE_REDIRECT
) &&
4050 !c0
->masq
&& !c0
->masqr
&& !c1
->masq
&& !c1
->masqr
) {
4051 /* Looks like they share a bridge method and nothing else is in the way */
4052 ast_set_flag(c0
, AST_FLAG_NBRIDGE
);
4053 ast_set_flag(c1
, AST_FLAG_NBRIDGE
);
4054 if ((res
= c0
->tech
->bridge(c0
, c1
, config
->flags
, fo
, rc
, to
)) == AST_BRIDGE_COMPLETE
) {
4055 /* \todo XXX here should check that cid_num is not NULL */
4056 manager_event(EVENT_FLAG_CALL
, "Unlink",
4062 "CallerID2: %s\r\n",
4063 c0
->name
, c1
->name
, c0
->uniqueid
, c1
->uniqueid
, c0
->cid
.cid_num
, c1
->cid
.cid_num
);
4065 ast_log(LOG_DEBUG
, "Returning from native bridge, channels: %s, %s\n", c0
->name
, c1
->name
);
4067 ast_clear_flag(c0
, AST_FLAG_NBRIDGE
);
4068 ast_clear_flag(c1
, AST_FLAG_NBRIDGE
);
4070 if (c0
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
|| c1
->_softhangup
== AST_SOFTHANGUP_UNBRIDGE
)
4078 ast_clear_flag(c0
, AST_FLAG_NBRIDGE
);
4079 ast_clear_flag(c1
, AST_FLAG_NBRIDGE
);
4082 case AST_BRIDGE_RETRY
:
4085 if (option_verbose
> 2)
4086 ast_verbose(VERBOSE_PREFIX_3
"Native bridging %s and %s ended\n",
4087 c0
->name
, c1
->name
);
4089 case AST_BRIDGE_FAILED_NOWARN
:
4095 if (((c0
->writeformat
!= c1
->readformat
) || (c0
->readformat
!= c1
->writeformat
) ||
4096 (c0
->nativeformats
!= o0nativeformats
) || (c1
->nativeformats
!= o1nativeformats
)) &&
4097 !(c0
->generator
|| c1
->generator
)) {
4098 if (ast_channel_make_compatible(c0
, c1
)) {
4099 ast_log(LOG_WARNING
, "Can't make %s and %s compatible\n", c0
->name
, c1
->name
);
4100 /* \todo XXX here should check that cid_num is not NULL */
4101 manager_event(EVENT_FLAG_CALL
, "Unlink",
4107 "CallerID2: %s\r\n",
4108 c0
->name
, c1
->name
, c0
->uniqueid
, c1
->uniqueid
, c0
->cid
.cid_num
, c1
->cid
.cid_num
);
4109 return AST_BRIDGE_FAILED
;
4111 o0nativeformats
= c0
->nativeformats
;
4112 o1nativeformats
= c1
->nativeformats
;
4114 res
= ast_generic_bridge(c0
, c1
, config
, fo
, rc
, nexteventts
);
4115 if (res
!= AST_BRIDGE_RETRY
)
4119 ast_clear_flag(c0
, AST_FLAG_END_DTMF_ONLY
);
4120 ast_clear_flag(c1
, AST_FLAG_END_DTMF_ONLY
);
4122 /* Now that we have broken the bridge the source will change yet again */
4123 ast_indicate(c0
, AST_CONTROL_SRCUPDATE
);
4124 ast_indicate(c1
, AST_CONTROL_SRCUPDATE
);
4129 /* \todo XXX here should check that cid_num is not NULL */
4130 manager_event(EVENT_FLAG_CALL
, "Unlink",
4136 "CallerID2: %s\r\n",
4137 c0
->name
, c1
->name
, c0
->uniqueid
, c1
->uniqueid
, c0
->cid
.cid_num
, c1
->cid
.cid_num
);
4139 ast_log(LOG_DEBUG
, "Bridge stops bridging channels %s and %s\n", c0
->name
, c1
->name
);
4144 /*! \brief Sets an option on a channel */
4145 int ast_channel_setoption(struct ast_channel
*chan
, int option
, void *data
, int datalen
, int block
)
4149 if (chan
->tech
->setoption
) {
4150 res
= chan
->tech
->setoption(chan
, option
, data
, datalen
);
4158 /* XXX Implement blocking -- just wait for our option frame reply, discarding
4159 intermediate packets. XXX */
4160 ast_log(LOG_ERROR
, "XXX Blocking not implemented yet XXX\n");
4166 struct tonepair_def
{
4173 struct tonepair_state
{
4187 unsigned char offset
[AST_FRIENDLY_OFFSET
];
4191 static void tonepair_release(struct ast_channel
*chan
, void *params
)
4193 struct tonepair_state
*ts
= params
;
4196 ast_set_write_format(chan
, ts
->origwfmt
);
4200 static void *tonepair_alloc(struct ast_channel
*chan
, void *params
)
4202 struct tonepair_state
*ts
;
4203 struct tonepair_def
*td
= params
;
4205 if (!(ts
= ast_calloc(1, sizeof(*ts
))))
4207 ts
->origwfmt
= chan
->writeformat
;
4208 if (ast_set_write_format(chan
, AST_FORMAT_SLINEAR
)) {
4209 ast_log(LOG_WARNING
, "Unable to set '%s' to signed linear format (write)\n", chan
->name
);
4210 tonepair_release(NULL
, ts
);
4213 ts
->fac1
= 2.0 * cos(2.0 * M_PI
* (td
->freq1
/ 8000.0)) * 32768.0;
4215 ts
->v2_1
= sin(-4.0 * M_PI
* (td
->freq1
/ 8000.0)) * td
->vol
;
4216 ts
->v3_1
= sin(-2.0 * M_PI
* (td
->freq1
/ 8000.0)) * td
->vol
;
4218 ts
->fac2
= 2.0 * cos(2.0 * M_PI
* (td
->freq2
/ 8000.0)) * 32768.0;
4219 ts
->v2_2
= sin(-4.0 * M_PI
* (td
->freq2
/ 8000.0)) * td
->vol
;
4220 ts
->v3_2
= sin(-2.0 * M_PI
* (td
->freq2
/ 8000.0)) * td
->vol
;
4221 ts
->duration
= td
->duration
;
4224 /* Let interrupts interrupt :) */
4225 ast_set_flag(chan
, AST_FLAG_WRITE_INT
);
4229 static int tonepair_generator(struct ast_channel
*chan
, void *data
, int len
, int samples
)
4231 struct tonepair_state
*ts
= data
;
4234 /* we need to prepare a frame with 16 * timelen samples as we're
4235 * generating SLIN audio
4239 if (len
> sizeof(ts
->data
) / 2 - 1) {
4240 ast_log(LOG_WARNING
, "Can't generate that much data!\n");
4243 memset(&ts
->f
, 0, sizeof(ts
->f
));
4244 for (x
=0;x
<len
/2;x
++) {
4245 ts
->v1_1
= ts
->v2_1
;
4246 ts
->v2_1
= ts
->v3_1
;
4247 ts
->v3_1
= (ts
->fac1
* ts
->v2_1
>> 15) - ts
->v1_1
;
4249 ts
->v1_2
= ts
->v2_2
;
4250 ts
->v2_2
= ts
->v3_2
;
4251 ts
->v3_2
= (ts
->fac2
* ts
->v2_2
>> 15) - ts
->v1_2
;
4254 p
= ts
->v3_2
- 32768;
4256 p
= ((p
* 9) / 10) + 1;
4257 ts
->data
[x
] = (ts
->v3_1
* p
) >> 15;
4259 ts
->data
[x
] = ts
->v3_1
+ ts
->v3_2
;
4261 ts
->f
.frametype
= AST_FRAME_VOICE
;
4262 ts
->f
.subclass
= AST_FORMAT_SLINEAR
;
4263 ts
->f
.datalen
= len
;
4264 ts
->f
.samples
= samples
;
4265 ts
->f
.offset
= AST_FRIENDLY_OFFSET
;
4266 ts
->f
.data
= ts
->data
;
4267 ast_write(chan
, &ts
->f
);
4269 if (ts
->duration
> 0) {
4270 if (ts
->pos
>= ts
->duration
* 8)
4276 static struct ast_generator tonepair
= {
4277 alloc
: tonepair_alloc
,
4278 release
: tonepair_release
,
4279 generate
: tonepair_generator
,
4282 int ast_tonepair_start(struct ast_channel
*chan
, int freq1
, int freq2
, int duration
, int vol
)
4284 struct tonepair_def d
= { 0, };
4288 d
.duration
= duration
;
4289 d
.vol
= (vol
< 1) ? 8192 : vol
; /* force invalid to 8192 */
4290 if (ast_activate_generator(chan
, &tonepair
, &d
))
4295 void ast_tonepair_stop(struct ast_channel
*chan
)
4297 ast_deactivate_generator(chan
);
4300 int ast_tonepair(struct ast_channel
*chan
, int freq1
, int freq2
, int duration
, int vol
)
4304 if ((res
= ast_tonepair_start(chan
, freq1
, freq2
, duration
, vol
)))
4307 /* Give us some wiggle room */
4308 while (chan
->generatordata
&& ast_waitfor(chan
, 100) >= 0) {
4309 struct ast_frame
*f
= ast_read(chan
);
4318 ast_group_t
ast_get_group(const char *s
)
4322 int start
=0, finish
=0, x
;
4323 ast_group_t group
= 0;
4325 if (ast_strlen_zero(s
))
4330 while ((piece
= strsep(&c
, ","))) {
4331 if (sscanf(piece
, "%d-%d", &start
, &finish
) == 2) {
4333 } else if (sscanf(piece
, "%d", &start
)) {
4337 ast_log(LOG_ERROR
, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s
, piece
);
4340 for (x
= start
; x
<= finish
; x
++) {
4341 if ((x
> 63) || (x
< 0)) {
4342 ast_log(LOG_WARNING
, "Ignoring invalid group %d (maximum group is 63)\n", x
);
4344 group
|= ((ast_group_t
) 1 << x
);
4350 static int (*ast_moh_start_ptr
)(struct ast_channel
*, const char *, const char *) = NULL
;
4351 static void (*ast_moh_stop_ptr
)(struct ast_channel
*) = NULL
;
4352 static void (*ast_moh_cleanup_ptr
)(struct ast_channel
*) = NULL
;
4354 void ast_install_music_functions(int (*start_ptr
)(struct ast_channel
*, const char *, const char *),
4355 void (*stop_ptr
)(struct ast_channel
*),
4356 void (*cleanup_ptr
)(struct ast_channel
*))
4358 ast_moh_start_ptr
= start_ptr
;
4359 ast_moh_stop_ptr
= stop_ptr
;
4360 ast_moh_cleanup_ptr
= cleanup_ptr
;
4363 void ast_uninstall_music_functions(void)
4365 ast_moh_start_ptr
= NULL
;
4366 ast_moh_stop_ptr
= NULL
;
4367 ast_moh_cleanup_ptr
= NULL
;
4370 /*! \brief Turn on music on hold on a given channel */
4371 int ast_moh_start(struct ast_channel
*chan
, const char *mclass
, const char *interpclass
)
4373 if (ast_moh_start_ptr
)
4374 return ast_moh_start_ptr(chan
, mclass
, interpclass
);
4376 if (option_verbose
> 2) {
4377 ast_verbose(VERBOSE_PREFIX_3
"Music class %s requested but no musiconhold loaded.\n",
4378 mclass
? mclass
: (interpclass
? interpclass
: "default"));
4384 /*! \brief Turn off music on hold on a given channel */
4385 void ast_moh_stop(struct ast_channel
*chan
)
4387 if (ast_moh_stop_ptr
)
4388 ast_moh_stop_ptr(chan
);
4391 void ast_moh_cleanup(struct ast_channel
*chan
)
4393 if (ast_moh_cleanup_ptr
)
4394 ast_moh_cleanup_ptr(chan
);
4397 void ast_channels_init(void)
4399 ast_cli_register_multiple(cli_channel
, sizeof(cli_channel
) / sizeof(struct ast_cli_entry
));
4402 /*! \brief Print call group and pickup group ---*/
4403 char *ast_print_group(char *buf
, int buflen
, ast_group_t group
)
4411 if (!group
) /* Return empty string if no group */
4414 for (i
= 0; i
<= 63; i
++) { /* Max group is 63 */
4415 if (group
& ((ast_group_t
) 1 << i
)) {
4417 strncat(buf
, ", ", buflen
- strlen(buf
) - 1);
4421 snprintf(num
, sizeof(num
), "%u", i
);
4422 strncat(buf
, num
, buflen
- strlen(buf
) - 1);
4428 void ast_set_variables(struct ast_channel
*chan
, struct ast_variable
*vars
)
4430 struct ast_variable
*cur
;
4432 for (cur
= vars
; cur
; cur
= cur
->next
)
4433 pbx_builtin_setvar_helper(chan
, cur
->name
, cur
->value
);
4436 static void *silence_generator_alloc(struct ast_channel
*chan
, void *data
)
4438 /* just store the data pointer in the channel structure */
4442 static void silence_generator_release(struct ast_channel
*chan
, void *data
)
4447 static int silence_generator_generate(struct ast_channel
*chan
, void *data
, int len
, int samples
)
4450 struct ast_frame frame
= {
4451 .frametype
= AST_FRAME_VOICE
,
4452 .subclass
= AST_FORMAT_SLINEAR
,
4455 .datalen
= sizeof(buf
),
4457 memset(buf
, 0, sizeof(buf
));
4458 if (ast_write(chan
, &frame
))
4463 static struct ast_generator silence_generator
= {
4464 .alloc
= silence_generator_alloc
,
4465 .release
= silence_generator_release
,
4466 .generate
= silence_generator_generate
,
4469 struct ast_silence_generator
{
4470 int old_write_format
;
4473 struct ast_silence_generator
*ast_channel_start_silence_generator(struct ast_channel
*chan
)
4475 struct ast_silence_generator
*state
;
4477 if (!(state
= ast_calloc(1, sizeof(*state
)))) {
4481 state
->old_write_format
= chan
->writeformat
;
4483 if (ast_set_write_format(chan
, AST_FORMAT_SLINEAR
) < 0) {
4484 ast_log(LOG_ERROR
, "Could not set write format to SLINEAR\n");
4489 ast_activate_generator(chan
, &silence_generator
, state
);
4492 ast_log(LOG_DEBUG
, "Started silence generator on '%s'\n", chan
->name
);
4497 void ast_channel_stop_silence_generator(struct ast_channel
*chan
, struct ast_silence_generator
*state
)
4502 ast_deactivate_generator(chan
);
4505 ast_log(LOG_DEBUG
, "Stopped silence generator on '%s'\n", chan
->name
);
4507 if (ast_set_write_format(chan
, state
->old_write_format
) < 0)
4508 ast_log(LOG_ERROR
, "Could not return write format to its original state\n");
4514 /*! \ brief Convert channel reloadreason (ENUM) to text string for manager event */
4515 const char *channelreloadreason2txt(enum channelreloadreason reason
)
4518 case CHANNEL_MODULE_LOAD
:
4519 return "LOAD (Channel module load)";
4521 case CHANNEL_MODULE_RELOAD
:
4522 return "RELOAD (Channel module reload)";
4524 case CHANNEL_CLI_RELOAD
:
4525 return "CLIRELOAD (Channel module reload by CLI command)";
4528 return "MANAGERRELOAD (Channel module reload by manager)";
4532 #ifdef DEBUG_CHANNEL_LOCKS
4534 /*! \brief Unlock AST channel (and print debugging output)
4535 \note You need to enable DEBUG_CHANNEL_LOCKS for this function
4537 int ast_channel_unlock(struct ast_channel
*chan
)
4540 if (option_debug
> 2)
4541 ast_log(LOG_DEBUG
, "::::==== Unlocking AST channel %s\n", chan
->name
);
4545 ast_log(LOG_DEBUG
, "::::==== Unlocking non-existing channel \n");
4549 res
= ast_mutex_unlock(&chan
->lock
);
4551 if (option_debug
> 2) {
4552 #ifdef DEBUG_THREADS
4554 if ((count
= chan
->lock
.reentrancy
))
4555 ast_log(LOG_DEBUG
, ":::=== Still have %d locks (recursive)\n", count
);
4559 ast_log(LOG_DEBUG
, "::::==== Channel %s was unlocked\n", chan
->name
);
4560 if (res
== EINVAL
) {
4562 ast_log(LOG_DEBUG
, "::::==== Channel %s had no lock by this thread. Failed unlocking\n", chan
->name
);
4566 /* We had no lock, so okay any way*/
4567 if (option_debug
> 3)
4568 ast_log(LOG_DEBUG
, "::::==== Channel %s was not locked at all \n", chan
->name
);
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_lock(struct ast_channel
*chan
)
4580 if (option_debug
> 3)
4581 ast_log(LOG_DEBUG
, "====:::: Locking AST channel %s\n", chan
->name
);
4583 res
= ast_mutex_lock(&chan
->lock
);
4585 if (option_debug
> 3) {
4586 #ifdef DEBUG_THREADS
4588 if ((count
= chan
->lock
.reentrancy
))
4589 ast_log(LOG_DEBUG
, ":::=== Now have %d locks (recursive)\n", count
);
4592 ast_log(LOG_DEBUG
, "::::==== Channel %s was locked\n", chan
->name
);
4593 if (res
== EDEADLK
) {
4594 /* We had no lock, so okey any way */
4595 if (option_debug
> 3)
4596 ast_log(LOG_DEBUG
, "::::==== Channel %s was not locked by us. Lock would cause deadlock.\n", chan
->name
);
4598 if (res
== EINVAL
) {
4599 if (option_debug
> 3)
4600 ast_log(LOG_DEBUG
, "::::==== Channel %s lock failed. No mutex.\n", chan
->name
);
4606 /*! \brief Lock AST channel (and print debugging output)
4607 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4608 int ast_channel_trylock(struct ast_channel
*chan
)
4612 if (option_debug
> 2)
4613 ast_log(LOG_DEBUG
, "====:::: Trying to lock AST channel %s\n", chan
->name
);
4615 res
= ast_mutex_trylock(&chan
->lock
);
4617 if (option_debug
> 2) {
4618 #ifdef DEBUG_THREADS
4620 if ((count
= chan
->lock
.reentrancy
))
4621 ast_log(LOG_DEBUG
, ":::=== Now have %d locks (recursive)\n", count
);
4624 ast_log(LOG_DEBUG
, "::::==== Channel %s was locked\n", chan
->name
);
4626 /* We failed to lock */
4627 if (option_debug
> 2)
4628 ast_log(LOG_DEBUG
, "::::==== Channel %s failed to lock. Not waiting around...\n", chan
->name
);
4630 if (res
== EDEADLK
) {
4631 /* We had no lock, so okey any way*/
4632 if (option_debug
> 2)
4633 ast_log(LOG_DEBUG
, "::::==== Channel %s was not locked. Lock would cause deadlock.\n", chan
->name
);
4635 if (res
== EINVAL
&& option_debug
> 2)
4636 ast_log(LOG_DEBUG
, "::::==== Channel %s lock failed. No mutex.\n", chan
->name
);
4644 * Wrappers for various ast_say_*() functions that call the full version
4645 * of the same functions.
4646 * The proper place would be say.c, but that file is optional and one
4647 * must be able to build asterisk even without it (using a loadable 'say'
4648 * implementation that only supplies the 'full' version of the functions.
4651 int ast_say_number(struct ast_channel
*chan
, int num
,
4652 const char *ints
, const char *language
, const char *options
)
4654 return ast_say_number_full(chan
, num
, ints
, language
, options
, -1, -1);
4657 int ast_say_enumeration(struct ast_channel
*chan
, int num
,
4658 const char *ints
, const char *language
, const char *options
)
4660 return ast_say_enumeration_full(chan
, num
, ints
, language
, options
, -1, -1);
4663 int ast_say_digits(struct ast_channel
*chan
, int num
,
4664 const char *ints
, const char *lang
)
4666 return ast_say_digits_full(chan
, num
, ints
, lang
, -1, -1);
4669 int ast_say_digit_str(struct ast_channel
*chan
, const char *str
,
4670 const char *ints
, const char *lang
)
4672 return ast_say_digit_str_full(chan
, str
, ints
, lang
, -1, -1);
4675 int ast_say_character_str(struct ast_channel
*chan
, const char *str
,
4676 const char *ints
, const char *lang
)
4678 return ast_say_character_str_full(chan
, str
, ints
, lang
, -1, -1);
4681 int ast_say_phonetic_str(struct ast_channel
*chan
, const char *str
,
4682 const char *ints
, const char *lang
)
4684 return ast_say_phonetic_str_full(chan
, str
, ints
, lang
, -1, -1);
4687 int ast_say_digits_full(struct ast_channel
*chan
, int num
,
4688 const char *ints
, const char *lang
, int audiofd
, int ctrlfd
)
4692 snprintf(buf
, sizeof(buf
), "%d", num
);
4693 return ast_say_digit_str_full(chan
, buf
, ints
, lang
, audiofd
, ctrlfd
);