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