2 * Asterisk -- A telephony toolkit for Linux.
4 * Use /dev/dsp as a channel, and the console to command it :).
6 * The full-duplex "simulation" is pretty weak. This is generally a
7 * VERY BADLY WRITTEN DRIVER so please don't use it as a model for
10 * Copyright (C) 1999, Mark Spencer
12 * Mark Spencer <markster@linux-support.net>
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License
18 #include <asterisk/frame.h>
19 #include <asterisk/logger.h>
20 #include <asterisk/channel.h>
21 #include <asterisk/module.h>
22 #include <asterisk/channel_pvt.h>
23 #include <asterisk/options.h>
24 #include <asterisk/pbx.h>
25 #include <asterisk/config.h>
26 #include <asterisk/cli.h>
30 #include <sys/ioctl.h>
35 #include <linux/soundcard.h>
41 /* Which device to use */
42 #define DEV_DSP "/dev/dsp"
44 /* Lets use 160 sample frames, just like GSM. */
45 #define FRAME_SIZE 160
47 /* When you set the frame size, you have to come up with
48 the right buffer format as well. */
49 /* 5 64-byte frames = one frame */
50 #define BUFFER_FMT ((buffersize * 10) << 16) | (0x0006);
52 /* Don't switch between read/write modes faster than every 300 ms */
53 #define MIN_SWITCH_TIME 600
55 static struct timeval lasttime;
58 static int needanswer = 0;
59 static int needringing = 0;
60 static int needhangup = 0;
61 static int silencesuppression = 0;
62 static int silencethreshold = 1000;
64 static char digits[80] = "";
65 static char text2send[80] = "";
67 static pthread_mutex_t usecnt_lock = PTHREAD_MUTEX_INITIALIZER;
69 static char *type = "Console";
70 static char *desc = "OSS Console Channel Driver";
71 static char *tdesc = "OSS Console Channel Driver";
72 static char *config = "oss.conf";
74 static char context[AST_MAX_EXTENSION] = "default";
75 static char language[MAX_LANGUAGE] = "";
76 static char exten[AST_MAX_EXTENSION] = "s";
83 static short silence[FRAME_SIZE] = {0, };
94 static struct sound sounds[] = {
95 { AST_CONTROL_RINGING, ringtone, sizeof(ringtone)/2, 16000, 32000, 1 },
96 { AST_CONTROL_BUSY, busy, sizeof(busy)/2, 4000, 4000, 1 },
97 { AST_CONTROL_CONGESTION, busy, sizeof(busy)/2, 2000, 2000, 1 },
98 { AST_CONTROL_RING, ring10, sizeof(ring10)/2, 16000, 32000, 1 },
99 { AST_CONTROL_ANSWER, answer, sizeof(answer)/2, 2200, 0, 0 },
102 /* Sound command pipe */
103 static int sndcmd[2];
105 static struct chan_oss_pvt {
106 /* We only have one OSS structure -- near sighted perhaps, but it
107 keeps this driver as simple as possible -- as it should be. */
108 struct ast_channel *owner;
109 char exten[AST_MAX_EXTENSION];
110 char context[AST_MAX_EXTENSION];
113 static int time_has_passed()
117 gettimeofday(&tv, NULL);
118 ms = (tv.tv_sec - lasttime.tv_sec) * 1000 +
119 (tv.tv_usec - lasttime.tv_usec) / 1000;
120 if (ms > MIN_SWITCH_TIME)
125 /* Number of buffers... Each is FRAMESIZE/8 ms long. For example
126 with 160 sample frames, and a buffer size of 3, we have a 60ms buffer,
131 #define MAX_BUFFER_SIZE 100
132 static int buffersize = 3;
134 static int full_duplex = 0;
136 /* Are we reading or writing (simulated full duplex) */
137 static int readmode = 1;
139 /* File descriptor for sound device */
140 static int sounddev = -1;
142 static int autoanswer = 1;
144 static int calc_loudness(short *frame)
148 for (x=0;x<FRAME_SIZE;x++) {
154 sum = sum/FRAME_SIZE;
158 static int cursound = -1;
159 static int sampsent = 0;
160 static int silencelen=0;
162 static int nosound=0;
164 static int send_sound(void)
166 short myframe[FRAME_SIZE];
167 int total = FRAME_SIZE;
174 res = ioctl(sounddev, SNDCTL_DSP_GETOSPACE ,&abi);
176 ast_log(LOG_WARNING, "Unable to read output space\n");
179 /* Calculate how many samples we can send, max */
180 if (total > (abi.fragments * abi.fragsize / 2))
181 total = abi.fragments * abi.fragsize / 2;
183 if (sampsent < sounds[cursound].samplen) {
187 if (amt > (sounds[cursound].datalen - offset))
188 amt = sounds[cursound].datalen - offset;
189 memcpy(myframe + myoff, sounds[cursound].data + offset, amt * 2);
194 if (offset >= sounds[cursound].datalen)
197 /* Set it up for silence */
198 if (sampsent >= sounds[cursound].samplen)
199 silencelen = sounds[cursound].silencelen;
202 if (silencelen > 0) {
206 if (sounds[cursound].repeat) {
216 res = write(sounddev, frame, res * 2);
224 static void *sound_thread(void *unused)
234 FD_SET(sndcmd[0], &rfds);
236 FD_SET(sounddev, &wfds);
240 res = select(max + 1, &rfds, &wfds, NULL, NULL);
242 ast_log(LOG_WARNING, "select failed: %s\n", strerror(errno));
245 if (FD_ISSET(sndcmd[0], &rfds)) {
246 read(sndcmd[0], &cursound, sizeof(cursound));
251 if (FD_ISSET(sounddev, &wfds))
253 ast_log(LOG_WARNING, "Failed to write sound\n");
260 static int silence_suppress(short *buf)
264 static int silentframes = 0;
265 static char silbuf[FRAME_SIZE * 2 * SILBUF];
266 static int silbufcnt=0;
267 if (!silencesuppression)
269 loudness = calc_loudness((short *)(buf));
271 ast_log(LOG_DEBUG, "loudness is %d\n", loudness);
272 if (loudness < silencethreshold) {
275 /* Keep track of the last few bits of silence so we can play
276 them as lead-in when the time is right */
277 if (silbufcnt >= SILBUF) {
278 /* Make way for more buffer */
279 memmove(silbuf, silbuf + FRAME_SIZE * 2, FRAME_SIZE * 2 * (SILBUF - 1));
282 memcpy(silbuf + FRAME_SIZE * 2 * silbufcnt, buf, FRAME_SIZE * 2);
283 if (silentframes > 10) {
284 /* We've had plenty of silence, so compress it now */
289 /* Write any buffered silence we have, it may have something
292 write(sounddev, silbuf, silbufcnt * FRAME_SIZE);
300 static int setformat(void)
302 int fmt, desired, res, fd = sounddev;
303 static int warnedalready = 0;
304 static int warnedalready2 = 0;
306 res = ioctl(fd, SNDCTL_DSP_SETFMT, &fmt);
308 ast_log(LOG_WARNING, "Unable to set format to 16-bit signed\n");
311 res = ioctl(fd, SNDCTL_DSP_SETDUPLEX, 0);
313 if (option_verbose > 1)
314 ast_verbose(VERBOSE_PREFIX_2 "Console is full duplex\n");
318 res = ioctl(fd, SNDCTL_DSP_STEREO, &fmt);
320 ast_log(LOG_WARNING, "Failed to set audio device to mono\n");
323 /* 8000 Hz desired */
326 res = ioctl(fd, SNDCTL_DSP_SPEED, &fmt);
328 ast_log(LOG_WARNING, "Failed to set audio device to mono\n");
331 if (fmt != desired) {
332 if (!warnedalready++)
333 ast_log(LOG_WARNING, "Requested %d Hz, got %d Hz -- sound may be choppy\n", desired, fmt);
337 res = ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &fmt);
339 if (!warnedalready2++)
340 ast_log(LOG_WARNING, "Unable to set fragment size -- sound may be choppy\n");
346 static int soundcard_setoutput(int force)
348 /* Make sure the soundcard is in output mode. */
350 if (full_duplex || (!readmode && !force))
353 if (force || time_has_passed()) {
354 ioctl(sounddev, SNDCTL_DSP_RESET);
355 /* Keep the same fd reserved by closing the sound device and copying stdin at the same
357 /* dup2(0, sound); */
359 fd = open(DEV_DSP, O_WRONLY |O_NONBLOCK);
361 ast_log(LOG_WARNING, "Unable to re-open DSP device: %s\n", strerror(errno));
364 /* dup2 will close the original and make fd be sound */
365 if (dup2(fd, sounddev) < 0) {
366 ast_log(LOG_WARNING, "dup2() failed: %s\n", strerror(errno));
377 static int soundcard_setinput(int force)
380 if (full_duplex || (readmode && !force))
383 if (force || time_has_passed()) {
384 ioctl(sounddev, SNDCTL_DSP_RESET);
386 /* dup2(0, sound); */
387 fd = open(DEV_DSP, O_RDONLY | O_NONBLOCK);
389 ast_log(LOG_WARNING, "Unable to re-open DSP device: %s\n", strerror(errno));
392 /* dup2 will close the original and make fd be sound */
393 if (dup2(fd, sounddev) < 0) {
394 ast_log(LOG_WARNING, "dup2() failed: %s\n", strerror(errno));
405 static int soundcard_init()
407 /* Assume it's full duplex for starters */
408 int fd = open(DEV_DSP, O_RDWR | O_NONBLOCK);
410 ast_log(LOG_WARNING, "Unable to open %s: %s\n", DEV_DSP, strerror(errno));
413 gettimeofday(&lasttime, NULL);
417 soundcard_setinput(1);
421 static int oss_digit(struct ast_channel *c, char digit)
423 ast_verbose( " << Console Received digit %c >> \n", digit);
427 static int oss_text(struct ast_channel *c, char *text)
429 ast_verbose( " << Console Received text %s >> \n", text);
433 static int oss_call(struct ast_channel *c, char *dest, int timeout)
436 ast_verbose( " << Call placed to '%s' on console >> \n", dest);
438 ast_verbose( " << Auto-answered >> \n" );
441 ast_verbose( " << Type 'answer' to answer, or use 'autoanswer' for future calls >> \n");
443 write(sndcmd[1], &res, sizeof(res));
448 static void answer_sound(void)
453 write(sndcmd[1], &res, sizeof(res));
457 static int oss_answer(struct ast_channel *c)
459 ast_verbose( " << Console call has been answered >> \n");
461 c->state = AST_STATE_UP;
466 static int oss_hangup(struct ast_channel *c)
472 ast_verbose( " << Hangup on console >> \n");
473 ast_pthread_mutex_lock(&usecnt_lock);
475 ast_pthread_mutex_unlock(&usecnt_lock);
480 /* Assume auto-hangup too */
483 /* Make congestion noise */
485 write(sndcmd[1], &res, sizeof(res));
491 static int soundcard_writeframe(short *data)
493 /* Write an exactly FRAME_SIZE sized of frame */
494 static int bufcnt = 0;
495 static short buffer[FRAME_SIZE * MAX_BUFFER_SIZE * 5];
496 struct audio_buf_info info;
500 if (ioctl(fd, SNDCTL_DSP_GETOSPACE, &info)) {
502 ast_log(LOG_WARNING, "Error reading output space\n");
506 if ((info.fragments >= buffersize * 5) && (bufcnt == buffersize)) {
507 /* We've run out of stuff, buffer again */
510 if (bufcnt == buffersize) {
511 /* Write sample immediately */
512 res = write(fd, ((void *)data), FRAME_SIZE * 2);
514 /* Copy the data into our buffer */
515 res = FRAME_SIZE * 2;
516 memcpy(buffer + (bufcnt * FRAME_SIZE), data, FRAME_SIZE * 2);
518 if (bufcnt == buffersize) {
519 res = write(fd, ((void *)buffer), FRAME_SIZE * 2 * buffersize);
526 static int oss_write(struct ast_channel *chan, struct ast_frame *f)
529 static char sizbuf[8000];
530 static int sizpos = 0;
533 /* Immediately return if no sound is enabled */
536 /* Stop any currently playing sound */
538 if (!full_duplex && (strlen(digits) || needhangup || needanswer)) {
539 /* If we're half duplex, we have to switch to read mode
540 to honor immediate needs if necessary */
541 res = soundcard_setinput(1);
543 ast_log(LOG_WARNING, "Unable to set device to input mode\n");
548 res = soundcard_setoutput(0);
550 ast_log(LOG_WARNING, "Unable to set output device\n");
552 } else if (res > 0) {
553 /* The device is still in read mode, and it's too soon to change it,
554 so just pretend we wrote it */
557 /* We have to digest the frame in 160-byte portions */
558 if (f->datalen > sizeof(sizbuf) - sizpos) {
559 ast_log(LOG_WARNING, "Frame too large\n");
562 memcpy(sizbuf + sizpos, f->data, f->datalen);
565 while(len - pos > FRAME_SIZE * 2) {
566 soundcard_writeframe((short *)(sizbuf + pos));
567 pos += FRAME_SIZE * 2;
570 memmove(sizbuf, sizbuf + pos, len - pos);
575 static struct ast_frame *oss_read(struct ast_channel *chan)
577 static struct ast_frame f;
578 static char buf[FRAME_SIZE * 2 + AST_FRIENDLY_OFFSET];
579 static int readpos = 0;
585 ast_log(LOG_DEBUG, "oss_read()\n");
588 /* Acknowledge any pending cmd */
589 res = read(cmd[0], &b, sizeof(b));
593 f.frametype = AST_FRAME_NULL;
603 f.frametype = AST_FRAME_CONTROL;
604 f.subclass = AST_CONTROL_RINGING;
613 if (strlen(text2send)) {
614 f.frametype = AST_FRAME_TEXT;
617 f.datalen = strlen(text2send);
618 strcpy(text2send,"");
621 if (strlen(digits)) {
622 f.frametype = AST_FRAME_DTMF;
623 f.subclass = digits[0];
624 for (res=0;res<strlen(digits);res++)
625 digits[res] = digits[res + 1];
631 f.frametype = AST_FRAME_CONTROL;
632 f.subclass = AST_CONTROL_ANSWER;
633 chan->state = AST_STATE_UP;
640 res = soundcard_setinput(0);
642 ast_log(LOG_WARNING, "Unable to set input mode\n");
646 /* Theoretically shouldn't happen, but anyway, return a NULL frame */
649 res = read(sounddev, buf + AST_FRIENDLY_OFFSET + readpos, FRAME_SIZE * 2 - readpos);
651 ast_log(LOG_WARNING, "Error reading from sound device (If you're running 'artsd' then kill it): %s\n", strerror(errno));
659 if (readpos >= FRAME_SIZE * 2) {
662 if (chan->state != AST_STATE_UP) {
663 /* Don't transmit unless it's up */
666 f.frametype = AST_FRAME_VOICE;
667 f.subclass = AST_FORMAT_SLINEAR;
668 f.timelen = FRAME_SIZE / 8;
669 f.datalen = FRAME_SIZE * 2;
670 f.data = buf + AST_FRIENDLY_OFFSET;
671 f.offset = AST_FRIENDLY_OFFSET;
675 { static int fd = -1;
677 fd = open("output.raw", O_RDWR | O_TRUNC | O_CREAT);
678 write(fd, f.data, f.datalen);
685 static int oss_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
687 struct chan_oss_pvt *p = newchan->pvt->pvt;
692 static int oss_indicate(struct ast_channel *chan, int cond)
696 case AST_CONTROL_BUSY:
699 case AST_CONTROL_CONGESTION:
702 case AST_CONTROL_RINGING:
706 ast_log(LOG_WARNING, "Don't know how to display condition %d on %s\n", cond, chan->name);
710 write(sndcmd[1], &res, sizeof(res));
715 static struct ast_channel *oss_new(struct chan_oss_pvt *p, int state)
717 struct ast_channel *tmp;
718 tmp = ast_channel_alloc();
720 snprintf(tmp->name, sizeof(tmp->name), "OSS/%s", DEV_DSP + 5);
722 tmp->fds[0] = sounddev;
723 tmp->fds[1] = cmd[0];
724 tmp->nativeformats = AST_FORMAT_SLINEAR;
726 tmp->pvt->send_digit = oss_digit;
727 tmp->pvt->send_text = oss_text;
728 tmp->pvt->hangup = oss_hangup;
729 tmp->pvt->answer = oss_answer;
730 tmp->pvt->read = oss_read;
731 tmp->pvt->call = oss_call;
732 tmp->pvt->write = oss_write;
733 tmp->pvt->indicate = oss_indicate;
734 tmp->pvt->fixup = oss_fixup;
735 if (strlen(p->context))
736 strncpy(tmp->context, p->context, sizeof(tmp->context)-1);
737 if (strlen(p->exten))
738 strncpy(tmp->exten, p->exten, sizeof(tmp->exten)-1);
739 if (strlen(language))
740 strncpy(tmp->language, language, sizeof(tmp->language)-1);
743 ast_pthread_mutex_lock(&usecnt_lock);
745 ast_pthread_mutex_unlock(&usecnt_lock);
746 ast_update_use_count();
747 if (state != AST_STATE_DOWN) {
748 if (ast_pbx_start(tmp)) {
749 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
758 static struct ast_channel *oss_request(char *type, int format, void *data)
760 int oldformat = format;
761 struct ast_channel *tmp;
762 format &= AST_FORMAT_SLINEAR;
764 ast_log(LOG_NOTICE, "Asked to get a channel of format '%d'\n", oldformat);
768 ast_log(LOG_NOTICE, "Already have a call on the OSS channel\n");
771 tmp= oss_new(&oss, AST_STATE_DOWN);
773 ast_log(LOG_WARNING, "Unable to create new OSS channel\n");
778 static int console_autoanswer(int fd, int argc, char *argv[])
780 if ((argc != 1) && (argc != 2))
781 return RESULT_SHOWUSAGE;
783 ast_cli(fd, "Auto answer is %s.\n", autoanswer ? "on" : "off");
784 return RESULT_SUCCESS;
786 if (!strcasecmp(argv[1], "on"))
788 else if (!strcasecmp(argv[1], "off"))
791 return RESULT_SHOWUSAGE;
793 return RESULT_SUCCESS;
796 static char *autoanswer_complete(char *line, char *word, int pos, int state)
799 #define MIN(a,b) ((a) < (b) ? (a) : (b))
803 if (strlen(word) && !strncasecmp(word, "on", MIN(strlen(word), 2)))
806 if (strlen(word) && !strncasecmp(word, "off", MIN(strlen(word), 3)))
807 return strdup("off");
814 static char autoanswer_usage[] =
815 "Usage: autoanswer [on|off]\n"
816 " Enables or disables autoanswer feature. If used without\n"
817 " argument, displays the current on/off status of autoanswer.\n"
818 " The default value of autoanswer is in 'oss.conf'.\n";
820 static int console_answer(int fd, int argc, char *argv[])
823 return RESULT_SHOWUSAGE;
825 ast_cli(fd, "No one is calling us\n");
826 return RESULT_FAILURE;
832 return RESULT_SUCCESS;
835 static char sendtext_usage[] =
836 "Usage: send text <message>\n"
837 " Sends a text message for display on the remote terminal.\n";
839 static int console_sendtext(int fd, int argc, char *argv[])
843 return RESULT_SHOWUSAGE;
845 ast_cli(fd, "No one is calling us\n");
846 return RESULT_FAILURE;
848 if (strlen(text2send))
849 ast_cli(fd, "Warning: message already waiting to be sent, overwriting\n");
850 strcpy(text2send, "");
851 while(tmparg <= argc) {
852 strncat(text2send, argv[tmparg++], sizeof(text2send) - strlen(text2send));
853 strncat(text2send, " ", sizeof(text2send) - strlen(text2send));
856 return RESULT_SUCCESS;
859 static char answer_usage[] =
861 " Answers an incoming call on the console (OSS) channel.\n";
863 static int console_hangup(int fd, int argc, char *argv[])
866 return RESULT_SHOWUSAGE;
868 if (!oss.owner && !hookstate) {
869 ast_cli(fd, "No call to hangup up\n");
870 return RESULT_FAILURE;
875 return RESULT_SUCCESS;
878 static char hangup_usage[] =
880 " Hangs up any call currently placed on the console.\n";
883 static int console_dial(int fd, int argc, char *argv[])
885 char tmp[256], *tmp2;
888 if ((argc != 1) && (argc != 2))
889 return RESULT_SHOWUSAGE;
892 strncat(digits, argv[1], sizeof(digits) - strlen(digits));
893 /* Wake up the polling thread */
894 write(cmd[1], &b, sizeof(b));
896 ast_cli(fd, "You're already in a call. You can use this only to dial digits until you hangup\n");
897 return RESULT_FAILURE;
899 return RESULT_SUCCESS;
904 strncpy(tmp, argv[1], sizeof(tmp)-1);
906 tmp2 = strtok(NULL, "@");
909 if (tmp2 && strlen(tmp2))
912 if (ast_exists_extension(NULL, myc, mye, 1, NULL)) {
913 strncpy(oss.exten, mye, sizeof(oss.exten)-1);
914 strncpy(oss.context, myc, sizeof(oss.context)-1);
916 oss_new(&oss, AST_STATE_UP);
918 ast_cli(fd, "No such extension '%s' in context '%s'\n", mye, myc);
919 return RESULT_SUCCESS;
922 static char dial_usage[] =
923 "Usage: dial [extension[@context]]\n"
924 " Dials a given extensison (";
927 static struct ast_cli_entry myclis[] = {
928 { { "answer", NULL }, console_answer, "Answer an incoming console call", answer_usage },
929 { { "hangup", NULL }, console_hangup, "Hangup a call on the console", hangup_usage },
930 { { "dial", NULL }, console_dial, "Dial an extension on the console", dial_usage },
931 { { "send text", NULL }, console_sendtext, "Send text to the remote device", sendtext_usage },
932 { { "autoanswer", NULL }, console_autoanswer, "Sets/displays autoanswer", autoanswer_usage, autoanswer_complete }
940 struct ast_config *cfg = ast_load(config);
941 struct ast_variable *v;
945 ast_log(LOG_ERROR, "Unable to create pipe\n");
948 flags = fcntl(cmd[0], F_GETFL);
949 fcntl(cmd[0], F_SETFL, flags | O_NONBLOCK);
950 flags = fcntl(cmd[1], F_GETFL);
951 fcntl(cmd[1], F_SETFL, flags | O_NONBLOCK);
952 res = soundcard_init();
956 if (option_verbose > 1) {
957 ast_verbose(VERBOSE_PREFIX_2 "No sound card detected -- console channel will be unavailable\n");
958 ast_verbose(VERBOSE_PREFIX_2 "Turn off OSS support by adding 'noload=chan_oss.so' in /etc/asterisk/modules.conf\n");
963 ast_log(LOG_WARNING, "XXX I don't work right with non-full duplex sound cards XXX\n");
964 res = ast_channel_register(type, tdesc, AST_FORMAT_SLINEAR, oss_request);
966 ast_log(LOG_ERROR, "Unable to register channel class '%s'\n", type);
969 for (x=0;x<sizeof(myclis)/sizeof(struct ast_cli_entry); x++)
970 ast_cli_register(myclis + x);
972 v = ast_variable_browse(cfg, "general");
974 if (!strcasecmp(v->name, "autoanswer"))
975 autoanswer = ast_true(v->value);
976 else if (!strcasecmp(v->name, "silencesuppression"))
977 silencesuppression = ast_true(v->value);
978 else if (!strcasecmp(v->name, "silencethreshold"))
979 silencethreshold = atoi(v->value);
980 else if (!strcasecmp(v->name, "context"))
981 strncpy(context, v->value, sizeof(context)-1);
982 else if (!strcasecmp(v->name, "language"))
983 strncpy(language, v->value, sizeof(language)-1);
984 else if (!strcasecmp(v->name, "extension"))
985 strncpy(exten, v->value, sizeof(exten)-1);
990 pthread_create(&sthread, NULL, sound_thread, NULL);
999 for (x=0;x<sizeof(myclis)/sizeof(struct ast_cli_entry); x++)
1000 ast_cli_unregister(myclis + x);
1006 if (sndcmd[0] > 0) {
1011 ast_softhangup(oss.owner);
1025 ast_pthread_mutex_lock(&usecnt_lock);
1027 ast_pthread_mutex_unlock(&usecnt_lock);
1033 return ASTERISK_GPL_KEY;