Merged revisions 53879 via svnmerge from
[asterisk/asterisk.git] / main / channel.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Channel Management
22  *
23  * \author Mark Spencer <markster@digium.com>
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <string.h>
34 #include <sys/time.h>
35 #include <signal.h>
36 #include <errno.h>
37 #include <unistd.h>
38 #include <math.h>
39
40 #include "asterisk/zapata.h"
41
42 #include "asterisk/pbx.h"
43 #include "asterisk/frame.h"
44 #include "asterisk/sched.h"
45 #include "asterisk/options.h"
46 #include "asterisk/channel.h"
47 #include "asterisk/chanspy.h"
48 #include "asterisk/musiconhold.h"
49 #include "asterisk/logger.h"
50 #include "asterisk/say.h"
51 #include "asterisk/file.h"
52 #include "asterisk/cli.h"
53 #include "asterisk/translate.h"
54 #include "asterisk/manager.h"
55 #include "asterisk/chanvars.h"
56 #include "asterisk/linkedlists.h"
57 #include "asterisk/indications.h"
58 #include "asterisk/monitor.h"
59 #include "asterisk/causes.h"
60 #include "asterisk/callerid.h"
61 #include "asterisk/utils.h"
62 #include "asterisk/lock.h"
63 #include "asterisk/app.h"
64 #include "asterisk/transcap.h"
65 #include "asterisk/devicestate.h"
66 #include "asterisk/sha1.h"
67 #include "asterisk/threadstorage.h"
68 #include "asterisk/slinfactory.h"
69
70 struct channel_spy_trans {
71         int last_format;
72         struct ast_trans_pvt *path;
73 };
74
75 struct ast_channel_spy_list {
76         struct channel_spy_trans read_translator;
77         struct channel_spy_trans write_translator;
78         AST_LIST_HEAD_NOLOCK(, ast_channel_spy) list;
79 };
80
81 struct ast_channel_whisper_buffer {
82         ast_mutex_t lock;
83         struct ast_slinfactory sf;
84         unsigned int original_format;
85         struct ast_trans_pvt *path;
86 };
87
88 /* uncomment if you have problems with 'monitoring' synchronized files */
89 #if 0
90 #define MONITOR_CONSTANT_DELAY
91 #define MONITOR_DELAY   150 * 8         /* 150 ms of MONITORING DELAY */
92 #endif
93
94 /*! Prevent new channel allocation if shutting down. */
95 static int shutting_down;
96
97 static int uniqueint;
98
99 unsigned long global_fin, global_fout;
100
101 AST_THREADSTORAGE(state2str_threadbuf);
102 #define STATE2STR_BUFSIZE   32
103
104 /*! 100ms */
105 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
106
107 struct chanlist {
108         const struct ast_channel_tech *tech;
109         AST_LIST_ENTRY(chanlist) list;
110 };
111
112 /*! the list of registered channel types */
113 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
114
115 /*! the list of channels we have. Note that the lock for this list is used for
116     both the channels list and the backends list.  */
117 static AST_LIST_HEAD_STATIC(channels, ast_channel);
118
119 /*! map AST_CAUSE's to readable string representations */
120 const struct ast_cause {
121         int cause;
122         const char *name;
123         const char *desc;
124 } causes[] = {
125         { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
126         { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
127         { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
128         { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
129         { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
130         { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
131         { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
132         { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
133         { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
134         { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
135         { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
136         { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
137         { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
138         { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
139         { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
140         { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
141         { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
142         { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
143         { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
144         { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
145         { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
146         { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
147         { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
148         { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
149         { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
150         { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
151         { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
152         { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
153         { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
154         { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
155         { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
156         { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
157         { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
158         { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
159         { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
160         { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
161         { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
162         { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
163         { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
164         { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
165         { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
166         { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
167         { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
168         { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
169 };
170
171 struct ast_variable *ast_channeltype_list(void)
172 {
173         struct chanlist *cl;
174         struct ast_variable *var=NULL, *prev = NULL;
175         AST_LIST_TRAVERSE(&backends, cl, list) {
176                 if (prev)  {
177                         if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description)))
178                                 prev = prev->next;
179                 } else {
180                         var = ast_variable_new(cl->tech->type, cl->tech->description);
181                         prev = var;
182                 }
183         }
184         return var;
185 }
186
187 static int show_channeltypes(int fd, int argc, char *argv[])
188 {
189 #define FORMAT  "%-10.10s  %-40.40s %-12.12s %-12.12s %-12.12s\n"
190         struct chanlist *cl;
191         int count_chan = 0;
192
193         ast_cli(fd, FORMAT, "Type", "Description",       "Devicestate", "Indications", "Transfer");
194         ast_cli(fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
195         if (AST_LIST_LOCK(&channels)) {
196                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
197                 return -1;
198         }
199         AST_LIST_TRAVERSE(&backends, cl, list) {
200                 ast_cli(fd, FORMAT, cl->tech->type, cl->tech->description,
201                         (cl->tech->devicestate) ? "yes" : "no",
202                         (cl->tech->indicate) ? "yes" : "no",
203                         (cl->tech->transfer) ? "yes" : "no");
204                 count_chan++;
205         }
206         AST_LIST_UNLOCK(&channels);
207         ast_cli(fd, "----------\n%d channel drivers registered.\n", count_chan);
208         return RESULT_SUCCESS;
209
210 #undef FORMAT
211
212 }
213
214 static int show_channeltype(int fd, int argc, char *argv[])
215 {
216         struct chanlist *cl = NULL;
217
218         if (argc != 4)
219                 return RESULT_SHOWUSAGE;
220         
221         if (AST_LIST_LOCK(&channels)) {
222                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
223                 return RESULT_FAILURE;
224         }
225
226         AST_LIST_TRAVERSE(&backends, cl, list) {
227                 if (!strncasecmp(cl->tech->type, argv[3], strlen(cl->tech->type))) {
228                         break;
229                 }
230         }
231
232
233         if (!cl) {
234                 ast_cli(fd, "\n%s is not a registered channel driver.\n", argv[3]);
235                 AST_LIST_UNLOCK(&channels);
236                 return RESULT_FAILURE;
237         }
238
239         ast_cli(fd,
240                 "-- Info about channel driver: %s --\n"
241                 "  Device State: %s\n"
242                 "    Indication: %s\n"
243                 "     Transfer : %s\n"
244                 "  Capabilities: %d\n"
245                 "   Digit Begin: %s\n"
246                 "     Digit End: %s\n"
247                 "    Send HTML : %s\n"
248                 " Image Support: %s\n"
249                 "  Text Support: %s\n",
250                 cl->tech->type,
251                 (cl->tech->devicestate) ? "yes" : "no",
252                 (cl->tech->indicate) ? "yes" : "no",
253                 (cl->tech->transfer) ? "yes" : "no",
254                 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
255                 (cl->tech->send_digit_begin) ? "yes" : "no",
256                 (cl->tech->send_digit_end) ? "yes" : "no",
257                 (cl->tech->send_html) ? "yes" : "no",
258                 (cl->tech->send_image) ? "yes" : "no",
259                 (cl->tech->send_text) ? "yes" : "no"
260                 
261         );
262
263         AST_LIST_UNLOCK(&channels);
264         return RESULT_SUCCESS;
265 }
266
267 static char *complete_channeltypes(const char *line, const char *word, int pos, int state)
268 {
269         struct chanlist *cl;
270         int which = 0;
271         int wordlen;
272         char *ret = NULL;
273
274         if (pos != 3)
275                 return NULL;
276
277         wordlen = strlen(word);
278
279         AST_LIST_TRAVERSE(&backends, cl, list) {
280                 if (!strncasecmp(word, cl->tech->type, wordlen) && ++which > state) {
281                         ret = strdup(cl->tech->type);
282                         break;
283                 }
284         }
285         
286         return ret;
287 }
288
289 static const char show_channeltypes_usage[] =
290 "Usage: core show channeltypes\n"
291 "       Lists available channel types registered in your Asterisk server.\n";
292
293 static const char show_channeltype_usage[] =
294 "Usage: core show channeltype <name>\n"
295 "       Show details about the specified channel type, <name>.\n";
296
297 static struct ast_cli_entry cli_channel[] = {
298         { { "core", "show", "channeltypes", NULL },
299         show_channeltypes, "List available channel types",
300         show_channeltypes_usage },
301
302         { { "core", "show", "channeltype", NULL },
303         show_channeltype, "Give more details on that channel type",
304         show_channeltype_usage, complete_channeltypes },
305 };
306
307 /*! \brief Checks to see if a channel is needing hang up */
308 int ast_check_hangup(struct ast_channel *chan)
309 {
310         if (chan->_softhangup)          /* yes if soft hangup flag set */
311                 return 1;
312         if (!chan->tech_pvt)            /* yes if no technology private data */
313                 return 1;
314         if (!chan->whentohangup)        /* no if no hangup scheduled */
315                 return 0;
316         if (chan->whentohangup > time(NULL))    /* no if hangup time has not come yet. */
317                 return 0;
318         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;    /* record event */
319         return 1;
320 }
321
322 static int ast_check_hangup_locked(struct ast_channel *chan)
323 {
324         int res;
325         ast_channel_lock(chan);
326         res = ast_check_hangup(chan);
327         ast_channel_unlock(chan);
328         return res;
329 }
330
331 /*! \brief Initiate system shutdown */
332 void ast_begin_shutdown(int hangup)
333 {
334         struct ast_channel *c;
335         shutting_down = 1;
336         if (hangup) {
337                 AST_LIST_LOCK(&channels);
338                 AST_LIST_TRAVERSE(&channels, c, chan_list)
339                         ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
340                 AST_LIST_UNLOCK(&channels);
341         }
342 }
343
344 /*! \brief returns number of active/allocated channels */
345 int ast_active_channels(void)
346 {
347         struct ast_channel *c;
348         int cnt = 0;
349         AST_LIST_LOCK(&channels);
350         AST_LIST_TRAVERSE(&channels, c, chan_list)
351                 cnt++;
352         AST_LIST_UNLOCK(&channels);
353         return cnt;
354 }
355
356 /*! \brief Cancel a shutdown in progress */
357 void ast_cancel_shutdown(void)
358 {
359         shutting_down = 0;
360 }
361
362 /*! \brief Returns non-zero if Asterisk is being shut down */
363 int ast_shutting_down(void)
364 {
365         return shutting_down;
366 }
367
368 /*! \brief Set when to hangup channel */
369 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
370 {
371         chan->whentohangup = offset ? time(NULL) + offset : 0;
372         ast_queue_frame(chan, &ast_null_frame);
373         return;
374 }
375
376 /*! \brief Compare a offset with when to hangup channel */
377 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
378 {
379         time_t whentohangup;
380
381         if (chan->whentohangup == 0) {
382                 return (offset == 0) ? 0 : -1;
383         } else {
384                 if (offset == 0)        /* XXX why is this special ? */
385                         return (1);
386                 else {
387                         whentohangup = offset + time (NULL);
388                         if (chan->whentohangup < whentohangup)
389                                 return (1);
390                         else if (chan->whentohangup == whentohangup)
391                                 return (0);
392                         else
393                                 return (-1);
394                 }
395         }
396 }
397
398 /*! \brief Register a new telephony channel in Asterisk */
399 int ast_channel_register(const struct ast_channel_tech *tech)
400 {
401         struct chanlist *chan;
402
403         AST_LIST_LOCK(&channels);
404
405         AST_LIST_TRAVERSE(&backends, chan, list) {
406                 if (!strcasecmp(tech->type, chan->tech->type)) {
407                         ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
408                         AST_LIST_UNLOCK(&channels);
409                         return -1;
410                 }
411         }
412         
413         if (!(chan = ast_calloc(1, sizeof(*chan)))) {
414                 AST_LIST_UNLOCK(&channels);
415                 return -1;
416         }
417         chan->tech = tech;
418         AST_LIST_INSERT_HEAD(&backends, chan, list);
419
420         if (option_debug)
421                 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
422
423         if (option_verbose > 1)
424                 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
425                             chan->tech->description);
426
427         AST_LIST_UNLOCK(&channels);
428         return 0;
429 }
430
431 void ast_channel_unregister(const struct ast_channel_tech *tech)
432 {
433         struct chanlist *chan;
434
435         if (option_debug)
436                 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
437
438         AST_LIST_LOCK(&channels);
439
440         AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
441                 if (chan->tech == tech) {
442                         AST_LIST_REMOVE_CURRENT(&backends, list);
443                         free(chan);
444                         if (option_verbose > 1)
445                                 ast_verbose(VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
446                         break;  
447                 }
448         }
449         AST_LIST_TRAVERSE_SAFE_END
450
451         AST_LIST_UNLOCK(&channels);
452 }
453
454 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
455 {
456         struct chanlist *chanls;
457         const struct ast_channel_tech *ret = NULL;
458
459         if (AST_LIST_LOCK(&channels)) {
460                 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
461                 return NULL;
462         }
463
464         AST_LIST_TRAVERSE(&backends, chanls, list) {
465                 if (!strcasecmp(name, chanls->tech->type)) {
466                         ret = chanls->tech;
467                         break;
468                 }
469         }
470
471         AST_LIST_UNLOCK(&channels);
472         
473         return ret;
474 }
475
476 /*! \brief Gives the string form of a given hangup cause */
477 const char *ast_cause2str(int cause)
478 {
479         int x;
480
481         for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++) {
482                 if (causes[x].cause == cause)
483                         return causes[x].desc;
484         }
485
486         return "Unknown";
487 }
488
489 /*! \brief Convert a symbolic hangup cause to number */
490 int ast_str2cause(const char *name)
491 {
492         int x;
493
494         for (x = 0; x < sizeof(causes) / sizeof(causes[0]); x++)
495                 if (strncasecmp(causes[x].name, name, strlen(causes[x].name)) == 0)
496                         return causes[x].cause;
497
498         return -1;
499 }
500
501 /*! \brief Gives the string form of a given channel state.
502         \note This function is not reentrant.
503  */
504 const char *ast_state2str(enum ast_channel_state state)
505 {
506         char *buf;
507
508         switch (state) {
509         case AST_STATE_DOWN:
510                 return "Down";
511         case AST_STATE_RESERVED:
512                 return "Rsrvd";
513         case AST_STATE_OFFHOOK:
514                 return "OffHook";
515         case AST_STATE_DIALING:
516                 return "Dialing";
517         case AST_STATE_RING:
518                 return "Ring";
519         case AST_STATE_RINGING:
520                 return "Ringing";
521         case AST_STATE_UP:
522                 return "Up";
523         case AST_STATE_BUSY:
524                 return "Busy";
525         case AST_STATE_DIALING_OFFHOOK:
526                 return "Dialing Offhook";
527         case AST_STATE_PRERING:
528                 return "Pre-ring";
529         default:
530                 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
531                         return "Unknown";
532                 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
533                 return buf;
534         }
535 }
536
537 /*! \brief Gives the string form of a given transfer capability */
538 char *ast_transfercapability2str(int transfercapability)
539 {
540         switch (transfercapability) {
541         case AST_TRANS_CAP_SPEECH:
542                 return "SPEECH";
543         case AST_TRANS_CAP_DIGITAL:
544                 return "DIGITAL";
545         case AST_TRANS_CAP_RESTRICTED_DIGITAL:
546                 return "RESTRICTED_DIGITAL";
547         case AST_TRANS_CAP_3_1K_AUDIO:
548                 return "3K1AUDIO";
549         case AST_TRANS_CAP_DIGITAL_W_TONES:
550                 return "DIGITAL_W_TONES";
551         case AST_TRANS_CAP_VIDEO:
552                 return "VIDEO";
553         default:
554                 return "UNKNOWN";
555         }
556 }
557
558 /*! \brief Pick the best audio codec */
559 int ast_best_codec(int fmts)
560 {
561         /* This just our opinion, expressed in code.  We are asked to choose
562            the best codec to use, given no information */
563         int x;
564         static int prefs[] =
565         {
566                 /*! Okay, ulaw is used by all telephony equipment, so start with it */
567                 AST_FORMAT_ULAW,
568                 /*! Unless of course, you're a silly European, so then prefer ALAW */
569                 AST_FORMAT_ALAW,
570                 /*! Okay, well, signed linear is easy to translate into other stuff */
571                 AST_FORMAT_SLINEAR,
572                 /*! G.726 is standard ADPCM, in RFC3551 packing order */
573                 AST_FORMAT_G726,
574                 /*! G.726 is standard ADPCM, in AAL2 packing order */
575                 AST_FORMAT_G726_AAL2,
576                 /*! ADPCM has great sound quality and is still pretty easy to translate */
577                 AST_FORMAT_ADPCM,
578                 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
579                     translate and sounds pretty good */
580                 AST_FORMAT_GSM,
581                 /*! iLBC is not too bad */
582                 AST_FORMAT_ILBC,
583                 /*! Speex is free, but computationally more expensive than GSM */
584                 AST_FORMAT_SPEEX,
585                 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
586                     to use it */
587                 AST_FORMAT_LPC10,
588                 /*! G.729a is faster than 723 and slightly less expensive */
589                 AST_FORMAT_G729A,
590                 /*! Down to G.723.1 which is proprietary but at least designed for voice */
591                 AST_FORMAT_G723_1,
592         };
593
594         /* Strip out video */
595         fmts &= AST_FORMAT_AUDIO_MASK;
596         
597         /* Find the first preferred codec in the format given */
598         for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
599                 if (fmts & prefs[x])
600                         return prefs[x];
601         ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
602         return 0;
603 }
604
605 static const struct ast_channel_tech null_tech = {
606         .type = "NULL",
607         .description = "Null channel (should not see this)",
608 };
609
610 /*! \brief Create a new channel structure */
611 struct ast_channel *ast_channel_alloc(int needqueue, int state, const char *cid_num, const char *cid_name, const char *name_fmt, ...)
612 {
613         struct ast_channel *tmp;
614         int x;
615         int flags;
616         struct varshead *headp;
617         va_list ap1, ap2;
618
619         /* If shutting down, don't allocate any new channels */
620         if (shutting_down) {
621                 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
622                 return NULL;
623         }
624
625         if (!(tmp = ast_calloc(1, sizeof(*tmp))))
626                 return NULL;
627
628         if (!(tmp->sched = sched_context_create())) {
629                 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
630                 free(tmp);
631                 return NULL;
632         }
633         
634         ast_string_field_init(tmp, 128);
635
636         /* Don't bother initializing the last two FD here, because they
637            will *always* be set just a few lines down (AST_TIMING_FD,
638            AST_ALERT_FD). */
639         for (x = 0; x < AST_MAX_FDS - 2; x++)
640                 tmp->fds[x] = -1;
641
642 #ifdef HAVE_ZAPTEL
643         tmp->timingfd = open("/dev/zap/timer", O_RDWR);
644         if (tmp->timingfd > -1) {
645                 /* Check if timing interface supports new
646                    ping/pong scheme */
647                 flags = 1;
648                 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
649                         needqueue = 0;
650         }
651 #else
652         tmp->timingfd = -1;                                     
653 #endif                                  
654
655         if (needqueue) {
656                 if (pipe(tmp->alertpipe)) {
657                         ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
658                         ast_string_field_free_pools(tmp);
659                         free(tmp);
660                         return NULL;
661                 } else {
662                         flags = fcntl(tmp->alertpipe[0], F_GETFL);
663                         fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
664                         flags = fcntl(tmp->alertpipe[1], F_GETFL);
665                         fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
666                 }
667         } else  /* Make sure we've got it done right if they don't */
668                 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
669
670         /* Always watch the alertpipe */
671         tmp->fds[AST_ALERT_FD] = tmp->alertpipe[0];
672         /* And timing pipe */
673         tmp->fds[AST_TIMING_FD] = tmp->timingfd;
674         ast_string_field_set(tmp, name, "**Unknown**");
675
676         /* Initial state */
677         tmp->_state = state;
678
679         tmp->streamid = -1;
680         
681         tmp->fin = global_fin;
682         tmp->fout = global_fout;
683
684         if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
685                 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL), 
686                                        ast_atomic_fetchadd_int(&uniqueint, 1));
687         } else {
688                 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME, 
689                                        (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
690         }
691
692         if (!ast_strlen_zero(name_fmt)) {
693                 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
694                  * And they all use slightly different formats for their name string.
695                  * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
696                  * This means, that the stringfields must have a routine that takes the va_lists directly, and 
697                  * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
698                  * This new function was written so this can be accomplished.
699                  */
700                 va_start(ap1, name_fmt);
701                 va_start(ap2, name_fmt);
702                 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
703                 va_end(ap1);
704                 va_end(ap2);
705
706                 /* and now, since the channel structure is built, and has its name, let's call the
707                  * manager event generator with this Newchannel event. This is the proper and correct
708                  * place to make this call, but you sure do have to pass a lot of data into this func
709                  * to do it here!
710                  */
711                 manager_event(EVENT_FLAG_CALL, "Newchannel",
712                               "Channel: %s\r\n"
713                               "State: %s\r\n"
714                               "CallerIDNum: %s\r\n"
715                               "CallerIDName: %s\r\n"
716                               "Uniqueid: %s\r\n",
717                               tmp->name, ast_state2str(state),
718                               S_OR(cid_num, "<unknown>"),
719                               S_OR(cid_name, "<unknown>"),
720                               tmp->uniqueid);
721         }
722         
723         headp = &tmp->varshead;
724         AST_LIST_HEAD_INIT_NOLOCK(headp);
725         
726         ast_mutex_init(&tmp->lock);
727         
728         AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
729         
730         strcpy(tmp->context, "default");
731         strcpy(tmp->exten, "s");
732         tmp->priority = 1;
733         
734         ast_string_field_set(tmp, language, defaultlanguage);
735         tmp->amaflags = ast_default_amaflags;
736         ast_string_field_set(tmp, accountcode, ast_default_accountcode);
737
738         tmp->tech = &null_tech;
739
740         AST_LIST_LOCK(&channels);
741         AST_LIST_INSERT_HEAD(&channels, tmp, chan_list);
742         AST_LIST_UNLOCK(&channels);
743
744         return tmp;
745 }
746
747 /*! \brief Queue an outgoing media frame */
748 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
749 {
750         struct ast_frame *f;
751         struct ast_frame *cur;
752         int blah = 1;
753         int qlen = 0;
754
755         /* Build us a copy and free the original one */
756         if (!(f = ast_frdup(fin))) {
757                 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
758                 return -1;
759         }
760         ast_channel_lock(chan);
761
762         /* See if the last frame on the queue is a hangup, if so don't queue anything */
763         if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
764                 ast_frfree(f);
765                 ast_channel_unlock(chan);
766                 return 0;
767         }
768
769         /* Count how many frames exist on the queue */
770         AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
771                 qlen++;
772         }
773
774         /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
775         if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen  > 128)) {
776                 if (fin->frametype != AST_FRAME_VOICE) {
777                         ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
778                         CRASH;
779                 } else {
780                         if (option_debug)
781                                 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
782                         ast_frfree(f);
783                         ast_channel_unlock(chan);
784                         return 0;
785                 }
786         }
787         AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
788         if (chan->alertpipe[1] > -1) {
789                 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
790                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
791                                 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
792 #ifdef HAVE_ZAPTEL
793         } else if (chan->timingfd > -1) {
794                 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
795 #endif                          
796         } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
797                 pthread_kill(chan->blocker, SIGURG);
798         }
799         ast_channel_unlock(chan);
800         return 0;
801 }
802
803 /*! \brief Queue a hangup frame for channel */
804 int ast_queue_hangup(struct ast_channel *chan)
805 {
806         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
807         /* Yeah, let's not change a lock-critical value without locking */
808         if (!ast_channel_trylock(chan)) {
809                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
810                 ast_channel_unlock(chan);
811         }
812         return ast_queue_frame(chan, &f);
813 }
814
815 /*! \brief Queue a control frame */
816 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
817 {
818         struct ast_frame f = { AST_FRAME_CONTROL, };
819
820         f.subclass = control;
821
822         return ast_queue_frame(chan, &f);
823 }
824
825 /*! \brief Queue a control frame with payload */
826 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
827                            const void *data, size_t datalen)
828 {
829         struct ast_frame f = { AST_FRAME_CONTROL, };
830
831         f.subclass = control;
832         f.data = (void *) data;
833         f.datalen = datalen;
834
835         return ast_queue_frame(chan, &f);
836 }
837
838 /*! \brief Set defer DTMF flag on channel */
839 int ast_channel_defer_dtmf(struct ast_channel *chan)
840 {
841         int pre = 0;
842
843         if (chan) {
844                 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
845                 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
846         }
847         return pre;
848 }
849
850 /*! \brief Unset defer DTMF flag on channel */
851 void ast_channel_undefer_dtmf(struct ast_channel *chan)
852 {
853         if (chan)
854                 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
855 }
856
857 /*!
858  * \brief Helper function to find channels.
859  *
860  * It supports these modes:
861  *
862  * prev != NULL : get channel next in list after prev
863  * name != NULL : get channel with matching name
864  * name != NULL && namelen != 0 : get channel whose name starts with prefix
865  * exten != NULL : get channel whose exten or macroexten matches
866  * context != NULL && exten != NULL : get channel whose context or macrocontext
867  *
868  * It returns with the channel's lock held. If getting the individual lock fails,
869  * unlock and retry quickly up to 10 times, then give up.
870  *
871  * \note XXX Note that this code has cost O(N) because of the need to verify
872  * that the object is still on the global list.
873  *
874  * \note XXX also note that accessing fields (e.g. c->name in ast_log())
875  * can only be done with the lock held or someone could delete the
876  * object while we work on it. This causes some ugliness in the code.
877  * Note that removing the first ast_log() may be harmful, as it would
878  * shorten the retry period and possibly cause failures.
879  * We should definitely go for a better scheme that is deadlock-free.
880  */
881 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
882                                                const char *name, const int namelen,
883                                                const char *context, const char *exten)
884 {
885         const char *msg = prev ? "deadlock" : "initial deadlock";
886         int retries;
887         struct ast_channel *c;
888
889         for (retries = 0; retries < 10; retries++) {
890                 int done;
891                 AST_LIST_LOCK(&channels);
892                 AST_LIST_TRAVERSE(&channels, c, chan_list) {
893                         if (prev) {     /* look for next item */
894                                 if (c != prev)  /* not this one */
895                                         continue;
896                                 /* found, prepare to return c->next */
897                                 c = AST_LIST_NEXT(c, chan_list);
898                         }
899                         if (name) { /* want match by name */
900                                 if ((!namelen && strcasecmp(c->name, name)) ||
901                                     (namelen && strncasecmp(c->name, name, namelen)))
902                                         continue;       /* name match failed */
903                         } else if (exten) {
904                                 if (context && strcasecmp(c->context, context) &&
905                                     strcasecmp(c->macrocontext, context))
906                                         continue;       /* context match failed */
907                                 if (strcasecmp(c->exten, exten) &&
908                                     strcasecmp(c->macroexten, exten))
909                                         continue;       /* exten match failed */
910                         }
911                         /* if we get here, c points to the desired record */
912                         break;
913                 }
914                 /* exit if chan not found or mutex acquired successfully */
915                 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
916                 done = c == NULL || ast_channel_trylock(c) == 0;
917                 if (!done) {
918                         if (option_debug)
919                                 ast_log(LOG_DEBUG, "Avoiding %s for channel '%p'\n", msg, c);
920                 }
921                 AST_LIST_UNLOCK(&channels);
922                 if (done)
923                         return c;
924                 usleep(1);      /* give other threads a chance before retrying */
925         }
926         /*
927          * c is surely not null, but we don't have the lock so cannot
928          * access c->name
929          */
930         if (option_debug)
931                 ast_log(LOG_DEBUG, "Failure, could not lock '%p' after %d retries!\n",
932                         c, retries);
933
934         return NULL;
935 }
936
937 /*! \brief Browse channels in use */
938 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
939 {
940         return channel_find_locked(prev, NULL, 0, NULL, NULL);
941 }
942
943 /*! \brief Get channel by name and lock it */
944 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
945 {
946         return channel_find_locked(NULL, name, 0, NULL, NULL);
947 }
948
949 /*! \brief Get channel by name prefix and lock it */
950 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
951 {
952         return channel_find_locked(NULL, name, namelen, NULL, NULL);
953 }
954
955 /*! \brief Get next channel by name prefix and lock it */
956 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
957                                                            const int namelen)
958 {
959         return channel_find_locked(chan, name, namelen, NULL, NULL);
960 }
961
962 /*! \brief Get channel by exten (and optionally context) and lock it */
963 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
964 {
965         return channel_find_locked(NULL, NULL, 0, context, exten);
966 }
967
968 /*! \brief Get next channel by exten (and optionally context) and lock it */
969 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
970                                                      const char *context)
971 {
972         return channel_find_locked(chan, NULL, 0, context, exten);
973 }
974
975 /*! \brief Wait, look for hangups and condition arg */
976 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
977 {
978         struct ast_frame *f;
979
980         while (ms > 0) {
981                 if (cond && ((*cond)(data) == 0))
982                         return 0;
983                 ms = ast_waitfor(chan, ms);
984                 if (ms < 0)
985                         return -1;
986                 if (ms > 0) {
987                         f = ast_read(chan);
988                         if (!f)
989                                 return -1;
990                         ast_frfree(f);
991                 }
992         }
993         return 0;
994 }
995
996 /*! \brief Wait, look for hangups */
997 int ast_safe_sleep(struct ast_channel *chan, int ms)
998 {
999         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1000 }
1001
1002 static void free_cid(struct ast_callerid *cid)
1003 {
1004         if (cid->cid_dnid)
1005                 free(cid->cid_dnid);
1006         if (cid->cid_num)
1007                 free(cid->cid_num);     
1008         if (cid->cid_name)
1009                 free(cid->cid_name);    
1010         if (cid->cid_ani)
1011                 free(cid->cid_ani);
1012         if (cid->cid_rdnis)
1013                 free(cid->cid_rdnis);
1014         cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1015 }
1016
1017 /*! \brief Free a channel structure */
1018 void ast_channel_free(struct ast_channel *chan)
1019 {
1020         int fd;
1021         struct ast_var_t *vardata;
1022         struct ast_frame *f;
1023         struct varshead *headp;
1024         struct ast_datastore *datastore = NULL;
1025         char name[AST_CHANNEL_NAME];
1026         
1027         headp=&chan->varshead;
1028         
1029         AST_LIST_LOCK(&channels);
1030         AST_LIST_REMOVE(&channels, chan, chan_list);
1031         /* Lock and unlock the channel just to be sure nobody
1032            has it locked still */
1033         ast_channel_lock(chan);
1034         ast_channel_unlock(chan);
1035         if (chan->tech_pvt) {
1036                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1037                 free(chan->tech_pvt);
1038         }
1039
1040         if (chan->sched)
1041                 sched_context_destroy(chan->sched);
1042
1043         ast_copy_string(name, chan->name, sizeof(name));
1044
1045         /* Stop monitoring */
1046         if (chan->monitor)
1047                 chan->monitor->stop( chan, 0 );
1048
1049         /* If there is native format music-on-hold state, free it */
1050         if (chan->music_state)
1051                 ast_moh_cleanup(chan);
1052
1053         /* if someone is whispering on the channel, stop them */
1054         if (chan->whisper)
1055                 ast_channel_whisper_stop(chan);
1056
1057         /* Free translators */
1058         if (chan->readtrans)
1059                 ast_translator_free_path(chan->readtrans);
1060         if (chan->writetrans)
1061                 ast_translator_free_path(chan->writetrans);
1062         if (chan->pbx)
1063                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1064         free_cid(&chan->cid);
1065         ast_mutex_destroy(&chan->lock);
1066         /* Close pipes if appropriate */
1067         if ((fd = chan->alertpipe[0]) > -1)
1068                 close(fd);
1069         if ((fd = chan->alertpipe[1]) > -1)
1070                 close(fd);
1071         if ((fd = chan->timingfd) > -1)
1072                 close(fd);
1073         while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1074                 ast_frfree(f);
1075         
1076         /* Get rid of each of the data stores on the channel */
1077         while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1078                 /* Free the data store */
1079                 ast_channel_datastore_free(datastore);
1080         AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1081
1082         /* loop over the variables list, freeing all data and deleting list items */
1083         /* no need to lock the list, as the channel is already locked */
1084         
1085         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1086                 ast_var_delete(vardata);
1087
1088         /* Destroy the jitterbuffer */
1089         ast_jb_destroy(chan);
1090
1091         ast_string_field_free_pools(chan);
1092         free(chan);
1093         AST_LIST_UNLOCK(&channels);
1094
1095         ast_device_state_changed_literal(name);
1096 }
1097
1098 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
1099 {
1100         struct ast_datastore *datastore = NULL;
1101
1102         /* Make sure we at least have type so we can identify this */
1103         if (info == NULL) {
1104                 return NULL;
1105         }
1106
1107         /* Allocate memory for datastore and clear it */
1108         datastore = ast_calloc(1, sizeof(*datastore));
1109         if (datastore == NULL) {
1110                 return NULL;
1111         }
1112
1113         datastore->info = info;
1114
1115         datastore->uid = ast_strdup(uid);
1116
1117         return datastore;
1118 }
1119
1120 int ast_channel_datastore_free(struct ast_datastore *datastore)
1121 {
1122         int res = 0;
1123
1124         /* Using the destroy function (if present) destroy the data */
1125         if (datastore->info->destroy != NULL && datastore->data != NULL) {
1126                 datastore->info->destroy(datastore->data);
1127                 datastore->data = NULL;
1128         }
1129
1130         /* Free allocated UID memory */
1131         if (datastore->uid != NULL) {
1132                 free(datastore->uid);
1133                 datastore->uid = NULL;
1134         }
1135
1136         /* Finally free memory used by ourselves */
1137         free(datastore);
1138
1139         return res;
1140 }
1141
1142 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1143 {
1144         int res = 0;
1145
1146         AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1147
1148         return res;
1149 }
1150
1151 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1152 {
1153         struct ast_datastore *datastore2 = NULL;
1154         int res = -1;
1155
1156         /* Find our position and remove ourselves */
1157         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1158                 if (datastore2 == datastore) {
1159                         AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1160                         res = 0;
1161                         break;
1162                 }
1163         }
1164         AST_LIST_TRAVERSE_SAFE_END
1165
1166         return res;
1167 }
1168
1169 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
1170 {
1171         struct ast_datastore *datastore = NULL;
1172         
1173         if (info == NULL)
1174                 return NULL;
1175
1176         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1177                 if (datastore->info == info) {
1178                         if (uid != NULL && datastore->uid != NULL) {
1179                                 if (!strcasecmp(uid, datastore->uid)) {
1180                                         /* Matched by type AND uid */
1181                                         break;
1182                                 }
1183                         } else {
1184                                 /* Matched by type at least */
1185                                 break;
1186                         }
1187                 }
1188         }
1189         AST_LIST_TRAVERSE_SAFE_END
1190
1191         return datastore;
1192 }
1193
1194 int ast_channel_spy_add(struct ast_channel *chan, struct ast_channel_spy *spy)
1195 {
1196         /* Link the owner channel to the spy */
1197         spy->chan = chan;
1198
1199         if (!ast_test_flag(spy, CHANSPY_FORMAT_AUDIO)) {
1200                 ast_log(LOG_WARNING, "Could not add channel spy '%s' to channel '%s', only audio format spies are supported.\n",
1201                         spy->type, chan->name);
1202                 return -1;
1203         }
1204
1205         if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST) && (spy->read_queue.format != AST_FORMAT_SLINEAR)) {
1206                 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1207                         ast_getformatname(spy->read_queue.format));
1208                 return -1;
1209         }
1210
1211         if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST) && (spy->write_queue.format != AST_FORMAT_SLINEAR)) {
1212                 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1213                         ast_getformatname(spy->write_queue.format));
1214                 return -1;
1215         }
1216
1217         if (ast_test_flag(spy, CHANSPY_MIXAUDIO) &&
1218             ((spy->read_queue.format != AST_FORMAT_SLINEAR) ||
1219              (spy->write_queue.format != AST_FORMAT_SLINEAR))) {
1220                 ast_log(LOG_WARNING, "Cannot provide audio mixing on '%s'-'%s' format spies\n",
1221                         ast_getformatname(spy->read_queue.format), ast_getformatname(spy->write_queue.format));
1222                 return -1;
1223         }
1224
1225         if (!chan->spies) {
1226                 if (!(chan->spies = ast_calloc(1, sizeof(*chan->spies)))) {
1227                         return -1;
1228                 }
1229
1230                 AST_LIST_HEAD_INIT_NOLOCK(&chan->spies->list);
1231                 AST_LIST_INSERT_HEAD(&chan->spies->list, spy, list);
1232         } else {
1233                 AST_LIST_INSERT_TAIL(&chan->spies->list, spy, list);
1234         }
1235
1236         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1237                 ast_cond_init(&spy->trigger, NULL);
1238                 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1239                 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1240         }
1241
1242         if (option_debug)
1243                 ast_log(LOG_DEBUG, "Spy %s added to channel %s\n",
1244                         spy->type, chan->name);
1245
1246         return 0;
1247 }
1248
1249 /* Clean up a channel's spy information */
1250 static void spy_cleanup(struct ast_channel *chan)
1251 {
1252         if (!AST_LIST_EMPTY(&chan->spies->list))
1253                 return;
1254         if (chan->spies->read_translator.path)
1255                 ast_translator_free_path(chan->spies->read_translator.path);
1256         if (chan->spies->write_translator.path)
1257                 ast_translator_free_path(chan->spies->write_translator.path);
1258         free(chan->spies);
1259         chan->spies = NULL;
1260         return;
1261 }
1262
1263 /* Detach a spy from it's channel */
1264 static void spy_detach(struct ast_channel_spy *spy, struct ast_channel *chan)
1265 {
1266         ast_mutex_lock(&spy->lock);
1267
1268         /* We only need to poke them if they aren't already done */
1269         if (spy->status != CHANSPY_DONE) {
1270                 /* Indicate to the spy to stop */
1271                 spy->status = CHANSPY_STOP;
1272                 spy->chan = NULL;
1273                 /* Poke the spy if needed */
1274                 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1275                         ast_cond_signal(&spy->trigger);
1276         }
1277
1278         /* Print it out while we still have a lock so the structure can't go away (if signalled above) */
1279         if (option_debug)
1280                 ast_log(LOG_DEBUG, "Spy %s removed from channel %s\n", spy->type, chan->name);
1281
1282         ast_mutex_unlock(&spy->lock);
1283
1284         return;
1285 }
1286
1287 void ast_channel_spy_stop_by_type(struct ast_channel *chan, const char *type)
1288 {
1289         struct ast_channel_spy *spy = NULL;
1290         
1291         if (!chan->spies)
1292                 return;
1293
1294         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1295                 ast_mutex_lock(&spy->lock);
1296                 if ((spy->type == type) && (spy->status == CHANSPY_RUNNING)) {
1297                         ast_mutex_unlock(&spy->lock);
1298                         AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1299                         spy_detach(spy, chan);
1300                 } else
1301                         ast_mutex_unlock(&spy->lock);
1302         }
1303         AST_LIST_TRAVERSE_SAFE_END
1304         spy_cleanup(chan);
1305 }
1306
1307 void ast_channel_spy_trigger_wait(struct ast_channel_spy *spy)
1308 {
1309         struct timeval tv;
1310         struct timespec ts;
1311
1312         tv = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
1313         ts.tv_sec = tv.tv_sec;
1314         ts.tv_nsec = tv.tv_usec * 1000;
1315
1316         ast_cond_timedwait(&spy->trigger, &spy->lock, &ts);
1317 }
1318
1319 void ast_channel_spy_remove(struct ast_channel *chan, struct ast_channel_spy *spy)
1320 {
1321         if (!chan->spies)
1322                 return;
1323
1324         AST_LIST_REMOVE(&chan->spies->list, spy, list);
1325         spy_detach(spy, chan);
1326         spy_cleanup(chan);
1327 }
1328
1329 void ast_channel_spy_free(struct ast_channel_spy *spy)
1330 {
1331         struct ast_frame *f = NULL;
1332
1333         if (spy->status == CHANSPY_DONE)
1334                 return;
1335
1336         /* Switch status to done in case we get called twice */
1337         spy->status = CHANSPY_DONE;
1338
1339         /* Drop any frames in the queue */
1340         while ((f = AST_LIST_REMOVE_HEAD(&spy->write_queue.list, frame_list)))
1341                 ast_frfree(f);
1342         while ((f = AST_LIST_REMOVE_HEAD(&spy->read_queue.list, frame_list)))
1343                 ast_frfree(f);
1344
1345         /* Destroy the condition if in use */
1346         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1347                 ast_cond_destroy(&spy->trigger);
1348
1349         /* Destroy our mutex since it is no longer in use */
1350         ast_mutex_destroy(&spy->lock);
1351
1352         return;
1353 }
1354
1355 static void detach_spies(struct ast_channel *chan)
1356 {
1357         struct ast_channel_spy *spy = NULL;
1358
1359         if (!chan->spies)
1360                 return;
1361
1362         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1363                 AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1364                 spy_detach(spy, chan);
1365         }
1366         AST_LIST_TRAVERSE_SAFE_END
1367
1368         spy_cleanup(chan);
1369 }
1370
1371 /*! \brief Softly hangup a channel, don't lock */
1372 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1373 {
1374         if (option_debug)
1375                 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
1376         /* Inform channel driver that we need to be hung up, if it cares */
1377         chan->_softhangup |= cause;
1378         ast_queue_frame(chan, &ast_null_frame);
1379         /* Interrupt any poll call or such */
1380         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1381                 pthread_kill(chan->blocker, SIGURG);
1382         return 0;
1383 }
1384
1385 /*! \brief Softly hangup a channel, lock */
1386 int ast_softhangup(struct ast_channel *chan, int cause)
1387 {
1388         int res;
1389         ast_channel_lock(chan);
1390         res = ast_softhangup_nolock(chan, cause);
1391         ast_channel_unlock(chan);
1392         return res;
1393 }
1394
1395 enum spy_direction {
1396         SPY_READ,
1397         SPY_WRITE,
1398 };
1399
1400 #define SPY_QUEUE_SAMPLE_LIMIT 4000                     /* half of one second */
1401
1402 static void queue_frame_to_spies(struct ast_channel *chan, struct ast_frame *f, enum spy_direction dir)
1403 {
1404         struct ast_frame *translated_frame = NULL;
1405         struct ast_channel_spy *spy;
1406         struct channel_spy_trans *trans;
1407
1408         trans = (dir == SPY_READ) ? &chan->spies->read_translator : &chan->spies->write_translator;
1409
1410         AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1411                 struct ast_channel_spy_queue *queue;
1412                 struct ast_frame *duped_fr;
1413
1414                 ast_mutex_lock(&spy->lock);
1415
1416                 queue = (dir == SPY_READ) ? &spy->read_queue : &spy->write_queue;
1417
1418                 if ((queue->format == AST_FORMAT_SLINEAR) && (f->subclass != AST_FORMAT_SLINEAR)) {
1419                         if (!translated_frame) {
1420                                 if (trans->path && (trans->last_format != f->subclass)) {
1421                                         ast_translator_free_path(trans->path);
1422                                         trans->path = NULL;
1423                                 }
1424                                 if (!trans->path) {
1425                                         if (option_debug)
1426                                                 ast_log(LOG_DEBUG, "Building translator from %s to SLINEAR for spies on channel %s\n",
1427                                                         ast_getformatname(f->subclass), chan->name);
1428                                         if ((trans->path = ast_translator_build_path(AST_FORMAT_SLINEAR, f->subclass)) == NULL) {
1429                                                 ast_log(LOG_WARNING, "Cannot build a path from %s to %s\n",
1430                                                         ast_getformatname(f->subclass), ast_getformatname(AST_FORMAT_SLINEAR));
1431                                                 ast_mutex_unlock(&spy->lock);
1432                                                 continue;
1433                                         } else {
1434                                                 trans->last_format = f->subclass;
1435                                         }
1436                                 }
1437                                 if (!(translated_frame = ast_translate(trans->path, f, 0))) {
1438                                         ast_log(LOG_ERROR, "Translation to %s failed, dropping frame for spies\n",
1439                                                 ast_getformatname(AST_FORMAT_SLINEAR));
1440                                         ast_mutex_unlock(&spy->lock);
1441                                         break;
1442                                 }
1443                         }
1444                         duped_fr = ast_frdup(translated_frame);
1445                 } else if (f->subclass != queue->format) {
1446                         ast_log(LOG_WARNING, "Spy '%s' on channel '%s' wants format '%s', but frame is '%s', dropping\n",
1447                                 spy->type, chan->name,
1448                                 ast_getformatname(queue->format), ast_getformatname(f->subclass));
1449                         ast_mutex_unlock(&spy->lock);
1450                         continue;
1451                 } else
1452                         duped_fr = ast_frdup(f);
1453
1454                 AST_LIST_INSERT_TAIL(&queue->list, duped_fr, frame_list);
1455
1456                 queue->samples += f->samples;
1457
1458                 if (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1459                         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1460                                 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1461                                 case CHANSPY_TRIGGER_READ:
1462                                         if (dir == SPY_WRITE) {
1463                                                 ast_set_flag(spy, CHANSPY_TRIGGER_WRITE);
1464                                                 ast_clear_flag(spy, CHANSPY_TRIGGER_READ);
1465                                                 if (option_debug)
1466                                                         ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to write-trigger mode\n",
1467                                                                 spy->type, chan->name);
1468                                         }
1469                                         break;
1470                                 case CHANSPY_TRIGGER_WRITE:
1471                                         if (dir == SPY_READ) {
1472                                                 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1473                                                 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1474                                                 if (option_debug)
1475                                                         ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to read-trigger mode\n",
1476                                                                 spy->type, chan->name);
1477                                         }
1478                                         break;
1479                                 }
1480                                 if (option_debug)
1481                                         ast_log(LOG_DEBUG, "Triggering queue flush for spy '%s' on '%s'\n",
1482                                                 spy->type, chan->name);
1483                                 ast_set_flag(spy, CHANSPY_TRIGGER_FLUSH);
1484                                 ast_cond_signal(&spy->trigger);
1485                         } else {
1486                                 if (option_debug)
1487                                         ast_log(LOG_DEBUG, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1488                                                 spy->type, chan->name, (dir == SPY_READ) ? "read" : "write");
1489                                 while (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1490                                         struct ast_frame *drop = AST_LIST_REMOVE_HEAD(&queue->list, frame_list);
1491                                         queue->samples -= drop->samples;
1492                                         ast_frfree(drop);
1493                                 }
1494                         }
1495                 } else {
1496                         switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1497                         case CHANSPY_TRIGGER_READ:
1498                                 if (dir == SPY_READ)
1499                                         ast_cond_signal(&spy->trigger);
1500                                 break;
1501                         case CHANSPY_TRIGGER_WRITE:
1502                                 if (dir == SPY_WRITE)
1503                                         ast_cond_signal(&spy->trigger);
1504                                 break;
1505                         }
1506                 }
1507
1508                 ast_mutex_unlock(&spy->lock);
1509         }
1510
1511         if (translated_frame)
1512                 ast_frfree(translated_frame);
1513 }
1514
1515 static void free_translation(struct ast_channel *clone)
1516 {
1517         if (clone->writetrans)
1518                 ast_translator_free_path(clone->writetrans);
1519         if (clone->readtrans)
1520                 ast_translator_free_path(clone->readtrans);
1521         clone->writetrans = NULL;
1522         clone->readtrans = NULL;
1523         clone->rawwriteformat = clone->nativeformats;
1524         clone->rawreadformat = clone->nativeformats;
1525 }
1526
1527 /*! \brief Hangup a channel */
1528 int ast_hangup(struct ast_channel *chan)
1529 {
1530         int res = 0;
1531
1532         /* Don't actually hang up a channel that will masquerade as someone else, or
1533            if someone is going to masquerade as us */
1534         ast_channel_lock(chan);
1535
1536         detach_spies(chan);             /* get rid of spies */
1537
1538         if (chan->masq) {
1539                 if (ast_do_masquerade(chan))
1540                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1541         }
1542
1543         if (chan->masq) {
1544                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1545                 ast_channel_unlock(chan);
1546                 return 0;
1547         }
1548         /* If this channel is one which will be masqueraded into something,
1549            mark it as a zombie already, so we know to free it later */
1550         if (chan->masqr) {
1551                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1552                 ast_channel_unlock(chan);
1553                 return 0;
1554         }
1555         free_translation(chan);
1556         /* Close audio stream */
1557         if (chan->stream) {
1558                 ast_closestream(chan->stream);
1559                 chan->stream = NULL;
1560         }
1561         /* Close video stream */
1562         if (chan->vstream) {
1563                 ast_closestream(chan->vstream);
1564                 chan->vstream = NULL;
1565         }
1566         if (chan->sched) {
1567                 sched_context_destroy(chan->sched);
1568                 chan->sched = NULL;
1569         }
1570         
1571         if (chan->generatordata)        /* Clear any tone stuff remaining */
1572                 if (chan->generator && chan->generator->release)
1573                         chan->generator->release(chan, chan->generatordata);
1574         chan->generatordata = NULL;
1575         chan->generator = NULL;
1576         if (chan->cdr) {                /* End the CDR if it hasn't already */
1577                 ast_cdr_end(chan->cdr);
1578                 ast_cdr_detach(chan->cdr);      /* Post and Free the CDR */
1579                 chan->cdr = NULL;
1580         }
1581         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1582                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1583                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
1584                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1585                 CRASH;
1586         }
1587         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1588                 if (option_debug)
1589                         ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1590                 if (chan->tech->hangup)
1591                         res = chan->tech->hangup(chan);
1592         } else {
1593                 if (option_debug)
1594                         ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1595         }
1596                         
1597         ast_channel_unlock(chan);
1598         manager_event(EVENT_FLAG_CALL, "Hangup",
1599                         "Channel: %s\r\n"
1600                         "Uniqueid: %s\r\n"
1601                         "Cause: %d\r\n"
1602                         "Cause-txt: %s\r\n",
1603                         chan->name,
1604                         chan->uniqueid,
1605                         chan->hangupcause,
1606                         ast_cause2str(chan->hangupcause)
1607                         );
1608         ast_channel_free(chan);
1609         return res;
1610 }
1611
1612 int __ast_answer(struct ast_channel *chan, unsigned int delay)
1613 {
1614         int res = 0;
1615
1616         ast_channel_lock(chan);
1617
1618         /* You can't answer an outbound call */
1619         if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1620                 ast_channel_unlock(chan);
1621                 return 0;
1622         }
1623
1624         /* Stop if we're a zombie or need a soft hangup */
1625         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1626                 ast_channel_unlock(chan);
1627                 return -1;
1628         }
1629
1630         switch (chan->_state) {
1631         case AST_STATE_RINGING:
1632         case AST_STATE_RING:
1633                 if (chan->tech->answer)
1634                         res = chan->tech->answer(chan);
1635                 ast_setstate(chan, AST_STATE_UP);
1636                 ast_cdr_answer(chan->cdr);
1637                 ast_channel_unlock(chan);
1638                 if (delay)
1639                         ast_safe_sleep(chan, delay);
1640                 return res;
1641                 break;
1642         case AST_STATE_UP:
1643                 ast_cdr_answer(chan->cdr);
1644                 break;
1645         default:
1646                 break;
1647         }
1648
1649         ast_channel_unlock(chan);
1650
1651         return res;
1652 }
1653
1654 int ast_answer(struct ast_channel *chan)
1655 {
1656         return __ast_answer(chan, 500);
1657 }
1658
1659 void ast_deactivate_generator(struct ast_channel *chan)
1660 {
1661         ast_channel_lock(chan);
1662         if (chan->generatordata) {
1663                 if (chan->generator && chan->generator->release)
1664                         chan->generator->release(chan, chan->generatordata);
1665                 chan->generatordata = NULL;
1666                 chan->generator = NULL;
1667                 chan->fds[AST_GENERATOR_FD] = -1;
1668                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1669                 ast_settimeout(chan, 0, NULL, NULL);
1670         }
1671         ast_channel_unlock(chan);
1672 }
1673
1674 static int generator_force(void *data)
1675 {
1676         /* Called if generator doesn't have data */
1677         void *tmp;
1678         int res;
1679         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1680         struct ast_channel *chan = data;
1681         tmp = chan->generatordata;
1682         chan->generatordata = NULL;
1683         generate = chan->generator->generate;
1684         res = generate(chan, tmp, 0, 160);
1685         chan->generatordata = tmp;
1686         if (res) {
1687                 if (option_debug)
1688                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1689                 ast_deactivate_generator(chan);
1690         }
1691         return 0;
1692 }
1693
1694 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1695 {
1696         int res = 0;
1697
1698         ast_channel_lock(chan);
1699
1700         if (chan->generatordata) {
1701                 if (chan->generator && chan->generator->release)
1702                         chan->generator->release(chan, chan->generatordata);
1703                 chan->generatordata = NULL;
1704         }
1705
1706         ast_prod(chan);
1707         if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1708                 res = -1;
1709         }
1710         
1711         if (!res) {
1712                 ast_settimeout(chan, 160, generator_force, chan);
1713                 chan->generator = gen;
1714         }
1715
1716         ast_channel_unlock(chan);
1717
1718         return res;
1719 }
1720
1721 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1722 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1723 {
1724         int winner = -1;
1725         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1726         return winner;
1727 }
1728
1729 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1730 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1731         int *exception, int *outfd, int *ms)
1732 {
1733         struct timeval start = { 0 , 0 };
1734         struct pollfd *pfds;
1735         int res;
1736         long rms;
1737         int x, y, max;
1738         int sz;
1739         time_t now = 0;
1740         long whentohangup = 0, diff;
1741         struct ast_channel *winner = NULL;
1742         struct fdmap {
1743                 int chan;
1744                 int fdno;
1745         } *fdmap;
1746
1747         sz = n * AST_MAX_FDS + nfds;
1748         pfds = alloca(sizeof(*pfds) * sz);
1749         fdmap = alloca(sizeof(*fdmap) * sz);
1750
1751         if (outfd)
1752                 *outfd = -99999;
1753         if (exception)
1754                 *exception = 0;
1755         
1756         /* Perform any pending masquerades */
1757         for (x=0; x < n; x++) {
1758                 ast_channel_lock(c[x]);
1759                 if (c[x]->masq) {
1760                         if (ast_do_masquerade(c[x])) {
1761                                 ast_log(LOG_WARNING, "Masquerade failed\n");
1762                                 *ms = -1;
1763                                 ast_channel_unlock(c[x]);
1764                                 return NULL;
1765                         }
1766                 }
1767                 if (c[x]->whentohangup) {
1768                         if (!whentohangup)
1769                                 time(&now);
1770                         diff = c[x]->whentohangup - now;
1771                         if (diff < 1) {
1772                                 /* Should already be hungup */
1773                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1774                                 ast_channel_unlock(c[x]);
1775                                 return c[x];
1776                         }
1777                         if (!whentohangup || (diff < whentohangup))
1778                                 whentohangup = diff;
1779                 }
1780                 ast_channel_unlock(c[x]);
1781         }
1782         /* Wait full interval */
1783         rms = *ms;
1784         if (whentohangup) {
1785                 rms = whentohangup * 1000;              /* timeout in milliseconds */
1786                 if (*ms >= 0 && *ms < rms)              /* original *ms still smaller */
1787                         rms =  *ms;
1788         }
1789         /*
1790          * Build the pollfd array, putting the channels' fds first,
1791          * followed by individual fds. Order is important because
1792          * individual fd's must have priority over channel fds.
1793          */
1794         max = 0;
1795         for (x=0; x<n; x++) {
1796                 for (y=0; y<AST_MAX_FDS; y++) {
1797                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
1798                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
1799                         max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1800                 }
1801                 CHECK_BLOCKING(c[x]);
1802         }
1803         /* Add the individual fds */
1804         for (x=0; x<nfds; x++) {
1805                 fdmap[max].chan = -1;
1806                 max += ast_add_fd(&pfds[max], fds[x]);
1807         }
1808
1809         if (*ms > 0)
1810                 start = ast_tvnow();
1811         
1812         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1813                 do {
1814                         int kbrms = rms;
1815                         if (kbrms > 600000)
1816                                 kbrms = 600000;
1817                         res = poll(pfds, max, kbrms);
1818                         if (!res)
1819                                 rms -= kbrms;
1820                 } while (!res && (rms > 0));
1821         } else {
1822                 res = poll(pfds, max, rms);
1823         }
1824         for (x=0; x<n; x++)
1825                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1826         if (res < 0) { /* Simulate a timeout if we were interrupted */
1827                 if (errno != EINTR)
1828                         *ms = -1;
1829                 return NULL;
1830         }
1831         if (whentohangup) {   /* if we have a timeout, check who expired */
1832                 time(&now);
1833                 for (x=0; x<n; x++) {
1834                         if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1835                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1836                                 if (winner == NULL)
1837                                         winner = c[x];
1838                         }
1839                 }
1840         }
1841         if (res == 0) { /* no fd ready, reset timeout and done */
1842                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
1843                 return winner;
1844         }
1845         /*
1846          * Then check if any channel or fd has a pending event.
1847          * Remember to check channels first and fds last, as they
1848          * must have priority on setting 'winner'
1849          */
1850         for (x = 0; x < max; x++) {
1851                 res = pfds[x].revents;
1852                 if (res == 0)
1853                         continue;
1854                 if (fdmap[x].chan >= 0) {       /* this is a channel */
1855                         winner = c[fdmap[x].chan];      /* override previous winners */
1856                         if (res & POLLPRI)
1857                                 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1858                         else
1859                                 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1860                         winner->fdno = fdmap[x].fdno;
1861                 } else {                        /* this is an fd */
1862                         if (outfd)
1863                                 *outfd = pfds[x].fd;
1864                         if (exception)
1865                                 *exception = (res & POLLPRI) ? -1 : 0;
1866                         winner = NULL;
1867                 }
1868         }
1869         if (*ms > 0) {
1870                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1871                 if (*ms < 0)
1872                         *ms = 0;
1873         }
1874         return winner;
1875 }
1876
1877 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1878 {
1879         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1880 }
1881
1882 int ast_waitfor(struct ast_channel *c, int ms)
1883 {
1884         int oldms = ms; /* -1 if no timeout */
1885
1886         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1887         if ((ms < 0) && (oldms < 0))
1888                 ms = 0;
1889         return ms;
1890 }
1891
1892 /* XXX never to be called with ms = -1 */
1893 int ast_waitfordigit(struct ast_channel *c, int ms)
1894 {
1895         return ast_waitfordigit_full(c, ms, -1, -1);
1896 }
1897
1898 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1899 {
1900         int res = -1;
1901 #ifdef HAVE_ZAPTEL
1902         if (c->timingfd > -1) {
1903                 if (!func) {
1904                         samples = 0;
1905                         data = 0;
1906                 }
1907                 if (option_debug)
1908                         ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1909                 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1910                 c->timingfunc = func;
1911                 c->timingdata = data;
1912         }
1913 #endif  
1914         return res;
1915 }
1916
1917 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1918 {
1919
1920         /* Stop if we're a zombie or need a soft hangup */
1921         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1922                 return -1;
1923         /* Wait for a digit, no more than ms milliseconds total. */
1924         while (ms) {
1925                 struct ast_channel *rchan;
1926                 int outfd;
1927
1928                 errno = 0;
1929                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1930                 if (!rchan && outfd < 0 && ms) {
1931                         if (errno == 0 || errno == EINTR)
1932                                 continue;
1933                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1934                         return -1;
1935                 } else if (outfd > -1) {
1936                         /* The FD we were watching has something waiting */
1937                         return 1;
1938                 } else if (rchan) {
1939                         int res;
1940                         struct ast_frame *f = ast_read(c);
1941                         if (!f)
1942                                 return -1;
1943
1944                         switch (f->frametype) {
1945                         case AST_FRAME_DTMF:
1946                                 res = f->subclass;
1947                                 ast_frfree(f);
1948                                 return res;
1949                         case AST_FRAME_CONTROL:
1950                                 switch (f->subclass) {
1951                                 case AST_CONTROL_HANGUP:
1952                                         ast_frfree(f);
1953                                         return -1;
1954                                 case AST_CONTROL_RINGING:
1955                                 case AST_CONTROL_ANSWER:
1956                                         /* Unimportant */
1957                                         break;
1958                                 default:
1959                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1960                                         break;
1961                                 }
1962                                 break;
1963                         case AST_FRAME_VOICE:
1964                                 /* Write audio if appropriate */
1965                                 if (audiofd > -1)
1966                                         write(audiofd, f->data, f->datalen);
1967                         default:
1968                                 /* Ignore */
1969                                 break;
1970                         }
1971                         ast_frfree(f);
1972                 }
1973         }
1974         return 0; /* Time is up */
1975 }
1976
1977 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
1978 {
1979         struct ast_frame *f = NULL;     /* the return value */
1980         int blah;
1981         int prestate;
1982
1983         /* this function is very long so make sure there is only one return
1984          * point at the end (there is only one exception to this).
1985          */
1986         ast_channel_lock(chan);
1987         if (chan->masq) {
1988                 if (ast_do_masquerade(chan))
1989                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1990                 else
1991                         f =  &ast_null_frame;
1992                 goto done;
1993         }
1994
1995         /* Stop if we're a zombie or need a soft hangup */
1996         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1997                 if (chan->generator)
1998                         ast_deactivate_generator(chan);
1999                 goto done;
2000         }
2001         prestate = chan->_state;
2002
2003         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) && 
2004             !ast_strlen_zero(chan->dtmfq)) {
2005                 /* We have DTMF that has been deferred.  Return it now */
2006                 chan->dtmff.subclass = chan->dtmfq[0];
2007                 /* Drop first digit from the buffer */
2008                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2009                 f = &chan->dtmff;
2010                 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY))
2011                         chan->dtmff.frametype = AST_FRAME_DTMF_END;
2012                 else {
2013                         chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2014                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2015                         chan->emulate_dtmf_digit = f->subclass;
2016                         chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2017                         chan->dtmf_begin_tv = ast_tvnow();
2018                 }
2019                 goto done;
2020         }
2021         
2022         /* Read and ignore anything on the alertpipe, but read only
2023            one sizeof(blah) per frame that we send from it */
2024         if (chan->alertpipe[0] > -1)
2025                 read(chan->alertpipe[0], &blah, sizeof(blah));
2026
2027 #ifdef HAVE_ZAPTEL
2028         if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2029                 int res;
2030
2031                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2032                 blah = -1;
2033                 /* IF we can't get event, assume it's an expired as-per the old interface */
2034                 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
2035                 if (res)
2036                         blah = ZT_EVENT_TIMER_EXPIRED;
2037
2038                 if (blah == ZT_EVENT_TIMER_PING) {
2039                         if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2040                                 /* Acknowledge PONG unless we need it again */
2041                                 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
2042                                         ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2043                                 }
2044                         }
2045                 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
2046                         ioctl(chan->timingfd, ZT_TIMERACK, &blah);
2047                         if (chan->timingfunc) {
2048                                 /* save a copy of func/data before unlocking the channel */
2049                                 int (*func)(void *) = chan->timingfunc;
2050                                 void *data = chan->timingdata;
2051                                 ast_channel_unlock(chan);
2052                                 func(data);
2053                         } else {
2054                                 blah = 0;
2055                                 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
2056                                 chan->timingdata = NULL;
2057                                 ast_channel_unlock(chan);
2058                         }
2059                         /* cannot 'goto done' because the channel is already unlocked */
2060                         return &ast_null_frame;
2061                 } else
2062                         ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2063         } else
2064 #endif
2065         if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2066                 /* if the AST_GENERATOR_FD is set, call the generator with args
2067                  * set to -1 so it can do whatever it needs to.
2068                  */
2069                 void *tmp = chan->generatordata;
2070                 chan->generatordata = NULL;     /* reset to let ast_write get through */
2071                 chan->generator->generate(chan, tmp, -1, -1);
2072                 chan->generatordata = tmp;
2073                 f = &ast_null_frame;
2074                 goto done;
2075         }
2076
2077         /* Check for pending read queue */
2078         if (!AST_LIST_EMPTY(&chan->readq)) {
2079                 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2080                 /* Interpret hangup and return NULL */
2081                 /* XXX why not the same for frames from the channel ? */
2082                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2083                         ast_frfree(f);
2084                         f = NULL;
2085                 }
2086         } else {
2087                 chan->blocker = pthread_self();
2088                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2089                         if (chan->tech->exception)
2090                                 f = chan->tech->exception(chan);
2091                         else {
2092                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2093                                 f = &ast_null_frame;
2094                         }
2095                         /* Clear the exception flag */
2096                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2097                 } else if (chan->tech->read)
2098                         f = chan->tech->read(chan);
2099                 else
2100                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2101         }
2102
2103         if (f) {
2104                 /* if the channel driver returned more than one frame, stuff the excess
2105                    into the readq for the next ast_read call (note that we can safely assume
2106                    that the readq is empty, because otherwise we would not have called into
2107                    the channel driver and f would be only a single frame)
2108                 */
2109                 if (AST_LIST_NEXT(f, frame_list)) {
2110                         AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2111                         AST_LIST_NEXT(f, frame_list) = NULL;
2112                 }
2113
2114                 switch (f->frametype) {
2115                 case AST_FRAME_CONTROL:
2116                         if (f->subclass == AST_CONTROL_ANSWER) {
2117                                 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2118                                         if (option_debug)
2119                                                 ast_log(LOG_DEBUG, "Ignoring answer on an inbound call!\n");
2120                                         ast_frfree(f);
2121                                         f = &ast_null_frame;
2122                                 } else if (prestate == AST_STATE_UP) {
2123                                         if (option_debug)
2124                                                 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
2125                                         ast_frfree(f);
2126                                         f = &ast_null_frame;
2127                                 } else {
2128                                         /* Answer the CDR */
2129                                         ast_setstate(chan, AST_STATE_UP);
2130                                         ast_cdr_answer(chan->cdr);
2131                                 }
2132                         }
2133                         break;
2134                 case AST_FRAME_DTMF_END:
2135                         ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2136                         /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2137                          * However, only let emulation be forced if the other end cares about BEGIN frames */
2138                         if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2139                                 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2140                                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
2141                                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2142                                 else
2143                                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2144                                 ast_frfree(f);
2145                                 f = &ast_null_frame;
2146                         } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2147                                 f->frametype = AST_FRAME_DTMF_BEGIN;
2148                                 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2149                                 chan->emulate_dtmf_digit = f->subclass;
2150                                 chan->dtmf_begin_tv = ast_tvnow();
2151                                 if (f->len)
2152                                         chan->emulate_dtmf_duration = f->len;
2153                                 else
2154                                         chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2155                         } else {
2156                                 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2157                                 if (!f->len)
2158                                         f->len = ast_tvdiff_ms(ast_tvnow(), chan->dtmf_begin_tv);
2159                         }
2160                         break;
2161                 case AST_FRAME_DTMF_BEGIN:
2162                         ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2163                         if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2164                                 ast_frfree(f);
2165                                 f = &ast_null_frame;
2166                         } else {
2167                                 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2168                                 chan->dtmf_begin_tv = ast_tvnow();
2169                         }
2170                         break;
2171                 case AST_FRAME_VOICE:
2172                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the samples
2173                          * first get to zero, because we want to make sure we pass at least one
2174                          * voice frame through before starting the next digit, to ensure a gap
2175                          * between DTMF digits. */
2176                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2177                                 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2178                                 chan->emulate_dtmf_digit = 0;
2179                         }
2180
2181                         if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2182                                 ast_frfree(f);
2183                                 f = &ast_null_frame;
2184                         } else if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2185                                 if ((f->samples / 8) >= chan->emulate_dtmf_duration) { /* XXX 8kHz */
2186                                         chan->emulate_dtmf_duration = 0;
2187                                         f->frametype = AST_FRAME_DTMF_END;
2188                                         f->subclass = chan->emulate_dtmf_digit;
2189                                         f->len = ast_tvdiff_ms(ast_tvnow(), chan->dtmf_begin_tv);
2190                                 } else {
2191                                         chan->emulate_dtmf_duration -= f->samples / 8; /* XXX 8kHz */
2192                                         ast_frfree(f);
2193                                         f = &ast_null_frame;
2194                                 }
2195                         } else if (!(f->subclass & chan->nativeformats)) {
2196                                 /* This frame can't be from the current native formats -- drop it on the
2197                                    floor */
2198                                 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2199                                         chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2200                                 ast_frfree(f);
2201                                 f = &ast_null_frame;
2202                         } else {
2203                                 if (chan->spies)
2204                                         queue_frame_to_spies(chan, f, SPY_READ);
2205                                 
2206                                 if (chan->monitor && chan->monitor->read_stream ) {
2207                                         /* XXX what does this do ? */
2208 #ifndef MONITOR_CONSTANT_DELAY
2209                                         int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2210                                         if (jump >= 0) {
2211                                                 jump = chan->outsmpl - chan->insmpl;
2212                                                 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2213                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2214                                                 chan->insmpl += jump + f->samples;
2215                                         } else
2216                                                 chan->insmpl+= f->samples;
2217 #else
2218                                         int jump = chan->outsmpl - chan->insmpl;
2219                                         if (jump - MONITOR_DELAY >= 0) {
2220                                                 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2221                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2222                                                 chan->insmpl += jump;
2223                                         } else
2224                                                 chan->insmpl += f->samples;
2225 #endif
2226                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2227                                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2228                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2229                                         }
2230                                 }
2231
2232                                 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2233                                         f = &ast_null_frame;
2234
2235                                 /* Run generator sitting on the line if timing device not available
2236                                 * and synchronous generation of outgoing frames is necessary       */
2237                                 if (chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
2238                                         void *tmp = chan->generatordata;
2239                                         int res;
2240
2241                                         if (chan->timingfunc) {
2242                                                 if (option_debug > 1)
2243                                                         ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2244                                                 ast_settimeout(chan, 0, NULL, NULL);
2245                                         }
2246
2247                                         chan->generatordata = NULL;     /* reset, to let writes go through */
2248                                         res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2249                                         chan->generatordata = tmp;
2250                                         if (res) {
2251                                                 if (option_debug > 1)
2252                                                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2253                                                 ast_deactivate_generator(chan);
2254                                         }
2255
2256                                 } else if (f->frametype == AST_FRAME_CNG) {
2257                                         if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2258                                                 if (option_debug > 1)
2259                                                         ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2260                                                 ast_settimeout(chan, 160, generator_force, chan);
2261                                         }
2262                                 }
2263                         }
2264                 default:
2265                         /* Just pass it on! */
2266                         break;
2267                 }
2268         } else {
2269                 /* Make sure we always return NULL in the future */
2270                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2271                 if (chan->generator)
2272                         ast_deactivate_generator(chan);
2273                 /* End the CDR if appropriate */
2274                 if (chan->cdr)
2275                         ast_cdr_end(chan->cdr);
2276         }
2277
2278         /* High bit prints debugging */
2279         if (chan->fin & DEBUGCHAN_FLAG)
2280                 ast_frame_dump(chan->name, f, "<<");
2281         chan->fin = FRAMECOUNT_INC(chan->fin);
2282
2283 done:
2284         ast_channel_unlock(chan);
2285         return f;
2286 }
2287
2288 int ast_internal_timing_enabled(struct ast_channel *chan)
2289 {
2290         int ret = ast_opt_internal_timing && chan->timingfd > -1;
2291         if (option_debug > 4)
2292                 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);
2293         return ret;
2294 }
2295
2296 struct ast_frame *ast_read(struct ast_channel *chan)
2297 {
2298         return __ast_read(chan, 0);
2299 }
2300
2301 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2302 {
2303         return __ast_read(chan, 1);
2304 }
2305
2306 int ast_indicate(struct ast_channel *chan, int condition)
2307 {
2308         return ast_indicate_data(chan, condition, NULL, 0);
2309 }
2310
2311 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2312 {
2313         int res = -1;
2314
2315         ast_channel_lock(chan);
2316         /* Stop if we're a zombie or need a soft hangup */
2317         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2318                 ast_channel_unlock(chan);
2319                 return -1;
2320         }
2321         if (chan->tech->indicate)
2322                 res = chan->tech->indicate(chan, condition, data, datalen);
2323         ast_channel_unlock(chan);
2324         if (!chan->tech->indicate || res) {
2325                 /*
2326                  * Device does not support (that) indication, lets fake
2327                  * it by doing our own tone generation. (PM2002)
2328                  */
2329                 if (condition < 0)
2330                         ast_playtones_stop(chan);
2331                 else {
2332                         const struct ind_tone_zone_sound *ts = NULL;
2333                         switch (condition) {
2334                         case AST_CONTROL_RINGING:
2335                                 ts = ast_get_indication_tone(chan->zone, "ring");
2336                                 break;
2337                         case AST_CONTROL_BUSY:
2338                                 ts = ast_get_indication_tone(chan->zone, "busy");
2339                                 break;
2340                         case AST_CONTROL_CONGESTION:
2341                                 ts = ast_get_indication_tone(chan->zone, "congestion");
2342                                 break;
2343                         }
2344                         if (ts && ts->data[0]) {
2345                                 if (option_debug)
2346                                         ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2347                                 ast_playtones_start(chan,0,ts->data, 1);
2348                                 res = 0;
2349                         } else if (condition == AST_CONTROL_PROGRESS) {
2350                                 /* ast_playtones_stop(chan); */
2351                         } else if (condition == AST_CONTROL_PROCEEDING) {
2352                                 /* Do nothing, really */
2353                         } else if (condition == AST_CONTROL_HOLD) {
2354                                 /* Do nothing.... */
2355                         } else if (condition == AST_CONTROL_UNHOLD) {
2356                                 /* Do nothing.... */
2357                         } else if (condition == AST_CONTROL_VIDUPDATE) {
2358                                 /* Do nothing.... */
2359                         } else {
2360                                 /* not handled */
2361                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2362                                 res = -1;
2363                         }
2364                 }
2365         }
2366         return res;
2367 }
2368
2369 int ast_recvchar(struct ast_channel *chan, int timeout)
2370 {
2371         int c;
2372         char *buf = ast_recvtext(chan, timeout);
2373         if (buf == NULL)
2374                 return -1;      /* error or timeout */
2375         c = *(unsigned char *)buf;
2376         free(buf);
2377         return c;
2378 }
2379
2380 char *ast_recvtext(struct ast_channel *chan, int timeout)
2381 {
2382         int res, done = 0;
2383         char *buf = NULL;
2384         
2385         while (!done) {
2386                 struct ast_frame *f;
2387                 if (ast_check_hangup(chan))
2388                         break;
2389                 res = ast_waitfor(chan, timeout);
2390                 if (res <= 0) /* timeout or error */
2391                         break;
2392                 timeout = res;  /* update timeout */
2393                 f = ast_read(chan);
2394                 if (f == NULL)
2395                         break; /* no frame */
2396                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2397                         done = 1;       /* force a break */
2398                 else if (f->frametype == AST_FRAME_TEXT) {              /* what we want */
2399                         buf = ast_strndup((char *) f->data, f->datalen);        /* dup and break */
2400                         done = 1;
2401                 }
2402                 ast_frfree(f);
2403         }
2404         return buf;
2405 }
2406
2407 int ast_sendtext(struct ast_channel *chan, const char *text)
2408 {
2409         int res = 0;
2410         /* Stop if we're a zombie or need a soft hangup */
2411         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2412                 return -1;
2413         CHECK_BLOCKING(chan);
2414         if (chan->tech->send_text)
2415                 res = chan->tech->send_text(chan, text);
2416         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2417         return res;
2418 }
2419
2420 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2421 {
2422         int res = -1;
2423
2424         if (chan->tech->send_digit_begin)
2425                 res = chan->tech->send_digit_begin(chan, digit);
2426
2427         if (res) {
2428                 /*
2429                  * Device does not support DTMF tones, lets fake
2430                  * it by doing our own generation. (PM2002)
2431                  */
2432                 static const char* dtmf_tones[] = {
2433                         "!941+1336/100,!0/100", /* 0 */
2434                         "!697+1209/100,!0/100", /* 1 */
2435                         "!697+1336/100,!0/100", /* 2 */
2436                         "!697+1477/100,!0/100", /* 3 */
2437                         "!770+1209/100,!0/100", /* 4 */
2438                         "!770+1336/100,!0/100", /* 5 */
2439                         "!770+1477/100,!0/100", /* 6 */
2440                         "!852+1209/100,!0/100", /* 7 */
2441                         "!852+1336/100,!0/100", /* 8 */
2442                         "!852+1477/100,!0/100", /* 9 */
2443                         "!697+1633/100,!0/100", /* A */
2444                         "!770+1633/100,!0/100", /* B */
2445                         "!852+1633/100,!0/100", /* C */
2446                         "!941+1633/100,!0/100", /* D */
2447                         "!941+1209/100,!0/100", /* * */
2448                         "!941+1477/100,!0/100" };       /* # */
2449                 if (digit >= '0' && digit <='9')
2450                         ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2451                 else if (digit >= 'A' && digit <= 'D')
2452                         ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2453                 else if (digit == '*')
2454                         ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2455                 else if (digit == '#')
2456                         ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2457                 else {
2458                         /* not handled */
2459                         if (option_debug)
2460                                 ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2461                 }
2462         }
2463
2464         return 0;
2465 }
2466
2467 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2468 {
2469         int res = -1;
2470
2471         if (chan->tech->send_digit_end)
2472                 res = chan->tech->send_digit_end(chan, digit, duration);
2473
2474         if (res && chan->generator)
2475                 ast_playtones_stop(chan);
2476         
2477         return 0;
2478 }
2479
2480 int ast_senddigit(struct ast_channel *chan, char digit)
2481 {
2482         if (!ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2483                 ast_senddigit_begin(chan, digit);
2484                 ast_safe_sleep(chan, 100); /* XXX 100ms ... probably should be configurable */
2485         }
2486         
2487         return ast_senddigit_end(chan, digit, 100);
2488 }
2489
2490 int ast_prod(struct ast_channel *chan)
2491 {
2492         struct ast_frame a = { AST_FRAME_VOICE };
2493         char nothing[128];
2494
2495         /* Send an empty audio frame to get things moving */
2496         if (chan->_state != AST_STATE_UP) {
2497                 if (option_debug)
2498                         ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
2499                 a.subclass = chan->rawwriteformat;
2500                 a.data = nothing + AST_FRIENDLY_OFFSET;
2501                 a.src = "ast_prod";
2502                 if (ast_write(chan, &a))
2503                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2504         }
2505         return 0;
2506 }
2507
2508 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2509 {
2510         int res;
2511         if (!chan->tech->write_video)
2512                 return 0;
2513         res = ast_write(chan, fr);
2514         if (!res)
2515                 res = 1;
2516         return res;
2517 }
2518
2519 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2520 {
2521         int res = -1;
2522         struct ast_frame *f = NULL;
2523
2524         /* Stop if we're a zombie or need a soft hangup */
2525         ast_channel_lock(chan);
2526         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2527                 goto done;
2528
2529         /* Handle any pending masquerades */
2530         if (chan->masq && ast_do_masquerade(chan)) {
2531                 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2532                 goto done;
2533         }
2534         if (chan->masqr) {
2535                 res = 0;        /* XXX explain, why 0 ? */
2536                 goto done;
2537         }
2538         if (chan->generatordata) {
2539                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2540                         ast_deactivate_generator(chan);
2541                 else {
2542                         res = 0;        /* XXX explain, why 0 ? */
2543                         goto done;
2544                 }
2545         }
2546         /* High bit prints debugging */
2547         if (chan->fout & DEBUGCHAN_FLAG)
2548                 ast_frame_dump(chan->name, fr, ">>");
2549         CHECK_BLOCKING(chan);
2550         switch (fr->frametype) {
2551         case AST_FRAME_CONTROL:
2552                 res = (chan->tech->indicate == NULL) ? 0 :
2553                         chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2554                 break;
2555         case AST_FRAME_DTMF_BEGIN:
2556                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2557                 ast_channel_unlock(chan);
2558                 res = ast_senddigit_begin(chan, fr->subclass);
2559                 ast_channel_lock(chan);
2560                 CHECK_BLOCKING(chan);
2561                 break;
2562         case AST_FRAME_DTMF_END:
2563                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2564                 ast_channel_unlock(chan);
2565                 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2566                 ast_channel_lock(chan);
2567                 CHECK_BLOCKING(chan);
2568                 break;
2569         case AST_FRAME_TEXT:
2570                 res = (chan->tech->send_text == NULL) ? 0 :
2571                         chan->tech->send_text(chan, (char *) fr->data);
2572                 break;
2573         case AST_FRAME_HTML:
2574                 res = (chan->tech->send_html == NULL) ? 0 :
2575                         chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2576                 break;
2577         case AST_FRAME_VIDEO:
2578                 /* XXX Handle translation of video codecs one day XXX */
2579                 res = (chan->tech->write_video == NULL) ? 0 :
2580                         chan->tech->write_video(chan, fr);
2581                 break;
2582         case AST_FRAME_MODEM:
2583                 res = (chan->tech->write == NULL) ? 0 :
2584                         chan->tech->write(chan, fr);
2585                 break;
2586         case AST_FRAME_VOICE:
2587                 if (chan->tech->write == NULL)
2588                         break;  /*! \todo XXX should return 0 maybe ? */
2589
2590                 /* If someone is whispering on this channel then we must ensure that we are always getting signed linear frames */
2591                 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2592                         if (fr->subclass == AST_FORMAT_SLINEAR)
2593                                 f = fr;
2594                         else {
2595                                 ast_mutex_lock(&chan->whisper->lock);
2596                                 if (chan->writeformat != AST_FORMAT_SLINEAR) {
2597                                         /* Rebuild the translation path and set our write format back to signed linear */
2598                                         chan->whisper->original_format = chan->writeformat;
2599                                         ast_set_write_format(chan, AST_FORMAT_SLINEAR);
2600                                         if (chan->whisper->path)
2601                                                 ast_translator_free_path(chan->whisper->path);
2602                                         chan->whisper->path = ast_translator_build_path(AST_FORMAT_SLINEAR, chan->whisper->original_format);
2603                                 }
2604                                 /* Translate frame using the above translation path */
2605                                 f = (chan->whisper->path) ? ast_translate(chan->whisper->path, fr, 0) : fr;
2606                                 ast_mutex_unlock(&chan->whisper->lock);
2607                         }
2608                 } else {
2609                         /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2610                         if (fr->subclass == chan->rawwriteformat)
2611                                 f = fr;
2612                         else
2613                                 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2614                 }
2615
2616                 /* If we have no frame of audio, then we have to bail out */
2617                 if (f == NULL) {
2618                         res = 0;
2619                         break;
2620                 }
2621
2622                 /* If spies are on the channel then queue the frame out to them */
2623                 if (chan->spies)
2624                         queue_frame_to_spies(chan, f, SPY_WRITE);
2625
2626                 /* If Monitor is running on this channel, then we have to write frames out there too */
2627                 if (chan->monitor && chan->monitor->write_stream) {
2628                         /* XXX must explain this code */
2629 #ifndef MONITOR_CONSTANT_DELAY
2630                         int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2631                         if (jump >= 0) {
2632                                 jump = chan->insmpl - chan->outsmpl;
2633                                 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
2634                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2635                                 chan->outsmpl += jump + f->samples;
2636                         } else
2637                                 chan->outsmpl += f->samples;
2638 #else
2639                         int jump = chan->insmpl - chan->outsmpl;
2640                         if (jump - MONITOR_DELAY >= 0) {
2641                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2642                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2643                                 chan->outsmpl += jump;
2644                         } else
2645                                 chan->outsmpl += f->samples;
2646 #endif
2647                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2648                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2649                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2650                         }
2651                 }
2652
2653                 /* Finally the good part! Write this out to the channel */
2654                 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2655                         /* frame is assumed to be in SLINEAR, since that is
2656                            required for whisper mode */
2657                         ast_frame_adjust_volume(f, -2);
2658                         if (ast_slinfactory_available(&chan->whisper->sf) >= f->samples) {
2659                                 short buf[f->samples];
2660                                 struct ast_frame whisper = {
2661                                         .frametype = AST_FRAME_VOICE,
2662                                         .subclass = AST_FORMAT_SLINEAR,
2663                                         .data = buf,
2664                                         .datalen = sizeof(buf),
2665                                         .samples = f->samples,
2666                                 };
2667                                 
2668                                 ast_mutex_lock(&chan->whisper->lock);
2669                                 if (ast_slinfactory_read(&chan->whisper->sf, buf, f->samples))
2670                                         ast_frame_slinear_sum(f, &whisper);
2671                                 ast_mutex_unlock(&chan->whisper->lock);
2672                         }
2673                         /* and now put it through the regular translator */
2674                         f = (chan->writetrans) ? ast_translate(chan->writetrans, f, 0) : f;
2675                 }
2676                 if (f)
2677                         res = chan->tech->write(chan, f);
2678                 else
2679                         res = 0;
2680                 break;
2681         case AST_FRAME_NULL:
2682         case AST_FRAME_IAX:
2683                 /* Ignore these */
2684                 res = 0;
2685                 break;
2686         default:
2687                 /* At this point, fr is the incoming frame and f is NULL.  Channels do
2688                  * not expect to get NULL as a frame pointer and will segfault.  Hence,
2689                  * we output the original frame passed in. */
2690                 res = chan->tech->write(chan, fr);
2691                 break;
2692         }
2693
2694         if (f && f != fr)
2695                 ast_frfree(f);
2696         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2697         /* Consider a write failure to force a soft hangup */
2698         if (res < 0)
2699                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2700         else {
2701                 chan->fout = FRAMECOUNT_INC(chan->fout);
2702         }
2703 done:
2704         ast_channel_unlock(chan);
2705         return res;
2706 }
2707
2708 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2709                       struct ast_trans_pvt **trans, const int direction)
2710 {
2711         int native;
2712         int res;
2713         
2714         /* Make sure we only consider audio */
2715         fmt &= AST_FORMAT_AUDIO_MASK;
2716         
2717         native = chan->nativeformats;
2718         /* Find a translation path from the native format to one of the desired formats */
2719         if (!direction)
2720                 /* reading */
2721                 res = ast_translator_best_choice(&fmt, &native);
2722         else
2723                 /* writing */
2724                 res = ast_translator_best_choice(&native, &fmt);
2725
2726         if (res < 0) {
2727                 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2728                         ast_getformatname(native), ast_getformatname(fmt));
2729                 return -1;
2730         }
2731         
2732         /* Now we have a good choice for both. */
2733         ast_channel_lock(chan);
2734
2735         if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2736                 /* the channel is already in these formats, so nothing to do */
2737                 ast_channel_unlock(chan);
2738                 return 0;
2739         }
2740
2741         *rawformat = native;
2742         /* User perspective is fmt */
2743         *format = fmt;
2744         /* Free any read translation we have right now */
2745         if (*trans)
2746                 ast_translator_free_path(*trans);
2747         /* Build a translation path from the raw format to the desired format */
2748         if (!direction)
2749                 /* reading */
2750                 *trans = ast_translator_build_path(*format, *rawformat);
2751         else
2752                 /* writing */
2753                 *trans = ast_translator_build_path(*rawformat, *format);
2754         ast_channel_unlock(chan);
2755         if (option_debug)
2756                 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2757                         direction ? "write" : "read", ast_getformatname(fmt));
2758         return 0;
2759 }
2760
2761 int ast_set_read_format(struct ast_channel *chan, int fmt)
2762 {
2763         return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2764                           &chan->readtrans, 0);
2765 }
2766
2767 int ast_set_write_format(struct ast_channel *chan, int fmt)
2768 {
2769         return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2770                           &chan->writetrans, 1);
2771 }
2772
2773 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)
2774 {
2775         int dummy_outstate;
2776         int cause = 0;
2777         struct ast_channel *chan;
2778         int res = 0;
2779         
2780         if (outstate)
2781                 *outstate = 0;
2782         else
2783                 outstate = &dummy_outstate;     /* make outstate always a valid pointer */
2784
2785         chan = ast_request(type, format, data, &cause);
2786         if (!chan) {
2787                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2788                 /* compute error and return */
2789                 if (cause == AST_CAUSE_BUSY)
2790                         *outstate = AST_CONTROL_BUSY;
2791                 else if (cause == AST_CAUSE_CONGESTION)
2792                         *outstate = AST_CONTROL_CONGESTION;
2793                 return NULL;
2794         }
2795
2796         if (oh) {
2797                 if (oh->vars)   
2798                         ast_set_variables(chan, oh->vars);
2799                 /* XXX why is this necessary, for the parent_channel perhaps ? */
2800                 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2801                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2802                 if (oh->parent_channel)
2803                         ast_channel_inherit_variables(oh->parent_channel, chan);
2804                 if (oh->account)
2805                         ast_cdr_setaccount(chan, oh->account);  
2806         }
2807         ast_set_callerid(chan, cid_num, cid_name, cid_num);
2808
2809         if (ast_call(chan, data, 0)) {  /* ast_call failed... */
2810                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2811         } else {
2812                 res = 1;        /* mark success in case chan->_state is already AST_STATE_UP */
2813                 while (timeout && chan->_state != AST_STATE_UP) {
2814                         struct ast_frame *f;
2815                         res = ast_waitfor(chan, timeout);
2816                         if (res <= 0) /* error, timeout, or done */
2817                                 break;
2818                         if (timeout > -1)
2819                                 timeout = res;
2820                         f = ast_read(chan);
2821                         if (!f) {
2822                                 *outstate = AST_CONTROL_HANGUP;
2823                                 res = 0;
2824                                 break;
2825                         }
2826                         if (f->frametype == AST_FRAME_CONTROL) {
2827                                 switch (f->subclass) {
2828                                 case AST_CONTROL_RINGING:       /* record but keep going */
2829                                         *outstate = f->subclass;
2830                                         break;
2831
2832                                 case AST_CONTROL_BUSY:
2833                                 case AST_CONTROL_CONGESTION:
2834                                 case AST_CONTROL_ANSWER:
2835                                         *outstate = f->subclass;
2836                                         timeout = 0;            /* trick to force exit from the while() */
2837                                         break;
2838
2839                                 /* Ignore these */
2840                                 case AST_CONTROL_PROGRESS:
2841                                 case AST_CONTROL_PROCEEDING:
2842                                 case AST_CONTROL_HOLD:
2843                                 case AST_CONTROL_UNHOLD:
2844                                 case AST_CONTROL_VIDUPDATE:
2845                                 case -1:                        /* Ignore -- just stopping indications */
2846                                         break;
2847
2848                                 default:
2849                                         ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2850                                 }
2851                         }
2852                         ast_frfree(f);
2853                 }
2854         }
2855
2856         /* Final fixups */
2857         if (oh) {
2858                 if (!ast_strlen_zero(oh->context))
2859                         ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2860                 if (!ast_strlen_zero(oh->exten))
2861                         ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2862                 if (oh->priority)       
2863                         chan->priority = oh->priority;
2864         }
2865         if (chan->_state == AST_STATE_UP)
2866                 *outstate = AST_CONTROL_ANSWER;
2867
2868         if (res <= 0) {
2869                 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
2870                         ast_cdr_init(chan->cdr, chan);
2871                 if (chan->cdr) {
2872                         char tmp[256];
2873                         snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
2874                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
2875                         ast_cdr_update(chan);
2876                         ast_cdr_start(chan->cdr);
2877                         ast_cdr_end(chan->cdr);
2878                         /* If the cause wasn't handled properly */
2879                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2880                                 ast_cdr_failed(chan->cdr);
2881                 }
2882                 ast_hangup(chan);
2883                 chan = NULL;
2884         }
2885         return chan;
2886 }
2887
2888 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2889 {
2890         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2891 }
2892
2893 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2894 {
2895         struct chanlist *chan;
2896         struct ast_channel *c;
2897         int capabilities;
2898         int fmt;
2899         int res;
2900         int foo;
2901         int videoformat = format & AST_FORMAT_VIDEO_MASK;
2902
2903         if (!cause)
2904                 cause = &foo;
2905         *cause = AST_CAUSE_NOTDEFINED;
2906
2907         if (AST_LIST_LOCK(&channels)) {
2908                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2909                 return NULL;
2910         }
2911
2912         AST_LIST_TRAVERSE(&backends, chan, list) {
2913                 if (strcasecmp(type, chan->tech->type))
2914                         continue;
2915
2916                 capabilities = chan->tech->capabilities;
2917                 fmt = format & AST_FORMAT_AUDIO_MASK;
2918                 res = ast_translator_best_choice(&fmt, &capabilities);
2919                 if (res < 0) {
2920                         ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2921                         AST_LIST_UNLOCK(&channels);
2922                         return NULL;
2923                 }
2924                 AST_LIST_UNLOCK(&channels);
2925                 if (!chan->tech->requester)
2926                         return NULL;
2927                 
2928                 if (!(c = chan->tech->requester(type, capabilities | videoformat, data, cause)))
2929                         return NULL;
2930                 
2931                 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
2932                 return c;
2933         }
2934
2935         ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2936         *cause = AST_CAUSE_NOSUCHDRIVER;
2937         AST_LIST_UNLOCK(&channels);
2938
2939         return NULL;
2940 }
2941
2942 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2943 {
2944         /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2945            If the remote end does not answer within the timeout, then do NOT hang up, but
2946            return anyway.  */
2947         int res = -1;
2948         /* Stop if we're a zombie or need a soft hangup */
2949         ast_channel_lock(chan);
2950         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2951                 if (chan->tech->call)
2952                         res = chan->tech->call(chan, addr, timeout);
2953                 ast_set_flag(chan, AST_FLAG_OUTGOING);
2954         }
2955         ast_channel_unlock(chan);
2956         return res;
2957 }
2958
2959 /*!
2960   \brief Transfer a call to dest, if the channel supports transfer
2961
2962   Called by:
2963     \arg app_transfer
2964     \arg the manager interface
2965 */
2966 int ast_transfer(struct ast_channel *chan, char *dest)
2967 {
2968         int res = -1;
2969
2970         /* Stop if we're a zombie or need a soft hangup */
2971         ast_channel_lock(chan);
2972         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2973                 if (chan->tech->transfer) {
2974                         res = chan->tech->transfer(chan, dest);
2975                         if (!res)
2976                                 res = 1;
2977                 } else
2978                         res = 0;
2979         }
2980         ast_channel_unlock(chan);
2981         return res;
2982 }
2983
2984 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2985 {
2986         return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
2987 }
2988
2989 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2990 {
2991         int pos = 0;    /* index in the buffer where we accumulate digits */
2992         int to = ftimeout;
2993
2994         /* Stop if we're a zombie or need a soft hangup */
2995         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2996                 return -1;
2997         if (!len)
2998                 return -1;
2999         for (;;) {
3000                 int d;
3001                 if (c->stream) {
3002                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
3003                         ast_stopstream(c);
3004                         usleep(1000);
3005                         if (!d)
3006                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3007                 } else {
3008                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3009                 }
3010                 if (d < 0)
3011                         return -1;
3012                 if (d == 0) {
3013                         s[pos]='\0';
3014                         return 1;
3015                 }
3016                 if (d == 1) {
3017                         s[pos]='\0';
3018                         return 2;
3019                 }
3020                 if (!strchr(enders, d))
3021                         s[pos++] = d;
3022                 if (strchr(enders, d) || (pos >= len)) {
3023                         s[pos]='\0';
3024                         return 0;
3025                 }
3026                 to = timeout;
3027         }
3028         /* Never reached */
3029         return 0;
3030 }
3031
3032 int ast_channel_supports_html(struct ast_channel *chan)
3033 {
3034         return (chan->tech->send_html) ? 1 : 0;
3035 }
3036
3037 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3038 {
3039         if (chan->tech->send_html)
3040                 return chan->tech->send_html(chan, subclass, data, datalen);
3041         return -1;
3042 }
3043
3044 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
3045 {
3046         return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
3047 }
3048
3049 /*! \brief Set up translation from one channel to another */
3050 static int ast_channel_make_compatible_helper(struct ast_channel *from, struct ast_channel *to)
3051 {
3052         int src;
3053         int dst;
3054
3055         /* Set up translation from the 'from' channel to the 'to' channel */
3056         src = from->nativeformats;
3057         dst = to->nativeformats;
3058         if (ast_translator_best_choice(&dst, &src) < 0) {
3059                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", from->name, src, to->name, dst);
3060                 return -1;
3061         }
3062
3063         /* if the best path is not 'pass through', then
3064            transcoding is needed; if desired, force transcode path
3065            to use SLINEAR between channels, but only if there is
3066            no direct conversion available */
3067         if ((src != dst) && ast_opt_transcode_via_slin &&
3068             (ast_translate_path_steps(dst, src) != 1))
3069                 dst = AST_FORMAT_SLINEAR;
3070         if (ast_set_read_format(from, dst) < 0) {
3071                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", from->name, dst);
3072                 return -1;
3073         }
3074         if (ast_set_write_format(to, dst) < 0) {
3075                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", to->name, dst);
3076                 return -1;
3077         }
3078         return 0;
3079 }
3080
3081 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
3082 {
3083         /* Some callers do not check return code, and we must try to set all call legs correctly */
3084         int rc = 0;