Cosmetic changes. Make main source files better conform to coding guidelines and...
[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\n", f->subclass, chan->name);
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(chan->dtmf_begin_tv, ast_tvnow());
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                                 } else {
2190                                         chan->emulate_dtmf_duration -= f->samples / 8; /* XXX 8kHz */
2191                                         ast_frfree(f);
2192                                         f = &ast_null_frame;
2193                                 }
2194                         } else if (!(f->subclass & chan->nativeformats)) {
2195                                 /* This frame can't be from the current native formats -- drop it on the
2196                                    floor */
2197                                 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2198                                         chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2199                                 ast_frfree(f);
2200                                 f = &ast_null_frame;
2201                         } else {
2202                                 if (chan->spies)
2203                                         queue_frame_to_spies(chan, f, SPY_READ);
2204                                 
2205                                 if (chan->monitor && chan->monitor->read_stream ) {
2206                                         /* XXX what does this do ? */
2207 #ifndef MONITOR_CONSTANT_DELAY
2208                                         int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2209                                         if (jump >= 0) {
2210                                                 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2211                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2212                                                 chan->insmpl += jump + 4 * f->samples;
2213                                         } else
2214                                                 chan->insmpl+= f->samples;
2215 #else
2216                                         int jump = chan->outsmpl - chan->insmpl;
2217                                         if (jump - MONITOR_DELAY >= 0) {
2218                                                 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2219                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2220                                                 chan->insmpl += jump;
2221                                         } else
2222                                                 chan->insmpl += f->samples;
2223 #endif
2224                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2225                                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2226                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2227                                         }
2228                                 }
2229
2230                                 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2231                                         f = &ast_null_frame;
2232
2233                                 /* Run generator sitting on the line if timing device not available
2234                                 * and synchronous generation of outgoing frames is necessary       */
2235                                 if (chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
2236                                         void *tmp = chan->generatordata;
2237                                         int res;
2238
2239                                         if (chan->timingfunc) {
2240                                                 if (option_debug > 1)
2241                                                         ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2242                                                 ast_settimeout(chan, 0, NULL, NULL);
2243                                         }
2244
2245                                         chan->generatordata = NULL;     /* reset, to let writes go through */
2246                                         res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2247                                         chan->generatordata = tmp;
2248                                         if (res) {
2249                                                 if (option_debug > 1)
2250                                                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2251                                                 ast_deactivate_generator(chan);
2252                                         }
2253
2254                                 } else if (f->frametype == AST_FRAME_CNG) {
2255                                         if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2256                                                 if (option_debug > 1)
2257                                                         ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2258                                                 ast_settimeout(chan, 160, generator_force, chan);
2259                                         }
2260                                 }
2261                         }
2262                 default:
2263                         /* Just pass it on! */
2264                         break;
2265                 }
2266         } else {
2267                 /* Make sure we always return NULL in the future */
2268                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2269                 if (chan->generator)
2270                         ast_deactivate_generator(chan);
2271                 /* End the CDR if appropriate */
2272                 if (chan->cdr)
2273                         ast_cdr_end(chan->cdr);
2274         }
2275
2276         /* High bit prints debugging */
2277         if (chan->fin & DEBUGCHAN_FLAG)
2278                 ast_frame_dump(chan->name, f, "<<");
2279         chan->fin = FRAMECOUNT_INC(chan->fin);
2280
2281 done:
2282         ast_channel_unlock(chan);
2283         return f;
2284 }
2285
2286 int ast_internal_timing_enabled(struct ast_channel *chan)
2287 {
2288         int ret = ast_opt_internal_timing && chan->timingfd > -1;
2289         if (option_debug > 4)
2290                 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);
2291         return ret;
2292 }
2293
2294 struct ast_frame *ast_read(struct ast_channel *chan)
2295 {
2296         return __ast_read(chan, 0);
2297 }
2298
2299 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2300 {
2301         return __ast_read(chan, 1);
2302 }
2303
2304 int ast_indicate(struct ast_channel *chan, int condition)
2305 {
2306         return ast_indicate_data(chan, condition, NULL, 0);
2307 }
2308
2309 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2310 {
2311         int res = -1;
2312
2313         ast_channel_lock(chan);
2314         /* Stop if we're a zombie or need a soft hangup */
2315         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2316                 ast_channel_unlock(chan);
2317                 return -1;
2318         }
2319         if (chan->tech->indicate)
2320                 res = chan->tech->indicate(chan, condition, data, datalen);
2321         ast_channel_unlock(chan);
2322         if (!chan->tech->indicate || res) {
2323                 /*
2324                  * Device does not support (that) indication, lets fake
2325                  * it by doing our own tone generation. (PM2002)
2326                  */
2327                 if (condition < 0)
2328                         ast_playtones_stop(chan);
2329                 else {
2330                         const struct ind_tone_zone_sound *ts = NULL;
2331                         switch (condition) {
2332                         case AST_CONTROL_RINGING:
2333                                 ts = ast_get_indication_tone(chan->zone, "ring");
2334                                 break;
2335                         case AST_CONTROL_BUSY:
2336                                 ts = ast_get_indication_tone(chan->zone, "busy");
2337                                 break;
2338                         case AST_CONTROL_CONGESTION:
2339                                 ts = ast_get_indication_tone(chan->zone, "congestion");
2340                                 break;
2341                         }
2342                         if (ts && ts->data[0]) {
2343                                 if (option_debug)
2344                                         ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2345                                 ast_playtones_start(chan,0,ts->data, 1);
2346                                 res = 0;
2347                         } else if (condition == AST_CONTROL_PROGRESS) {
2348                                 /* ast_playtones_stop(chan); */
2349                         } else if (condition == AST_CONTROL_PROCEEDING) {
2350                                 /* Do nothing, really */
2351                         } else if (condition == AST_CONTROL_HOLD) {
2352                                 /* Do nothing.... */
2353                         } else if (condition == AST_CONTROL_UNHOLD) {
2354                                 /* Do nothing.... */
2355                         } else if (condition == AST_CONTROL_VIDUPDATE) {
2356                                 /* Do nothing.... */
2357                         } else {
2358                                 /* not handled */
2359                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2360                                 res = -1;
2361                         }
2362                 }
2363         }
2364         return res;
2365 }
2366
2367 int ast_recvchar(struct ast_channel *chan, int timeout)
2368 {
2369         int c;
2370         char *buf = ast_recvtext(chan, timeout);
2371         if (buf == NULL)
2372                 return -1;      /* error or timeout */
2373         c = *(unsigned char *)buf;
2374         free(buf);
2375         return c;
2376 }
2377
2378 char *ast_recvtext(struct ast_channel *chan, int timeout)
2379 {
2380         int res, done = 0;
2381         char *buf = NULL;
2382         
2383         while (!done) {
2384                 struct ast_frame *f;
2385                 if (ast_check_hangup(chan))
2386                         break;
2387                 res = ast_waitfor(chan, timeout);
2388                 if (res <= 0) /* timeout or error */
2389                         break;
2390                 timeout = res;  /* update timeout */
2391                 f = ast_read(chan);
2392                 if (f == NULL)
2393                         break; /* no frame */
2394                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2395                         done = 1;       /* force a break */
2396                 else if (f->frametype == AST_FRAME_TEXT) {              /* what we want */
2397                         buf = ast_strndup((char *) f->data, f->datalen);        /* dup and break */
2398                         done = 1;
2399                 }
2400                 ast_frfree(f);
2401         }
2402         return buf;
2403 }
2404
2405 int ast_sendtext(struct ast_channel *chan, const char *text)
2406 {
2407         int res = 0;
2408         /* Stop if we're a zombie or need a soft hangup */
2409         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2410                 return -1;
2411         CHECK_BLOCKING(chan);
2412         if (chan->tech->send_text)
2413                 res = chan->tech->send_text(chan, text);
2414         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2415         return res;
2416 }
2417
2418 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2419 {
2420         int res = -1;
2421
2422         if (chan->tech->send_digit_begin)
2423                 res = chan->tech->send_digit_begin(chan, digit);
2424
2425         if (res) {
2426                 /*
2427                  * Device does not support DTMF tones, lets fake
2428                  * it by doing our own generation. (PM2002)
2429                  */
2430                 static const char* dtmf_tones[] = {
2431                         "!941+1336/100,!0/100", /* 0 */
2432                         "!697+1209/100,!0/100", /* 1 */
2433                         "!697+1336/100,!0/100", /* 2 */
2434                         "!697+1477/100,!0/100", /* 3 */
2435                         "!770+1209/100,!0/100", /* 4 */
2436                         "!770+1336/100,!0/100", /* 5 */
2437                         "!770+1477/100,!0/100", /* 6 */
2438                         "!852+1209/100,!0/100", /* 7 */
2439                         "!852+1336/100,!0/100", /* 8 */
2440                         "!852+1477/100,!0/100", /* 9 */
2441                         "!697+1633/100,!0/100", /* A */
2442                         "!770+1633/100,!0/100", /* B */
2443                         "!852+1633/100,!0/100", /* C */
2444                         "!941+1633/100,!0/100", /* D */
2445                         "!941+1209/100,!0/100", /* * */
2446                         "!941+1477/100,!0/100" };       /* # */
2447                 if (digit >= '0' && digit <='9')
2448                         ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2449                 else if (digit >= 'A' && digit <= 'D')
2450                         ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2451                 else if (digit == '*')
2452                         ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2453                 else if (digit == '#')
2454                         ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2455                 else {
2456                         /* not handled */
2457                         if (option_debug)
2458                                 ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2459                 }
2460         }
2461
2462         return 0;
2463 }
2464
2465 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2466 {
2467         int res = -1;
2468
2469         if (chan->tech->send_digit_end)
2470                 res = chan->tech->send_digit_end(chan, digit, duration);
2471
2472         if (res && chan->generator)
2473                 ast_playtones_stop(chan);
2474         
2475         return 0;
2476 }
2477
2478 int ast_senddigit(struct ast_channel *chan, char digit)
2479 {
2480         if (!ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2481                 ast_senddigit_begin(chan, digit);
2482                 ast_safe_sleep(chan, 100); /* XXX 100ms ... probably should be configurable */
2483         }
2484         
2485         return ast_senddigit_end(chan, digit, 100);
2486 }
2487
2488 int ast_prod(struct ast_channel *chan)
2489 {
2490         struct ast_frame a = { AST_FRAME_VOICE };
2491         char nothing[128];
2492
2493         /* Send an empty audio frame to get things moving */
2494         if (chan->_state != AST_STATE_UP) {
2495                 if (option_debug)
2496                         ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
2497                 a.subclass = chan->rawwriteformat;
2498                 a.data = nothing + AST_FRIENDLY_OFFSET;
2499                 a.src = "ast_prod";
2500                 if (ast_write(chan, &a))
2501                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2502         }
2503         return 0;
2504 }
2505
2506 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2507 {
2508         int res;
2509         if (!chan->tech->write_video)
2510                 return 0;
2511         res = ast_write(chan, fr);
2512         if (!res)
2513                 res = 1;
2514         return res;
2515 }
2516
2517 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2518 {
2519         int res = -1;
2520         struct ast_frame *f = NULL;
2521
2522         /* Stop if we're a zombie or need a soft hangup */
2523         ast_channel_lock(chan);
2524         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2525                 goto done;
2526
2527         /* Handle any pending masquerades */
2528         if (chan->masq && ast_do_masquerade(chan)) {
2529                 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2530                 goto done;
2531         }
2532         if (chan->masqr) {
2533                 res = 0;        /* XXX explain, why 0 ? */
2534                 goto done;
2535         }
2536         if (chan->generatordata) {
2537                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2538                         ast_deactivate_generator(chan);
2539                 else {
2540                         res = 0;        /* XXX explain, why 0 ? */
2541                         goto done;
2542                 }
2543         }
2544         /* High bit prints debugging */
2545         if (chan->fout & DEBUGCHAN_FLAG)
2546                 ast_frame_dump(chan->name, fr, ">>");
2547         CHECK_BLOCKING(chan);
2548         switch (fr->frametype) {
2549         case AST_FRAME_CONTROL:
2550                 res = (chan->tech->indicate == NULL) ? 0 :
2551                         chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2552                 break;
2553         case AST_FRAME_DTMF_BEGIN:
2554                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2555                 ast_channel_unlock(chan);
2556                 res = ast_senddigit_begin(chan, fr->subclass);
2557                 ast_channel_lock(chan);
2558                 CHECK_BLOCKING(chan);
2559                 break;
2560         case AST_FRAME_DTMF_END:
2561                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2562                 ast_channel_unlock(chan);
2563                 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2564                 ast_channel_lock(chan);
2565                 CHECK_BLOCKING(chan);
2566                 break;
2567         case AST_FRAME_TEXT:
2568                 res = (chan->tech->send_text == NULL) ? 0 :
2569                         chan->tech->send_text(chan, (char *) fr->data);
2570                 break;
2571         case AST_FRAME_HTML:
2572                 res = (chan->tech->send_html == NULL) ? 0 :
2573                         chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2574                 break;
2575         case AST_FRAME_VIDEO:
2576                 /* XXX Handle translation of video codecs one day XXX */
2577                 res = (chan->tech->write_video == NULL) ? 0 :
2578                         chan->tech->write_video(chan, fr);
2579                 break;
2580         case AST_FRAME_MODEM:
2581                 res = (chan->tech->write == NULL) ? 0 :
2582                         chan->tech->write(chan, fr);
2583                 break;
2584         case AST_FRAME_VOICE:
2585                 if (chan->tech->write == NULL)
2586                         break;  /*! \todo XXX should return 0 maybe ? */
2587
2588                 /* If someone is whispering on this channel then we must ensure that we are always getting signed linear frames */
2589                 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2590                         if (fr->subclass == AST_FORMAT_SLINEAR)
2591                                 f = fr;
2592                         else {
2593                                 ast_mutex_lock(&chan->whisper->lock);
2594                                 if (chan->writeformat != AST_FORMAT_SLINEAR) {
2595                                         /* Rebuild the translation path and set our write format back to signed linear */
2596                                         chan->whisper->original_format = chan->writeformat;
2597                                         ast_set_write_format(chan, AST_FORMAT_SLINEAR);
2598                                         if (chan->whisper->path)
2599                                                 ast_translator_free_path(chan->whisper->path);
2600                                         chan->whisper->path = ast_translator_build_path(AST_FORMAT_SLINEAR, chan->whisper->original_format);
2601                                 }
2602                                 /* Translate frame using the above translation path */
2603                                 f = (chan->whisper->path) ? ast_translate(chan->whisper->path, fr, 0) : fr;
2604                                 ast_mutex_unlock(&chan->whisper->lock);
2605                         }
2606                 } else {
2607                         /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2608                         if (fr->subclass == chan->rawwriteformat)
2609                                 f = fr;
2610                         else
2611                                 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2612                 }
2613
2614                 /* If we have no frame of audio, then we have to bail out */
2615                 if (f == NULL) {
2616                         res = 0;
2617                         break;
2618                 }
2619
2620                 /* If spies are on the channel then queue the frame out to them */
2621                 if (chan->spies)
2622                         queue_frame_to_spies(chan, f, SPY_WRITE);
2623
2624                 /* If Monitor is running on this channel, then we have to write frames out there too */
2625                 if (chan->monitor && chan->monitor->write_stream) {
2626                         /* XXX must explain this code */
2627 #ifndef MONITOR_CONSTANT_DELAY
2628                         int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2629                         if (jump >= 0) {
2630                                 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2631                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2632                                 chan->outsmpl += jump + 4 * f->samples;
2633                         } else
2634                                 chan->outsmpl += f->samples;
2635 #else
2636                         int jump = chan->insmpl - chan->outsmpl;
2637                         if (jump - MONITOR_DELAY >= 0) {
2638                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2639                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2640                                 chan->outsmpl += jump;
2641                         } else
2642                                 chan->outsmpl += f->samples;
2643 #endif
2644                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2645                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2646                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2647                         }
2648                 }
2649
2650                 /* Finally the good part! Write this out to the channel */
2651                 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2652                         /* frame is assumed to be in SLINEAR, since that is
2653                            required for whisper mode */
2654                         ast_frame_adjust_volume(f, -2);
2655                         if (ast_slinfactory_available(&chan->whisper->sf) >= f->samples) {
2656                                 short buf[f->samples];
2657                                 struct ast_frame whisper = {
2658                                         .frametype = AST_FRAME_VOICE,
2659                                         .subclass = AST_FORMAT_SLINEAR,
2660                                         .data = buf,
2661                                         .datalen = sizeof(buf),
2662                                         .samples = f->samples,
2663                                 };
2664                                 
2665                                 ast_mutex_lock(&chan->whisper->lock);
2666                                 if (ast_slinfactory_read(&chan->whisper->sf, buf, f->samples))
2667                                         ast_frame_slinear_sum(f, &whisper);
2668                                 ast_mutex_unlock(&chan->whisper->lock);
2669                         }
2670                         /* and now put it through the regular translator */
2671                         f = (chan->writetrans) ? ast_translate(chan->writetrans, f, 0) : f;
2672                 }
2673                 if (f)
2674                         res = chan->tech->write(chan, f);
2675                 else
2676                         res = 0;
2677                 break;
2678         case AST_FRAME_NULL:
2679         case AST_FRAME_IAX:
2680                 /* Ignore these */
2681                 res = 0;
2682                 break;
2683         default:
2684                 /* At this point, fr is the incoming frame and f is NULL.  Channels do
2685                  * not expect to get NULL as a frame pointer and will segfault.  Hence,
2686                  * we output the original frame passed in. */
2687                 res = chan->tech->write(chan, fr);
2688                 break;
2689         }
2690
2691         if (f && f != fr)
2692                 ast_frfree(f);
2693         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2694         /* Consider a write failure to force a soft hangup */
2695         if (res < 0)
2696                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2697         else {
2698                 chan->fout = FRAMECOUNT_INC(chan->fout);
2699         }
2700 done:
2701         ast_channel_unlock(chan);
2702         return res;
2703 }
2704
2705 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2706                       struct ast_trans_pvt **trans, const int direction)
2707 {
2708         int native;
2709         int res;
2710         
2711         /* Make sure we only consider audio */
2712         fmt &= AST_FORMAT_AUDIO_MASK;
2713         
2714         native = chan->nativeformats;
2715         /* Find a translation path from the native format to one of the desired formats */
2716         if (!direction)
2717                 /* reading */
2718                 res = ast_translator_best_choice(&fmt, &native);
2719         else
2720                 /* writing */
2721                 res = ast_translator_best_choice(&native, &fmt);
2722
2723         if (res < 0) {
2724                 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2725                         ast_getformatname(native), ast_getformatname(fmt));
2726                 return -1;
2727         }
2728         
2729         /* Now we have a good choice for both. */
2730         ast_channel_lock(chan);
2731
2732         if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2733                 /* the channel is already in these formats, so nothing to do */
2734                 ast_channel_unlock(chan);
2735                 return 0;
2736         }
2737
2738         *rawformat = native;
2739         /* User perspective is fmt */
2740         *format = fmt;
2741         /* Free any read translation we have right now */
2742         if (*trans)
2743                 ast_translator_free_path(*trans);
2744         /* Build a translation path from the raw format to the desired format */
2745         if (!direction)
2746                 /* reading */
2747                 *trans = ast_translator_build_path(*format, *rawformat);
2748         else
2749                 /* writing */
2750                 *trans = ast_translator_build_path(*rawformat, *format);
2751         ast_channel_unlock(chan);
2752         if (option_debug)
2753                 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2754                         direction ? "write" : "read", ast_getformatname(fmt));
2755         return 0;
2756 }
2757
2758 int ast_set_read_format(struct ast_channel *chan, int fmt)
2759 {
2760         return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2761                           &chan->readtrans, 0);
2762 }
2763
2764 int ast_set_write_format(struct ast_channel *chan, int fmt)
2765 {
2766         return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2767                           &chan->writetrans, 1);
2768 }
2769
2770 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)
2771 {
2772         int dummy_outstate;
2773         int cause = 0;
2774         struct ast_channel *chan;
2775         int res = 0;
2776         
2777         if (outstate)
2778                 *outstate = 0;
2779         else
2780                 outstate = &dummy_outstate;     /* make outstate always a valid pointer */
2781
2782         chan = ast_request(type, format, data, &cause);
2783         if (!chan) {
2784                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2785                 /* compute error and return */
2786                 if (cause == AST_CAUSE_BUSY)
2787                         *outstate = AST_CONTROL_BUSY;
2788                 else if (cause == AST_CAUSE_CONGESTION)
2789                         *outstate = AST_CONTROL_CONGESTION;
2790                 return NULL;
2791         }
2792
2793         if (oh) {
2794                 if (oh->vars)   
2795                         ast_set_variables(chan, oh->vars);
2796                 /* XXX why is this necessary, for the parent_channel perhaps ? */
2797                 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2798                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2799                 if (oh->parent_channel)
2800                         ast_channel_inherit_variables(oh->parent_channel, chan);
2801                 if (oh->account)
2802                         ast_cdr_setaccount(chan, oh->account);  
2803         }
2804         ast_set_callerid(chan, cid_num, cid_name, cid_num);
2805
2806         if (ast_call(chan, data, 0)) {  /* ast_call failed... */
2807                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2808         } else {
2809                 res = 1;        /* mark success in case chan->_state is already AST_STATE_UP */
2810                 while (timeout && chan->_state != AST_STATE_UP) {
2811                         struct ast_frame *f;
2812                         res = ast_waitfor(chan, timeout);
2813                         if (res <= 0) /* error, timeout, or done */
2814                                 break;
2815                         if (timeout > -1)
2816                                 timeout = res;
2817                         f = ast_read(chan);
2818                         if (!f) {
2819                                 *outstate = AST_CONTROL_HANGUP;
2820                                 res = 0;
2821                                 break;
2822                         }
2823                         if (f->frametype == AST_FRAME_CONTROL) {
2824                                 switch (f->subclass) {
2825                                 case AST_CONTROL_RINGING:       /* record but keep going */
2826                                         *outstate = f->subclass;
2827                                         break;
2828
2829                                 case AST_CONTROL_BUSY:
2830                                 case AST_CONTROL_CONGESTION:
2831                                 case AST_CONTROL_ANSWER:
2832                                         *outstate = f->subclass;
2833                                         timeout = 0;            /* trick to force exit from the while() */
2834                                         break;
2835
2836                                 /* Ignore these */
2837                                 case AST_CONTROL_PROGRESS:
2838                                 case AST_CONTROL_PROCEEDING:
2839                                 case AST_CONTROL_HOLD:
2840                                 case AST_CONTROL_UNHOLD:
2841                                 case AST_CONTROL_VIDUPDATE:
2842                                 case -1:                        /* Ignore -- just stopping indications */
2843                                         break;
2844
2845                                 default:
2846                                         ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2847                                 }
2848                         }
2849                         ast_frfree(f);
2850                 }
2851         }
2852
2853         /* Final fixups */
2854         if (oh) {
2855                 if (!ast_strlen_zero(oh->context))
2856                         ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2857                 if (!ast_strlen_zero(oh->exten))
2858                         ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2859                 if (oh->priority)       
2860                         chan->priority = oh->priority;
2861         }
2862         if (chan->_state == AST_STATE_UP)
2863                 *outstate = AST_CONTROL_ANSWER;
2864
2865         if (res <= 0) {
2866                 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
2867                         ast_cdr_init(chan->cdr, chan);
2868                 if (chan->cdr) {
2869                         char tmp[256];
2870                         snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
2871                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
2872                         ast_cdr_update(chan);
2873                         ast_cdr_start(chan->cdr);
2874                         ast_cdr_end(chan->cdr);
2875                         /* If the cause wasn't handled properly */
2876                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2877                                 ast_cdr_failed(chan->cdr);
2878                 }
2879                 ast_hangup(chan);
2880                 chan = NULL;
2881         }
2882         return chan;
2883 }
2884
2885 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2886 {
2887         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2888 }
2889
2890 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2891 {
2892         struct chanlist *chan;
2893         struct ast_channel *c;
2894         int capabilities;
2895         int fmt;
2896         int res;
2897         int foo;
2898         int videoformat = format & AST_FORMAT_VIDEO_MASK;
2899
2900         if (!cause)
2901                 cause = &foo;
2902         *cause = AST_CAUSE_NOTDEFINED;
2903
2904         if (AST_LIST_LOCK(&channels)) {
2905                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2906                 return NULL;
2907         }
2908
2909         AST_LIST_TRAVERSE(&backends, chan, list) {
2910                 if (strcasecmp(type, chan->tech->type))
2911                         continue;
2912
2913                 capabilities = chan->tech->capabilities;
2914                 fmt = format & AST_FORMAT_AUDIO_MASK;
2915                 res = ast_translator_best_choice(&fmt, &capabilities);
2916                 if (res < 0) {
2917                         ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2918                         AST_LIST_UNLOCK(&channels);
2919                         return NULL;
2920                 }
2921                 AST_LIST_UNLOCK(&channels);
2922                 if (!chan->tech->requester)
2923                         return NULL;
2924                 
2925                 if (!(c = chan->tech->requester(type, capabilities | videoformat, data, cause)))
2926                         return NULL;
2927                 
2928                 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
2929                 return c;
2930         }
2931
2932         ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2933         *cause = AST_CAUSE_NOSUCHDRIVER;
2934         AST_LIST_UNLOCK(&channels);
2935
2936         return NULL;
2937 }
2938
2939 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2940 {
2941         /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2942            If the remote end does not answer within the timeout, then do NOT hang up, but
2943            return anyway.  */
2944         int res = -1;
2945         /* Stop if we're a zombie or need a soft hangup */
2946         ast_channel_lock(chan);
2947         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2948                 if (chan->tech->call)
2949                         res = chan->tech->call(chan, addr, timeout);
2950                 ast_set_flag(chan, AST_FLAG_OUTGOING);
2951         }
2952         ast_channel_unlock(chan);
2953         return res;
2954 }
2955
2956 /*!
2957   \brief Transfer a call to dest, if the channel supports transfer
2958
2959   Called by:
2960     \arg app_transfer
2961     \arg the manager interface
2962 */
2963 int ast_transfer(struct ast_channel *chan, char *dest)
2964 {
2965         int res = -1;
2966
2967         /* Stop if we're a zombie or need a soft hangup */
2968         ast_channel_lock(chan);
2969         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2970                 if (chan->tech->transfer) {
2971                         res = chan->tech->transfer(chan, dest);
2972                         if (!res)
2973                                 res = 1;
2974                 } else
2975                         res = 0;
2976         }
2977         ast_channel_unlock(chan);
2978         return res;
2979 }
2980
2981 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2982 {
2983         return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
2984 }
2985
2986 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2987 {
2988         int pos = 0;    /* index in the buffer where we accumulate digits */
2989         int to = ftimeout;
2990
2991         /* Stop if we're a zombie or need a soft hangup */
2992         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2993                 return -1;
2994         if (!len)
2995                 return -1;
2996         for (;;) {
2997                 int d;
2998                 if (c->stream) {
2999                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
3000                         ast_stopstream(c);
3001                         usleep(1000);
3002                         if (!d)
3003                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3004                 } else {
3005                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3006                 }
3007                 if (d < 0)
3008                         return -1;
3009                 if (d == 0) {
3010                         s[pos]='\0';
3011                         return 1;
3012                 }
3013                 if (d == 1) {
3014                         s[pos]='\0';
3015                         return 2;
3016                 }
3017                 if (!strchr(enders, d))
3018                         s[pos++] = d;
3019                 if (strchr(enders, d) || (pos >= len)) {
3020                         s[pos]='\0';
3021                         return 0;
3022                 }
3023                 to = timeout;
3024         }
3025         /* Never reached */
3026         return 0;
3027 }
3028
3029 int ast_channel_supports_html(struct ast_channel *chan)
3030 {
3031         return (chan->tech->send_html) ? 1 : 0;
3032 }
3033
3034 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3035 {
3036         if (chan->tech->send_html)
3037                 return chan->tech->send_html(chan, subclass, data, datalen);
3038         return -1;
3039 }
3040
3041 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
3042 {
3043         return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
3044 }
3045
3046 /*! \brief Set up translation from one channel to another */
3047 static int ast_channel_make_compatible_helper(struct ast_channel *from, struct ast_channel *to)
3048 {
3049         int src;
3050         int dst;
3051
3052         /* Set up translation from the 'from' channel to the 'to' channel */
3053         src = from->nativeformats;
3054         dst = to->nativeformats;
3055         if (ast_translator_best_choice(&dst, &src) < 0) {
3056                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", from->name, src, to->name, dst);
3057                 return -1;
3058         }
3059
3060         /* if the best path is not 'pass through', then
3061            transcoding is needed; if desired, force transcode path
3062            to use SLINEAR between channels, but only if there is
3063            no direct conversion available */
3064         if ((src != dst) && ast_opt_transcode_via_slin &&
3065             (ast_translate_path_steps(dst, src) != 1))
3066                 dst = AST_FORMAT_SLINEAR;
3067         if (ast_set_read_format(from, dst) < 0) {
3068                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", from->name, dst);
3069                 return -1;
3070         }
3071         if (ast_set_write_format(to, dst) < 0) {
3072                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", to->name, dst);
3073                 return -1;
3074         }
3075         return 0;
3076 }
3077
3078 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
3079 {
3080         /* Some callers do not check return code, and we must try to set all call legs correctly */
3081         int rc = 0;
3082
3083         /* Set up translation from the chan to the peer */
3084         rc = ast_channel_make_compatible_helper(chan, peer);
3085
3086         if (rc < 0)