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/lock.h>
19 #include <asterisk/frame.h>
20 #include <asterisk/logger.h>
21 #include <asterisk/channel.h>
22 #include <asterisk/module.h>
23 #include <asterisk/channel_pvt.h>
24 #include <asterisk/options.h>
25 #include <asterisk/pbx.h>
26 #include <asterisk/config.h>
27 #include <asterisk/cli.h>
31 #include <sys/ioctl.h>
36 #include <linux/soundcard.h>
42 /* Which device to use */
43 #define DEV_DSP "/dev/dsp"
45 /* Lets use 160 sample frames, just like GSM. */
46 #define FRAME_SIZE 160
48 /* When you set the frame size, you have to come up with
49 the right buffer format as well. */
50 /* 5 64-byte frames = one frame */
51 #define BUFFER_FMT ((buffersize * 10) << 16) | (0x0006);
53 /* Don't switch between read/write modes faster than every 300 ms */
54 #define MIN_SWITCH_TIME 600
56 static struct timeval lasttime;
59 static int silencesuppression = 0;
60 static int silencethreshold = 1000;
63 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
65 static char *type = "Console";
66 static char *desc = "OSS Console Channel Driver";
67 static char *tdesc = "OSS Console Channel Driver";
68 static char *config = "oss.conf";
70 static char context[AST_MAX_EXTENSION] = "default";
71 static char language[MAX_LANGUAGE] = "";
72 static char exten[AST_MAX_EXTENSION] = "s";
76 static short silence[FRAME_SIZE] = {0, };
87 static struct sound sounds[] = {
88 { AST_CONTROL_RINGING, ringtone, sizeof(ringtone)/2, 16000, 32000, 1 },
89 { AST_CONTROL_BUSY, busy, sizeof(busy)/2, 4000, 4000, 1 },
90 { AST_CONTROL_CONGESTION, busy, sizeof(busy)/2, 2000, 2000, 1 },
91 { AST_CONTROL_RING, ring10, sizeof(ring10)/2, 16000, 32000, 1 },
92 { AST_CONTROL_ANSWER, answer, sizeof(answer)/2, 2200, 0, 0 },
95 /* Sound command pipe */
98 static struct chan_oss_pvt {
99 /* We only have one OSS structure -- near sighted perhaps, but it
100 keeps this driver as simple as possible -- as it should be. */
101 struct ast_channel *owner;
102 char exten[AST_MAX_EXTENSION];
103 char context[AST_MAX_EXTENSION];
106 static int time_has_passed()
110 gettimeofday(&tv, NULL);
111 ms = (tv.tv_sec - lasttime.tv_sec) * 1000 +
112 (tv.tv_usec - lasttime.tv_usec) / 1000;
113 if (ms > MIN_SWITCH_TIME)
118 /* Number of buffers... Each is FRAMESIZE/8 ms long. For example
119 with 160 sample frames, and a buffer size of 3, we have a 60ms buffer,
124 #define MAX_BUFFER_SIZE 100
125 static int buffersize = 3;
127 static int full_duplex = 0;
129 /* Are we reading or writing (simulated full duplex) */
130 static int readmode = 1;
132 /* File descriptor for sound device */
133 static int sounddev = -1;
135 static int autoanswer = 1;
137 static int calc_loudness(short *frame)
141 for (x=0;x<FRAME_SIZE;x++) {
147 sum = sum/FRAME_SIZE;
151 static int cursound = -1;
152 static int sampsent = 0;
153 static int silencelen=0;
155 static int nosound=0;
157 static int send_sound(void)
159 short myframe[FRAME_SIZE];
160 int total = FRAME_SIZE;
167 res = ioctl(sounddev, SNDCTL_DSP_GETOSPACE ,&abi);
169 ast_log(LOG_WARNING, "Unable to read output space\n");
172 /* Calculate how many samples we can send, max */
173 if (total > (abi.fragments * abi.fragsize / 2))
174 total = abi.fragments * abi.fragsize / 2;
176 if (sampsent < sounds[cursound].samplen) {
180 if (amt > (sounds[cursound].datalen - offset))
181 amt = sounds[cursound].datalen - offset;
182 memcpy(myframe + myoff, sounds[cursound].data + offset, amt * 2);
187 if (offset >= sounds[cursound].datalen)
190 /* Set it up for silence */
191 if (sampsent >= sounds[cursound].samplen)
192 silencelen = sounds[cursound].silencelen;
195 if (silencelen > 0) {
199 if (sounds[cursound].repeat) {
209 res = write(sounddev, frame, res * 2);
217 static void *sound_thread(void *unused)
227 FD_SET(sndcmd[0], &rfds);
229 FD_SET(sounddev, &wfds);
233 res = select(max + 1, &rfds, &wfds, NULL, NULL);
235 ast_log(LOG_WARNING, "select failed: %s\n", strerror(errno));
238 if (FD_ISSET(sndcmd[0], &rfds)) {
239 read(sndcmd[0], &cursound, sizeof(cursound));
244 if (FD_ISSET(sounddev, &wfds))
246 ast_log(LOG_WARNING, "Failed to write sound\n");
253 static int silence_suppress(short *buf)
257 static int silentframes = 0;
258 static char silbuf[FRAME_SIZE * 2 * SILBUF];
259 static int silbufcnt=0;
260 if (!silencesuppression)
262 loudness = calc_loudness((short *)(buf));
264 ast_log(LOG_DEBUG, "loudness is %d\n", loudness);
265 if (loudness < silencethreshold) {
268 /* Keep track of the last few bits of silence so we can play
269 them as lead-in when the time is right */
270 if (silbufcnt >= SILBUF) {
271 /* Make way for more buffer */
272 memmove(silbuf, silbuf + FRAME_SIZE * 2, FRAME_SIZE * 2 * (SILBUF - 1));
275 memcpy(silbuf + FRAME_SIZE * 2 * silbufcnt, buf, FRAME_SIZE * 2);
276 if (silentframes > 10) {
277 /* We've had plenty of silence, so compress it now */
282 /* Write any buffered silence we have, it may have something
285 write(sounddev, silbuf, silbufcnt * FRAME_SIZE);
293 static int setformat(void)
295 int fmt, desired, res, fd = sounddev;
296 static int warnedalready = 0;
297 static int warnedalready2 = 0;
299 res = ioctl(fd, SNDCTL_DSP_SETFMT, &fmt);
301 ast_log(LOG_WARNING, "Unable to set format to 16-bit signed\n");
304 res = ioctl(fd, SNDCTL_DSP_SETDUPLEX, 0);
306 if (option_verbose > 1)
307 ast_verbose(VERBOSE_PREFIX_2 "Console is full duplex\n");
311 res = ioctl(fd, SNDCTL_DSP_STEREO, &fmt);
313 ast_log(LOG_WARNING, "Failed to set audio device to mono\n");
316 /* 8000 Hz desired */
319 res = ioctl(fd, SNDCTL_DSP_SPEED, &fmt);
321 ast_log(LOG_WARNING, "Failed to set audio device to mono\n");
324 if (fmt != desired) {
325 if (!warnedalready++)
326 ast_log(LOG_WARNING, "Requested %d Hz, got %d Hz -- sound may be choppy\n", desired, fmt);
330 res = ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &fmt);
332 if (!warnedalready2++)
333 ast_log(LOG_WARNING, "Unable to set fragment size -- sound may be choppy\n");
339 static int soundcard_setoutput(int force)
341 /* Make sure the soundcard is in output mode. */
343 if (full_duplex || (!readmode && !force))
346 if (force || time_has_passed()) {
347 ioctl(sounddev, SNDCTL_DSP_RESET);
348 /* Keep the same fd reserved by closing the sound device and copying stdin at the same
350 /* dup2(0, sound); */
352 fd = open(DEV_DSP, O_WRONLY |O_NONBLOCK);
354 ast_log(LOG_WARNING, "Unable to re-open DSP device: %s\n", strerror(errno));
357 /* dup2 will close the original and make fd be sound */
358 if (dup2(fd, sounddev) < 0) {
359 ast_log(LOG_WARNING, "dup2() failed: %s\n", strerror(errno));
370 static int soundcard_setinput(int force)
373 if (full_duplex || (readmode && !force))
376 if (force || time_has_passed()) {
377 ioctl(sounddev, SNDCTL_DSP_RESET);
379 /* dup2(0, sound); */
380 fd = open(DEV_DSP, O_RDONLY | O_NONBLOCK);
382 ast_log(LOG_WARNING, "Unable to re-open DSP device: %s\n", strerror(errno));
385 /* dup2 will close the original and make fd be sound */
386 if (dup2(fd, sounddev) < 0) {
387 ast_log(LOG_WARNING, "dup2() failed: %s\n", strerror(errno));
398 static int soundcard_init()
400 /* Assume it's full duplex for starters */
401 int fd = open(DEV_DSP, O_RDWR | O_NONBLOCK);
403 ast_log(LOG_WARNING, "Unable to open %s: %s\n", DEV_DSP, strerror(errno));
406 gettimeofday(&lasttime, NULL);
410 soundcard_setinput(1);
414 static int oss_digit(struct ast_channel *c, char digit)
416 ast_verbose( " << Console Received digit %c >> \n", digit);
420 static int oss_text(struct ast_channel *c, char *text)
422 ast_verbose( " << Console Received text %s >> \n", text);
426 static int oss_call(struct ast_channel *c, char *dest, int timeout)
429 struct ast_frame f = { 0, };
430 ast_verbose( " << Call placed to '%s' on console >> \n", dest);
432 ast_verbose( " << Auto-answered >> \n" );
433 f.frametype = AST_FRAME_CONTROL;
434 f.subclass = AST_CONTROL_ANSWER;
435 ast_queue_frame(c, &f, 0);
437 ast_verbose( " << Type 'answer' to answer, or use 'autoanswer' for future calls >> \n");
438 f.frametype = AST_FRAME_CONTROL;
439 f.subclass = AST_CONTROL_RINGING;
440 ast_queue_frame(c, &f, 0);
441 write(sndcmd[1], &res, sizeof(res));
446 static void answer_sound(void)
451 write(sndcmd[1], &res, sizeof(res));
455 static int oss_answer(struct ast_channel *c)
457 ast_verbose( " << Console call has been answered >> \n");
459 c->state = AST_STATE_UP;
464 static int oss_hangup(struct ast_channel *c)
470 ast_verbose( " << Hangup on console >> \n");
471 ast_pthread_mutex_lock(&usecnt_lock);
473 ast_pthread_mutex_unlock(&usecnt_lock);
476 /* Assume auto-hangup too */
479 /* Make congestion noise */
481 write(sndcmd[1], &res, sizeof(res));
487 static int soundcard_writeframe(short *data)
489 /* Write an exactly FRAME_SIZE sized of frame */
490 static int bufcnt = 0;
491 static short buffer[FRAME_SIZE * MAX_BUFFER_SIZE * 5];
492 struct audio_buf_info info;
496 if (ioctl(fd, SNDCTL_DSP_GETOSPACE, &info)) {
498 ast_log(LOG_WARNING, "Error reading output space\n");
502 if ((info.fragments >= buffersize * 5) && (bufcnt == buffersize)) {
503 /* We've run out of stuff, buffer again */
506 if (bufcnt == buffersize) {
507 /* Write sample immediately */
508 res = write(fd, ((void *)data), FRAME_SIZE * 2);
510 /* Copy the data into our buffer */
511 res = FRAME_SIZE * 2;
512 memcpy(buffer + (bufcnt * FRAME_SIZE), data, FRAME_SIZE * 2);
514 if (bufcnt == buffersize) {
515 res = write(fd, ((void *)buffer), FRAME_SIZE * 2 * buffersize);
522 static int oss_write(struct ast_channel *chan, struct ast_frame *f)
525 static char sizbuf[8000];
526 static int sizpos = 0;
529 /* Immediately return if no sound is enabled */
532 /* Stop any currently playing sound */
535 /* If we're half duplex, we have to switch to read mode
536 to honor immediate needs if necessary */
537 res = soundcard_setinput(1);
539 ast_log(LOG_WARNING, "Unable to set device to input mode\n");
544 res = soundcard_setoutput(0);
546 ast_log(LOG_WARNING, "Unable to set output device\n");
548 } else if (res > 0) {
549 /* The device is still in read mode, and it's too soon to change it,
550 so just pretend we wrote it */
553 /* We have to digest the frame in 160-byte portions */
554 if (f->datalen > sizeof(sizbuf) - sizpos) {
555 ast_log(LOG_WARNING, "Frame too large\n");
558 memcpy(sizbuf + sizpos, f->data, f->datalen);
561 while(len - pos > FRAME_SIZE * 2) {
562 soundcard_writeframe((short *)(sizbuf + pos));
563 pos += FRAME_SIZE * 2;
566 memmove(sizbuf, sizbuf + pos, len - pos);
571 static struct ast_frame *oss_read(struct ast_channel *chan)
573 static struct ast_frame f;
574 static char buf[FRAME_SIZE * 2 + AST_FRIENDLY_OFFSET];
575 static int readpos = 0;
579 ast_log(LOG_DEBUG, "oss_read()\n");
582 f.frametype = AST_FRAME_NULL;
591 res = soundcard_setinput(0);
593 ast_log(LOG_WARNING, "Unable to set input mode\n");
597 /* Theoretically shouldn't happen, but anyway, return a NULL frame */
600 res = read(sounddev, buf + AST_FRIENDLY_OFFSET + readpos, FRAME_SIZE * 2 - readpos);
602 ast_log(LOG_WARNING, "Error reading from sound device (If you're running 'artsd' then kill it): %s\n", strerror(errno));
610 if (readpos >= FRAME_SIZE * 2) {
613 if (chan->state != AST_STATE_UP) {
614 /* Don't transmit unless it's up */
617 f.frametype = AST_FRAME_VOICE;
618 f.subclass = AST_FORMAT_SLINEAR;
619 f.timelen = FRAME_SIZE / 8;
620 f.datalen = FRAME_SIZE * 2;
621 f.data = buf + AST_FRIENDLY_OFFSET;
622 f.offset = AST_FRIENDLY_OFFSET;
626 { static int fd = -1;
628 fd = open("output.raw", O_RDWR | O_TRUNC | O_CREAT);
629 write(fd, f.data, f.datalen);
636 static int oss_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
638 struct chan_oss_pvt *p = newchan->pvt->pvt;
643 static int oss_indicate(struct ast_channel *chan, int cond)
647 case AST_CONTROL_BUSY:
650 case AST_CONTROL_CONGESTION:
653 case AST_CONTROL_RINGING:
657 ast_log(LOG_WARNING, "Don't know how to display condition %d on %s\n", cond, chan->name);
661 write(sndcmd[1], &res, sizeof(res));
666 static struct ast_channel *oss_new(struct chan_oss_pvt *p, int state)
668 struct ast_channel *tmp;
669 tmp = ast_channel_alloc(1);
671 snprintf(tmp->name, sizeof(tmp->name), "OSS/%s", DEV_DSP + 5);
673 tmp->fds[0] = sounddev;
674 tmp->nativeformats = AST_FORMAT_SLINEAR;
676 tmp->pvt->send_digit = oss_digit;
677 tmp->pvt->send_text = oss_text;
678 tmp->pvt->hangup = oss_hangup;
679 tmp->pvt->answer = oss_answer;
680 tmp->pvt->read = oss_read;
681 tmp->pvt->call = oss_call;
682 tmp->pvt->write = oss_write;
683 tmp->pvt->indicate = oss_indicate;
684 tmp->pvt->fixup = oss_fixup;
685 if (strlen(p->context))
686 strncpy(tmp->context, p->context, sizeof(tmp->context)-1);
687 if (strlen(p->exten))
688 strncpy(tmp->exten, p->exten, sizeof(tmp->exten)-1);
689 if (strlen(language))
690 strncpy(tmp->language, language, sizeof(tmp->language)-1);
693 ast_pthread_mutex_lock(&usecnt_lock);
695 ast_pthread_mutex_unlock(&usecnt_lock);
696 ast_update_use_count();
697 if (state != AST_STATE_DOWN) {
698 if (ast_pbx_start(tmp)) {
699 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
708 static struct ast_channel *oss_request(char *type, int format, void *data)
710 int oldformat = format;
711 struct ast_channel *tmp;
712 format &= AST_FORMAT_SLINEAR;
714 ast_log(LOG_NOTICE, "Asked to get a channel of format '%d'\n", oldformat);
718 ast_log(LOG_NOTICE, "Already have a call on the OSS channel\n");
721 tmp= oss_new(&oss, AST_STATE_DOWN);
723 ast_log(LOG_WARNING, "Unable to create new OSS channel\n");
728 static int console_autoanswer(int fd, int argc, char *argv[])
730 if ((argc != 1) && (argc != 2))
731 return RESULT_SHOWUSAGE;
733 ast_cli(fd, "Auto answer is %s.\n", autoanswer ? "on" : "off");
734 return RESULT_SUCCESS;
736 if (!strcasecmp(argv[1], "on"))
738 else if (!strcasecmp(argv[1], "off"))
741 return RESULT_SHOWUSAGE;
743 return RESULT_SUCCESS;
746 static char *autoanswer_complete(char *line, char *word, int pos, int state)
749 #define MIN(a,b) ((a) < (b) ? (a) : (b))
753 if (strlen(word) && !strncasecmp(word, "on", MIN(strlen(word), 2)))
756 if (strlen(word) && !strncasecmp(word, "off", MIN(strlen(word), 3)))
757 return strdup("off");
764 static char autoanswer_usage[] =
765 "Usage: autoanswer [on|off]\n"
766 " Enables or disables autoanswer feature. If used without\n"
767 " argument, displays the current on/off status of autoanswer.\n"
768 " The default value of autoanswer is in 'oss.conf'.\n";
770 static int console_answer(int fd, int argc, char *argv[])
772 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_ANSWER };
774 return RESULT_SHOWUSAGE;
776 ast_cli(fd, "No one is calling us\n");
777 return RESULT_FAILURE;
781 ast_queue_frame(oss.owner, &f, 1);
783 return RESULT_SUCCESS;
786 static char sendtext_usage[] =
787 "Usage: send text <message>\n"
788 " Sends a text message for display on the remote terminal.\n";
790 static int console_sendtext(int fd, int argc, char *argv[])
794 struct ast_frame f = { 0, };
796 return RESULT_SHOWUSAGE;
798 ast_cli(fd, "No one is calling us\n");
799 return RESULT_FAILURE;
801 if (strlen(text2send))
802 ast_cli(fd, "Warning: message already waiting to be sent, overwriting\n");
803 strcpy(text2send, "");
804 while(tmparg <= argc) {
805 strncat(text2send, argv[tmparg++], sizeof(text2send) - strlen(text2send));
806 strncat(text2send, " ", sizeof(text2send) - strlen(text2send));
808 if (strlen(text2send)) {
809 f.frametype = AST_FRAME_TEXT;
812 f.datalen = strlen(text2send);
813 ast_queue_frame(oss.owner, &f, 1);
815 return RESULT_SUCCESS;
818 static char answer_usage[] =
820 " Answers an incoming call on the console (OSS) channel.\n";
822 static int console_hangup(int fd, int argc, char *argv[])
825 return RESULT_SHOWUSAGE;
827 if (!oss.owner && !hookstate) {
828 ast_cli(fd, "No call to hangup up\n");
829 return RESULT_FAILURE;
833 ast_queue_hangup(oss.owner, 1);
835 return RESULT_SUCCESS;
838 static char hangup_usage[] =
840 " Hangs up any call currently placed on the console.\n";
843 static int console_dial(int fd, int argc, char *argv[])
845 char tmp[256], *tmp2;
848 struct ast_frame f = { AST_FRAME_DTMF, 0 };
849 if ((argc != 1) && (argc != 2))
850 return RESULT_SHOWUSAGE;
853 for (x=0;x<strlen(argv[1]);x++) {
854 f.subclass = argv[1][x];
855 ast_queue_frame(oss.owner, &f, 1);
858 ast_cli(fd, "You're already in a call. You can use this only to dial digits until you hangup\n");
859 return RESULT_FAILURE;
861 return RESULT_SUCCESS;
866 strncpy(tmp, argv[1], sizeof(tmp)-1);
868 tmp2 = strtok(NULL, "@");
871 if (tmp2 && strlen(tmp2))
874 if (ast_exists_extension(NULL, myc, mye, 1, NULL)) {
875 strncpy(oss.exten, mye, sizeof(oss.exten)-1);
876 strncpy(oss.context, myc, sizeof(oss.context)-1);
878 oss_new(&oss, AST_STATE_UP);
880 ast_cli(fd, "No such extension '%s' in context '%s'\n", mye, myc);
881 return RESULT_SUCCESS;
884 static char dial_usage[] =
885 "Usage: dial [extension[@context]]\n"
886 " Dials a given extensison (";
889 static struct ast_cli_entry myclis[] = {
890 { { "answer", NULL }, console_answer, "Answer an incoming console call", answer_usage },
891 { { "hangup", NULL }, console_hangup, "Hangup a call on the console", hangup_usage },
892 { { "dial", NULL }, console_dial, "Dial an extension on the console", dial_usage },
893 { { "send text", NULL }, console_sendtext, "Send text to the remote device", sendtext_usage },
894 { { "autoanswer", NULL }, console_autoanswer, "Sets/displays autoanswer", autoanswer_usage, autoanswer_complete }
901 struct ast_config *cfg = ast_load(config);
902 struct ast_variable *v;
905 ast_log(LOG_ERROR, "Unable to create pipe\n");
908 res = soundcard_init();
910 if (option_verbose > 1) {
911 ast_verbose(VERBOSE_PREFIX_2 "No sound card detected -- console channel will be unavailable\n");
912 ast_verbose(VERBOSE_PREFIX_2 "Turn off OSS support by adding 'noload=chan_oss.so' in /etc/asterisk/modules.conf\n");
917 ast_log(LOG_WARNING, "XXX I don't work right with non-full duplex sound cards XXX\n");
918 res = ast_channel_register(type, tdesc, AST_FORMAT_SLINEAR, oss_request);
920 ast_log(LOG_ERROR, "Unable to register channel class '%s'\n", type);
923 for (x=0;x<sizeof(myclis)/sizeof(struct ast_cli_entry); x++)
924 ast_cli_register(myclis + x);
926 v = ast_variable_browse(cfg, "general");
928 if (!strcasecmp(v->name, "autoanswer"))
929 autoanswer = ast_true(v->value);
930 else if (!strcasecmp(v->name, "silencesuppression"))
931 silencesuppression = ast_true(v->value);
932 else if (!strcasecmp(v->name, "silencethreshold"))
933 silencethreshold = atoi(v->value);
934 else if (!strcasecmp(v->name, "context"))
935 strncpy(context, v->value, sizeof(context)-1);
936 else if (!strcasecmp(v->name, "language"))
937 strncpy(language, v->value, sizeof(language)-1);
938 else if (!strcasecmp(v->name, "extension"))
939 strncpy(exten, v->value, sizeof(exten)-1);
944 pthread_create(&sthread, NULL, sound_thread, NULL);
953 for (x=0;x<sizeof(myclis)/sizeof(struct ast_cli_entry); x++)
954 ast_cli_unregister(myclis + x);
961 ast_softhangup(oss.owner);
975 ast_pthread_mutex_lock(&usecnt_lock);
977 ast_pthread_mutex_unlock(&usecnt_lock);
983 return ASTERISK_GPL_KEY;