Merged revisions 163448 via svnmerge from
[asterisk/asterisk.git] / include / asterisk / channel.h
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  * \brief General Asterisk PBX channel definitions.
21  * \par See also:
22  *  \arg \ref Def_Channel
23  *  \arg \ref channel_drivers
24  */
25
26 /*! \page Def_Channel Asterisk Channels
27         \par What is a Channel?
28         A phone call through Asterisk consists of an incoming
29         connection and an outbound connection. Each call comes
30         in through a channel driver that supports one technology,
31         like SIP, DAHDI, IAX2 etc. 
32         \par
33         Each channel driver, technology, has it's own private
34         channel or dialog structure, that is technology-dependent.
35         Each private structure is "owned" by a generic Asterisk
36         channel structure, defined in channel.h and handled by
37         channel.c .
38         \par Call scenario
39         This happens when an incoming call arrives to Asterisk
40         -# Call arrives on a channel driver interface
41         -# Channel driver creates a PBX channel and starts a 
42            pbx thread on the channel
43         -# The dial plan is executed
44         -# At this point at least two things can happen:
45                 -# The call is answered by Asterisk and 
46                    Asterisk plays a media stream or reads media
47                 -# The dial plan forces Asterisk to create an outbound 
48                    call somewhere with the dial (see \ref app_dial.c)
49                    application
50         .
51
52         \par Bridging channels
53         If Asterisk dials out this happens:
54         -# Dial creates an outbound PBX channel and asks one of the
55            channel drivers to create a call
56         -# When the call is answered, Asterisk bridges the media streams
57            so the caller on the first channel can speak with the callee
58            on the second, outbound channel
59         -# In some cases where we have the same technology on both
60            channels and compatible codecs, a native bridge is used.
61            In a native bridge, the channel driver handles forwarding
62            of incoming audio to the outbound stream internally, without
63            sending audio frames through the PBX.
64         -# In SIP, theres an "external native bridge" where Asterisk
65            redirects the endpoint, so audio flows directly between the
66            caller's phone and the callee's phone. Signalling stays in
67            Asterisk in order to be able to provide a proper CDR record
68            for the call.
69
70         
71         \par Masquerading channels
72         In some cases, a channel can masquerade itself into another
73         channel. This happens frequently in call transfers, where 
74         a new channel takes over a channel that is already involved
75         in a call. The new channel sneaks in and takes over the bridge
76         and the old channel, now a zombie, is hung up.
77         
78         \par Reference
79         \arg channel.c - generic functions
80         \arg channel.h - declarations of functions, flags and structures
81         \arg translate.h - Transcoding support functions
82         \arg \ref channel_drivers - Implemented channel drivers
83         \arg \ref Def_Frame Asterisk Multimedia Frames
84         \arg \ref Def_Bridge
85
86 */
87 /*! \page Def_Bridge Asterisk Channel Bridges
88
89         In Asterisk, there's several media bridges. 
90
91         The Core bridge handles two channels (a "phone call") and bridge
92         them together.
93         
94         The conference bridge (meetme) handles several channels simultaneously
95         with the support of an external timer (DAHDI timer). This is used
96         not only by the Conference application (meetme) but also by the
97         page application and the SLA system introduced in 1.4.
98         The conference bridge does not handle video.
99
100         When two channels of the same type connect, the channel driver
101         or the media subsystem used by the channel driver (i.e. RTP)
102         can create a native bridge without sending media through the
103         core.
104
105         Native briding can be disabled by a number of reasons,
106         like DTMF being needed by the core or codecs being incompatible
107         so a transcoding module is needed.
108
109 References:
110         \li \see ast_channel_early_bridge()
111         \li \see ast_channel_bridge()
112         \li \see app_meetme.c
113         \li \ref AstRTPbridge
114         \li \see ast_rtp_bridge() 
115         \li \ref Def_Channel
116 */
117
118 /*! \page AstFileDesc File descriptors 
119         Asterisk File descriptors are connected to each channel (see \ref Def_Channel)
120         in the \ref ast_channel structure.
121 */
122
123 #ifndef _ASTERISK_CHANNEL_H
124 #define _ASTERISK_CHANNEL_H
125
126 #include "asterisk/abstract_jb.h"
127
128 #ifdef HAVE_SYS_POLL_H
129 #include <sys/poll.h>
130 #else
131 #include "asterisk/poll-compat.h"
132 #endif
133
134 #if defined(__cplusplus) || defined(c_plusplus)
135 extern "C" {
136 #endif
137
138 #define AST_MAX_EXTENSION       80      /*!< Max length of an extension */
139 #define AST_MAX_CONTEXT         80      /*!< Max length of a context */
140 #define AST_CHANNEL_NAME        80      /*!< Max length of an ast_channel name */
141 #define MAX_LANGUAGE            20      /*!< Max length of the language setting */
142 #define MAX_MUSICCLASS          80      /*!< Max length of the music class setting */
143
144 #include "asterisk/frame.h"
145 #include "asterisk/sched.h"
146 #include "asterisk/chanvars.h"
147 #include "asterisk/config.h"
148 #include "asterisk/lock.h"
149 #include "asterisk/cdr.h"
150 #include "asterisk/utils.h"
151 #include "asterisk/linkedlists.h"
152 #include "asterisk/stringfields.h"
153 #include "asterisk/datastore.h"
154
155 #define DATASTORE_INHERIT_FOREVER       INT_MAX
156
157 #define AST_MAX_FDS             10
158 /*
159  * We have AST_MAX_FDS file descriptors in a channel.
160  * Some of them have a fixed use:
161  */
162 #define AST_ALERT_FD    (AST_MAX_FDS-1)         /*!< used for alertpipe */
163 #define AST_TIMING_FD   (AST_MAX_FDS-2)         /*!< used for timingfd */
164 #define AST_AGENT_FD    (AST_MAX_FDS-3)         /*!< used by agents for pass through */
165 #define AST_GENERATOR_FD        (AST_MAX_FDS-4) /*!< used by generator */
166
167 enum ast_bridge_result {
168         AST_BRIDGE_COMPLETE = 0,
169         AST_BRIDGE_FAILED = -1,
170         AST_BRIDGE_FAILED_NOWARN = -2,
171         AST_BRIDGE_RETRY = -3,
172 };
173
174 typedef unsigned long long ast_group_t;
175
176 /*! \todo Add an explanation of an Asterisk generator 
177 */
178 struct ast_generator {
179         void *(*alloc)(struct ast_channel *chan, void *params);
180         void (*release)(struct ast_channel *chan, void *data);
181         /*! This function gets called with the channel unlocked, but is called in
182          *  the context of the channel thread so we know the channel is not going
183          *  to disappear.  This callback is responsible for locking the channel as
184          *  necessary. */
185         int (*generate)(struct ast_channel *chan, void *data, int len, int samples);
186         /*! This gets called when DTMF_END frames are read from the channel */
187         void (*digit)(struct ast_channel *chan, char digit);
188 };
189
190 /*! \brief Structure for all kinds of caller ID identifications.
191  * \note All string fields here are malloc'ed, so they need to be
192  * freed when the structure is deleted.
193  * Also, NULL and "" must be considered equivalent.
194  * 
195  * SIP and IAX2 has utf8 encoded Unicode caller ID names.
196  * In some cases, we also have an alternative (RPID) E.164 number that can be used
197  * as caller ID on numeric E.164 phone networks (DAHDI or SIP/IAX2 to pstn gateway).
198  *
199  * \todo Implement settings for transliteration between UTF8 caller ID names in
200  *       to Ascii Caller ID's (DAHDI). Ã–sten Ã…sklund might be transliterated into
201  *       Osten Asklund or Oesten Aasklund depending upon language and person...
202  *       We need automatic routines for incoming calls and static settings for
203  *       our own accounts.
204  */
205 struct ast_callerid {
206         char *cid_dnid;         /*!< Malloc'd Dialed Number Identifier */
207         char *cid_num;          /*!< Malloc'd Caller Number */
208         char *cid_name;         /*!< Malloc'd Caller Name (ASCII) */
209         char *cid_ani;          /*!< Malloc'd ANI */
210         char *cid_rdnis;        /*!< Malloc'd RDNIS */
211         int cid_pres;           /*!< Callerid presentation/screening */
212         int cid_ani2;           /*!< Callerid ANI 2 (Info digits) */
213         int cid_ton;            /*!< Callerid Type of Number */
214         int cid_tns;            /*!< Callerid Transit Network Select */
215 };
216
217 /*! \brief 
218         Structure to describe a channel "technology", ie a channel driver 
219         See for examples:
220         \arg chan_iax2.c - The Inter-Asterisk exchange protocol
221         \arg chan_sip.c - The SIP channel driver
222         \arg chan_dahdi.c - PSTN connectivity (TDM, PRI, T1/E1, FXO, FXS)
223
224         If you develop your own channel driver, this is where you
225         tell the PBX at registration of your driver what properties
226         this driver supports and where different callbacks are 
227         implemented.
228 */
229 struct ast_channel_tech {
230         const char * const type;
231         const char * const description;
232
233         int capabilities;               /*!< Bitmap of formats this channel can handle */
234
235         int properties;                 /*!< Technology Properties */
236
237         /*! \brief Requester - to set up call data structures (pvt's) */
238         struct ast_channel *(* const requester)(const char *type, int format, void *data, int *cause);
239
240         int (* const devicestate)(void *data);  /*!< Devicestate call back */
241
242         /*! 
243          * \brief Start sending a literal DTMF digit 
244          *
245          * \note The channel is not locked when this function gets called. 
246          */
247         int (* const send_digit_begin)(struct ast_channel *chan, char digit);
248
249         /*! 
250          * \brief Stop sending a literal DTMF digit 
251          *
252          * \note The channel is not locked when this function gets called. 
253          */
254         int (* const send_digit_end)(struct ast_channel *chan, char digit, unsigned int duration);
255
256         /*! \brief Call a given phone number (address, etc), but don't
257            take longer than timeout seconds to do so.  */
258         int (* const call)(struct ast_channel *chan, char *addr, int timeout);
259
260         /*! \brief Hangup (and possibly destroy) the channel */
261         int (* const hangup)(struct ast_channel *chan);
262
263         /*! \brief Answer the channel */
264         int (* const answer)(struct ast_channel *chan);
265
266         /*! \brief Read a frame, in standard format (see frame.h) */
267         struct ast_frame * (* const read)(struct ast_channel *chan);
268
269         /*! \brief Write a frame, in standard format (see frame.h) */
270         int (* const write)(struct ast_channel *chan, struct ast_frame *frame);
271
272         /*! \brief Display or transmit text */
273         int (* const send_text)(struct ast_channel *chan, const char *text);
274
275         /*! \brief Display or send an image */
276         int (* const send_image)(struct ast_channel *chan, struct ast_frame *frame);
277
278         /*! \brief Send HTML data */
279         int (* const send_html)(struct ast_channel *chan, int subclass, const char *data, int len);
280
281         /*! \brief Handle an exception, reading a frame */
282         struct ast_frame * (* const exception)(struct ast_channel *chan);
283
284         /*! \brief Bridge two channels of the same type together */
285         enum ast_bridge_result (* const bridge)(struct ast_channel *c0, struct ast_channel *c1, int flags,
286                                                 struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
287
288         /*! \brief Bridge two channels of the same type together (early) */
289         enum ast_bridge_result (* const early_bridge)(struct ast_channel *c0, struct ast_channel *c1);
290
291         /*! \brief Indicate a particular condition (e.g. AST_CONTROL_BUSY or AST_CONTROL_RINGING or AST_CONTROL_CONGESTION */
292         int (* const indicate)(struct ast_channel *c, int condition, const void *data, size_t datalen);
293
294         /*! \brief Fix up a channel:  If a channel is consumed, this is called.  Basically update any ->owner links */
295         int (* const fixup)(struct ast_channel *oldchan, struct ast_channel *newchan);
296
297         /*! \brief Set a given option */
298         int (* const setoption)(struct ast_channel *chan, int option, void *data, int datalen);
299
300         /*! \brief Query a given option */
301         int (* const queryoption)(struct ast_channel *chan, int option, void *data, int *datalen);
302
303         /*! \brief Blind transfer other side (see app_transfer.c and ast_transfer() */
304         int (* const transfer)(struct ast_channel *chan, const char *newdest);
305
306         /*! \brief Write a frame, in standard format */
307         int (* const write_video)(struct ast_channel *chan, struct ast_frame *frame);
308
309         /*! \brief Write a text frame, in standard format */
310         int (* const write_text)(struct ast_channel *chan, struct ast_frame *frame);
311
312         /*! \brief Find bridged channel */
313         struct ast_channel *(* const bridged_channel)(struct ast_channel *chan, struct ast_channel *bridge);
314
315         /*! \brief Provide additional read items for CHANNEL() dialplan function */
316         int (* func_channel_read)(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len);
317
318         /*! \brief Provide additional write items for CHANNEL() dialplan function */
319         int (* func_channel_write)(struct ast_channel *chan, const char *function, char *data, const char *value);
320
321         /*! \brief Retrieve base channel (agent and local) */
322         struct ast_channel* (* get_base_channel)(struct ast_channel *chan);
323         
324         /*! \brief Set base channel (agent and local) */
325         int (* set_base_channel)(struct ast_channel *chan, struct ast_channel *base);
326
327         /*! \brief Get the unique identifier for the PVT, i.e. SIP call-ID for SIP */
328         const char * (* get_pvt_uniqueid)(struct ast_channel *chan);
329 };
330
331 struct ast_epoll_data;
332
333 /*!
334  * The high bit of the frame count is used as a debug marker, so
335  * increments of the counters must be done with care.
336  * Please use c->fin = FRAMECOUNT_INC(c->fin) and the same for c->fout.
337  */
338 #define DEBUGCHAN_FLAG  0x80000000
339
340 /* XXX not ideal to evaluate x twice... */
341 #define FRAMECOUNT_INC(x)       ( ((x) & DEBUGCHAN_FLAG) | (((x)+1) & ~DEBUGCHAN_FLAG) )
342
343 /*!
344  * The current value of the debug flags is stored in the two
345  * variables global_fin and global_fout (declared in main/channel.c)
346  */
347 extern unsigned long global_fin, global_fout;
348
349 enum ast_channel_adsicpe {
350         AST_ADSI_UNKNOWN,
351         AST_ADSI_AVAILABLE,
352         AST_ADSI_UNAVAILABLE,
353         AST_ADSI_OFFHOOKONLY,
354 };
355
356 /*! 
357  * \brief ast_channel states
358  *
359  * \note Bits 0-15 of state are reserved for the state (up/down) of the line
360  *       Bits 16-32 of state are reserved for flags
361  */
362 enum ast_channel_state {
363         AST_STATE_DOWN,                 /*!< Channel is down and available */
364         AST_STATE_RESERVED,             /*!< Channel is down, but reserved */
365         AST_STATE_OFFHOOK,              /*!< Channel is off hook */
366         AST_STATE_DIALING,              /*!< Digits (or equivalent) have been dialed */
367         AST_STATE_RING,                 /*!< Line is ringing */
368         AST_STATE_RINGING,              /*!< Remote end is ringing */
369         AST_STATE_UP,                   /*!< Line is up */
370         AST_STATE_BUSY,                 /*!< Line is busy */
371         AST_STATE_DIALING_OFFHOOK,      /*!< Digits (or equivalent) have been dialed while offhook */
372         AST_STATE_PRERING,              /*!< Channel has detected an incoming call and is waiting for ring */
373
374         AST_STATE_MUTE = (1 << 16),     /*!< Do not transmit voice data */
375 };
376
377 /*!
378  * \brief Possible T38 states on channels
379  */
380 enum ast_t38_state {
381         T38_STATE_UNAVAILABLE,  /*!< T38 is unavailable on this channel or disabled by configuration */
382         T38_STATE_UNKNOWN,      /*!< The channel supports T38 but the current status is unknown */
383         T38_STATE_NEGOTIATING,  /*!< T38 is being negotiated */
384         T38_STATE_REJECTED,     /*!< Remote side has rejected our offer */
385         T38_STATE_NEGOTIATED,   /*!< T38 established */
386 };
387
388 /*! \brief Main Channel structure associated with a channel. 
389  * This is the side of it mostly used by the pbx and call management.
390  *
391  * \note XXX It is important to remember to increment .cleancount each time
392  *       this structure is changed. XXX
393  *
394  * \note When adding fields to this structure, it is important to add the field
395  *       'in position' with like-aligned fields, so as to keep the compiler from
396  *       having to add padding to align fields. The structure's fields are sorted
397  *       in this order: pointers, structures, long, int/enum, short, char. This
398  *       is especially important on 64-bit architectures, where mixing 4-byte
399  *       and 8-byte fields causes 4 bytes of padding to be added before many
400  *       8-byte fields.
401  */
402
403 struct ast_channel {
404         const struct ast_channel_tech *tech;            /*!< Technology (point to channel driver) */
405         void *tech_pvt;                                 /*!< Private data used by the technology driver */
406         void *music_state;                              /*!< Music State*/
407         void *generatordata;                            /*!< Current generator data if there is any */
408         struct ast_generator *generator;                /*!< Current active data generator */
409         struct ast_channel *_bridge;                    /*!< Who are we bridged to, if we're bridged.
410                                                              Who is proxying for us, if we are proxied (i.e. chan_agent).
411                                                              Do not access directly, use ast_bridged_channel(chan) */
412         struct ast_channel *masq;                       /*!< Channel that will masquerade as us */
413         struct ast_channel *masqr;                      /*!< Who we are masquerading as */
414         const char *blockproc;                          /*!< Procedure causing blocking */
415         const char *appl;                               /*!< Current application */
416         const char *data;                               /*!< Data passed to current application */
417         struct sched_context *sched;                    /*!< Schedule context */
418         struct ast_filestream *stream;                  /*!< Stream itself. */
419         struct ast_filestream *vstream;                 /*!< Video Stream itself. */
420         int (*timingfunc)(const void *data);
421         void *timingdata;
422         struct ast_pbx *pbx;                            /*!< PBX private structure for this channel */
423         struct ast_trans_pvt *writetrans;               /*!< Write translation path */
424         struct ast_trans_pvt *readtrans;                /*!< Read translation path */
425         struct ast_audiohook_list *audiohooks;
426         struct ast_cdr *cdr;                            /*!< Call Detail Record */
427         struct ind_tone_zone *zone;                     /*!< Tone zone as set in indications.conf or
428                                                              in the CHANNEL dialplan function */
429         struct ast_channel_monitor *monitor;            /*!< Channel monitoring */
430 #ifdef HAVE_EPOLL
431         struct ast_epoll_data *epfd_data[AST_MAX_FDS];
432 #endif
433
434         AST_DECLARE_STRING_FIELDS(
435                 AST_STRING_FIELD(name);                 /*!< ASCII unique channel name */
436                 AST_STRING_FIELD(language);             /*!< Language requested for voice prompts */
437                 AST_STRING_FIELD(musicclass);           /*!< Default music class */
438                 AST_STRING_FIELD(accountcode);          /*!< Account code for billing */
439                 AST_STRING_FIELD(call_forward);         /*!< Where to forward to if asked to dial on this interface */
440                 AST_STRING_FIELD(uniqueid);             /*!< Unique Channel Identifier */
441                 AST_STRING_FIELD(parkinglot);           /*! Default parking lot, if empty, default parking lot  */
442                 AST_STRING_FIELD(dialcontext);          /*!< Dial: Extension context that we were called from */
443         );
444         
445         struct timeval whentohangup;                    /*!< Non-zero, set to actual time when channel is to be hung up */
446         pthread_t blocker;                              /*!< If anyone is blocking, this is them */
447         ast_mutex_t lock_dont_use;                      /*!< Lock a channel for some operations. See ast_channel_lock() */
448         struct ast_callerid cid;                        /*!< Caller ID, name, presentation etc */
449         struct ast_frame dtmff;                         /*!< DTMF frame */
450         struct varshead varshead;                       /*!< A linked list for channel variables. See \ref AstChanVar */
451         ast_group_t callgroup;                          /*!< Call group for call pickups */
452         ast_group_t pickupgroup;                        /*!< Pickup group - which calls groups can be picked up? */
453         AST_LIST_HEAD_NOLOCK(, ast_frame) readq;
454         AST_LIST_ENTRY(ast_channel) chan_list;          /*!< For easy linking */
455         struct ast_jb jb;                               /*!< The jitterbuffer state */
456         struct timeval dtmf_tv;                         /*!< The time that an in process digit began, or the last digit ended */
457         AST_LIST_HEAD_NOLOCK(datastores, ast_datastore) datastores; /*!< Data stores on the channel */
458
459         unsigned long insmpl;                           /*!< Track the read/written samples for monitor use */
460         unsigned long outsmpl;                          /*!< Track the read/written samples for monitor use */
461
462         int fds[AST_MAX_FDS];                           /*!< File descriptors for channel -- Drivers will poll on
463                                                              these file descriptors, so at least one must be non -1.
464                                                              See \arg \ref AstFileDesc */
465         int cdrflags;                                   /*!< Call Detail Record Flags */
466         int _softhangup;                                /*!< Whether or not we have been hung up...  Do not set this value
467                                                              directly, use ast_softhangup() */
468         int fdno;                                       /*!< Which fd had an event detected on */
469         int streamid;                                   /*!< For streaming playback, the schedule ID */
470         int vstreamid;                                  /*!< For streaming video playback, the schedule ID */
471         int oldwriteformat;                             /*!< Original writer format */
472         int timingfd;                                   /*!< Timing fd */
473         enum ast_channel_state _state;                  /*!< State of line -- Don't write directly, use ast_setstate() */
474         int rings;                                      /*!< Number of rings so far */
475         int priority;                                   /*!< Dialplan: Current extension priority */
476         int macropriority;                              /*!< Macro: Current non-macro priority. See app_macro.c */
477         int amaflags;                                   /*!< Set BEFORE PBX is started to determine AMA flags */
478         enum ast_channel_adsicpe adsicpe;               /*!< Whether or not ADSI is detected on CPE */
479         unsigned int fin;                               /*!< Frames in counters. The high bit is a debug mask, so
480                                                              the counter is only in the remaining bits */
481         unsigned int fout;                              /*!< Frames out counters. The high bit is a debug mask, so
482                                                              the counter is only in the remaining bits */
483         int hangupcause;                                /*!< Why is the channel hanged up. See causes.h */
484         unsigned int flags;                             /*!< channel flags of AST_FLAG_ type */
485         int alertpipe[2];
486         int nativeformats;                              /*!< Kinds of data this channel can natively handle */
487         int readformat;                                 /*!< Requested read format */
488         int writeformat;                                /*!< Requested write format */
489         int rawreadformat;                              /*!< Raw read format */
490         int rawwriteformat;                             /*!< Raw write format */
491         unsigned int emulate_dtmf_duration;             /*!< Number of ms left to emulate DTMF for */
492 #ifdef HAVE_EPOLL
493         int epfd;
494 #endif
495         int visible_indication;                         /*!< Indication currently playing on the channel */
496
497         unsigned short transfercapability;              /*!< ISDN Transfer Capbility - AST_FLAG_DIGITAL is not enough */
498
499         char unused_old_dtmfq[AST_MAX_EXTENSION];                       /*!< (deprecated, use readq instead) Any/all queued DTMF characters */
500         char context[AST_MAX_CONTEXT];                  /*!< Dialplan: Current extension context */
501         char exten[AST_MAX_EXTENSION];                  /*!< Dialplan: Current extension number */
502         char macrocontext[AST_MAX_CONTEXT];             /*!< Macro: Current non-macro context. See app_macro.c */
503         char macroexten[AST_MAX_EXTENSION];             /*!< Macro: Current non-macro extension. See app_macro.c */
504         char emulate_dtmf_digit;                        /*!< Digit being emulated */
505 };
506
507 /*! \brief ast_channel_tech Properties */
508 enum {
509         /*! \brief Channels have this property if they can accept input with jitter; 
510          *         i.e. most VoIP channels */
511         AST_CHAN_TP_WANTSJITTER = (1 << 0),
512         /*! \brief Channels have this property if they can create jitter; 
513          *         i.e. most VoIP channels */
514         AST_CHAN_TP_CREATESJITTER = (1 << 1),
515 };
516
517 /*! \brief ast_channel flags */
518 enum {
519         /*! Queue incoming dtmf, to be released when this flag is turned off */
520         AST_FLAG_DEFER_DTMF =    (1 << 1),
521         /*! write should be interrupt generator */
522         AST_FLAG_WRITE_INT =     (1 << 2),
523         /*! a thread is blocking on this channel */
524         AST_FLAG_BLOCKING =      (1 << 3),
525         /*! This is a zombie channel */
526         AST_FLAG_ZOMBIE =        (1 << 4),
527         /*! There is an exception pending */
528         AST_FLAG_EXCEPTION =     (1 << 5),
529         /*! Listening to moh XXX anthm promises me this will disappear XXX */
530         AST_FLAG_MOH =           (1 << 6),
531         /*! This channel is spying on another channel */
532         AST_FLAG_SPYING =        (1 << 7),
533         /*! This channel is in a native bridge */
534         AST_FLAG_NBRIDGE =       (1 << 8),
535         /*! the channel is in an auto-incrementing dialplan processor,
536          *  so when ->priority is set, it will get incremented before
537          *  finding the next priority to run */
538         AST_FLAG_IN_AUTOLOOP =   (1 << 9),
539         /*! This is an outgoing call */
540         AST_FLAG_OUTGOING =      (1 << 10),
541         /*! A DTMF_BEGIN frame has been read from this channel, but not yet an END */
542         AST_FLAG_IN_DTMF =       (1 << 12),
543         /*! A DTMF_END was received when not IN_DTMF, so the length of the digit is 
544          *  currently being emulated */
545         AST_FLAG_EMULATE_DTMF =  (1 << 13),
546         /*! This is set to tell the channel not to generate DTMF begin frames, and
547          *  to instead only generate END frames. */
548         AST_FLAG_END_DTMF_ONLY = (1 << 14),
549         /*! Flag to show channels that this call is hangup due to the fact that the call
550             was indeed anwered, but in another channel */
551         AST_FLAG_ANSWERED_ELSEWHERE = (1 << 15),
552         /*! This flag indicates that on a masquerade, an active stream should not
553          *  be carried over */
554         AST_FLAG_MASQ_NOSTREAM = (1 << 16),
555         /*! This flag indicates that the hangup exten was run when the bridge terminated,
556          *  a message aimed at preventing a subsequent hangup exten being run at the pbx_run
557          *  level */
558         AST_FLAG_BRIDGE_HANGUP_RUN = (1 << 17),
559 };
560
561 /*! \brief ast_bridge_config flags */
562 enum {
563         AST_FEATURE_PLAY_WARNING = (1 << 0),
564         AST_FEATURE_REDIRECT =     (1 << 1),
565         AST_FEATURE_DISCONNECT =   (1 << 2),
566         AST_FEATURE_ATXFER =       (1 << 3),
567         AST_FEATURE_AUTOMON =      (1 << 4),
568         AST_FEATURE_PARKCALL =     (1 << 5),
569         AST_FEATURE_AUTOMIXMON =   (1 << 6),
570         AST_FEATURE_NO_H_EXTEN =   (1 << 7),
571 };
572
573 /*! \brief bridge configuration */
574 struct ast_bridge_config {
575         struct ast_flags features_caller;
576         struct ast_flags features_callee;
577         struct timeval start_time;
578         long feature_timer;
579         long timelimit;
580         long play_warning;
581         long warning_freq;
582         const char *warning_sound;
583         const char *end_sound;
584         const char *start_sound;
585         int firstpass;
586         unsigned int flags;
587         void (* end_bridge_callback)(void *);   /*!< A callback that is called after a bridge attempt */
588         void *end_bridge_callback_data;         /*!< Data passed to the callback */
589         /*! If the end_bridge_callback_data refers to a channel which no longer is going to
590          * exist when the end_bridge_callback is called, then it needs to be fixed up properly
591          */
592         void (*end_bridge_callback_data_fixup)(struct ast_bridge_config *bconfig, struct ast_channel *originator, struct ast_channel *terminator);
593 };
594
595 struct chanmon;
596
597 struct outgoing_helper {
598         const char *context;
599         const char *exten;
600         int priority;
601         const char *cid_num;
602         const char *cid_name;
603         const char *account;
604         struct ast_variable *vars;
605         struct ast_channel *parent_channel;
606 };
607
608 enum {
609         AST_CDR_TRANSFER =   (1 << 0),
610         AST_CDR_FORWARD =    (1 << 1),
611         AST_CDR_CALLWAIT =   (1 << 2),
612         AST_CDR_CONFERENCE = (1 << 3),
613 };
614
615 enum {
616         /*! Soft hangup by device */
617         AST_SOFTHANGUP_DEV =       (1 << 0),
618         /*! Soft hangup for async goto */
619         AST_SOFTHANGUP_ASYNCGOTO = (1 << 1),
620         AST_SOFTHANGUP_SHUTDOWN =  (1 << 2),
621         AST_SOFTHANGUP_TIMEOUT =   (1 << 3),
622         AST_SOFTHANGUP_APPUNLOAD = (1 << 4),
623         AST_SOFTHANGUP_EXPLICIT =  (1 << 5),
624         AST_SOFTHANGUP_UNBRIDGE =  (1 << 6),
625 };
626
627
628 /*! \brief Channel reload reasons for manager events at load or reload of configuration */
629 enum channelreloadreason {
630         CHANNEL_MODULE_LOAD,
631         CHANNEL_MODULE_RELOAD,
632         CHANNEL_CLI_RELOAD,
633         CHANNEL_MANAGER_RELOAD,
634 };
635
636 /*! 
637  * \note None of the datastore API calls lock the ast_channel they are using.
638  *       So, the channel should be locked before calling the functions that
639  *       take a channel argument.
640  */
641
642 /*! 
643  * \brief Create a channel data store object
644  * \deprecated You should use the ast_datastore_alloc() generic function instead.
645  */
646 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
647         __attribute__((deprecated));
648
649 /*!
650  * \brief Free a channel data store object
651  * \deprecated You should use the ast_datastore_free() generic function instead.
652  */
653 int ast_channel_datastore_free(struct ast_datastore *datastore)
654         __attribute__((deprecated));
655
656 /*! \brief Inherit datastores from a parent to a child. */
657 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to);
658
659 /*! 
660  * \brief Add a datastore to a channel 
661  *
662  * \note The channel should be locked before calling this function.
663  *
664  * \retval 0 success
665  * \retval non-zero failure
666  */
667
668 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore);
669
670 /*! 
671  * \brief Remove a datastore from a channel 
672  *
673  * \note The channel should be locked before calling this function.
674  *
675  * \retval 0 success
676  * \retval non-zero failure
677  */
678 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore);
679
680 /*! 
681  * \brief Find a datastore on a channel 
682  *
683  * \note The channel should be locked before calling this function.
684  *
685  * \note The datastore returned from this function must not be used if the
686  *       reference to the channel is released.
687  *
688  * \retval pointer to the datastore if found
689  * \retval NULL if not found
690  */
691 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid);
692
693 /*! \brief Change the state of a channel */
694 int ast_setstate(struct ast_channel *chan, enum ast_channel_state);
695
696 /*! 
697  * \brief Create a channel structure 
698  *
699  * \retval NULL failure
700  * \retval non-NULL successfully allocated channel
701  *
702  * \note By default, new channels are set to the "s" extension
703  *       and "default" context.
704  */
705 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, ...) __attribute__((format(printf, 9, 10)));
706
707 /*! 
708  * \brief Queue an outgoing frame 
709  *
710  * \note The channel does not need to be locked before calling this function.
711  */
712 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *f);
713
714 /*!
715  * \brief Queue an outgoing frame to the head of the frame queue
716  *
717  * \param chan the channel to queue the frame on
718  * \param f the frame to queue.  Note that this frame will be duplicated by
719  *        this function.  It is the responsibility of the caller to handle
720  *        freeing the memory associated with the frame being passed if
721  *        necessary.
722  *
723  * \retval 0 success
724  * \retval non-zero failure
725  */
726 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *f);
727
728 /*! 
729  * \brief Queue a hangup frame 
730  *
731  * \note The channel does not need to be locked before calling this function.
732  */
733 int ast_queue_hangup(struct ast_channel *chan);
734
735 /*! 
736  * \brief Queue a hangup frame with hangupcause set
737  *
738  * \note The channel does not need to be locked before calling this function.
739  * \param chan channel to queue frame onto
740  * \param cause the hangup cause
741  */
742 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause);
743
744 /*!
745  * \brief Queue a control frame with payload
746  *
747  * \param chan channel to queue frame onto
748  * \param control type of control frame
749  *
750  * \note The channel does not need to be locked before calling this function.
751  *
752  * \retval zero on success
753  * \retval non-zero on failure
754  */
755 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control);
756
757 /*!
758  * \brief Queue a control frame with payload
759  *
760  * \param chan channel to queue frame onto
761  * \param control type of control frame
762  * \param data pointer to payload data to be included in frame
763  * \param datalen number of bytes of payload data
764  *
765  * \retval 0 success
766  * \retval non-zero failure
767  *
768  * The supplied payload data is copied into the frame, so the caller's copy
769  * is not modified nor freed, and the resulting frame will retain a copy of
770  * the data even if the caller frees their local copy.
771  *
772  * \note This method should be treated as a 'network transport'; in other
773  * words, your frames may be transferred across an IAX2 channel to another
774  * system, which may be a different endianness than yours. Because of this,
775  * you should ensure that either your frames will never be expected to work
776  * across systems, or that you always put your payload data into 'network byte
777  * order' before calling this function.
778  *
779  * \note The channel does not need to be locked before calling this function.
780  */
781 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
782                            const void *data, size_t datalen);
783
784 /*! 
785  * \brief Change channel name 
786  *
787  * \note The channel must be locked before calling this function.
788  */
789 void ast_change_name(struct ast_channel *chan, char *newname);
790
791 /*! \brief Free a channel structure */
792 void  ast_channel_free(struct ast_channel *);
793
794 /*! 
795  * \brief Requests a channel 
796  *
797  * \param type type of channel to request
798  * \param format requested channel format (codec)
799  * \param data data to pass to the channel requester
800  * \param status status
801  *
802  * Request a channel of a given type, with data as optional information used 
803  * by the low level module
804  *
805  * \retval NULL failure
806  * \retval non-NULL channel on success
807  */
808 struct ast_channel *ast_request(const char *type, int format, void *data, int *status);
809
810 /*!
811  * \brief Request a channel of a given type, with data as optional information used 
812  *        by the low level module and attempt to place a call on it
813  *
814  * \param type type of channel to request
815  * \param format requested channel format
816  * \param data data to pass to the channel requester
817  * \param timeout maximum amount of time to wait for an answer
818  * \param reason why unsuccessful (if unsuccessful)
819  * \param cid_num Caller-ID Number
820  * \param cid_name Caller-ID Name (ascii)
821  *
822  * \return Returns an ast_channel on success or no answer, NULL on failure.  Check the value of chan->_state
823  * to know if the call was answered or not.
824  */
825 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data,
826         int timeout, int *reason, const char *cid_num, const char *cid_name);
827
828 /*!
829  * \brief Request a channel of a given type, with data as optional information used 
830  * by the low level module and attempt to place a call on it
831  * \param type type of channel to request
832  * \param format requested channel format
833  * \param data data to pass to the channel requester
834  * \param timeout maximum amount of time to wait for an answer
835  * \param reason why unsuccessful (if unsuccessful)
836  * \param cid_num Caller-ID Number
837  * \param cid_name Caller-ID Name (ascii)
838  * \param oh Outgoing helper
839  * \return Returns an ast_channel on success or no answer, NULL on failure.  Check the value of chan->_state
840  * to know if the call was answered or not.
841  */
842 struct ast_channel *__ast_request_and_dial(const char *type, int format, void *data,
843         int timeout, int *reason, const char *cid_num, const char *cid_name, struct outgoing_helper *oh);
844
845 /*!\brief Register a channel technology (a new channel driver)
846  * Called by a channel module to register the kind of channels it supports.
847  * \param tech Structure defining channel technology or "type"
848  * \return Returns 0 on success, -1 on failure.
849  */
850 int ast_channel_register(const struct ast_channel_tech *tech);
851
852 /*! \brief Unregister a channel technology 
853  * \param tech Structure defining channel technology or "type" that was previously registered
854  * \return No return value.
855  */
856 void ast_channel_unregister(const struct ast_channel_tech *tech);
857
858 /*! \brief Get a channel technology structure by name
859  * \param name name of technology to find
860  * \return a pointer to the structure, or NULL if no matching technology found
861  */
862 const struct ast_channel_tech *ast_get_channel_tech(const char *name);
863
864 #ifdef CHANNEL_TRACE
865 /*! \brief Update the context backtrace if tracing is enabled
866  * \return Returns 0 on success, -1 on failure
867  */
868 int ast_channel_trace_update(struct ast_channel *chan);
869
870 /*! \brief Enable context tracing in the channel
871  * \return Returns 0 on success, -1 on failure
872  */
873 int ast_channel_trace_enable(struct ast_channel *chan);
874
875 /*! \brief Disable context tracing in the channel.
876  * \note Does not remove current trace entries
877  * \return Returns 0 on success, -1 on failure
878  */
879 int ast_channel_trace_disable(struct ast_channel *chan);
880
881 /*! \brief Whether or not context tracing is enabled
882  * \return Returns -1 when the trace is enabled. 0 if not.
883  */
884 int ast_channel_trace_is_enabled(struct ast_channel *chan);
885
886 /*! \brief Put the channel backtrace in a string
887  * \return Returns the amount of lines in the backtrace. -1 on error.
888  */
889 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **out);
890 #endif
891
892 /*! \brief Hang up a channel  
893  * \note This function performs a hard hangup on a channel.  Unlike the soft-hangup, this function
894  * performs all stream stopping, etc, on the channel that needs to end.
895  * chan is no longer valid after this call.
896  * \param chan channel to hang up
897  * \return Returns 0 on success, -1 on failure.
898  */
899 int ast_hangup(struct ast_channel *chan);
900
901 /*! 
902  * \brief Softly hangup up a channel 
903  *
904  * \param chan channel to be soft-hung-up
905  * \param cause Ast hangupcause for hangup
906  *
907  * Call the protocol layer, but don't destroy the channel structure 
908  * (use this if you are trying to
909  * safely hangup a channel managed by another thread.
910  *
911  * \note The channel passed to this function does not need to be locked.
912  *
913  * \return Returns 0 regardless
914  */
915 int ast_softhangup(struct ast_channel *chan, int cause);
916
917 /*! \brief Softly hangup up a channel (no channel lock) 
918  * \param chan channel to be soft-hung-up
919  * \param cause Ast hangupcause for hangup (see cause.h) */
920 int ast_softhangup_nolock(struct ast_channel *chan, int cause);
921
922 /*! \brief Check to see if a channel is needing hang up 
923  * \param chan channel on which to check for hang up
924  * This function determines if the channel is being requested to be hung up.
925  * \return Returns 0 if not, or 1 if hang up is requested (including time-out).
926  */
927 int ast_check_hangup(struct ast_channel *chan);
928
929 /*! \brief Compare a offset with the settings of when to hang a channel up 
930  * \param chan channel on which to check for hang up
931  * \param offset offset in seconds and useconds from current time
932  * \return 1, 0, or -1
933  * This function compares a offset from current time with the absolute time 
934  * out on a channel (when to hang up). If the absolute time out on a channel
935  * is earlier than current time plus the offset, it returns 1, if the two
936  * time values are equal, it return 0, otherwise, it return -1.
937  */
938 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset) __attribute__((deprecated));
939 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset);
940
941 /*! \brief Set when to hang a channel up 
942  *
943  * \param chan channel on which to check for hang up
944  * \param offset offset in seconds and useconds relative to the current time of when to hang up
945  *
946  * This function sets the absolute time out on a channel (when to hang up).
947  *
948  * \note This function does not require that the channel is locked before
949  *       calling it.
950  *
951  * \return Nothing
952  */
953 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset) __attribute__((deprecated));
954 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset);
955
956 /*! 
957  * \brief Answer a channel
958  * 
959  * \param chan channel to answer
960  *
961  * This function answers a channel and handles all necessary call
962  * setup functions.
963  *
964  * \note The channel passed does not need to be locked.
965  *
966  * \retval 0 on success
967  * \retval non-zero on failure
968  */
969 int ast_answer(struct ast_channel *chan);
970 int __ast_answer(struct ast_channel *chan, unsigned int delay);
971
972 /*! \brief Make a call 
973  * \param chan which channel to make the call on
974  * \param addr destination of the call
975  * \param timeout time to wait on for connect
976  * Place a call, take no longer than timeout ms. 
977    \return Returns -1 on failure, 0 on not enough time 
978    (does not automatically stop ringing), and  
979    the number of seconds the connect took otherwise.
980    */
981 int ast_call(struct ast_channel *chan, char *addr, int timeout);
982
983 /*! \brief Indicates condition of channel 
984  * \note Indicate a condition such as AST_CONTROL_BUSY, AST_CONTROL_RINGING, or AST_CONTROL_CONGESTION on a channel
985  * \param chan channel to change the indication
986  * \param condition which condition to indicate on the channel
987  * \return Returns 0 on success, -1 on failure
988  */
989 int ast_indicate(struct ast_channel *chan, int condition);
990
991 /*! \brief Indicates condition of channel, with payload
992  * \note Indicate a condition such as AST_CONTROL_HOLD with payload being music on hold class
993  * \param chan channel to change the indication
994  * \param condition which condition to indicate on the channel
995  * \param data pointer to payload data
996  * \param datalen size of payload data
997  * \return Returns 0 on success, -1 on failure
998  */
999 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen);
1000
1001 /* Misc stuff ------------------------------------------------ */
1002
1003 /*! \brief Wait for input on a channel 
1004  * \param chan channel to wait on
1005  * \param ms length of time to wait on the channel
1006  * Wait for input on a channel for a given # of milliseconds (<0 for indefinite). 
1007   \return Returns < 0 on  failure, 0 if nothing ever arrived, and the # of ms remaining otherwise */
1008 int ast_waitfor(struct ast_channel *chan, int ms);
1009
1010 /*! \brief Wait for a specified amount of time, looking for hangups 
1011  * \param chan channel to wait for
1012  * \param ms length of time in milliseconds to sleep
1013  * Waits for a specified amount of time, servicing the channel as required.
1014  * \return returns -1 on hangup, otherwise 0.
1015  */
1016 int ast_safe_sleep(struct ast_channel *chan, int ms);
1017
1018 /*! \brief Wait for a specified amount of time, looking for hangups and a condition argument 
1019  * \param chan channel to wait for
1020  * \param ms length of time in milliseconds to sleep
1021  * \param cond a function pointer for testing continue condition
1022  * \param data argument to be passed to the condition test function
1023  * \return returns -1 on hangup, otherwise 0.
1024  * Waits for a specified amount of time, servicing the channel as required. If cond
1025  * returns 0, this function returns.
1026  */
1027 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data );
1028
1029 /*! \brief Waits for activity on a group of channels 
1030  * \param chan an array of pointers to channels
1031  * \param n number of channels that are to be waited upon
1032  * \param fds an array of fds to wait upon
1033  * \param nfds the number of fds to wait upon
1034  * \param exception exception flag
1035  * \param outfd fd that had activity on it
1036  * \param ms how long the wait was
1037  * Big momma function here.  Wait for activity on any of the n channels, or any of the nfds
1038    file descriptors.
1039    \return Returns the channel with activity, or NULL on error or if an FD
1040    came first.  If the FD came first, it will be returned in outfd, otherwise, outfd
1041    will be -1 */
1042 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **chan, int n,
1043         int *fds, int nfds, int *exception, int *outfd, int *ms);
1044
1045 /*! \brief Waits for input on a group of channels
1046    Wait for input on an array of channels for a given # of milliseconds. 
1047         \return Return channel with activity, or NULL if none has activity.  
1048         \param chan an array of pointers to channels
1049         \param n number of channels that are to be waited upon
1050         \param ms time "ms" is modified in-place, if applicable */
1051 struct ast_channel *ast_waitfor_n(struct ast_channel **chan, int n, int *ms);
1052
1053 /*! \brief Waits for input on an fd
1054         This version works on fd's only.  Be careful with it. */
1055 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception);
1056
1057
1058 /*! \brief Reads a frame
1059  * \param chan channel to read a frame from
1060  * \return Returns a frame, or NULL on error.  If it returns NULL, you
1061         best just stop reading frames and assume the channel has been
1062         disconnected. */
1063 struct ast_frame *ast_read(struct ast_channel *chan);
1064
1065 /*! \brief Reads a frame, returning AST_FRAME_NULL frame if audio. 
1066         \param chan channel to read a frame from
1067         \return  Returns a frame, or NULL on error.  If it returns NULL, you
1068                 best just stop reading frames and assume the channel has been
1069                 disconnected.  
1070         \note Audio is replaced with AST_FRAME_NULL to avoid 
1071         transcode when the resulting audio is not necessary. */
1072 struct ast_frame *ast_read_noaudio(struct ast_channel *chan);
1073
1074 /*! \brief Write a frame to a channel 
1075  * This function writes the given frame to the indicated channel.
1076  * \param chan destination channel of the frame
1077  * \param frame frame that will be written
1078  * \return It returns 0 on success, -1 on failure.
1079  */
1080 int ast_write(struct ast_channel *chan, struct ast_frame *frame);
1081
1082 /*! \brief Write video frame to a channel 
1083  * This function writes the given frame to the indicated channel.
1084  * \param chan destination channel of the frame
1085  * \param frame frame that will be written
1086  * \return It returns 1 on success, 0 if not implemented, and -1 on failure.
1087  */
1088 int ast_write_video(struct ast_channel *chan, struct ast_frame *frame);
1089
1090 /*! \brief Write text frame to a channel 
1091  * This function writes the given frame to the indicated channel.
1092  * \param chan destination channel of the frame
1093  * \param frame frame that will be written
1094  * \return It returns 1 on success, 0 if not implemented, and -1 on failure.
1095  */
1096 int ast_write_text(struct ast_channel *chan, struct ast_frame *frame);
1097
1098 /*! \brief Send empty audio to prime a channel driver */
1099 int ast_prod(struct ast_channel *chan);
1100
1101 /*! \brief Sets read format on channel chan
1102  * Set read format for channel to whichever component of "format" is best. 
1103  * \param chan channel to change
1104  * \param format format to change to
1105  * \return Returns 0 on success, -1 on failure
1106  */
1107 int ast_set_read_format(struct ast_channel *chan, int format);
1108
1109 /*! \brief Sets write format on channel chan
1110  * Set write format for channel to whichever component of "format" is best. 
1111  * \param chan channel to change
1112  * \param format new format for writing
1113  * \return Returns 0 on success, -1 on failure
1114  */
1115 int ast_set_write_format(struct ast_channel *chan, int format);
1116
1117 /*! 
1118  * \brief Sends text to a channel 
1119  *
1120  * \param chan channel to act upon
1121  * \param text string of text to send on the channel
1122  *
1123  * Write text to a display on a channel
1124  *
1125  * \note The channel does not need to be locked before calling this function.
1126  *
1127  * \retval 0 on success 
1128  * \retval -1 on failure
1129  */
1130 int ast_sendtext(struct ast_channel *chan, const char *text);
1131
1132 /*! \brief Receives a text character from a channel
1133  * \param chan channel to act upon
1134  * \param timeout timeout in milliseconds (0 for infinite wait)
1135  * Read a char of text from a channel
1136  * Returns 0 on success, -1 on failure
1137  */
1138 int ast_recvchar(struct ast_channel *chan, int timeout);
1139
1140 /*! \brief Send a DTMF digit to a channel
1141  * Send a DTMF digit to a channel.
1142  * \param chan channel to act upon
1143  * \param digit the DTMF digit to send, encoded in ASCII
1144  * \param duration the duration of the digit ending in ms
1145  * \return Returns 0 on success, -1 on failure
1146  */
1147 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration);
1148
1149 /*! \brief Send a DTMF digit to a channel
1150  * Send a DTMF digit to a channel.
1151  * \param chan channel to act upon
1152  * \param digit the DTMF digit to send, encoded in ASCII
1153  * \return Returns 0 on success, -1 on failure
1154  */
1155 int ast_senddigit_begin(struct ast_channel *chan, char digit);
1156
1157 /*! \brief Send a DTMF digit to a channel
1158
1159  * Send a DTMF digit to a channel.
1160  * \param chan channel to act upon
1161  * \param digit the DTMF digit to send, encoded in ASCII
1162  * \param duration the duration of the digit ending in ms
1163  * \return Returns 0 on success, -1 on failure
1164  */
1165 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration);
1166
1167 /*! \brief Receives a text string from a channel
1168  * Read a string of text from a channel
1169  * \param chan channel to act upon
1170  * \param timeout timeout in milliseconds (0 for infinite wait)
1171  * \return the received text, or NULL to signify failure.
1172  */
1173 char *ast_recvtext(struct ast_channel *chan, int timeout);
1174
1175 /*! \brief Browse channels in use
1176  * Browse the channels currently in use 
1177  * \param prev where you want to start in the channel list
1178  * \return Returns the next channel in the list, NULL on end.
1179  *      If it returns a channel, that channel *has been locked*!
1180  */
1181 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev);
1182
1183 /*! \brief Get channel by name or uniqueid (locks channel) */
1184 struct ast_channel *ast_get_channel_by_name_locked(const char *chan);
1185
1186 /*! \brief Get channel by name or uniqueid prefix (locks channel) */
1187 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen);
1188
1189 /*! \brief Get channel by name or uniqueid prefix (locks channel) */
1190 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name, const int namelen);
1191
1192 /*! \brief Get channel by exten (and optionally context) and lock it */
1193 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context);
1194
1195 /*! \brief Get next channel by exten (and optionally context) and lock it */
1196 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1197                                                      const char *context);
1198
1199 /*! \brief Search for a channel based on the passed channel matching callback
1200  * Search for a channel based on the specified is_match callback, and return the
1201  * first channel that we match.  When returned, the channel will be locked.  Note
1202  * that the is_match callback is called with the passed channel locked, and should
1203  * return 0 if there is no match, and non-zero if there is.
1204  * \param is_match callback executed on each channel until non-zero is returned, or we
1205  *        run out of channels to search.
1206  * \param data data passed to the is_match callback during each invocation.
1207  * \return Returns the matched channel, or NULL if no channel was matched.
1208  */
1209 struct ast_channel *ast_channel_search_locked(int (*is_match)(struct ast_channel *, void *), void *data);
1210
1211 /*! ! \brief Waits for a digit
1212  * \param c channel to wait for a digit on
1213  * \param ms how many milliseconds to wait
1214  * \return Returns <0 on error, 0 on no entry, and the digit on success. */
1215 int ast_waitfordigit(struct ast_channel *c, int ms);
1216
1217 /*! \brief Wait for a digit
1218  Same as ast_waitfordigit() with audio fd for outputting read audio and ctrlfd to monitor for reading. 
1219  * \param c channel to wait for a digit on
1220  * \param ms how many milliseconds to wait
1221  * \param audiofd audio file descriptor to write to if audio frames are received
1222  * \param ctrlfd control file descriptor to monitor for reading
1223  * \return Returns 1 if ctrlfd becomes available */
1224 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int ctrlfd);
1225
1226 /*! Reads multiple digits 
1227  * \param c channel to read from
1228  * \param s string to read in to.  Must be at least the size of your length
1229  * \param len how many digits to read (maximum)
1230  * \param timeout how long to timeout between digits
1231  * \param rtimeout timeout to wait on the first digit
1232  * \param enders digits to end the string
1233  * Read in a digit string "s", max length "len", maximum timeout between 
1234    digits "timeout" (-1 for none), terminated by anything in "enders".  Give them rtimeout
1235    for the first digit.  Returns 0 on normal return, or 1 on a timeout.  In the case of
1236    a timeout, any digits that were read before the timeout will still be available in s.  
1237    RETURNS 2 in full version when ctrlfd is available, NOT 1*/
1238 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int rtimeout, char *enders);
1239 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int rtimeout, char *enders, int audiofd, int ctrlfd);
1240
1241 /*! \brief Report DTMF on channel 0 */
1242 #define AST_BRIDGE_DTMF_CHANNEL_0               (1 << 0)                
1243 /*! \brief Report DTMF on channel 1 */
1244 #define AST_BRIDGE_DTMF_CHANNEL_1               (1 << 1)                
1245 /*! \brief Return all voice frames on channel 0 */
1246 #define AST_BRIDGE_REC_CHANNEL_0                (1 << 2)                
1247 /*! \brief Return all voice frames on channel 1 */
1248 #define AST_BRIDGE_REC_CHANNEL_1                (1 << 3)                
1249 /*! \brief Ignore all signal frames except NULL */
1250 #define AST_BRIDGE_IGNORE_SIGS                  (1 << 4)                
1251
1252
1253 /*! \brief Makes two channel formats compatible 
1254  * \param c0 first channel to make compatible
1255  * \param c1 other channel to make compatible
1256  * Set two channels to compatible formats -- call before ast_channel_bridge in general .  
1257  * \return Returns 0 on success and -1 if it could not be done */
1258 int ast_channel_make_compatible(struct ast_channel *c0, struct ast_channel *c1);
1259
1260 /*! Bridge two channels together (early)
1261  * \param c0 first channel to bridge
1262  * \param c1 second channel to bridge
1263  * Bridge two channels (c0 and c1) together early. This implies either side may not be answered yet.
1264  * \return Returns 0 on success and -1 if it could not be done */
1265 int ast_channel_early_bridge(struct ast_channel *c0, struct ast_channel *c1);
1266
1267 /*! Bridge two channels together 
1268  * \param c0 first channel to bridge
1269  * \param c1 second channel to bridge
1270  * \param config config for the channels
1271  * \param fo destination frame(?)
1272  * \param rc destination channel(?)
1273  * Bridge two channels (c0 and c1) together.  If an important frame occurs, we return that frame in
1274    *rf (remember, it could be NULL) and which channel (0 or 1) in rc */
1275 /* int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc); */
1276 int ast_channel_bridge(struct ast_channel *c0,struct ast_channel *c1,
1277         struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc);
1278
1279 /*! 
1280  * \brief Weird function made for call transfers
1281  *
1282  * \param original channel to make a copy of
1283  * \param clone copy of the original channel
1284  *
1285  * This is a very strange and freaky function used primarily for transfer.  Suppose that
1286  * "original" and "clone" are two channels in random situations.  This function takes
1287  * the guts out of "clone" and puts them into the "original" channel, then alerts the
1288  * channel driver of the change, asking it to fixup any private information (like the
1289  * p->owner pointer) that is affected by the change.  The physical layer of the original
1290  * channel is hung up.  
1291  *
1292  * \note Neither channel passed here needs to be locked before calling this function.
1293  */
1294 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone);
1295
1296 /*! Gives the string form of a given cause code */
1297 /*! 
1298  * \param state cause to get the description of
1299  * Give a name to a cause code
1300  * Returns the text form of the binary cause code given
1301  */
1302 const char *ast_cause2str(int state) attribute_pure;
1303
1304 /*! Convert the string form of a cause code to a number */
1305 /*! 
1306  * \param name string form of the cause
1307  * Returns the cause code
1308  */
1309 int ast_str2cause(const char *name) attribute_pure;
1310
1311 /*! Gives the string form of a given channel state */
1312 /*! 
1313  * \param ast_channel_state state to get the name of
1314  * Give a name to a state 
1315  * Returns the text form of the binary state given
1316  */
1317 const char *ast_state2str(enum ast_channel_state);
1318
1319 /*! Gives the string form of a given transfer capability */
1320 /*!
1321  * \param transfercapability transfercapabilty to get the name of
1322  * Give a name to a transfercapbility
1323  * See above
1324  * Returns the text form of the binary transfer capability
1325  */
1326 char *ast_transfercapability2str(int transfercapability) attribute_const;
1327
1328 /* Options: Some low-level drivers may implement "options" allowing fine tuning of the
1329    low level channel.  See frame.h for options.  Note that many channel drivers may support
1330    none or a subset of those features, and you should not count on this if you want your
1331    asterisk application to be portable.  They're mainly useful for tweaking performance */
1332
1333 /*! Sets an option on a channel */
1334 /*! 
1335  * \param channel channel to set options on
1336  * \param option option to change
1337  * \param data data specific to option
1338  * \param datalen length of the data
1339  * \param block blocking or not
1340  * Set an option on a channel (see frame.h), optionally blocking awaiting the reply 
1341  * Returns 0 on success and -1 on failure
1342  */
1343 int ast_channel_setoption(struct ast_channel *channel, int option, void *data, int datalen, int block);
1344
1345 /*! Pick the best codec  */
1346 /* Choose the best codec...  Uhhh...   Yah. */
1347 int ast_best_codec(int fmts);
1348
1349
1350 /*! Checks the value of an option */
1351 /*! 
1352  * Query the value of an option
1353  * Works similarly to setoption except only reads the options.
1354  */
1355 int ast_channel_queryoption(struct ast_channel *channel, int option, void *data, int *datalen, int block);
1356
1357 /*! Checks for HTML support on a channel */
1358 /*! Returns 0 if channel does not support HTML or non-zero if it does */
1359 int ast_channel_supports_html(struct ast_channel *channel);
1360
1361 /*! Sends HTML on given channel */
1362 /*! Send HTML or URL on link.  Returns 0 on success or -1 on failure */
1363 int ast_channel_sendhtml(struct ast_channel *channel, int subclass, const char *data, int datalen);
1364
1365 /*! Sends a URL on a given link */
1366 /*! Send URL on link.  Returns 0 on success or -1 on failure */
1367 int ast_channel_sendurl(struct ast_channel *channel, const char *url);
1368
1369 /*! Defers DTMF */
1370 /*! Defer DTMF so that you only read things like hangups and audio.  Returns
1371    non-zero if channel was already DTMF-deferred or 0 if channel is just now
1372    being DTMF-deferred */
1373 int ast_channel_defer_dtmf(struct ast_channel *chan);
1374
1375 /*! Undo defer.  ast_read will return any dtmf characters that were queued */
1376 void ast_channel_undefer_dtmf(struct ast_channel *chan);
1377
1378 /*! Initiate system shutdown -- prevents new channels from being allocated.
1379     If "hangup" is non-zero, all existing channels will receive soft
1380      hangups */
1381 void ast_begin_shutdown(int hangup);
1382
1383 /*! Cancels an existing shutdown and returns to normal operation */
1384 void ast_cancel_shutdown(void);
1385
1386 /*! Returns number of active/allocated channels */
1387 int ast_active_channels(void);
1388
1389 /*! Returns non-zero if Asterisk is being shut down */
1390 int ast_shutting_down(void);
1391
1392 /*! Activate a given generator */
1393 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params);
1394
1395 /*! Deactivate an active generator */
1396 void ast_deactivate_generator(struct ast_channel *chan);
1397
1398 /*!
1399  * \brief Set caller ID number, name and ANI
1400  *
1401  * \note The channel does not need to be locked before calling this function.
1402  */
1403 void ast_set_callerid(struct ast_channel *chan, const char *cid_num, const char *cid_name, const char *cid_ani);
1404
1405 /*! Set the file descriptor on the channel */
1406 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd);
1407
1408 /*! Add a channel to an optimized waitfor */
1409 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1);
1410
1411 /*! Delete a channel from an optimized waitfor */
1412 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1);
1413
1414 /*! Start a tone going */
1415 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol);
1416 /*! Stop a tone from playing */
1417 void ast_tonepair_stop(struct ast_channel *chan);
1418 /*! Play a tone pair for a given amount of time */
1419 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol);
1420
1421 /*!
1422  * \brief Automatically service a channel for us... 
1423  *
1424  * \retval 0 success
1425  * \retval -1 failure, or the channel is already being autoserviced
1426  */
1427 int ast_autoservice_start(struct ast_channel *chan);
1428
1429 /*! 
1430  * \brief Stop servicing a channel for us...  
1431  *
1432  * \retval 0 success
1433  * \retval -1 error, or the channel has been hungup 
1434  */
1435 int ast_autoservice_stop(struct ast_channel *chan);
1436
1437 /*!
1438  * \brief Enable or disable timer ticks for a channel
1439  *
1440  * \arg rate number of timer ticks per second
1441  *
1442  * If timers are supported, force a scheduled expiration on the
1443  * timer fd, at which point we call the callback function / data 
1444  *
1445  * Call this function with a rate of 0 to turn off the timer ticks
1446  */
1447 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data);
1448
1449 /*!     \brief Transfer a channel (if supported).  Returns -1 on error, 0 if not supported
1450    and 1 if supported and requested 
1451         \param chan current channel
1452         \param dest destination extension for transfer
1453 */
1454 int ast_transfer(struct ast_channel *chan, char *dest);
1455
1456 /*!     \brief  Start masquerading a channel
1457         XXX This is a seriously whacked out operation.  We're essentially putting the guts of
1458            the clone channel into the original channel.  Start by killing off the original
1459            channel's backend.   I'm not sure we're going to keep this function, because
1460            while the features are nice, the cost is very high in terms of pure nastiness. XXX
1461         \param chan     Channel to masquerade
1462 */
1463 int ast_do_masquerade(struct ast_channel *chan);
1464
1465 /*!     \brief Find bridged channel 
1466         \param chan Current channel
1467 */
1468 struct ast_channel *ast_bridged_channel(struct ast_channel *chan);
1469
1470 /*!
1471   \brief Inherits channel variable from parent to child channel
1472   \param parent Parent channel
1473   \param child Child channel
1474
1475   Scans all channel variables in the parent channel, looking for those
1476   that should be copied into the child channel.
1477   Variables whose names begin with a single '_' are copied into the
1478   child channel with the prefix removed.
1479   Variables whose names begin with '__' are copied into the child
1480   channel with their names unchanged.
1481 */
1482 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child);
1483
1484 /*!
1485   \brief adds a list of channel variables to a channel
1486   \param chan the channel
1487   \param vars a linked list of variables
1488
1489   Variable names can be for a regular channel variable or a dialplan function
1490   that has the ability to be written to.
1491 */
1492 void ast_set_variables(struct ast_channel *chan, struct ast_variable *vars);
1493
1494 /*!
1495   \brief An opaque 'object' structure use by silence generators on channels.
1496  */
1497 struct ast_silence_generator;
1498
1499 /*!
1500   \brief Starts a silence generator on the given channel.
1501   \param chan The channel to generate silence on
1502   \return An ast_silence_generator pointer, or NULL if an error occurs
1503
1504   This function will cause SLINEAR silence to be generated on the supplied
1505   channel until it is disabled; if the channel cannot be put into SLINEAR
1506   mode then the function will fail.
1507
1508   The pointer returned by this function must be preserved and passed to
1509   ast_channel_stop_silence_generator when you wish to stop the silence
1510   generation.
1511  */
1512 struct ast_silence_generator *ast_channel_start_silence_generator(struct ast_channel *chan);
1513
1514 /*!
1515   \brief Stops a previously-started silence generator on the given channel.
1516   \param chan The channel to operate on
1517   \param state The ast_silence_generator pointer return by a previous call to
1518   ast_channel_start_silence_generator.
1519   \return nothing
1520
1521   This function will stop the operating silence generator and return the channel
1522   to its previous write format.
1523  */
1524 void ast_channel_stop_silence_generator(struct ast_channel *chan, struct ast_silence_generator *state);
1525
1526 /*!
1527   \brief Check if the channel can run in internal timing mode.
1528   \param chan The channel to check
1529   \return boolean
1530
1531   This function will return 1 if internal timing is enabled and the timing
1532   device is available.
1533  */
1534 int ast_internal_timing_enabled(struct ast_channel *chan);
1535
1536 /* Misc. functions below */
1537
1538 /*! \brief if fd is a valid descriptor, set *pfd with the descriptor
1539  * \return Return 1 (not -1!) if added, 0 otherwise (so we can add the
1540  * return value to the index into the array)
1541  */
1542 static inline int ast_add_fd(struct pollfd *pfd, int fd)
1543 {
1544         pfd->fd = fd;
1545         pfd->events = POLLIN | POLLPRI;
1546         return fd >= 0;
1547 }
1548
1549 /*! \brief Helper function for migrating select to poll */
1550 static inline int ast_fdisset(struct pollfd *pfds, int fd, int maximum, int *start)
1551 {
1552         int x;
1553         int dummy = 0;
1554
1555         if (fd < 0)
1556                 return 0;
1557         if (!start)
1558                 start = &dummy;
1559         for (x = *start; x < maximum; x++)
1560                 if (pfds[x].fd == fd) {
1561                         if (x == *start)
1562                                 (*start)++;
1563                         return pfds[x].revents;
1564                 }
1565         return 0;
1566 }
1567
1568 #ifndef HAVE_TIMERSUB
1569 static inline void timersub(struct timeval *tvend, struct timeval *tvstart, struct timeval *tvdiff)
1570 {
1571         tvdiff->tv_sec = tvend->tv_sec - tvstart->tv_sec;
1572         tvdiff->tv_usec = tvend->tv_usec - tvstart->tv_usec;
1573         if (tvdiff->tv_usec < 0) {
1574                 tvdiff->tv_sec --;
1575                 tvdiff->tv_usec += 1000000;
1576         }
1577
1578 }
1579 #endif
1580
1581 /*! \brief Waits for activity on a group of channels 
1582  * \param nfds the maximum number of file descriptors in the sets
1583  * \param rfds file descriptors to check for read availability
1584  * \param wfds file descriptors to check for write availability
1585  * \param efds file descriptors to check for exceptions (OOB data)
1586  * \param tvp timeout while waiting for events
1587  * This is the same as a standard select(), except it guarantees the
1588  * behaviour where the passed struct timeval is updated with how much
1589  * time was not slept while waiting for the specified events
1590  */
1591 static inline int ast_select(int nfds, fd_set *rfds, fd_set *wfds, fd_set *efds, struct timeval *tvp)
1592 {
1593 #ifdef __linux__
1594         return select(nfds, rfds, wfds, efds, tvp);
1595 #else
1596         if (tvp) {
1597                 struct timeval tv, tvstart, tvend, tvlen;
1598                 int res;
1599
1600                 tv = *tvp;
1601                 gettimeofday(&tvstart, NULL);
1602                 res = select(nfds, rfds, wfds, efds, tvp);
1603                 gettimeofday(&tvend, NULL);
1604                 timersub(&tvend, &tvstart, &tvlen);
1605                 timersub(&tv, &tvlen, tvp);
1606                 if (tvp->tv_sec < 0 || (tvp->tv_sec == 0 && tvp->tv_usec < 0)) {
1607                         tvp->tv_sec = 0;
1608                         tvp->tv_usec = 0;
1609                 }
1610                 return res;
1611         }
1612         else
1613                 return select(nfds, rfds, wfds, efds, NULL);
1614 #endif
1615 }
1616
1617 /*! \brief Retrieves the current T38 state of a channel */
1618 static inline enum ast_t38_state ast_channel_get_t38_state(struct ast_channel *chan)
1619 {
1620         enum ast_t38_state state = T38_STATE_UNAVAILABLE;
1621         int datalen = sizeof(state);
1622
1623         ast_channel_queryoption(chan, AST_OPTION_T38_STATE, &state, &datalen, 0);
1624
1625         return state;
1626 }
1627
1628 #define CHECK_BLOCKING(c) do {   \
1629         if (ast_test_flag(c, AST_FLAG_BLOCKING)) {\
1630                 if (option_debug) \
1631                         ast_log(LOG_DEBUG, "Thread %ld Blocking '%s', already blocked by thread %ld in procedure %s\n", (long) pthread_self(), (c)->name, (long) (c)->blocker, (c)->blockproc); \
1632         } else { \
1633                 (c)->blocker = pthread_self(); \
1634                 (c)->blockproc = __PRETTY_FUNCTION__; \
1635                 ast_set_flag(c, AST_FLAG_BLOCKING); \
1636         } } while (0)
1637
1638 ast_group_t ast_get_group(const char *s);
1639
1640 /*! \brief print call- and pickup groups into buffer */
1641 char *ast_print_group(char *buf, int buflen, ast_group_t group);
1642
1643 /*! \brief Convert enum channelreloadreason to text string for manager event
1644         \param reason   Enum channelreloadreason - reason for reload (manager, cli, start etc)
1645 */
1646 const char *channelreloadreason2txt(enum channelreloadreason reason);
1647
1648 /*! \brief return an ast_variable list of channeltypes */
1649 struct ast_variable *ast_channeltype_list(void);
1650
1651 /*!
1652   \brief return an english explanation of the code returned thru __ast_request_and_dial's 'outstate' argument
1653   \param reason  The integer argument, usually taken from AST_CONTROL_ macros
1654   \return char pointer explaining the code
1655  */
1656 const char *ast_channel_reason2str(int reason);
1657
1658 /*! \brief channel group info
1659  */
1660 struct ast_group_info {
1661         struct ast_channel *chan;
1662         char *category;
1663         char *group;
1664         AST_LIST_ENTRY(ast_group_info) list;   
1665 };
1666
1667
1668 #if defined(__cplusplus) || defined(c_plusplus)
1669 }
1670 #endif
1671
1672 #endif /* _ASTERISK_CHANNEL_H */