Merged revisions 77771 via svnmerge from
[asterisk/asterisk.git] / main / channel.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Channel Management
22  *
23  * \author Mark Spencer <markster@digium.com>
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <string.h>
34 #include <sys/time.h>
35 #include <signal.h>
36 #include <errno.h>
37 #include <unistd.h>
38 #include <math.h>
39
40 #include "asterisk/zapata.h"
41
42 #include "asterisk/pbx.h"
43 #include "asterisk/frame.h"
44 #include "asterisk/sched.h"
45 #include "asterisk/options.h"
46 #include "asterisk/channel.h"
47 #include "asterisk/chanspy.h"
48 #include "asterisk/musiconhold.h"
49 #include "asterisk/logger.h"
50 #include "asterisk/say.h"
51 #include "asterisk/file.h"
52 #include "asterisk/cli.h"
53 #include "asterisk/translate.h"
54 #include "asterisk/manager.h"
55 #include "asterisk/chanvars.h"
56 #include "asterisk/linkedlists.h"
57 #include "asterisk/indications.h"
58 #include "asterisk/monitor.h"
59 #include "asterisk/causes.h"
60 #include "asterisk/callerid.h"
61 #include "asterisk/utils.h"
62 #include "asterisk/lock.h"
63 #include "asterisk/app.h"
64 #include "asterisk/transcap.h"
65 #include "asterisk/devicestate.h"
66 #include "asterisk/sha1.h"
67 #include "asterisk/threadstorage.h"
68 #include "asterisk/slinfactory.h"
69
70 struct channel_spy_trans {
71         int last_format;
72         struct ast_trans_pvt *path;
73 };
74
75 /*! \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                         if (prev) {     /* look for next item */
939                                 if (c != prev)  /* not this one */
940                                         continue;
941                                 /* found, prepare to return c->next */
942                                 if ((c = AST_RWLIST_NEXT(c, chan_list)) == NULL) break;
943                                 /* If prev was the last item on the channel list, then we just
944                                  * want to return NULL, instead of trying to deref NULL in the
945                                  * next section.
946                                  */
947                                 prev = NULL;
948                                 /* We want prev to be NULL in case we end up doing more searching through
949                                  * the channel list to find the channel (ie: name searching). If we didn't
950                                  * set this to NULL the logic would just blow up
951                                  */
952                         }
953                         if (name) { /* want match by name */
954                                 if ((!namelen && strcasecmp(c->name, name)) ||
955                                     (namelen && strncasecmp(c->name, name, namelen)))
956                                         continue;       /* name match failed */
957                         } else if (exten) {
958                                 if (context && strcasecmp(c->context, context) &&
959                                     strcasecmp(c->macrocontext, context))
960                                         continue;       /* context match failed */
961                                 if (strcasecmp(c->exten, exten) &&
962                                     strcasecmp(c->macroexten, exten))
963                                         continue;       /* exten match failed */
964                         }
965                         /* if we get here, c points to the desired record */
966                         break;
967                 }
968                 /* exit if chan not found or mutex acquired successfully */
969                 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
970                 done = c == NULL || ast_channel_trylock(c) == 0;
971                 if (!done) {
972                         ast_debug(1, "Avoiding %s for channel '%p'\n", msg, c);
973                         if (retries == 9) {
974                                 /* We are about to fail due to a deadlock, so report this
975                                  * while we still have the list lock.
976                                  */
977                                 ast_debug(1, "Failure, could not lock '%p' after %d retries!\n", c, retries);
978                                 /* As we have deadlocked, we will skip this channel and
979                                  * see if there is another match.
980                                  * NOTE: No point doing this for a full-name match,
981                                  * as there can be no more matches.
982                                  */
983                                 if (!(name && !namelen)) {
984                                         prev = c;
985                                         retries = -1;
986                                 }
987                         }
988                 }
989                 AST_RWLIST_UNLOCK(&channels);
990                 if (done)
991                         return c;
992                 /* If we reach this point we basically tried to lock a channel and failed. Instead of
993                  * starting from the beginning of the list we can restore our saved pointer to the previous
994                  * channel and start from there.
995                  */
996                 prev = _prev;
997                 usleep(1);      /* give other threads a chance before retrying */
998         }
999
1000         return NULL;
1001 }
1002
1003 /*! \brief Browse channels in use */
1004 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
1005 {
1006         return channel_find_locked(prev, NULL, 0, NULL, NULL);
1007 }
1008
1009 /*! \brief Get channel by name and lock it */
1010 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
1011 {
1012         return channel_find_locked(NULL, name, 0, NULL, NULL);
1013 }
1014
1015 /*! \brief Get channel by name prefix and lock it */
1016 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
1017 {
1018         return channel_find_locked(NULL, name, namelen, NULL, NULL);
1019 }
1020
1021 /*! \brief Get next channel by name prefix and lock it */
1022 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
1023                                                            const int namelen)
1024 {
1025         return channel_find_locked(chan, name, namelen, NULL, NULL);
1026 }
1027
1028 /*! \brief Get channel by exten (and optionally context) and lock it */
1029 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
1030 {
1031         return channel_find_locked(NULL, NULL, 0, context, exten);
1032 }
1033
1034 /*! \brief Get next channel by exten (and optionally context) and lock it */
1035 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1036                                                      const char *context)
1037 {
1038         return channel_find_locked(chan, NULL, 0, context, exten);
1039 }
1040
1041 /*! \brief Wait, look for hangups and condition arg */
1042 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1043 {
1044         struct ast_frame *f;
1045
1046         while (ms > 0) {
1047                 if (cond && ((*cond)(data) == 0))
1048                         return 0;
1049                 ms = ast_waitfor(chan, ms);
1050                 if (ms < 0)
1051                         return -1;
1052                 if (ms > 0) {
1053                         f = ast_read(chan);
1054                         if (!f)
1055                                 return -1;
1056                         ast_frfree(f);
1057                 }
1058         }
1059         return 0;
1060 }
1061
1062 /*! \brief Wait, look for hangups */
1063 int ast_safe_sleep(struct ast_channel *chan, int ms)
1064 {
1065         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1066 }
1067
1068 static void free_cid(struct ast_callerid *cid)
1069 {
1070         if (cid->cid_dnid)
1071                 ast_free(cid->cid_dnid);
1072         if (cid->cid_num)
1073                 ast_free(cid->cid_num); 
1074         if (cid->cid_name)
1075                 ast_free(cid->cid_name);        
1076         if (cid->cid_ani)
1077                 ast_free(cid->cid_ani);
1078         if (cid->cid_rdnis)
1079                 ast_free(cid->cid_rdnis);
1080         cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1081 }
1082
1083 /*! \brief Free a channel structure */
1084 void ast_channel_free(struct ast_channel *chan)
1085 {
1086         int fd;
1087         struct ast_var_t *vardata;
1088         struct ast_frame *f;
1089         struct varshead *headp;
1090         struct ast_datastore *datastore = NULL;
1091         char name[AST_CHANNEL_NAME];
1092         
1093         headp=&chan->varshead;
1094         
1095         AST_RWLIST_WRLOCK(&channels);
1096         if (!AST_RWLIST_REMOVE(&channels, chan, chan_list)) {
1097                 AST_RWLIST_UNLOCK(&channels);
1098                 ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
1099         }
1100         /* Lock and unlock the channel just to be sure nobody
1101            has it locked still */
1102         ast_channel_lock(chan);
1103         ast_channel_unlock(chan);
1104         if (chan->tech_pvt) {
1105                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1106                 ast_free(chan->tech_pvt);
1107         }
1108
1109         if (chan->sched)
1110                 sched_context_destroy(chan->sched);
1111
1112         ast_copy_string(name, chan->name, sizeof(name));
1113
1114         /* Stop monitoring */
1115         if (chan->monitor)
1116                 chan->monitor->stop( chan, 0 );
1117
1118         /* If there is native format music-on-hold state, free it */
1119         if (chan->music_state)
1120                 ast_moh_cleanup(chan);
1121
1122         /* if someone is whispering on the channel, stop them */
1123         if (chan->whisper)
1124                 ast_channel_whisper_stop(chan);
1125
1126         /* Free translators */
1127         if (chan->readtrans)
1128                 ast_translator_free_path(chan->readtrans);
1129         if (chan->writetrans)
1130                 ast_translator_free_path(chan->writetrans);
1131         if (chan->pbx)
1132                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1133         free_cid(&chan->cid);
1134         ast_mutex_destroy(&chan->lock);
1135         /* Close pipes if appropriate */
1136         if ((fd = chan->alertpipe[0]) > -1)
1137                 close(fd);
1138         if ((fd = chan->alertpipe[1]) > -1)
1139                 close(fd);
1140         if ((fd = chan->timingfd) > -1)
1141                 close(fd);
1142         while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1143                 ast_frfree(f);
1144         
1145         /* Get rid of each of the data stores on the channel */
1146         while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1147                 /* Free the data store */
1148                 ast_channel_datastore_free(datastore);
1149         AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1150
1151         /* loop over the variables list, freeing all data and deleting list items */
1152         /* no need to lock the list, as the channel is already locked */
1153         
1154         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1155                 ast_var_delete(vardata);
1156
1157         ast_app_group_discard(chan);
1158
1159         /* Destroy the jitterbuffer */
1160         ast_jb_destroy(chan);
1161
1162         ast_string_field_free_pools(chan);
1163         ast_free(chan);
1164         AST_RWLIST_UNLOCK(&channels);
1165
1166         ast_device_state_changed_literal(name);
1167 }
1168
1169 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
1170 {
1171         struct ast_datastore *datastore = NULL;
1172
1173         /* Make sure we at least have type so we can identify this */
1174         if (!info) {
1175                 return NULL;
1176         }
1177
1178         /* Allocate memory for datastore and clear it */
1179         datastore = ast_calloc(1, sizeof(*datastore));
1180         if (!datastore) {
1181                 return NULL;
1182         }
1183
1184         datastore->info = info;
1185
1186         datastore->uid = ast_strdup(uid);
1187
1188         return datastore;
1189 }
1190
1191 int ast_channel_datastore_free(struct ast_datastore *datastore)
1192 {
1193         int res = 0;
1194
1195         /* Using the destroy function (if present) destroy the data */
1196         if (datastore->info->destroy != NULL && datastore->data != NULL) {
1197                 datastore->info->destroy(datastore->data);
1198                 datastore->data = NULL;
1199         }
1200
1201         /* Free allocated UID memory */
1202         if (datastore->uid != NULL) {
1203                 ast_free(datastore->uid);
1204                 datastore->uid = NULL;
1205         }
1206
1207         /* Finally free memory used by ourselves */
1208         ast_free(datastore);
1209
1210         return res;
1211 }
1212
1213 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1214 {
1215         struct ast_datastore *datastore = NULL, *datastore2;
1216
1217         AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1218                 if (datastore->inheritance > 0) {
1219                         datastore2 = ast_channel_datastore_alloc(datastore->info, datastore->uid);
1220                         if (datastore2) {
1221                                 datastore2->data = datastore->info->duplicate(datastore->data);
1222                                 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1223                                 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1224                         }
1225                 }
1226         }
1227         return 0;
1228 }
1229
1230 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1231 {
1232         int res = 0;
1233
1234         AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1235
1236         return res;
1237 }
1238
1239 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1240 {
1241         struct ast_datastore *datastore2 = NULL;
1242         int res = -1;
1243
1244         /* Find our position and remove ourselves */
1245         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1246                 if (datastore2 == datastore) {
1247                         AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1248                         res = 0;
1249                         break;
1250                 }
1251         }
1252         AST_LIST_TRAVERSE_SAFE_END
1253
1254         return res;
1255 }
1256
1257 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
1258 {
1259         struct ast_datastore *datastore = NULL;
1260         
1261         if (info == NULL)
1262                 return NULL;
1263
1264         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1265                 if (datastore->info == info) {
1266                         if (uid != NULL && datastore->uid != NULL) {
1267                                 if (!strcasecmp(uid, datastore->uid)) {
1268                                         /* Matched by type AND uid */
1269                                         break;
1270                                 }
1271                         } else {
1272                                 /* Matched by type at least */
1273                                 break;
1274                         }
1275                 }
1276         }
1277         AST_LIST_TRAVERSE_SAFE_END
1278
1279         return datastore;
1280 }
1281
1282 int ast_channel_spy_add(struct ast_channel *chan, struct ast_channel_spy *spy)
1283 {
1284         /* Link the owner channel to the spy */
1285         spy->chan = chan;
1286
1287         if (!ast_test_flag(spy, CHANSPY_FORMAT_AUDIO)) {
1288                 ast_log(LOG_WARNING, "Could not add channel spy '%s' to channel '%s', only audio format spies are supported.\n",
1289                         spy->type, chan->name);
1290                 return -1;
1291         }
1292
1293         if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST) && (spy->read_queue.format != AST_FORMAT_SLINEAR)) {
1294                 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1295                         ast_getformatname(spy->read_queue.format));
1296                 return -1;
1297         }
1298
1299         if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST) && (spy->write_queue.format != AST_FORMAT_SLINEAR)) {
1300                 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1301                         ast_getformatname(spy->write_queue.format));
1302                 return -1;
1303         }
1304
1305         if (ast_test_flag(spy, CHANSPY_MIXAUDIO) &&
1306             ((spy->read_queue.format != AST_FORMAT_SLINEAR) ||
1307              (spy->write_queue.format != AST_FORMAT_SLINEAR))) {
1308                 ast_log(LOG_WARNING, "Cannot provide audio mixing on '%s'-'%s' format spies\n",
1309                         ast_getformatname(spy->read_queue.format), ast_getformatname(spy->write_queue.format));
1310                 return -1;
1311         }
1312
1313         if (!chan->spies) {
1314                 if (!(chan->spies = ast_calloc(1, sizeof(*chan->spies)))) {
1315                         return -1;
1316                 }
1317
1318                 AST_LIST_HEAD_INIT_NOLOCK(&chan->spies->list);
1319                 AST_LIST_INSERT_HEAD(&chan->spies->list, spy, list);
1320         } else {
1321                 AST_LIST_INSERT_TAIL(&chan->spies->list, spy, list);
1322         }
1323
1324         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1325                 ast_cond_init(&spy->trigger, NULL);
1326                 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1327                 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1328         }
1329
1330         ast_debug(1, "Spy %s added to channel %s\n",
1331                 spy->type, chan->name);
1332
1333         return 0;
1334 }
1335
1336 /* Clean up a channel's spy information */
1337 static void spy_cleanup(struct ast_channel *chan)
1338 {
1339         if (!AST_LIST_EMPTY(&chan->spies->list))
1340                 return;
1341         if (chan->spies->read_translator.path)
1342                 ast_translator_free_path(chan->spies->read_translator.path);
1343         if (chan->spies->write_translator.path)
1344                 ast_translator_free_path(chan->spies->write_translator.path);
1345         ast_free(chan->spies);
1346         chan->spies = NULL;
1347         return;
1348 }
1349
1350 /* Detach a spy from it's channel */
1351 static void spy_detach(struct ast_channel_spy *spy, struct ast_channel *chan)
1352 {
1353         /* We only need to poke them if they aren't already done */
1354         if (spy->status != CHANSPY_DONE) {
1355                 ast_mutex_lock(&spy->lock);
1356                 /* Indicate to the spy to stop */
1357                 spy->status = CHANSPY_STOP;
1358                 spy->chan = NULL;
1359                 /* Poke the spy if needed */
1360                 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1361                         ast_cond_signal(&spy->trigger);
1362                 ast_mutex_unlock(&spy->lock);
1363         }
1364
1365         /* Print it out while we still have a lock so the structure can't go away (if signalled above) */
1366         ast_debug(1, "Spy %s removed from channel %s\n", spy->type, chan->name);
1367
1368         return;
1369 }
1370
1371 void ast_channel_spy_stop_by_type(struct ast_channel *chan, const char *type)
1372 {
1373         struct ast_channel_spy *spy = NULL;
1374         
1375         if (!chan->spies)
1376                 return;
1377
1378         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1379                 if ((spy->type == type) && (spy->status == CHANSPY_RUNNING)) {
1380                         AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1381                         spy_detach(spy, chan);
1382                 }
1383         }
1384         AST_LIST_TRAVERSE_SAFE_END
1385         spy_cleanup(chan);
1386 }
1387
1388 void ast_channel_spy_trigger_wait(struct ast_channel_spy *spy)
1389 {
1390         struct timeval tv;
1391         struct timespec ts;
1392
1393         tv = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
1394         ts.tv_sec = tv.tv_sec;
1395         ts.tv_nsec = tv.tv_usec * 1000;
1396
1397         ast_cond_timedwait(&spy->trigger, &spy->lock, &ts);
1398 }
1399
1400 void ast_channel_spy_remove(struct ast_channel *chan, struct ast_channel_spy *spy)
1401 {
1402         if (!chan->spies)
1403                 return;
1404
1405         AST_LIST_REMOVE(&chan->spies->list, spy, list);
1406         spy_detach(spy, chan);
1407         spy_cleanup(chan);
1408 }
1409
1410 void ast_channel_spy_free(struct ast_channel_spy *spy)
1411 {
1412         struct ast_frame *f = NULL;
1413
1414         if (spy->status == CHANSPY_DONE)
1415                 return;
1416
1417         /* Switch status to done in case we get called twice */
1418         spy->status = CHANSPY_DONE;
1419
1420         /* Drop any frames in the queue */
1421         while ((f = AST_LIST_REMOVE_HEAD(&spy->write_queue.list, frame_list)))
1422                 ast_frfree(f);
1423         while ((f = AST_LIST_REMOVE_HEAD(&spy->read_queue.list, frame_list)))
1424                 ast_frfree(f);
1425
1426         /* Destroy the condition if in use */
1427         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1428                 ast_cond_destroy(&spy->trigger);
1429
1430         /* Destroy our mutex since it is no longer in use */
1431         ast_mutex_destroy(&spy->lock);
1432
1433         return;
1434 }
1435
1436 static void detach_spies(struct ast_channel *chan)
1437 {
1438         struct ast_channel_spy *spy = NULL;
1439
1440         if (!chan->spies)
1441                 return;
1442
1443         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1444                 AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1445                 spy_detach(spy, chan);
1446         }
1447         AST_LIST_TRAVERSE_SAFE_END
1448
1449         spy_cleanup(chan);
1450 }
1451
1452 /*! \brief Softly hangup a channel, don't lock */
1453 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1454 {
1455         ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
1456         /* Inform channel driver that we need to be hung up, if it cares */
1457         chan->_softhangup |= cause;
1458         ast_queue_frame(chan, &ast_null_frame);
1459         /* Interrupt any poll call or such */
1460         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1461                 pthread_kill(chan->blocker, SIGURG);
1462         return 0;
1463 }
1464
1465 /*! \brief Softly hangup a channel, lock */
1466 int ast_softhangup(struct ast_channel *chan, int cause)
1467 {
1468         int res;
1469         ast_channel_lock(chan);
1470         res = ast_softhangup_nolock(chan, cause);
1471         ast_channel_unlock(chan);
1472         return res;
1473 }
1474
1475 enum spy_direction {
1476         SPY_READ,
1477         SPY_WRITE,
1478 };
1479
1480 #define SPY_QUEUE_SAMPLE_LIMIT 4000                     /* half of one second */
1481
1482 static void queue_frame_to_spies(struct ast_channel *chan, struct ast_frame *f, enum spy_direction dir)
1483 {
1484         struct ast_frame *translated_frame = NULL;
1485         struct ast_channel_spy *spy;
1486         struct channel_spy_trans *trans;
1487
1488         trans = (dir == SPY_READ) ? &chan->spies->read_translator : &chan->spies->write_translator;
1489
1490         AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1491                 struct ast_channel_spy_queue *queue;
1492                 struct ast_frame *duped_fr;
1493
1494                 if (spy->status != CHANSPY_RUNNING)
1495                         continue;
1496
1497                 ast_mutex_lock(&spy->lock);
1498
1499                 queue = (dir == SPY_READ) ? &spy->read_queue : &spy->write_queue;
1500
1501                 if ((queue->format == AST_FORMAT_SLINEAR) && (f->subclass != AST_FORMAT_SLINEAR)) {
1502                         if (!translated_frame) {
1503                                 if (trans->path && (trans->last_format != f->subclass)) {
1504                                         ast_translator_free_path(trans->path);
1505                                         trans->path = NULL;
1506                                 }
1507                                 if (!trans->path) {
1508                                         ast_debug(1, "Building translator from %s to SLINEAR for spies on channel %s\n",
1509                                                         ast_getformatname(f->subclass), chan->name);
1510                                         if ((trans->path = ast_translator_build_path(AST_FORMAT_SLINEAR, f->subclass)) == NULL) {
1511                                                 ast_log(LOG_WARNING, "Cannot build a path from %s to %s\n",
1512                                                         ast_getformatname(f->subclass), ast_getformatname(AST_FORMAT_SLINEAR));
1513                                                 ast_mutex_unlock(&spy->lock);
1514                                                 continue;
1515                                         } else {
1516                                                 trans->last_format = f->subclass;
1517                                         }
1518                                 }
1519                                 if (!(translated_frame = ast_translate(trans->path, f, 0))) {
1520                                         ast_log(LOG_ERROR, "Translation to %s failed, dropping frame for spies\n",
1521                                                 ast_getformatname(AST_FORMAT_SLINEAR));
1522                                         ast_mutex_unlock(&spy->lock);
1523                                         break;
1524                                 }
1525                         }
1526                         duped_fr = ast_frdup(translated_frame);
1527                 } else if (f->subclass != queue->format) {
1528                         ast_log(LOG_WARNING, "Spy '%s' on channel '%s' wants format '%s', but frame is '%s', dropping\n",
1529                                 spy->type, chan->name,
1530                                 ast_getformatname(queue->format), ast_getformatname(f->subclass));
1531                         ast_mutex_unlock(&spy->lock);
1532                         continue;
1533                 } else
1534                         duped_fr = ast_frdup(f);
1535
1536                 AST_LIST_INSERT_TAIL(&queue->list, duped_fr, frame_list);
1537
1538                 queue->samples += f->samples;
1539
1540                 if (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1541                         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1542                                 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1543                                 case CHANSPY_TRIGGER_READ:
1544                                         if (dir == SPY_WRITE) {
1545                                                 ast_set_flag(spy, CHANSPY_TRIGGER_WRITE);
1546                                                 ast_clear_flag(spy, CHANSPY_TRIGGER_READ);
1547                                                 ast_debug(1, "Switching spy '%s' on '%s' to write-trigger mode\n",
1548                                                         spy->type, chan->name);
1549                                         }
1550                                         break;
1551                                 case CHANSPY_TRIGGER_WRITE:
1552                                         if (dir == SPY_READ) {
1553                                                 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1554                                                 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1555                                                 ast_debug(1, "Switching spy '%s' on '%s' to read-trigger mode\n",
1556                                                         spy->type, chan->name);
1557                                         }
1558                                         break;
1559                                 }
1560                                 ast_debug(1, "Triggering queue flush for spy '%s' on '%s'\n",
1561                                         spy->type, chan->name);
1562                                 ast_set_flag(spy, CHANSPY_TRIGGER_FLUSH);
1563                                 ast_cond_signal(&spy->trigger);
1564                         } else {
1565                                 ast_debug(1, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1566                                         spy->type, chan->name, (dir == SPY_READ) ? "read" : "write");
1567                                 while (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1568                                         struct ast_frame *drop = AST_LIST_REMOVE_HEAD(&queue->list, frame_list);
1569                                         queue->samples -= drop->samples;
1570                                         ast_frfree(drop);
1571                                 }
1572                         }
1573                 } else {
1574                         switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1575                         case CHANSPY_TRIGGER_READ:
1576                                 if (dir == SPY_READ)
1577                                         ast_cond_signal(&spy->trigger);
1578                                 break;
1579                         case CHANSPY_TRIGGER_WRITE:
1580                                 if (dir == SPY_WRITE)
1581                                         ast_cond_signal(&spy->trigger);
1582                                 break;
1583                         }
1584                 }
1585
1586                 ast_mutex_unlock(&spy->lock);
1587         }
1588
1589         if (translated_frame)
1590                 ast_frfree(translated_frame);
1591 }
1592
1593 static void free_translation(struct ast_channel *clone)
1594 {
1595         if (clone->writetrans)
1596                 ast_translator_free_path(clone->writetrans);
1597         if (clone->readtrans)
1598                 ast_translator_free_path(clone->readtrans);
1599         clone->writetrans = NULL;
1600         clone->readtrans = NULL;
1601         clone->rawwriteformat = clone->nativeformats;
1602         clone->rawreadformat = clone->nativeformats;
1603 }
1604
1605 /*! \brief Hangup a channel */
1606 int ast_hangup(struct ast_channel *chan)
1607 {
1608         int res = 0;
1609         struct ast_cdr *cdr = NULL;
1610
1611         /* Don't actually hang up a channel that will masquerade as someone else, or
1612            if someone is going to masquerade as us */
1613         ast_channel_lock(chan);
1614
1615         detach_spies(chan);             /* get rid of spies */
1616
1617         if (chan->masq) {
1618                 if (ast_do_masquerade(chan))
1619                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1620         }
1621
1622         if (chan->masq) {
1623                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1624                 ast_channel_unlock(chan);
1625                 return 0;
1626         }
1627         /* If this channel is one which will be masqueraded into something,
1628            mark it as a zombie already, so we know to free it later */
1629         if (chan->masqr) {
1630                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1631                 ast_channel_unlock(chan);
1632                 return 0;
1633         }
1634         free_translation(chan);
1635         /* Close audio stream */
1636         if (chan->stream) {
1637                 ast_closestream(chan->stream);
1638                 chan->stream = NULL;
1639         }
1640         /* Close video stream */
1641         if (chan->vstream) {
1642                 ast_closestream(chan->vstream);
1643                 chan->vstream = NULL;
1644         }
1645         if (chan->sched) {
1646                 sched_context_destroy(chan->sched);
1647                 chan->sched = NULL;
1648         }
1649         
1650         if (chan->generatordata)        /* Clear any tone stuff remaining */
1651                 if (chan->generator && chan->generator->release)
1652                         chan->generator->release(chan, chan->generatordata);
1653         chan->generatordata = NULL;
1654         chan->generator = NULL;
1655         if (chan->cdr) {                /* End the CDR if it hasn't already */
1656                 ast_cdr_end(chan->cdr);
1657                 cdr = chan->cdr;
1658                 chan->cdr = NULL;
1659         }
1660         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1661                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1662                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
1663                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1664                 CRASH;
1665         }
1666         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1667                 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
1668                 if (chan->tech->hangup)
1669                         res = chan->tech->hangup(chan);
1670         } else {
1671                 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
1672         }
1673                         
1674         ast_channel_unlock(chan);
1675         manager_event(EVENT_FLAG_CALL, "Hangup",
1676                         "Channel: %s\r\n"
1677                         "Uniqueid: %s\r\n"
1678                         "Cause: %d\r\n"
1679                         "Cause-txt: %s\r\n",
1680                         chan->name,
1681                         chan->uniqueid,
1682                         chan->hangupcause,
1683                         ast_cause2str(chan->hangupcause)
1684                         );
1685         ast_channel_free(chan);
1686
1687         if (cdr)
1688                 ast_cdr_detach(cdr);
1689
1690         return res;
1691 }
1692
1693 int __ast_answer(struct ast_channel *chan, unsigned int delay)
1694 {
1695         int res = 0;
1696
1697         ast_channel_lock(chan);
1698
1699         /* You can't answer an outbound call */
1700         if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1701                 ast_channel_unlock(chan);
1702                 return 0;
1703         }
1704
1705         /* Stop if we're a zombie or need a soft hangup */
1706         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1707                 ast_channel_unlock(chan);
1708                 return -1;
1709         }
1710
1711         switch (chan->_state) {
1712         case AST_STATE_RINGING:
1713         case AST_STATE_RING:
1714                 if (chan->tech->answer)
1715                         res = chan->tech->answer(chan);
1716                 ast_setstate(chan, AST_STATE_UP);
1717                 ast_cdr_answer(chan->cdr);
1718                 ast_channel_unlock(chan);
1719                 if (delay)
1720                         ast_safe_sleep(chan, delay);
1721                 return res;
1722                 break;
1723         case AST_STATE_UP:
1724                 ast_cdr_answer(chan->cdr);
1725                 break;
1726         default:
1727                 break;
1728         }
1729
1730         ast_channel_unlock(chan);
1731
1732         return res;
1733 }
1734
1735 int ast_answer(struct ast_channel *chan)
1736 {
1737         return __ast_answer(chan, 500);
1738 }
1739
1740 void ast_deactivate_generator(struct ast_channel *chan)
1741 {
1742         ast_channel_lock(chan);
1743         if (chan->generatordata) {
1744                 if (chan->generator && chan->generator->release)
1745                         chan->generator->release(chan, chan->generatordata);
1746                 chan->generatordata = NULL;
1747                 chan->generator = NULL;
1748                 chan->fds[AST_GENERATOR_FD] = -1;
1749                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1750                 ast_settimeout(chan, 0, NULL, NULL);
1751         }
1752         ast_channel_unlock(chan);
1753 }
1754
1755 static int generator_force(void *data)
1756 {
1757         /* Called if generator doesn't have data */
1758         void *tmp;
1759         int res;
1760         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1761         struct ast_channel *chan = data;
1762         tmp = chan->generatordata;
1763         chan->generatordata = NULL;
1764         generate = chan->generator->generate;
1765         res = generate(chan, tmp, 0, 160);
1766         chan->generatordata = tmp;
1767         if (res) {
1768                 ast_debug(1, "Auto-deactivating generator\n");
1769                 ast_deactivate_generator(chan);
1770         }
1771         return 0;
1772 }
1773
1774 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1775 {
1776         int res = 0;
1777
1778         ast_channel_lock(chan);
1779
1780         if (chan->generatordata) {
1781                 if (chan->generator && chan->generator->release)
1782                         chan->generator->release(chan, chan->generatordata);
1783                 chan->generatordata = NULL;
1784         }
1785
1786         ast_prod(chan);
1787         if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1788                 res = -1;
1789         }
1790         
1791         if (!res) {
1792                 ast_settimeout(chan, 160, generator_force, chan);
1793                 chan->generator = gen;
1794         }
1795
1796         ast_channel_unlock(chan);
1797
1798         return res;
1799 }
1800
1801 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1802 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1803 {
1804         int winner = -1;
1805         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1806         return winner;
1807 }
1808
1809 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1810 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1811         int *exception, int *outfd, int *ms)
1812 {
1813         struct timeval start = { 0 , 0 };
1814         struct pollfd *pfds;
1815         int res;
1816         long rms;
1817         int x, y, max;
1818         int sz;
1819         time_t now = 0;
1820         long whentohangup = 0, diff;
1821         struct ast_channel *winner = NULL;
1822         struct fdmap {
1823                 int chan;
1824                 int fdno;
1825         } *fdmap;
1826
1827         sz = n * AST_MAX_FDS + nfds;
1828         pfds = alloca(sizeof(*pfds) * sz);
1829         fdmap = alloca(sizeof(*fdmap) * sz);
1830
1831         if (outfd)
1832                 *outfd = -99999;
1833         if (exception)
1834                 *exception = 0;
1835         
1836         /* Perform any pending masquerades */
1837         for (x=0; x < n; x++) {
1838                 ast_channel_lock(c[x]);
1839                 if (c[x]->masq) {
1840                         if (ast_do_masquerade(c[x])) {
1841                                 ast_log(LOG_WARNING, "Masquerade failed\n");
1842                                 *ms = -1;
1843                                 ast_channel_unlock(c[x]);
1844                                 return NULL;
1845                         }
1846                 }
1847                 if (c[x]->whentohangup) {
1848                         if (!whentohangup)
1849                                 time(&now);
1850                         diff = c[x]->whentohangup - now;
1851                         if (diff < 1) {
1852                                 /* Should already be hungup */
1853                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1854                                 ast_channel_unlock(c[x]);
1855                                 return c[x];
1856                         }
1857                         if (!whentohangup || (diff < whentohangup))
1858                                 whentohangup = diff;
1859                 }
1860                 ast_channel_unlock(c[x]);
1861         }
1862         /* Wait full interval */
1863         rms = *ms;
1864         if (whentohangup) {
1865                 rms = whentohangup * 1000;              /* timeout in milliseconds */
1866                 if (*ms >= 0 && *ms < rms)              /* original *ms still smaller */
1867                         rms =  *ms;
1868         }
1869         /*
1870          * Build the pollfd array, putting the channels' fds first,
1871          * followed by individual fds. Order is important because
1872          * individual fd's must have priority over channel fds.
1873          */
1874         max = 0;
1875         for (x=0; x<n; x++) {
1876                 for (y=0; y<AST_MAX_FDS; y++) {
1877                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
1878                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
1879                         max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1880                 }
1881                 CHECK_BLOCKING(c[x]);
1882         }
1883         /* Add the individual fds */
1884         for (x=0; x<nfds; x++) {
1885                 fdmap[max].chan = -1;
1886                 max += ast_add_fd(&pfds[max], fds[x]);
1887         }
1888
1889         if (*ms > 0)
1890                 start = ast_tvnow();
1891         
1892         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1893                 do {
1894                         int kbrms = rms;
1895                         if (kbrms > 600000)
1896                                 kbrms = 600000;
1897                         res = poll(pfds, max, kbrms);
1898                         if (!res)
1899                                 rms -= kbrms;
1900                 } while (!res && (rms > 0));
1901         } else {
1902                 res = poll(pfds, max, rms);
1903         }
1904         for (x=0; x<n; x++)
1905                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1906         if (res < 0) { /* Simulate a timeout if we were interrupted */
1907                 if (errno != EINTR)
1908                         *ms = -1;
1909                 return NULL;
1910         }
1911         if (whentohangup) {   /* if we have a timeout, check who expired */
1912                 time(&now);
1913                 for (x=0; x<n; x++) {
1914                         if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1915                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1916                                 if (winner == NULL)
1917                                         winner = c[x];
1918                         }
1919                 }
1920         }
1921         if (res == 0) { /* no fd ready, reset timeout and done */
1922                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
1923                 return winner;
1924         }
1925         /*
1926          * Then check if any channel or fd has a pending event.
1927          * Remember to check channels first and fds last, as they
1928          * must have priority on setting 'winner'
1929          */
1930         for (x = 0; x < max; x++) {
1931                 res = pfds[x].revents;
1932                 if (res == 0)
1933                         continue;
1934                 if (fdmap[x].chan >= 0) {       /* this is a channel */
1935                         winner = c[fdmap[x].chan];      /* override previous winners */
1936                         if (res & POLLPRI)
1937                                 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1938                         else
1939                                 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1940                         winner->fdno = fdmap[x].fdno;
1941                 } else {                        /* this is an fd */
1942                         if (outfd)
1943                                 *outfd = pfds[x].fd;
1944                         if (exception)
1945                                 *exception = (res & POLLPRI) ? -1 : 0;
1946                         winner = NULL;
1947                 }
1948         }
1949         if (*ms > 0) {
1950                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1951                 if (*ms < 0)
1952                         *ms = 0;
1953         }
1954         return winner;
1955 }
1956
1957 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1958 {
1959         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1960 }
1961
1962 int ast_waitfor(struct ast_channel *c, int ms)
1963 {
1964         int oldms = ms; /* -1 if no timeout */
1965
1966         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1967         if ((ms < 0) && (oldms < 0))
1968                 ms = 0;
1969         return ms;
1970 }
1971
1972 /* XXX never to be called with ms = -1 */
1973 int ast_waitfordigit(struct ast_channel *c, int ms)
1974 {
1975         return ast_waitfordigit_full(c, ms, -1, -1);
1976 }
1977
1978 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1979 {
1980         int res = -1;
1981 #ifdef HAVE_ZAPTEL
1982         if (c->timingfd > -1) {
1983                 if (!func) {
1984                         samples = 0;
1985                         data = 0;
1986                 }
1987                 ast_debug(1, "Scheduling timer at %d sample intervals\n", samples);
1988                 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1989                 c->timingfunc = func;
1990                 c->timingdata = data;
1991         }
1992 #endif  
1993         return res;
1994 }
1995
1996 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1997 {
1998         int begin_digit = 0;
1999
2000         /* Stop if we're a zombie or need a soft hangup */
2001         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2002                 return -1;
2003         /* Wait for a digit, no more than ms milliseconds total. */
2004         while (ms) {
2005                 struct ast_channel *rchan;
2006                 int outfd;
2007
2008                 errno = 0;
2009                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2010                 if (!rchan && outfd < 0 && ms) {
2011                         if (errno == 0 || errno == EINTR)
2012                                 continue;
2013                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2014                         return -1;
2015                 } else if (outfd > -1) {
2016                         /* The FD we were watching has something waiting */
2017                         return 1;
2018                 } else if (rchan) {
2019                         int res;
2020                         struct ast_frame *f = ast_read(c);
2021                         if (!f)
2022                                 return -1;
2023
2024                         switch (f->frametype) {
2025                         case AST_FRAME_DTMF_BEGIN:
2026                                 begin_digit = f->subclass;
2027                                 break;
2028                         case AST_FRAME_DTMF_END:
2029                                 if (begin_digit != f->subclass)
2030                                         break;
2031                                 res = f->subclass;
2032                                 ast_frfree(f);
2033                                 return res;
2034                         case AST_FRAME_CONTROL:
2035                                 switch (f->subclass) {
2036                                 case AST_CONTROL_HANGUP:
2037                                         ast_frfree(f);
2038                                         return -1;
2039                                 case AST_CONTROL_RINGING:
2040                                 case AST_CONTROL_ANSWER:
2041                                         /* Unimportant */
2042                                         break;
2043                                 default:
2044                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2045                                         break;
2046                                 }
2047                                 break;
2048                         case AST_FRAME_VOICE:
2049                                 /* Write audio if appropriate */
2050                                 if (audiofd > -1)
2051                                         write(audiofd, f->data, f->datalen);
2052                         default:
2053                                 /* Ignore */
2054                                 break;
2055                         }
2056                         ast_frfree(f);
2057                 }
2058         }
2059         return 0; /* Time is up */
2060 }
2061
2062 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2063 {
2064         manager_event(EVENT_FLAG_DTMF,
2065                         "DTMF",
2066                         "Channel: %s\r\n"
2067                         "Uniqueid: %s\r\n"
2068                         "Digit: %c\r\n"
2069                         "Direction: %s\r\n"
2070                         "Begin: %s\r\n"
2071                         "End: %s\r\n",
2072                         chan->name, chan->uniqueid, digit, direction, begin, end);
2073 }
2074
2075 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2076 {
2077         if (chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
2078                 void *tmp = chan->generatordata;
2079                 int res;
2080
2081                 if (chan->timingfunc) {
2082                         if (option_debug > 1)
2083                                 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2084                         ast_settimeout(chan, 0, NULL, NULL);
2085                 }
2086
2087                 chan->generatordata = NULL;     /* reset, to let writes go through */
2088                 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2089                 chan->generatordata = tmp;
2090                 if (res) {
2091                         if (option_debug > 1)
2092                                 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2093                         ast_deactivate_generator(chan);
2094                 }
2095
2096         } else if (f->frametype == AST_FRAME_CNG) {
2097                 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2098                         if (option_debug > 1)
2099                                 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2100                         ast_settimeout(chan, 160, generator_force, chan);
2101                 }
2102         }
2103 }
2104
2105 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2106 {
2107         struct ast_frame *f = NULL;     /* the return value */
2108         int blah;
2109         int prestate;
2110
2111         /* this function is very long so make sure there is only one return
2112          * point at the end (there is only one exception to this).
2113          */
2114         ast_channel_lock(chan);
2115         if (chan->masq) {
2116                 if (ast_do_masquerade(chan))
2117                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2118                 else
2119                         f =  &ast_null_frame;
2120                 goto done;
2121         }
2122
2123         /* Stop if we're a zombie or need a soft hangup */
2124         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2125                 if (chan->generator)
2126                         ast_deactivate_generator(chan);
2127                 goto done;
2128         }
2129         prestate = chan->_state;
2130
2131         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) && 
2132             !ast_strlen_zero(chan->dtmfq) && 
2133                 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
2134                 /* We have DTMF that has been deferred.  Return it now */
2135                 chan->dtmff.subclass = chan->dtmfq[0];
2136                 /* Drop first digit from the buffer */
2137                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2138                 f = &chan->dtmff;
2139                 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2140                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2141                         chan->dtmff.frametype = AST_FRAME_DTMF_END;
2142                 } else {
2143                         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);
2144                         chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2145                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2146                         chan->emulate_dtmf_digit = f->subclass;
2147                         chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2148                 }
2149                 chan->dtmf_tv = ast_tvnow();
2150                 goto done;
2151         }
2152         
2153         /* Read and ignore anything on the alertpipe, but read only
2154            one sizeof(blah) per frame that we send from it */
2155         if (chan->alertpipe[0] > -1)
2156                 read(chan->alertpipe[0], &blah, sizeof(blah));
2157
2158 #ifdef HAVE_ZAPTEL
2159         if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2160                 int res;
2161
2162                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2163                 blah = -1;
2164                 /* IF we can't get event, assume it's an expired as-per the old interface */
2165                 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
2166                 if (res)
2167                         blah = ZT_EVENT_TIMER_EXPIRED;
2168
2169                 if (blah == ZT_EVENT_TIMER_PING) {
2170                         if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2171                                 /* Acknowledge PONG unless we need it again */
2172                                 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
2173                                         ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2174                                 }
2175                         }
2176                 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
2177                         ioctl(chan->timingfd, ZT_TIMERACK, &blah);
2178                         if (chan->timingfunc) {
2179                                 /* save a copy of func/data before unlocking the channel */
2180                                 int (*func)(void *) = chan->timingfunc;
2181                                 void *data = chan->timingdata;
2182                                 ast_channel_unlock(chan);
2183                                 func(data);
2184                         } else {
2185                                 blah = 0;
2186                                 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
2187                                 chan->timingdata = NULL;
2188                                 ast_channel_unlock(chan);
2189                         }
2190                         /* cannot 'goto done' because the channel is already unlocked */
2191                         return &ast_null_frame;
2192                 } else
2193                         ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2194         } else
2195 #endif
2196         if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2197                 /* if the AST_GENERATOR_FD is set, call the generator with args
2198                  * set to -1 so it can do whatever it needs to.
2199                  */
2200                 void *tmp = chan->generatordata;
2201                 chan->generatordata = NULL;     /* reset to let ast_write get through */
2202                 chan->generator->generate(chan, tmp, -1, -1);
2203                 chan->generatordata = tmp;
2204                 f = &ast_null_frame;
2205                 goto done;
2206         }
2207
2208         /* Check for pending read queue */
2209         if (!AST_LIST_EMPTY(&chan->readq)) {
2210                 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2211                 /* Interpret hangup and return NULL */
2212                 /* XXX why not the same for frames from the channel ? */
2213                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2214                         ast_frfree(f);
2215                         f = NULL;
2216                 }
2217         } else {
2218                 chan->blocker = pthread_self();
2219                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2220                         if (chan->tech->exception)
2221                                 f = chan->tech->exception(chan);
2222                         else {
2223                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2224                                 f = &ast_null_frame;
2225                         }
2226                         /* Clear the exception flag */
2227                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2228                 } else if (chan->tech->read)
2229                         f = chan->tech->read(chan);
2230                 else
2231                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2232         }
2233
2234         if (f) {
2235                 /* if the channel driver returned more than one frame, stuff the excess
2236                    into the readq for the next ast_read call (note that we can safely assume
2237                    that the readq is empty, because otherwise we would not have called into
2238                    the channel driver and f would be only a single frame)
2239                 */
2240                 if (AST_LIST_NEXT(f, frame_list)) {
2241                         AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2242                         AST_LIST_NEXT(f, frame_list) = NULL;
2243                 }
2244
2245                 switch (f->frametype) {
2246                 case AST_FRAME_CONTROL:
2247                         if (f->subclass == AST_CONTROL_ANSWER) {
2248                                 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2249                                         ast_debug(1, "Ignoring answer on an inbound call!\n");
2250                                         ast_frfree(f);
2251                                         f = &ast_null_frame;
2252                                 } else if (prestate == AST_STATE_UP) {
2253                                         ast_debug(1, "Dropping duplicate answer!\n");
2254                                         ast_frfree(f);
2255                                         f = &ast_null_frame;
2256                                 } else {
2257                                         /* Answer the CDR */
2258                                         ast_setstate(chan, AST_STATE_UP);
2259                                         if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2260                                                                                  to keep from throwing off the basic order of the universe,
2261                                                                                  we will try to keep this cdr from getting posted. */
2262                                                 chan->cdr = ast_cdr_alloc();
2263                                                 ast_cdr_init(chan->cdr, chan);
2264                                                 ast_cdr_start(chan->cdr);
2265                                         }
2266                                         
2267                                         ast_cdr_answer(chan->cdr);
2268                                 }
2269                         }
2270                         break;
2271                 case AST_FRAME_DTMF_END:
2272                         send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
2273                         ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2274                         /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2275                          * However, only let emulation be forced if the other end cares about BEGIN frames */
2276                         if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2277                                 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2278                                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
2279                                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2280                                 else
2281                                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2282                                 ast_frfree(f);
2283                                 f = &ast_null_frame;
2284                         } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2285                                 if (!ast_tvzero(chan->dtmf_tv) && 
2286                                     ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2287                                         /* If it hasn't been long enough, defer this digit */
2288                                         if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
2289                                                 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2290                                         else
2291                                                 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2292                                         ast_frfree(f);
2293                                         f = &ast_null_frame;
2294                                 } else {
2295                                         /* There was no begin, turn this into a begin and send the end later */
2296                                         f->frametype = AST_FRAME_DTMF_BEGIN;
2297                                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2298                                         chan->emulate_dtmf_digit = f->subclass;
2299                                         chan->dtmf_tv = ast_tvnow();
2300                                         if (f->len) {
2301                                                 if (f->len > AST_MIN_DTMF_DURATION)
2302                                                         chan->emulate_dtmf_duration = f->len;
2303                                                 else 
2304                                                         chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2305                                         } else
2306                                                 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2307                                         ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2308                                 }
2309                         } else {
2310                                 struct timeval now = ast_tvnow();
2311                                 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2312                                         ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2313                                         if (!f->len)
2314                                                 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2315                                 } else if (!f->len)
2316                                         f->len = AST_MIN_DTMF_DURATION;
2317                                 if (f->len < AST_MIN_DTMF_DURATION) {
2318                                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2319                                         chan->emulate_dtmf_digit = f->subclass;
2320                                         chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2321                                         f = &ast_null_frame;
2322                                 } else
2323                                         chan->dtmf_tv = now;
2324                         }
2325                         break;
2326                 case AST_FRAME_DTMF_BEGIN:
2327                         send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
2328                         ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2329                         if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY) || 
2330                             (!ast_tvzero(chan->dtmf_tv) && 
2331                               ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2332                                 ast_frfree(f);
2333                                 f = &ast_null_frame;
2334                         } else {
2335                                 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2336                                 chan->dtmf_tv = ast_tvnow();
2337                         }
2338                         break;
2339                 case AST_FRAME_NULL:
2340                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2341                                 struct timeval now = ast_tvnow();
2342                                 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2343                                         chan->emulate_dtmf_duration = 0;
2344                                         ast_frfree(f);
2345                                         f = &chan->dtmff;
2346                                         f->frametype = AST_FRAME_DTMF_END;
2347                                         f->subclass = chan->emulate_dtmf_digit;
2348                                         f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2349                                         chan->dtmf_tv = now;
2350                                         ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2351                                         chan->emulate_dtmf_digit = 0;
2352                                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2353                                 }
2354                         }
2355                         break;
2356                 case AST_FRAME_VOICE:
2357                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2358                          * is reached , because we want to make sure we pass at least one
2359                          * voice frame through before starting the next digit, to ensure a gap
2360                          * between DTMF digits. */
2361                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2362                                 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2363                                 chan->emulate_dtmf_digit = 0;
2364                         }
2365
2366                         if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2367                                 if (dropaudio)
2368                                         ast_read_generator_actions(chan, f);
2369                                 ast_frfree(f);
2370                                 f = &ast_null_frame;
2371                         }
2372
2373                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2374                                 struct timeval now = ast_tvnow();
2375                                 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2376                                         chan->emulate_dtmf_duration = 0;
2377                                         ast_frfree(f);
2378                                         f = &chan->dtmff;
2379                                         f->frametype = AST_FRAME_DTMF_END;
2380                                         f->subclass = chan->emulate_dtmf_digit;
2381                                         f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2382                                         chan->dtmf_tv = now;
2383                                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2384                                 } else {
2385                                         /* Drop voice frames while we're still in the middle of the digit */
2386                                         ast_frfree(f);
2387                                         f = &ast_null_frame;
2388                                 }
2389                         } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2390                                 /* This frame can't be from the current native formats -- drop it on the
2391                                    floor */
2392                                 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2393                                         chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2394                                 ast_frfree(f);
2395                                 f = &ast_null_frame;
2396                         } else if ((f->frametype == AST_FRAME_VOICE)) {
2397                                 if (chan->spies)
2398                                         queue_frame_to_spies(chan, f, SPY_READ);
2399                                 
2400                                 if (chan->monitor && chan->monitor->read_stream ) {
2401                                         /* XXX what does this do ? */
2402 #ifndef MONITOR_CONSTANT_DELAY
2403                                         int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2404                                         if (jump >= 0) {
2405                                                 jump = chan->outsmpl - chan->insmpl;
2406                                                 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2407                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2408                                                 chan->insmpl += jump + f->samples;
2409                                         } else
2410                                                 chan->insmpl+= f->samples;
2411 #else
2412                                         int jump = chan->outsmpl - chan->insmpl;
2413                                         if (jump - MONITOR_DELAY >= 0) {
2414                                                 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2415                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2416                                                 chan->insmpl += jump;
2417                                         } else
2418                                                 chan->insmpl += f->samples;
2419 #endif
2420                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2421                                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2422                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2423                                         }
2424                                 }
2425
2426                                 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2427                                         f = &ast_null_frame;
2428                                 else
2429                                         /* Run generator sitting on the line if timing device not available
2430                                          * and synchronous generation of outgoing frames is necessary       */
2431                                         ast_read_generator_actions(chan, f);
2432                         }
2433                 default:
2434                         /* Just pass it on! */
2435                         break;
2436                 }
2437         } else {
2438                 /* Make sure we always return NULL in the future */
2439                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2440                 if (chan->generator)
2441                         ast_deactivate_generator(chan);
2442                 /* End the CDR if appropriate */
2443                 if (chan->cdr)
2444                         ast_cdr_end(chan->cdr);
2445         }
2446
2447         /* High bit prints debugging */
2448         if (chan->fin & DEBUGCHAN_FLAG)
2449                 ast_frame_dump(chan->name, f, "<<");
2450         chan->fin = FRAMECOUNT_INC(chan->fin);
2451
2452 done:
2453         if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
2454                 chan->generator->digit(chan, f->subclass);
2455
2456         ast_channel_unlock(chan);
2457         return f;
2458 }
2459
2460 int ast_internal_timing_enabled(struct ast_channel *chan)
2461 {
2462         int ret = ast_opt_internal_timing && chan->timingfd > -1;
2463         ast_debug(5, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2464         return ret;
2465 }
2466
2467 struct ast_frame *ast_read(struct ast_channel *chan)
2468 {
2469         return __ast_read(chan, 0);
2470 }
2471
2472 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2473 {
2474         return __ast_read(chan, 1);
2475 }
2476
2477 int ast_indicate(struct ast_channel *chan, int condition)
2478 {
2479         return ast_indicate_data(chan, condition, NULL, 0);
2480 }
2481
2482 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2483 {
2484         int res = -1;
2485
2486         ast_channel_lock(chan);
2487         /* Stop if we're a zombie or need a soft hangup */
2488         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2489                 ast_channel_unlock(chan);
2490                 return -1;
2491         }
2492         if (chan->tech->indicate)
2493                 res = chan->tech->indicate(chan, condition, data, datalen);
2494         ast_channel_unlock(chan);
2495         if (!chan->tech->indicate || res) {
2496                 /*
2497                  * Device does not support (that) indication, lets fake
2498                  * it by doing our own tone generation. (PM2002)
2499                  */
2500                 if (condition < 0)
2501                         ast_playtones_stop(chan);
2502                 else {
2503                         const struct ind_tone_zone_sound *ts = NULL;
2504                         switch (condition) {
2505                         case AST_CONTROL_RINGING:
2506                                 ts = ast_get_indication_tone(chan->zone, "ring");
2507                                 break;
2508                         case AST_CONTROL_BUSY:
2509                                 ts = ast_get_indication_tone(chan->zone, "busy");
2510                                 break;
2511                         case AST_CONTROL_CONGESTION:
2512                                 ts = ast_get_indication_tone(chan->zone, "congestion");
2513                                 break;
2514                         }
2515                         if (ts && ts->data[0]) {
2516                                 ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2517                                 ast_playtones_start(chan,0,ts->data, 1);
2518                                 res = 0;
2519                         } else if (condition == AST_CONTROL_PROGRESS) {
2520                                 /* ast_playtones_stop(chan); */
2521                         } else if (condition == AST_CONTROL_PROCEEDING) {
2522                                 /* Do nothing, really */
2523                         } else if (condition == AST_CONTROL_HOLD) {
2524                                 /* Do nothing.... */
2525                         } else if (condition == AST_CONTROL_UNHOLD) {
2526                                 /* Do nothing.... */
2527                         } else if (condition == AST_CONTROL_VIDUPDATE) {
2528                                 /* Do nothing.... */
2529                         } else {
2530                                 /* not handled */
2531                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2532                                 res = -1;
2533                         }
2534                 }
2535         }
2536         return res;
2537 }
2538
2539 int ast_recvchar(struct ast_channel *chan, int timeout)
2540 {
2541         int c;
2542         char *buf = ast_recvtext(chan, timeout);
2543         if (buf == NULL)
2544                 return -1;      /* error or timeout */
2545         c = *(unsigned char *)buf;
2546         ast_free(buf);
2547         return c;
2548 }
2549
2550 char *ast_recvtext(struct ast_channel *chan, int timeout)
2551 {
2552         int res, done = 0;
2553         char *buf = NULL;
2554         
2555         while (!done) {
2556                 struct ast_frame *f;
2557                 if (ast_check_hangup(chan))
2558                         break;
2559                 res = ast_waitfor(chan, timeout);
2560                 if (res <= 0) /* timeout or error */
2561                         break;
2562                 timeout = res;  /* update timeout */
2563                 f = ast_read(chan);
2564                 if (f == NULL)
2565                         break; /* no frame */
2566                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2567                         done = 1;       /* force a break */
2568                 else if (f->frametype == AST_FRAME_TEXT) {              /* what we want */
2569                         buf = ast_strndup((char *) f->data, f->datalen);        /* dup and break */
2570                         done = 1;
2571                 }
2572                 ast_frfree(f);
2573         }
2574         return buf;
2575 }
2576
2577 int ast_sendtext(struct ast_channel *chan, const char *text)
2578 {
2579         int res = 0;
2580         /* Stop if we're a zombie or need a soft hangup */
2581         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2582                 return -1;
2583         CHECK_BLOCKING(chan);
2584         if (chan->tech->send_text)
2585                 res = chan->tech->send_text(chan, text);
2586         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2587         return res;
2588 }
2589
2590 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2591 {
2592         /* Device does not support DTMF tones, lets fake
2593          * it by doing our own generation. */
2594         static const char* dtmf_tones[] = {
2595                 "941+1336", /* 0 */
2596                 "697+1209", /* 1 */
2597                 "697+1336", /* 2 */
2598                 "697+1477", /* 3 */
2599                 "770+1209", /* 4 */
2600                 "770+1336", /* 5 */
2601                 "770+1477", /* 6 */
2602                 "852+1209", /* 7 */
2603                 "852+1336", /* 8 */
2604                 "852+1477", /* 9 */
2605                 "697+1633", /* A */
2606                 "770+1633", /* B */
2607                 "852+1633", /* C */
2608                 "941+1633", /* D */
2609                 "941+1209", /* * */
2610                 "941+1477"  /* # */
2611         };
2612
2613         if (!chan->tech->send_digit_begin)
2614                 return 0;
2615
2616         if (!chan->tech->send_digit_begin(chan, digit))
2617                 return 0;
2618
2619         if (digit >= '0' && digit <='9')
2620                 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2621         else if (digit >= 'A' && digit <= 'D')
2622                 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2623         else if (digit == '*')
2624                 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2625         else if (digit == '#')
2626                 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2627         else {
2628                 /* not handled */
2629                 ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2630         }
2631
2632         return 0;
2633 }
2634
2635 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2636 {
2637         int res = -1;
2638
2639         if (chan->tech->send_digit_end)
2640                 res = chan->tech->send_digit_end(chan, digit, duration);
2641
2642         if (res && chan->generator)
2643                 ast_playtones_stop(chan);
2644         
2645         return 0;
2646 }
2647
2648 int ast_senddigit(struct ast_channel *chan, char digit)
2649 {
2650         if (chan->tech->send_digit_begin) {
2651                 ast_senddigit_begin(chan, digit);
2652                 ast_safe_sleep(chan, AST_DEFAULT_EMULATE_DTMF_DURATION);
2653         }
2654         
2655         return ast_senddigit_end(chan, digit, AST_DEFAULT_EMULATE_DTMF_DURATION);
2656 }
2657
2658 int ast_prod(struct ast_channel *chan)
2659 {
2660         struct ast_frame a = { AST_FRAME_VOICE };
2661         char nothing[128];
2662
2663         /* Send an empty audio frame to get things moving */
2664         if (chan->_state != AST_STATE_UP) {
2665                 ast_debug(1, "Prodding channel '%s'\n", chan->name);
2666                 a.subclass = chan->rawwriteformat;
2667                 a.data = nothing + AST_FRIENDLY_OFFSET;
2668                 a.src = "ast_prod";
2669                 if (ast_write(chan, &a))
2670                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2671         }
2672         return 0;
2673 }
2674
2675 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2676 {
2677         int res;
2678         if (!chan->tech->write_video)
2679                 return 0;
2680         res = ast_write(chan, fr);
2681         if (!res)
2682                 res = 1;
2683         return res;
2684 }
2685
2686 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2687 {
2688         int res = -1;
2689         struct ast_frame *f = NULL;
2690
2691         /* Stop if we're a zombie or need a soft hangup */
2692         ast_channel_lock(chan);
2693         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2694                 goto done;
2695
2696         /* Handle any pending masquerades */
2697         if (chan->masq && ast_do_masquerade(chan)) {
2698                 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2699                 goto done;
2700         }
2701         if (chan->masqr) {
2702                 res = 0;        /* XXX explain, why 0 ? */
2703                 goto done;
2704         }
2705         if (chan->generatordata) {
2706                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2707                         ast_deactivate_generator(chan);
2708                 else {
2709                         if (fr->frametype == AST_FRAME_DTMF_END) {
2710                                 /* There is a generator running while we're in the middle of a digit.
2711                                  * It's probably inband DTMF, so go ahead and pass it so it can
2712                                  * stop the generator */
2713                                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2714                                 ast_channel_unlock(chan);
2715                                 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2716                                 ast_channel_lock(chan);
2717                                 CHECK_BLOCKING(chan);
2718                         } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
2719                                 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
2720                                 res = (chan->tech->indicate == NULL) ? 0 :
2721                                         chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2722                         }
2723                         res = 0;        /* XXX explain, why 0 ? */
2724                         goto done;
2725                 }
2726         }
2727         /* High bit prints debugging */
2728         if (chan->fout & DEBUGCHAN_FLAG)
2729                 ast_frame_dump(chan->name, fr, ">>");
2730         CHECK_BLOCKING(chan);
2731         switch (fr->frametype) {
2732         case AST_FRAME_CONTROL:
2733                 res = (chan->tech->indicate == NULL) ? 0 :
2734                         chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2735                 break;
2736         case AST_FRAME_DTMF_BEGIN:
2737                 send_dtmf_event(chan, "Sent", fr->subclass, "Yes", "No");
2738                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2739                 ast_channel_unlock(chan);
2740                 res = ast_senddigit_begin(chan, fr->subclass);
2741                 ast_channel_lock(chan);
2742                 CHECK_BLOCKING(chan);
2743                 break;
2744         case AST_FRAME_DTMF_END:
2745                 send_dtmf_event(chan, "Sent", fr->subclass, "No", "Yes");
2746                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2747                 ast_channel_unlock(chan);
2748                 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2749                 ast_channel_lock(chan);
2750                 CHECK_BLOCKING(chan);
2751                 break;
2752         case AST_FRAME_TEXT:
2753                 if (fr->subclass == AST_FORMAT_T140) {
2754                         res = (chan->tech->write_text == NULL) ? 0 :
2755                                 chan->tech->write_text(chan, fr);
2756                 } else {
2757                         res = (chan->tech->send_text == NULL) ? 0 :
2758                                 chan->tech->send_text(chan, (char *) fr->data);
2759                 }
2760                 break;
2761         case AST_FRAME_HTML:
2762                 res = (chan->tech->send_html == NULL) ? 0 :
2763                         chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2764                 break;
2765         case AST_FRAME_VIDEO:
2766                 /* XXX Handle translation of video codecs one day XXX */
2767                 res = (chan->tech->write_video == NULL) ? 0 :
2768                         chan->tech->write_video(chan, fr);
2769                 break;
2770         case AST_FRAME_MODEM:
2771                 res = (chan->tech->write == NULL) ? 0 :
2772                         chan->tech->write(chan, fr);
2773                 break;
2774         case AST_FRAME_VOICE:
2775                 if (chan->tech->write == NULL)
2776                         break;  /*! \todo XXX should return 0 maybe ? */
2777
2778                 /* If someone is whispering on this channel then we must ensure that we are always getting signed linear frames */
2779                 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2780                         if (fr->subclass == AST_FORMAT_SLINEAR)
2781                                 f = fr;
2782                         else {
2783                                 ast_mutex_lock(&chan->whisper->lock);
2784                                 if (chan->writeformat != AST_FORMAT_SLINEAR) {
2785                                         /* Rebuild the translation path and set our write format back to signed linear */
2786                                         chan->whisper->original_format = chan->writeformat;
2787                                         ast_set_write_format(chan, AST_FORMAT_SLINEAR);
2788                                         if (chan->whisper->path)
2789                                                 ast_translator_free_path(chan->whisper->path);
2790                                         chan->whisper->path = ast_translator_build_path(AST_FORMAT_SLINEAR, chan->whisper->original_format);
2791                                 }
2792                                 /* Translate frame using the above translation path */
2793                                 f = (chan->whisper->path) ? ast_translate(chan->whisper->path, fr, 0) : fr;
2794                                 ast_mutex_unlock(&chan->whisper->lock);
2795                         }
2796                 } else {
2797                         /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2798                         if (fr->subclass == chan->rawwriteformat)
2799                                 f = fr;
2800                         else
2801                                 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2802                 }
2803
2804                 /* If we have no frame of audio, then we have to bail out */
2805                 if (f == NULL) {
2806                         res = 0;
2807                         break;
2808                 }
2809
2810                 /* If spies are on the channel then queue the frame out to them */
2811                 if (chan->spies)
2812                         queue_frame_to_spies(chan, f, SPY_WRITE);
2813
2814                 /* If Monitor is running on this channel, then we have to write frames out there too */
2815                 if (chan->monitor && chan->monitor->write_stream) {
2816                         /* XXX must explain this code */
2817 #ifndef MONITOR_CONSTANT_DELAY
2818                         int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2819                         if (jump >= 0) {
2820                                 jump = chan->insmpl - chan->outsmpl;
2821                                 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
2822                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2823                                 chan->outsmpl += jump + f->samples;
2824                         } else
2825                                 chan->outsmpl += f->samples;
2826 #else
2827                         int jump = chan->insmpl - chan->outsmpl;
2828                         if (jump - MONITOR_DELAY >= 0) {
2829                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2830                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2831                                 chan->outsmpl += jump;
2832                         } else
2833                                 chan->outsmpl += f->samples;
2834 #endif
2835                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2836                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2837                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2838                         }
2839                 }
2840
2841                 /* Finally the good part! Write this out to the channel */
2842                 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2843                         /* frame is assumed to be in SLINEAR, since that is
2844                            required for whisper mode */
2845                         ast_frame_adjust_volume(f, -2);
2846                         if (ast_slinfactory_available(&chan->whisper->sf) >= f->samples) {
2847                                 short buf[f->samples];
2848                                 struct ast_frame whisper = {
2849                                         .frametype = AST_FRAME_VOICE,
2850                                         .subclass = AST_FORMAT_SLINEAR,
2851                                         .data = buf,
2852                                         .datalen = sizeof(buf),
2853                                         .samples = f->samples,
2854                                 };
2855                                 
2856                                 ast_mutex_lock(&chan->whisper->lock);
2857                                 if (ast_slinfactory_read(&chan->whisper->sf, buf, f->samples))
2858                                         ast_frame_slinear_sum(f, &whisper);
2859                                 ast_mutex_unlock(&chan->whisper->lock);
2860                         }
2861                         /* and now put it through the regular translator */
2862                         f = (chan->writetrans) ? ast_translate(chan->writetrans, f, 0) : f;
2863                 }
2864                 res = f ? chan->tech->write(chan, f) : 0;
2865                 break;
2866         case AST_FRAME_NULL:
2867         case AST_FRAME_IAX:
2868                 /* Ignore these */
2869                 res = 0;
2870                 break;
2871         default:
2872                 /* At this point, fr is the incoming frame and f is NULL.  Channels do
2873                  * not expect to get NULL as a frame pointer and will segfault.  Hence,
2874                  * we output the original frame passed in. */
2875                 res = chan->tech->write(chan, fr);
2876                 break;
2877         }
2878
2879         if (f && f != fr)
2880                 ast_frfree(f);
2881         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2882         /* Consider a write failure to force a soft hangup */
2883         if (res < 0)
2884                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2885         else {
2886                 chan->fout = FRAMECOUNT_INC(chan->fout);
2887         }
2888 done:
2889         ast_channel_unlock(chan);
2890         return res;
2891 }
2892
2893 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2894                       struct ast_trans_pvt **trans, const int direction)
2895 {
2896         int native;
2897         int res;
2898         
2899         /* Make sure we only consider audio */
2900         fmt &= AST_FORMAT_AUDIO_MASK;
2901         
2902         native = chan->nativeformats;
2903         /* Find a translation path from the native format to one of the desired formats */
2904         if (!direction)
2905                 /* reading */
2906                 res = ast_translator_best_choice(&fmt, &native);
2907         else
2908                 /* writing */
2909                 res = ast_translator_best_choice(&native, &fmt);
2910
2911         if (res < 0) {
2912                 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2913                         ast_getformatname(native), ast_getformatname(fmt));
2914                 return -1;
2915         }
2916         
2917         /* Now we have a good choice for both. */
2918         ast_channel_lock(chan);
2919
2920         if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2921                 /* the channel is already in these formats, so nothing to do */
2922                 ast_channel_unlock(chan);
2923                 return 0;
2924         }
2925
2926         *rawformat = native;
2927         /* User perspective is fmt */
2928         *format = fmt;
2929         /* Free any read translation we have right now */
2930         if (*trans)
2931                 ast_translator_free_path(*trans);
2932         /* Build a translation path from the raw format to the desired format */
2933         if (!direction)
2934                 /* reading */
2935                 *trans = ast_translator_build_path(*format, *rawformat);
2936         else
2937                 /* writing */
2938                 *trans = ast_translator_build_path(*rawformat, *format);
2939         ast_channel_unlock(chan);
2940         ast_debug(1, "Set channel %s to %s format %s\n", chan->name,
2941                 direction ? "write" : "read", ast_getformatname(fmt));
2942         return 0;
2943 }
2944
2945 int ast_set_read_format(struct ast_channel *chan, int fmt)
2946 {
2947         return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2948                           &chan->readtrans, 0);
2949 }
2950
2951 int ast_set_write_format(struct ast_channel *chan, int fmt)
2952 {
2953         return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2954                           &chan->writetrans, 1);
2955 }
2956
2957 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)
2958 {
2959         int dummy_outstate;
2960         int cause = 0;
2961         struct ast_channel *chan;
2962         int res = 0;
2963         
2964         if (outstate)
2965                 *outstate = 0;
2966         else
2967                 outstate = &dummy_outstate;     /* make outstate always a valid pointer */
2968
2969         chan = ast_request(type, format, data, &cause);
2970         if (!chan) {
2971                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2972                 /* compute error and return */
2973                 if (cause == AST_CAUSE_BUSY)
2974                         *outstate = AST_CONTROL_BUSY;
2975                 else if (cause == AST_CAUSE_CONGESTION)
2976                         *outstate = AST_CONTROL_CONGESTION;
2977                 return NULL;
2978         }
2979
2980         if (oh) {
2981                 if (oh->vars)   
2982                         ast_set_variables(chan, oh->vars);
2983                 /* XXX why is this necessary, for the parent_channel perhaps ? */
2984                 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2985                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2986                 if (oh->parent_channel) {
2987                         ast_channel_inherit_variables(oh->parent_channel, chan);
2988                         ast_channel_datastore_inherit(oh->parent_channel, chan);
2989                 }
2990                 if (oh->account)
2991                         ast_cdr_setaccount(chan, oh->account);  
2992         }
2993         ast_set_callerid(chan, cid_num, cid_name, cid_num);
2994
2995         
2996
2997         if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2998                                 to keep from throwing off the basic order of the universe,
2999                                 we will try to keep this cdr from getting posted. */
3000                 chan->cdr = ast_cdr_alloc();
3001                 ast_cdr_init(chan->cdr, chan);
3002                 ast_cdr_start(chan->cdr);
3003         }
3004         if (ast_call(chan, data, 0)) {  /* ast_call failed... */
3005                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
3006         } else {
3007                 res = 1;        /* mark success in case chan->_state is already AST_STATE_UP */
3008                 while (timeout && chan->_state != AST_STATE_UP) {
3009                         struct ast_frame *f;
3010                         res = ast_waitfor(chan, timeout);
3011                         if (res <= 0) /* error, timeout, or done */
3012                                 break;
3013                         if (timeout > -1)
3014                                 timeout = res;
3015                         f = ast_read(chan);
3016                         if (!f) {
3017                                 *outstate = AST_CONTROL_HANGUP;
3018                                 res = 0;
3019                                 break;
3020                         }
3021                         if (f->frametype == AST_FRAME_CONTROL) {
3022                                 switch (f->subclass) {
3023                                 case AST_CONTROL_RINGING:       /* record but keep going */
3024                                         *outstate = f->subclass;
3025                                         break;
3026
3027                                 case AST_CONTROL_BUSY:
3028                                 case AST_CONTROL_CONGESTION:
3029                                 case AST_CONTROL_ANSWER:
3030                                         *outstate = f->subclass;
3031                                         timeout = 0;            /* trick to force exit from the while() */
3032                                         break;
3033
3034                                 /* Ignore these */
3035                                 case AST_CONTROL_PROGRESS:
3036                                 case AST_CONTROL_PROCEEDING:
3037                                 case AST_CONTROL_HOLD:
3038                                 case AST_CONTROL_UNHOLD:
3039                                 case AST_CONTROL_VIDUPDATE:
3040                                 case -1:                        /* Ignore -- just stopping indications */
3041                                         break;
3042
3043                                 default:
3044                                         ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
3045                                 }
3046                         }
3047                      &nbs