ae785a298b0fea8ad61bdf09b27fd148c673e5eb
[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 dtmfq[AST_MAX_EXTENSION];                  /*!< 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 a hangup frame 
716  *
717  * \note The channel does not need to be locked before calling this function.
718  */
719 int ast_queue_hangup(struct ast_channel *chan);
720
721 /*! 
722  * \brief Queue a hangup frame with hangupcause set
723  *
724  * \note The channel does not need to be locked before calling this function.
725  * \param chan channel to queue frame onto
726  * \param cause the hangup cause
727  */
728 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause);
729
730 /*!
731  * \brief Queue a control frame with payload
732  *
733  * \param chan channel to queue frame onto
734  * \param control type of control frame
735  *
736  * \note The channel does not need to be locked before calling this function.
737  *
738  * \retval zero on success
739  * \retval non-zero on failure
740  */
741 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control);
742
743 /*!
744  * \brief Queue a control frame with payload
745  *
746  * \param chan channel to queue frame onto
747  * \param control type of control frame
748  * \param data pointer to payload data to be included in frame
749  * \param datalen number of bytes of payload data
750  *
751  * \retval 0 success
752  * \retval non-zero failure
753  *
754  * The supplied payload data is copied into the frame, so the caller's copy
755  * is not modified nor freed, and the resulting frame will retain a copy of
756  * the data even if the caller frees their local copy.
757  *
758  * \note This method should be treated as a 'network transport'; in other
759  * words, your frames may be transferred across an IAX2 channel to another
760  * system, which may be a different endianness than yours. Because of this,
761  * you should ensure that either your frames will never be expected to work
762  * across systems, or that you always put your payload data into 'network byte
763  * order' before calling this function.
764  *
765  * \note The channel does not need to be locked before calling this function.
766  */
767 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
768                            const void *data, size_t datalen);
769
770 /*! 
771  * \brief Change channel name 
772  *
773  * \note The channel must be locked before calling this function.
774  */
775 void ast_change_name(struct ast_channel *chan, char *newname);
776
777 /*! \brief Free a channel structure */
778 void  ast_channel_free(struct ast_channel *);
779
780 /*! 
781  * \brief Requests a channel 
782  *
783  * \param type type of channel to request
784  * \param format requested channel format (codec)
785  * \param data data to pass to the channel requester
786  * \param status status
787  *
788  * Request a channel of a given type, with data as optional information used 
789  * by the low level module
790  *
791  * \retval NULL failure
792  * \retval non-NULL channel on success
793  */
794 struct ast_channel *ast_request(const char *type, int format, void *data, int *status);
795
796 /*!
797  * \brief Request a channel of a given type, with data as optional information used 
798  *        by the low level module and attempt to place a call on it
799  *
800  * \param type type of channel to request
801  * \param format requested channel format
802  * \param data data to pass to the channel requester
803  * \param timeout maximum amount of time to wait for an answer
804  * \param reason why unsuccessful (if unsuccessful)
805  * \param cid_num Caller-ID Number
806  * \param cid_name Caller-ID Name (ascii)
807  *
808  * \return Returns an ast_channel on success or no answer, NULL on failure.  Check the value of chan->_state
809  * to know if the call was answered or not.
810  */
811 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data,
812         int timeout, int *reason, const char *cid_num, const char *cid_name);
813
814 /*!
815  * \brief Request a channel of a given type, with data as optional information used 
816  * by the low level module and attempt to place a call on it
817  * \param type type of channel to request
818  * \param format requested channel format
819  * \param data data to pass to the channel requester
820  * \param timeout maximum amount of time to wait for an answer
821  * \param reason why unsuccessful (if unsuccessful)
822  * \param cid_num Caller-ID Number
823  * \param cid_name Caller-ID Name (ascii)
824  * \param oh Outgoing helper
825  * \return Returns an ast_channel on success or no answer, NULL on failure.  Check the value of chan->_state
826  * to know if the call was answered or not.
827  */
828 struct ast_channel *__ast_request_and_dial(const char *type, int format, void *data,
829         int timeout, int *reason, const char *cid_num, const char *cid_name, struct outgoing_helper *oh);
830
831 /*!\brief Register a channel technology (a new channel driver)
832  * Called by a channel module to register the kind of channels it supports.
833  * \param tech Structure defining channel technology or "type"
834  * \return Returns 0 on success, -1 on failure.
835  */
836 int ast_channel_register(const struct ast_channel_tech *tech);
837
838 /*! \brief Unregister a channel technology 
839  * \param tech Structure defining channel technology or "type" that was previously registered
840  * \return No return value.
841  */
842 void ast_channel_unregister(const struct ast_channel_tech *tech);
843
844 /*! \brief Get a channel technology structure by name
845  * \param name name of technology to find
846  * \return a pointer to the structure, or NULL if no matching technology found
847  */
848 const struct ast_channel_tech *ast_get_channel_tech(const char *name);
849
850 #ifdef CHANNEL_TRACE
851 /*! \brief Update the context backtrace if tracing is enabled
852  * \return Returns 0 on success, -1 on failure
853  */
854 int ast_channel_trace_update(struct ast_channel *chan);
855
856 /*! \brief Enable context tracing in the channel
857  * \return Returns 0 on success, -1 on failure
858  */
859 int ast_channel_trace_enable(struct ast_channel *chan);
860
861 /*! \brief Disable context tracing in the channel.
862  * \note Does not remove current trace entries
863  * \return Returns 0 on success, -1 on failure
864  */
865 int ast_channel_trace_disable(struct ast_channel *chan);
866
867 /*! \brief Whether or not context tracing is enabled
868  * \return Returns -1 when the trace is enabled. 0 if not.
869  */
870 int ast_channel_trace_is_enabled(struct ast_channel *chan);
871
872 /*! \brief Put the channel backtrace in a string
873  * \return Returns the amount of lines in the backtrace. -1 on error.
874  */
875 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **out);
876 #endif
877
878 /*! \brief Hang up a channel  
879  * \note This function performs a hard hangup on a channel.  Unlike the soft-hangup, this function
880  * performs all stream stopping, etc, on the channel that needs to end.
881  * chan is no longer valid after this call.
882  * \param chan channel to hang up
883  * \return Returns 0 on success, -1 on failure.
884  */
885 int ast_hangup(struct ast_channel *chan);
886
887 /*! 
888  * \brief Softly hangup up a channel 
889  *
890  * \param chan channel to be soft-hung-up
891  * \param cause Ast hangupcause for hangup
892  *
893  * Call the protocol layer, but don't destroy the channel structure 
894  * (use this if you are trying to
895  * safely hangup a channel managed by another thread.
896  *
897  * \note The channel passed to this function does not need to be locked.
898  *
899  * \return Returns 0 regardless
900  */
901 int ast_softhangup(struct ast_channel *chan, int cause);
902
903 /*! \brief Softly hangup up a channel (no channel lock) 
904  * \param chan channel to be soft-hung-up
905  * \param cause Ast hangupcause for hangup (see cause.h) */
906 int ast_softhangup_nolock(struct ast_channel *chan, int cause);
907
908 /*! \brief Check to see if a channel is needing hang up 
909  * \param chan channel on which to check for hang up
910  * This function determines if the channel is being requested to be hung up.
911  * \return Returns 0 if not, or 1 if hang up is requested (including time-out).
912  */
913 int ast_check_hangup(struct ast_channel *chan);
914
915 /*! \brief Compare a offset with the settings of when to hang a channel up 
916  * \param chan channel on which to check for hang up
917  * \param offset offset in seconds and useconds from current time
918  * \return 1, 0, or -1
919  * This function compares a offset from current time with the absolute time 
920  * out on a channel (when to hang up). If the absolute time out on a channel
921  * is earlier than current time plus the offset, it returns 1, if the two
922  * time values are equal, it return 0, otherwise, it return -1.
923  */
924 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset) __attribute__((deprecated));
925 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset);
926
927 /*! \brief Set when to hang a channel up 
928  *
929  * \param chan channel on which to check for hang up
930  * \param offset offset in seconds and useconds relative to the current time of when to hang up
931  *
932  * This function sets the absolute time out on a channel (when to hang up).
933  *
934  * \note This function does not require that the channel is locked before
935  *       calling it.
936  *
937  * \return Nothing
938  */
939 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset) __attribute__((deprecated));
940 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset);
941
942 /*! 
943  * \brief Answer a channel
944  * 
945  * \param chan channel to answer
946  *
947  * This function answers a channel and handles all necessary call
948  * setup functions.
949  *
950  * \note The channel passed does not need to be locked.
951  *
952  * \retval 0 on success
953  * \retval non-zero on failure
954  */
955 int ast_answer(struct ast_channel *chan);
956 int __ast_answer(struct ast_channel *chan, unsigned int delay);
957
958 /*! \brief Make a call 
959  * \param chan which channel to make the call on
960  * \param addr destination of the call
961  * \param timeout time to wait on for connect
962  * Place a call, take no longer than timeout ms. 
963    \return Returns -1 on failure, 0 on not enough time 
964    (does not automatically stop ringing), and  
965    the number of seconds the connect took otherwise.
966    */
967 int ast_call(struct ast_channel *chan, char *addr, int timeout);
968
969 /*! \brief Indicates condition of channel 
970  * \note Indicate a condition such as AST_CONTROL_BUSY, AST_CONTROL_RINGING, or AST_CONTROL_CONGESTION on a channel
971  * \param chan channel to change the indication
972  * \param condition which condition to indicate on the channel
973  * \return Returns 0 on success, -1 on failure
974  */
975 int ast_indicate(struct ast_channel *chan, int condition);
976
977 /*! \brief Indicates condition of channel, with payload
978  * \note Indicate a condition such as AST_CONTROL_HOLD with payload being music on hold class
979  * \param chan channel to change the indication
980  * \param condition which condition to indicate on the channel
981  * \param data pointer to payload data
982  * \param datalen size of payload data
983  * \return Returns 0 on success, -1 on failure
984  */
985 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen);
986
987 /* Misc stuff ------------------------------------------------ */
988
989 /*! \brief Wait for input on a channel 
990  * \param chan channel to wait on
991  * \param ms length of time to wait on the channel
992  * Wait for input on a channel for a given # of milliseconds (<0 for indefinite). 
993   \return Returns < 0 on  failure, 0 if nothing ever arrived, and the # of ms remaining otherwise */
994 int ast_waitfor(struct ast_channel *chan, int ms);
995
996 /*! \brief Wait for a specified amount of time, looking for hangups 
997  * \param chan channel to wait for
998  * \param ms length of time in milliseconds to sleep
999  * Waits for a specified amount of time, servicing the channel as required.
1000  * \return returns -1 on hangup, otherwise 0.
1001  */
1002 int ast_safe_sleep(struct ast_channel *chan, int ms);
1003
1004 /*! \brief Wait for a specified amount of time, looking for hangups and a condition argument 
1005  * \param chan channel to wait for
1006  * \param ms length of time in milliseconds to sleep
1007  * \param cond a function pointer for testing continue condition
1008  * \param data argument to be passed to the condition test function
1009  * \return returns -1 on hangup, otherwise 0.
1010  * Waits for a specified amount of time, servicing the channel as required. If cond
1011  * returns 0, this function returns.
1012  */
1013 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data );
1014
1015 /*! \brief Waits for activity on a group of channels 
1016  * \param chan an array of pointers to channels
1017  * \param n number of channels that are to be waited upon
1018  * \param fds an array of fds to wait upon
1019  * \param nfds the number of fds to wait upon
1020  * \param exception exception flag
1021  * \param outfd fd that had activity on it
1022  * \param ms how long the wait was
1023  * Big momma function here.  Wait for activity on any of the n channels, or any of the nfds
1024    file descriptors.
1025    \return Returns the channel with activity, or NULL on error or if an FD
1026    came first.  If the FD came first, it will be returned in outfd, otherwise, outfd
1027    will be -1 */
1028 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **chan, int n,
1029         int *fds, int nfds, int *exception, int *outfd, int *ms);
1030
1031 /*! \brief Waits for input on a group of channels
1032    Wait for input on an array of channels for a given # of milliseconds. 
1033         \return Return channel with activity, or NULL if none has activity.  
1034         \param chan an array of pointers to channels
1035         \param n number of channels that are to be waited upon
1036         \param ms time "ms" is modified in-place, if applicable */
1037 struct ast_channel *ast_waitfor_n(struct ast_channel **chan, int n, int *ms);
1038
1039 /*! \brief Waits for input on an fd
1040         This version works on fd's only.  Be careful with it. */
1041 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception);
1042
1043
1044 /*! \brief Reads a frame
1045  * \param chan channel to read a frame from
1046  * \return Returns a frame, or NULL on error.  If it returns NULL, you
1047         best just stop reading frames and assume the channel has been
1048         disconnected. */
1049 struct ast_frame *ast_read(struct ast_channel *chan);
1050
1051 /*! \brief Reads a frame, returning AST_FRAME_NULL frame if audio. 
1052         \param chan channel to read a frame from
1053         \return  Returns a frame, or NULL on error.  If it returns NULL, you
1054                 best just stop reading frames and assume the channel has been
1055                 disconnected.  
1056         \note Audio is replaced with AST_FRAME_NULL to avoid 
1057         transcode when the resulting audio is not necessary. */
1058 struct ast_frame *ast_read_noaudio(struct ast_channel *chan);
1059
1060 /*! \brief Write a frame to a channel 
1061  * This function writes the given frame to the indicated channel.
1062  * \param chan destination channel of the frame
1063  * \param frame frame that will be written
1064  * \return It returns 0 on success, -1 on failure.
1065  */
1066 int ast_write(struct ast_channel *chan, struct ast_frame *frame);
1067
1068 /*! \brief Write video frame to a channel 
1069  * This function writes the given frame to the indicated channel.
1070  * \param chan destination channel of the frame
1071  * \param frame frame that will be written
1072  * \return It returns 1 on success, 0 if not implemented, and -1 on failure.
1073  */
1074 int ast_write_video(struct ast_channel *chan, struct ast_frame *frame);
1075
1076 /*! \brief Write text frame to a channel 
1077  * This function writes the given frame to the indicated channel.
1078  * \param chan destination channel of the frame
1079  * \param frame frame that will be written
1080  * \return It returns 1 on success, 0 if not implemented, and -1 on failure.
1081  */
1082 int ast_write_text(struct ast_channel *chan, struct ast_frame *frame);
1083
1084 /*! \brief Send empty audio to prime a channel driver */
1085 int ast_prod(struct ast_channel *chan);
1086
1087 /*! \brief Sets read format on channel chan
1088  * Set read format for channel to whichever component of "format" is best. 
1089  * \param chan channel to change
1090  * \param format format to change to
1091  * \return Returns 0 on success, -1 on failure
1092  */
1093 int ast_set_read_format(struct ast_channel *chan, int format);
1094
1095 /*! \brief Sets write format on channel chan
1096  * Set write format for channel to whichever component of "format" is best. 
1097  * \param chan channel to change
1098  * \param format new format for writing
1099  * \return Returns 0 on success, -1 on failure
1100  */
1101 int ast_set_write_format(struct ast_channel *chan, int format);
1102
1103 /*! 
1104  * \brief Sends text to a channel 
1105  *
1106  * \param chan channel to act upon
1107  * \param text string of text to send on the channel
1108  *
1109  * Write text to a display on a channel
1110  *
1111  * \note The channel does not need to be locked before calling this function.
1112  *
1113  * \retval 0 on success 
1114  * \retval -1 on failure
1115  */
1116 int ast_sendtext(struct ast_channel *chan, const char *text);
1117
1118 /*! \brief Receives a text character from a channel
1119  * \param chan channel to act upon
1120  * \param timeout timeout in milliseconds (0 for infinite wait)
1121  * Read a char of text from a channel
1122  * Returns 0 on success, -1 on failure
1123  */
1124 int ast_recvchar(struct ast_channel *chan, int timeout);
1125
1126 /*! \brief Send a DTMF digit to a channel
1127  * Send a DTMF digit to a channel.
1128  * \param chan channel to act upon
1129  * \param digit the DTMF digit to send, encoded in ASCII
1130  * \param duration the duration of the digit ending in ms
1131  * \return Returns 0 on success, -1 on failure
1132  */
1133 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration);
1134
1135 /*! \brief Send a DTMF digit to a channel
1136  * Send a DTMF digit to a channel.
1137  * \param chan channel to act upon
1138  * \param digit the DTMF digit to send, encoded in ASCII
1139  * \return Returns 0 on success, -1 on failure
1140  */
1141 int ast_senddigit_begin(struct ast_channel *chan, char digit);
1142
1143 /*! \brief Send a DTMF digit to a channel
1144
1145  * Send a DTMF digit to a channel.
1146  * \param chan channel to act upon
1147  * \param digit the DTMF digit to send, encoded in ASCII
1148  * \param duration the duration of the digit ending in ms
1149  * \return Returns 0 on success, -1 on failure
1150  */
1151 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration);
1152
1153 /*! \brief Receives a text string from a channel
1154  * Read a string of text from a channel
1155  * \param chan channel to act upon
1156  * \param timeout timeout in milliseconds (0 for infinite wait)
1157  * \return the received text, or NULL to signify failure.
1158  */
1159 char *ast_recvtext(struct ast_channel *chan, int timeout);
1160
1161 /*! \brief Browse channels in use
1162  * Browse the channels currently in use 
1163  * \param prev where you want to start in the channel list
1164  * \return Returns the next channel in the list, NULL on end.
1165  *      If it returns a channel, that channel *has been locked*!
1166  */
1167 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev);
1168
1169 /*! \brief Get channel by name or uniqueid (locks channel) */
1170 struct ast_channel *ast_get_channel_by_name_locked(const char *chan);
1171
1172 /*! \brief Get channel by name or uniqueid prefix (locks channel) */
1173 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen);
1174
1175 /*! \brief Get channel by name or uniqueid prefix (locks channel) */
1176 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name, const int namelen);
1177
1178 /*! \brief Get channel by exten (and optionally context) and lock it */
1179 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context);
1180
1181 /*! \brief Get next channel by exten (and optionally context) and lock it */
1182 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1183                                                      const char *context);
1184
1185 /*! \brief Search for a channel based on the passed channel matching callback
1186  * Search for a channel based on the specified is_match callback, and return the
1187  * first channel that we match.  When returned, the channel will be locked.  Note
1188  * that the is_match callback is called with the passed channel locked, and should
1189  * return 0 if there is no match, and non-zero if there is.
1190  * \param is_match callback executed on each channel until non-zero is returned, or we
1191  *        run out of channels to search.
1192  * \param data data passed to the is_match callback during each invocation.
1193  * \return Returns the matched channel, or NULL if no channel was matched.
1194  */
1195 struct ast_channel *ast_channel_search_locked(int (*is_match)(struct ast_channel *, void *), void *data);
1196
1197 /*! ! \brief Waits for a digit
1198  * \param c channel to wait for a digit on
1199  * \param ms how many milliseconds to wait
1200  * \return Returns <0 on error, 0 on no entry, and the digit on success. */
1201 int ast_waitfordigit(struct ast_channel *c, int ms);
1202
1203 /*! \brief Wait for a digit
1204  Same as ast_waitfordigit() with audio fd for outputting read audio and ctrlfd to monitor for reading. 
1205  * \param c channel to wait for a digit on
1206  * \param ms how many milliseconds to wait
1207  * \param audiofd audio file descriptor to write to if audio frames are received
1208  * \param ctrlfd control file descriptor to monitor for reading
1209  * \return Returns 1 if ctrlfd becomes available */
1210 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int ctrlfd);
1211
1212 /*! Reads multiple digits 
1213  * \param c channel to read from
1214  * \param s string to read in to.  Must be at least the size of your length
1215  * \param len how many digits to read (maximum)
1216  * \param timeout how long to timeout between digits
1217  * \param rtimeout timeout to wait on the first digit
1218  * \param enders digits to end the string
1219  * Read in a digit string "s", max length "len", maximum timeout between 
1220    digits "timeout" (-1 for none), terminated by anything in "enders".  Give them rtimeout
1221    for the first digit.  Returns 0 on normal return, or 1 on a timeout.  In the case of
1222    a timeout, any digits that were read before the timeout will still be available in s.  
1223    RETURNS 2 in full version when ctrlfd is available, NOT 1*/
1224 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int rtimeout, char *enders);
1225 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int rtimeout, char *enders, int audiofd, int ctrlfd);
1226
1227 /*! \brief Report DTMF on channel 0 */
1228 #define AST_BRIDGE_DTMF_CHANNEL_0               (1 << 0)                
1229 /*! \brief Report DTMF on channel 1 */
1230 #define AST_BRIDGE_DTMF_CHANNEL_1               (1 << 1)                
1231 /*! \brief Return all voice frames on channel 0 */
1232 #define AST_BRIDGE_REC_CHANNEL_0                (1 << 2)                
1233 /*! \brief Return all voice frames on channel 1 */
1234 #define AST_BRIDGE_REC_CHANNEL_1                (1 << 3)                
1235 /*! \brief Ignore all signal frames except NULL */
1236 #define AST_BRIDGE_IGNORE_SIGS                  (1 << 4)                
1237
1238
1239 /*! \brief Makes two channel formats compatible 
1240  * \param c0 first channel to make compatible
1241  * \param c1 other channel to make compatible
1242  * Set two channels to compatible formats -- call before ast_channel_bridge in general .  
1243  * \return Returns 0 on success and -1 if it could not be done */
1244 int ast_channel_make_compatible(struct ast_channel *c0, struct ast_channel *c1);
1245
1246 /*! Bridge two channels together (early)
1247  * \param c0 first channel to bridge
1248  * \param c1 second channel to bridge
1249  * Bridge two channels (c0 and c1) together early. This implies either side may not be answered yet.
1250  * \return Returns 0 on success and -1 if it could not be done */
1251 int ast_channel_early_bridge(struct ast_channel *c0, struct ast_channel *c1);
1252
1253 /*! Bridge two channels together 
1254  * \param c0 first channel to bridge
1255  * \param c1 second channel to bridge
1256  * \param config config for the channels
1257  * \param fo destination frame(?)
1258  * \param rc destination channel(?)
1259  * Bridge two channels (c0 and c1) together.  If an important frame occurs, we return that frame in
1260    *rf (remember, it could be NULL) and which channel (0 or 1) in rc */
1261 /* int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc); */
1262 int ast_channel_bridge(struct ast_channel *c0,struct ast_channel *c1,
1263         struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc);
1264
1265 /*! 
1266  * \brief Weird function made for call transfers
1267  *
1268  * \param original channel to make a copy of
1269  * \param clone copy of the original channel
1270  *
1271  * This is a very strange and freaky function used primarily for transfer.  Suppose that
1272  * "original" and "clone" are two channels in random situations.  This function takes
1273  * the guts out of "clone" and puts them into the "original" channel, then alerts the
1274  * channel driver of the change, asking it to fixup any private information (like the
1275  * p->owner pointer) that is affected by the change.  The physical layer of the original
1276  * channel is hung up.  
1277  *
1278  * \note Neither channel passed here needs to be locked before calling this function.
1279  */
1280 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone);
1281
1282 /*! Gives the string form of a given cause code */
1283 /*! 
1284  * \param state cause to get the description of
1285  * Give a name to a cause code
1286  * Returns the text form of the binary cause code given
1287  */
1288 const char *ast_cause2str(int state) attribute_pure;
1289
1290 /*! Convert the string form of a cause code to a number */
1291 /*! 
1292  * \param name string form of the cause
1293  * Returns the cause code
1294  */
1295 int ast_str2cause(const char *name) attribute_pure;
1296
1297 /*! Gives the string form of a given channel state */
1298 /*! 
1299  * \param ast_channel_state state to get the name of
1300  * Give a name to a state 
1301  * Returns the text form of the binary state given
1302  */
1303 const char *ast_state2str(enum ast_channel_state);
1304
1305 /*! Gives the string form of a given transfer capability */
1306 /*!
1307  * \param transfercapability transfercapabilty to get the name of
1308  * Give a name to a transfercapbility
1309  * See above
1310  * Returns the text form of the binary transfer capability
1311  */
1312 char *ast_transfercapability2str(int transfercapability) attribute_const;
1313
1314 /* Options: Some low-level drivers may implement "options" allowing fine tuning of the
1315    low level channel.  See frame.h for options.  Note that many channel drivers may support
1316    none or a subset of those features, and you should not count on this if you want your
1317    asterisk application to be portable.  They're mainly useful for tweaking performance */
1318
1319 /*! Sets an option on a channel */
1320 /*! 
1321  * \param channel channel to set options on
1322  * \param option option to change
1323  * \param data data specific to option
1324  * \param datalen length of the data
1325  * \param block blocking or not
1326  * Set an option on a channel (see frame.h), optionally blocking awaiting the reply 
1327  * Returns 0 on success and -1 on failure
1328  */
1329 int ast_channel_setoption(struct ast_channel *channel, int option, void *data, int datalen, int block);
1330
1331 /*! Pick the best codec  */
1332 /* Choose the best codec...  Uhhh...   Yah. */
1333 int ast_best_codec(int fmts);
1334
1335
1336 /*! Checks the value of an option */
1337 /*! 
1338  * Query the value of an option
1339  * Works similarly to setoption except only reads the options.
1340  */
1341 int ast_channel_queryoption(struct ast_channel *channel, int option, void *data, int *datalen, int block);
1342
1343 /*! Checks for HTML support on a channel */
1344 /*! Returns 0 if channel does not support HTML or non-zero if it does */
1345 int ast_channel_supports_html(struct ast_channel *channel);
1346
1347 /*! Sends HTML on given channel */
1348 /*! Send HTML or URL on link.  Returns 0 on success or -1 on failure */
1349 int ast_channel_sendhtml(struct ast_channel *channel, int subclass, const char *data, int datalen);
1350
1351 /*! Sends a URL on a given link */
1352 /*! Send URL on link.  Returns 0 on success or -1 on failure */
1353 int ast_channel_sendurl(struct ast_channel *channel, const char *url);
1354
1355 /*! Defers DTMF */
1356 /*! Defer DTMF so that you only read things like hangups and audio.  Returns
1357    non-zero if channel was already DTMF-deferred or 0 if channel is just now
1358    being DTMF-deferred */
1359 int ast_channel_defer_dtmf(struct ast_channel *chan);
1360
1361 /*! Undo defer.  ast_read will return any dtmf characters that were queued */
1362 void ast_channel_undefer_dtmf(struct ast_channel *chan);
1363
1364 /*! Initiate system shutdown -- prevents new channels from being allocated.
1365     If "hangup" is non-zero, all existing channels will receive soft
1366      hangups */
1367 void ast_begin_shutdown(int hangup);
1368
1369 /*! Cancels an existing shutdown and returns to normal operation */
1370 void ast_cancel_shutdown(void);
1371
1372 /*! Returns number of active/allocated channels */
1373 int ast_active_channels(void);
1374
1375 /*! Returns non-zero if Asterisk is being shut down */
1376 int ast_shutting_down(void);
1377
1378 /*! Activate a given generator */
1379 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params);
1380
1381 /*! Deactivate an active generator */
1382 void ast_deactivate_generator(struct ast_channel *chan);
1383
1384 /*!
1385  * \brief Set caller ID number, name and ANI
1386  *
1387  * \note The channel does not need to be locked before calling this function.
1388  */
1389 void ast_set_callerid(struct ast_channel *chan, const char *cid_num, const char *cid_name, const char *cid_ani);
1390
1391 /*! Set the file descriptor on the channel */
1392 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd);
1393
1394 /*! Add a channel to an optimized waitfor */
1395 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1);
1396
1397 /*! Delete a channel from an optimized waitfor */
1398 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1);
1399
1400 /*! Start a tone going */
1401 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol);
1402 /*! Stop a tone from playing */
1403 void ast_tonepair_stop(struct ast_channel *chan);
1404 /*! Play a tone pair for a given amount of time */
1405 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol);
1406
1407 /*!
1408  * \brief Automatically service a channel for us... 
1409  *
1410  * \retval 0 success
1411  * \retval -1 failure, or the channel is already being autoserviced
1412  */
1413 int ast_autoservice_start(struct ast_channel *chan);
1414
1415 /*! 
1416  * \brief Stop servicing a channel for us...  
1417  *
1418  * \retval 0 success
1419  * \retval -1 error, or the channel has been hungup 
1420  */
1421 int ast_autoservice_stop(struct ast_channel *chan);
1422
1423 /*!
1424  * \brief Enable or disable timer ticks for a channel
1425  *
1426  * \arg rate number of timer ticks per second
1427  *
1428  * If timers are supported, force a scheduled expiration on the
1429  * timer fd, at which point we call the callback function / data 
1430  *
1431  * Call this function with a rate of 0 to turn off the timer ticks
1432  */
1433 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data);
1434
1435 /*!     \brief Transfer a channel (if supported).  Returns -1 on error, 0 if not supported
1436    and 1 if supported and requested 
1437         \param chan current channel
1438         \param dest destination extension for transfer
1439 */
1440 int ast_transfer(struct ast_channel *chan, char *dest);
1441
1442 /*!     \brief  Start masquerading a channel
1443         XXX This is a seriously whacked out operation.  We're essentially putting the guts of
1444            the clone channel into the original channel.  Start by killing off the original
1445            channel's backend.   I'm not sure we're going to keep this function, because
1446            while the features are nice, the cost is very high in terms of pure nastiness. XXX
1447         \param chan     Channel to masquerade
1448 */
1449 int ast_do_masquerade(struct ast_channel *chan);
1450
1451 /*!     \brief Find bridged channel 
1452         \param chan Current channel
1453 */
1454 struct ast_channel *ast_bridged_channel(struct ast_channel *chan);
1455
1456 /*!
1457   \brief Inherits channel variable from parent to child channel
1458   \param parent Parent channel
1459   \param child Child channel
1460
1461   Scans all channel variables in the parent channel, looking for those
1462   that should be copied into the child channel.
1463   Variables whose names begin with a single '_' are copied into the
1464   child channel with the prefix removed.
1465   Variables whose names begin with '__' are copied into the child
1466   channel with their names unchanged.
1467 */
1468 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child);
1469
1470 /*!
1471   \brief adds a list of channel variables to a channel
1472   \param chan the channel
1473   \param vars a linked list of variables
1474
1475   Variable names can be for a regular channel variable or a dialplan function
1476   that has the ability to be written to.
1477 */
1478 void ast_set_variables(struct ast_channel *chan, struct ast_variable *vars);
1479
1480 /*!
1481   \brief An opaque 'object' structure use by silence generators on channels.
1482  */
1483 struct ast_silence_generator;
1484
1485 /*!
1486   \brief Starts a silence generator on the given channel.
1487   \param chan The channel to generate silence on
1488   \return An ast_silence_generator pointer, or NULL if an error occurs
1489
1490   This function will cause SLINEAR silence to be generated on the supplied
1491   channel until it is disabled; if the channel cannot be put into SLINEAR
1492   mode then the function will fail.
1493
1494   The pointer returned by this function must be preserved and passed to
1495   ast_channel_stop_silence_generator when you wish to stop the silence
1496   generation.
1497  */
1498 struct ast_silence_generator *ast_channel_start_silence_generator(struct ast_channel *chan);
1499
1500 /*!
1501   \brief Stops a previously-started silence generator on the given channel.
1502   \param chan The channel to operate on
1503   \param state The ast_silence_generator pointer return by a previous call to
1504   ast_channel_start_silence_generator.
1505   \return nothing
1506
1507   This function will stop the operating silence generator and return the channel
1508   to its previous write format.
1509  */
1510 void ast_channel_stop_silence_generator(struct ast_channel *chan, struct ast_silence_generator *state);
1511
1512 /*!
1513   \brief Check if the channel can run in internal timing mode.
1514   \param chan The channel to check
1515   \return boolean
1516
1517   This function will return 1 if internal timing is enabled and the timing
1518   device is available.
1519  */
1520 int ast_internal_timing_enabled(struct ast_channel *chan);
1521
1522 /* Misc. functions below */
1523
1524 /*! \brief if fd is a valid descriptor, set *pfd with the descriptor
1525  * \return Return 1 (not -1!) if added, 0 otherwise (so we can add the
1526  * return value to the index into the array)
1527  */
1528 static inline int ast_add_fd(struct pollfd *pfd, int fd)
1529 {
1530         pfd->fd = fd;
1531         pfd->events = POLLIN | POLLPRI;
1532         return fd >= 0;
1533 }
1534
1535 /*! \brief Helper function for migrating select to poll */
1536 static inline int ast_fdisset(struct pollfd *pfds, int fd, int maximum, int *start)
1537 {
1538         int x;
1539         int dummy = 0;
1540
1541         if (fd < 0)
1542                 return 0;
1543         if (!start)
1544                 start = &dummy;
1545         for (x = *start; x < maximum; x++)
1546                 if (pfds[x].fd == fd) {
1547                         if (x == *start)
1548                                 (*start)++;
1549                         return pfds[x].revents;
1550                 }
1551         return 0;
1552 }
1553
1554 #ifndef HAVE_TIMERSUB
1555 static inline void timersub(struct timeval *tvend, struct timeval *tvstart, struct timeval *tvdiff)
1556 {
1557         tvdiff->tv_sec = tvend->tv_sec - tvstart->tv_sec;
1558         tvdiff->tv_usec = tvend->tv_usec - tvstart->tv_usec;
1559         if (tvdiff->tv_usec < 0) {
1560                 tvdiff->tv_sec --;
1561                 tvdiff->tv_usec += 1000000;
1562         }
1563
1564 }
1565 #endif
1566
1567 /*! \brief Waits for activity on a group of channels 
1568  * \param nfds the maximum number of file descriptors in the sets
1569  * \param rfds file descriptors to check for read availability
1570  * \param wfds file descriptors to check for write availability
1571  * \param efds file descriptors to check for exceptions (OOB data)
1572  * \param tvp timeout while waiting for events
1573  * This is the same as a standard select(), except it guarantees the
1574  * behaviour where the passed struct timeval is updated with how much
1575  * time was not slept while waiting for the specified events
1576  */
1577 static inline int ast_select(int nfds, fd_set *rfds, fd_set *wfds, fd_set *efds, struct timeval *tvp)
1578 {
1579 #ifdef __linux__
1580         return select(nfds, rfds, wfds, efds, tvp);
1581 #else
1582         if (tvp) {
1583                 struct timeval tv, tvstart, tvend, tvlen;
1584                 int res;
1585
1586                 tv = *tvp;
1587                 gettimeofday(&tvstart, NULL);
1588                 res = select(nfds, rfds, wfds, efds, tvp);
1589                 gettimeofday(&tvend, NULL);
1590                 timersub(&tvend, &tvstart, &tvlen);
1591                 timersub(&tv, &tvlen, tvp);
1592                 if (tvp->tv_sec < 0 || (tvp->tv_sec == 0 && tvp->tv_usec < 0)) {
1593                         tvp->tv_sec = 0;
1594                         tvp->tv_usec = 0;
1595                 }
1596                 return res;
1597         }
1598         else
1599                 return select(nfds, rfds, wfds, efds, NULL);
1600 #endif
1601 }
1602
1603 /*! \brief Retrieves the current T38 state of a channel */
1604 static inline enum ast_t38_state ast_channel_get_t38_state(struct ast_channel *chan)
1605 {
1606         enum ast_t38_state state = T38_STATE_UNAVAILABLE;
1607         int datalen = sizeof(state);
1608
1609         ast_channel_queryoption(chan, AST_OPTION_T38_STATE, &state, &datalen, 0);
1610
1611         return state;
1612 }
1613
1614 #define CHECK_BLOCKING(c) do {   \
1615         if (ast_test_flag(c, AST_FLAG_BLOCKING)) {\
1616                 if (option_debug) \
1617                         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); \
1618         } else { \
1619                 (c)->blocker = pthread_self(); \
1620                 (c)->blockproc = __PRETTY_FUNCTION__; \
1621                 ast_set_flag(c, AST_FLAG_BLOCKING); \
1622         } } while (0)
1623
1624 ast_group_t ast_get_group(const char *s);
1625
1626 /*! \brief print call- and pickup groups into buffer */
1627 char *ast_print_group(char *buf, int buflen, ast_group_t group);
1628
1629 /*! \brief Convert enum channelreloadreason to text string for manager event
1630         \param reason   Enum channelreloadreason - reason for reload (manager, cli, start etc)
1631 */
1632 const char *channelreloadreason2txt(enum channelreloadreason reason);
1633
1634 /*! \brief return an ast_variable list of channeltypes */
1635 struct ast_variable *ast_channeltype_list(void);
1636
1637 /*!
1638   \brief return an english explanation of the code returned thru __ast_request_and_dial's 'outstate' argument
1639   \param reason  The integer argument, usually taken from AST_CONTROL_ macros
1640   \return char pointer explaining the code
1641  */
1642 const char *ast_channel_reason2str(int reason);
1643
1644 /*! \brief channel group info
1645  */
1646 struct ast_group_info {
1647         struct ast_channel *chan;
1648         char *category;
1649         char *group;
1650         AST_LIST_ENTRY(ast_group_info) list;   
1651 };
1652
1653
1654 #if defined(__cplusplus) || defined(c_plusplus)
1655 }
1656 #endif
1657
1658 #endif /* _ASTERISK_CHANNEL_H */