chan_alsa.c 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. /*
  2. * Asterisk -- A telephony toolkit for Linux.
  3. *
  4. * Copyright (C) 2002, Linux Support Services
  5. *
  6. * By Matthew Fredrickson <creslin@linux-support.net>
  7. *
  8. * This program is free software, distributed under the terms of
  9. * the GNU General Public License
  10. */
  11. #include <asterisk/frame.h>
  12. #include <asterisk/logger.h>
  13. #include <asterisk/channel.h>
  14. #include <asterisk/module.h>
  15. #include <asterisk/channel_pvt.h>
  16. #include <asterisk/options.h>
  17. #include <asterisk/pbx.h>
  18. #include <asterisk/config.h>
  19. #include <asterisk/cli.h>
  20. #include <unistd.h>
  21. #include <fcntl.h>
  22. #include <errno.h>
  23. #include <sys/ioctl.h>
  24. #include <sys/time.h>
  25. #include <string.h>
  26. #include <stdlib.h>
  27. #include <stdio.h>
  28. #define ALSA_PCM_NEW_HW_PARAMS_API
  29. #define ALSA_PCM_NEW_SW_PARAMS_API
  30. #include <alsa/asoundlib.h>
  31. #include "busy.h"
  32. #include "ringtone.h"
  33. #include "ring10.h"
  34. #include "answer.h"
  35. #ifdef ALSA_MONITOR
  36. #include "alsa-monitor.h"
  37. #endif
  38. #define DEBUG 0
  39. /* Which device to use */
  40. #define ALSA_INDEV "default"
  41. #define ALSA_OUTDEV "default"
  42. #define DESIRED_RATE 8000
  43. /* Lets use 160 sample frames, just like GSM. */
  44. #define FRAME_SIZE 160
  45. #define PERIOD_FRAMES 80 /* 80 Frames, at 2 bytes each */
  46. /* When you set the frame size, you have to come up with
  47. the right buffer format as well. */
  48. /* 5 64-byte frames = one frame */
  49. #define BUFFER_FMT ((buffersize * 10) << 16) | (0x0006);
  50. /* Don't switch between read/write modes faster than every 300 ms */
  51. #define MIN_SWITCH_TIME 600
  52. static snd_pcm_format_t format = SND_PCM_FORMAT_S16_LE;
  53. //static int block = O_NONBLOCK;
  54. static char indevname[50] = ALSA_INDEV;
  55. static char outdevname[50] = ALSA_OUTDEV;
  56. #if 0
  57. static struct timeval lasttime;
  58. #endif
  59. static int usecnt;
  60. static int needanswer = 0;
  61. static int needringing = 0;
  62. static int needhangup = 0;
  63. static int silencesuppression = 0;
  64. static int silencethreshold = 1000;
  65. static char digits[80] = "";
  66. static char text2send[80] = "";
  67. static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
  68. static char *type = "Console";
  69. static char *desc = "ALSA Console Channel Driver";
  70. static char *tdesc = "ALSA Console Channel Driver";
  71. static char *config = "alsa.conf";
  72. static char context[AST_MAX_EXTENSION] = "default";
  73. static char language[MAX_LANGUAGE] = "";
  74. static char exten[AST_MAX_EXTENSION] = "s";
  75. /* Command pipe */
  76. static int cmd[2];
  77. int hookstate=0;
  78. static short silence[FRAME_SIZE] = {0, };
  79. struct sound {
  80. int ind;
  81. short *data;
  82. int datalen;
  83. int samplen;
  84. int silencelen;
  85. int repeat;
  86. };
  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 },
  93. };
  94. /* Sound command pipe */
  95. static int sndcmd[2];
  96. static struct chan_alsa_pvt {
  97. /* We only have one ALSA structure -- near sighted perhaps, but it
  98. keeps this driver as simple as possible -- as it should be. */
  99. struct ast_channel *owner;
  100. char exten[AST_MAX_EXTENSION];
  101. char context[AST_MAX_EXTENSION];
  102. #if 0
  103. snd_pcm_t *card;
  104. #endif
  105. snd_pcm_t *icard, *ocard;
  106. } alsa;
  107. #if 0
  108. static int time_has_passed(void)
  109. {
  110. struct timeval tv;
  111. int ms;
  112. gettimeofday(&tv, NULL);
  113. ms = (tv.tv_sec - lasttime.tv_sec) * 1000 +
  114. (tv.tv_usec - lasttime.tv_usec) / 1000;
  115. if (ms > MIN_SWITCH_TIME)
  116. return -1;
  117. return 0;
  118. }
  119. #endif
  120. /* Number of buffers... Each is FRAMESIZE/8 ms long. For example
  121. with 160 sample frames, and a buffer size of 3, we have a 60ms buffer,
  122. usually plenty. */
  123. pthread_t sthread;
  124. #define MAX_BUFFER_SIZE 100
  125. //static int buffersize = 3;
  126. //static int full_duplex = 0;
  127. /* Are we reading or writing (simulated full duplex) */
  128. //static int readmode = 1;
  129. /* File descriptors for sound device */
  130. static int readdev = -1;
  131. static int writedev = -1;
  132. static int autoanswer = 1;
  133. #if 0
  134. static int calc_loudness(short *frame)
  135. {
  136. int sum = 0;
  137. int x;
  138. for (x=0;x<FRAME_SIZE;x++) {
  139. if (frame[x] < 0)
  140. sum -= frame[x];
  141. else
  142. sum += frame[x];
  143. }
  144. sum = sum/FRAME_SIZE;
  145. return sum;
  146. }
  147. #endif
  148. static int cursound = -1;
  149. static int sampsent = 0;
  150. static int silencelen=0;
  151. static int offset=0;
  152. static int nosound=0;
  153. static int send_sound(void)
  154. {
  155. short myframe[FRAME_SIZE];
  156. int total = FRAME_SIZE;
  157. short *frame = NULL;
  158. int amt=0;
  159. int res;
  160. int myoff;
  161. snd_pcm_state_t state;
  162. if (cursound > -1) {
  163. res = total;
  164. if (sampsent < sounds[cursound].samplen) {
  165. myoff=0;
  166. while(total) {
  167. amt = total;
  168. if (amt > (sounds[cursound].datalen - offset))
  169. amt = sounds[cursound].datalen - offset;
  170. memcpy(myframe + myoff, sounds[cursound].data + offset, amt * 2);
  171. total -= amt;
  172. offset += amt;
  173. sampsent += amt;
  174. myoff += amt;
  175. if (offset >= sounds[cursound].datalen)
  176. offset = 0;
  177. }
  178. /* Set it up for silence */
  179. if (sampsent >= sounds[cursound].samplen)
  180. silencelen = sounds[cursound].silencelen;
  181. frame = myframe;
  182. } else {
  183. if (silencelen > 0) {
  184. frame = silence;
  185. silencelen -= res;
  186. } else {
  187. if (sounds[cursound].repeat) {
  188. /* Start over */
  189. sampsent = 0;
  190. offset = 0;
  191. } else {
  192. cursound = -1;
  193. nosound = 0;
  194. }
  195. return 0;
  196. }
  197. }
  198. if (res == 0 || !frame) {
  199. return 0;
  200. }
  201. #ifdef ALSA_MONITOR
  202. alsa_monitor_write((char *)frame, res * 2);
  203. #endif
  204. state = snd_pcm_state(alsa.ocard);
  205. if (state == SND_PCM_STATE_XRUN) {
  206. snd_pcm_prepare(alsa.ocard);
  207. }
  208. res = snd_pcm_writei(alsa.ocard, frame, res);
  209. if (res > 0)
  210. return 0;
  211. return 0;
  212. }
  213. return 0;
  214. }
  215. static void *sound_thread(void *unused)
  216. {
  217. fd_set rfds;
  218. fd_set wfds;
  219. int max;
  220. int res;
  221. for(;;) {
  222. FD_ZERO(&rfds);
  223. FD_ZERO(&wfds);
  224. max = sndcmd[0];
  225. FD_SET(sndcmd[0], &rfds);
  226. if (cursound > -1) {
  227. FD_SET(writedev, &wfds);
  228. if (writedev > max)
  229. max = writedev;
  230. }
  231. #ifdef ALSA_MONITOR
  232. if (!alsa.owner) {
  233. FD_SET(readdev, &rfds);
  234. if (readdev > max)
  235. max = readdev;
  236. }
  237. #endif
  238. res = ast_select(max + 1, &rfds, &wfds, NULL, NULL);
  239. if (res < 1) {
  240. ast_log(LOG_WARNING, "select failed: %s\n", strerror(errno));
  241. continue;
  242. }
  243. #ifdef ALSA_MONITOR
  244. if (FD_ISSET(readdev, &rfds)) {
  245. /* Keep the pipe going with read audio */
  246. snd_pcm_state_t state;
  247. short buf[FRAME_SIZE];
  248. int r;
  249. state = snd_pcm_state(alsa.ocard);
  250. if (state == SND_PCM_STATE_XRUN) {
  251. snd_pcm_prepare(alsa.ocard);
  252. }
  253. r = snd_pcm_readi(alsa.icard, buf, FRAME_SIZE);
  254. if (r == -EPIPE) {
  255. #if DEBUG
  256. ast_log(LOG_ERROR, "XRUN read\n");
  257. #endif
  258. snd_pcm_prepare(alsa.icard);
  259. } else if (r == -ESTRPIPE) {
  260. ast_log(LOG_ERROR, "-ESTRPIPE\n");
  261. snd_pcm_prepare(alsa.icard);
  262. } else if (r < 0) {
  263. ast_log(LOG_ERROR, "Read error: %s\n", snd_strerror(r));
  264. } else
  265. alsa_monitor_read((char *)buf, r * 2);
  266. }
  267. #endif
  268. if (FD_ISSET(sndcmd[0], &rfds)) {
  269. read(sndcmd[0], &cursound, sizeof(cursound));
  270. silencelen = 0;
  271. offset = 0;
  272. sampsent = 0;
  273. }
  274. if (FD_ISSET(writedev, &wfds))
  275. if (send_sound())
  276. ast_log(LOG_WARNING, "Failed to write sound\n");
  277. }
  278. /* Never reached */
  279. return NULL;
  280. }
  281. static snd_pcm_t *alsa_card_init(char *dev, snd_pcm_stream_t stream)
  282. {
  283. int err;
  284. int direction;
  285. snd_pcm_t *handle = NULL;
  286. snd_pcm_hw_params_t *hwparams = NULL;
  287. snd_pcm_sw_params_t *swparams = NULL;
  288. struct pollfd pfd;
  289. snd_pcm_uframes_t period_size = PERIOD_FRAMES * 4;
  290. //int period_bytes = 0;
  291. snd_pcm_uframes_t buffer_size = 0;
  292. unsigned int rate = DESIRED_RATE;
  293. unsigned int per_min = 1;
  294. //unsigned int per_max = 8;
  295. snd_pcm_uframes_t start_threshold, stop_threshold;
  296. err = snd_pcm_open(&handle, dev, stream, O_NONBLOCK);
  297. if (err < 0) {
  298. ast_log(LOG_ERROR, "snd_pcm_open failed: %s\n", snd_strerror(err));
  299. return NULL;
  300. } else {
  301. ast_log(LOG_DEBUG, "Opening device %s in %s mode\n", dev, (stream == SND_PCM_STREAM_CAPTURE) ? "read" : "write");
  302. }
  303. snd_pcm_hw_params_alloca(&hwparams);
  304. snd_pcm_hw_params_any(handle, hwparams);
  305. err = snd_pcm_hw_params_set_access(handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED);
  306. if (err < 0) {
  307. ast_log(LOG_ERROR, "set_access failed: %s\n", snd_strerror(err));
  308. }
  309. err = snd_pcm_hw_params_set_format(handle, hwparams, format);
  310. if (err < 0) {
  311. ast_log(LOG_ERROR, "set_format failed: %s\n", snd_strerror(err));
  312. }
  313. err = snd_pcm_hw_params_set_channels(handle, hwparams, 1);
  314. if (err < 0) {
  315. ast_log(LOG_ERROR, "set_channels failed: %s\n", snd_strerror(err));
  316. }
  317. direction = 0;
  318. err = snd_pcm_hw_params_set_rate_near(handle, hwparams, &rate, &direction);
  319. if (rate != DESIRED_RATE) {
  320. ast_log(LOG_WARNING, "Rate not correct, requested %d, got %d\n", DESIRED_RATE, rate);
  321. }
  322. direction = 0;
  323. err = snd_pcm_hw_params_set_period_size_near(handle, hwparams, &period_size, &direction);
  324. if (err < 0) {
  325. ast_log(LOG_ERROR, "period_size(%ld frames) is bad: %s\n", period_size, snd_strerror(err));
  326. } else {
  327. ast_log(LOG_DEBUG, "Period size is %d\n", err);
  328. }
  329. buffer_size = 4096 * 2; //period_size * 16;
  330. err = snd_pcm_hw_params_set_buffer_size_near(handle, hwparams, &buffer_size);
  331. if (err < 0) {
  332. ast_log(LOG_WARNING, "Problem setting buffer size of %ld: %s\n", buffer_size, snd_strerror(err));
  333. } else {
  334. ast_log(LOG_DEBUG, "Buffer size is set to %d frames\n", err);
  335. }
  336. #if 0
  337. direction = 0;
  338. err = snd_pcm_hw_params_set_periods_min(handle, hwparams, &per_min, &direction);
  339. if (err < 0) {
  340. ast_log(LOG_ERROR, "periods_min: %s\n", snd_strerror(err));
  341. }
  342. err = snd_pcm_hw_params_set_periods_max(handle, hwparams, &per_max, 0);
  343. if (err < 0) {
  344. ast_log(LOG_ERROR, "periods_max: %s\n", snd_strerror(err));
  345. }
  346. #endif
  347. err = snd_pcm_hw_params(handle, hwparams);
  348. if (err < 0) {
  349. ast_log(LOG_ERROR, "Couldn't set the new hw params: %s\n", snd_strerror(err));
  350. }
  351. snd_pcm_sw_params_alloca(&swparams);
  352. snd_pcm_sw_params_current(handle, swparams);
  353. #if 1
  354. if (stream == SND_PCM_STREAM_PLAYBACK) {
  355. start_threshold = period_size;
  356. } else {
  357. start_threshold = 1;
  358. }
  359. err = snd_pcm_sw_params_set_start_threshold(handle, swparams, start_threshold);
  360. if (err < 0) {
  361. ast_log(LOG_ERROR, "start threshold: %s\n", snd_strerror(err));
  362. }
  363. #endif
  364. #if 1
  365. if (stream == SND_PCM_STREAM_PLAYBACK) {
  366. stop_threshold = buffer_size;
  367. } else {
  368. stop_threshold = buffer_size;
  369. }
  370. err = snd_pcm_sw_params_set_stop_threshold(handle, swparams, stop_threshold);
  371. if (err < 0) {
  372. ast_log(LOG_ERROR, "stop threshold: %s\n", snd_strerror(err));
  373. }
  374. #endif
  375. #if 0
  376. err = snd_pcm_sw_params_set_xfer_align(handle, swparams, PERIOD_FRAMES);
  377. if (err < 0) {
  378. ast_log(LOG_ERROR, "Unable to set xfer alignment: %s\n", snd_strerror(err));
  379. }
  380. #endif
  381. #if 0
  382. err = snd_pcm_sw_params_set_silence_threshold(handle, swparams, silencethreshold);
  383. if (err < 0) {
  384. ast_log(LOG_ERROR, "Unable to set silence threshold: %s\n", snd_strerror(err));
  385. }
  386. #endif
  387. err = snd_pcm_sw_params(handle, swparams);
  388. if (err < 0) {
  389. ast_log(LOG_ERROR, "sw_params: %s\n", snd_strerror(err));
  390. }
  391. err = snd_pcm_poll_descriptors_count(handle);
  392. if (err <= 0) {
  393. ast_log(LOG_ERROR, "Unable to get a poll descriptors count, error is %s\n", snd_strerror(err));
  394. }
  395. if (err != 1) {
  396. ast_log(LOG_DEBUG, "Can't handle more than one device\n");
  397. }
  398. snd_pcm_poll_descriptors(handle, &pfd, err);
  399. ast_log(LOG_DEBUG, "Acquired fd %d from the poll descriptor\n", pfd.fd);
  400. if (stream == SND_PCM_STREAM_CAPTURE)
  401. readdev = pfd.fd;
  402. else
  403. writedev = pfd.fd;
  404. return handle;
  405. }
  406. static int soundcard_init(void)
  407. {
  408. alsa.icard = alsa_card_init(indevname, SND_PCM_STREAM_CAPTURE);
  409. alsa.ocard = alsa_card_init(outdevname, SND_PCM_STREAM_PLAYBACK);
  410. if (!alsa.icard || !alsa.ocard) {
  411. ast_log(LOG_ERROR, "Problem opening alsa I/O devices\n");
  412. return -1;
  413. }
  414. return readdev;
  415. }
  416. static int alsa_digit(struct ast_channel *c, char digit)
  417. {
  418. ast_verbose( " << Console Received digit %c >> \n", digit);
  419. return 0;
  420. }
  421. static int alsa_text(struct ast_channel *c, char *text)
  422. {
  423. ast_verbose( " << Console Received text %s >> \n", text);
  424. return 0;
  425. }
  426. static int alsa_call(struct ast_channel *c, char *dest, int timeout)
  427. {
  428. int res = 3;
  429. ast_verbose( " << Call placed to '%s' on console >> \n", dest);
  430. if (autoanswer) {
  431. ast_verbose( " << Auto-answered >> \n" );
  432. needanswer = 1;
  433. } else {
  434. ast_verbose( " << Type 'answer' to answer, or use 'autoanswer' for future calls >> \n");
  435. needringing = 1;
  436. write(sndcmd[1], &res, sizeof(res));
  437. }
  438. return 0;
  439. }
  440. static void answer_sound(void)
  441. {
  442. int res;
  443. nosound = 1;
  444. res = 4;
  445. write(sndcmd[1], &res, sizeof(res));
  446. }
  447. static int alsa_answer(struct ast_channel *c)
  448. {
  449. ast_verbose( " << Console call has been answered >> \n");
  450. answer_sound();
  451. ast_setstate(c, AST_STATE_UP);
  452. cursound = -1;
  453. return 0;
  454. }
  455. static int alsa_hangup(struct ast_channel *c)
  456. {
  457. int res;
  458. cursound = -1;
  459. c->pvt->pvt = NULL;
  460. alsa.owner = NULL;
  461. ast_verbose( " << Hangup on console >> \n");
  462. ast_mutex_lock(&usecnt_lock);
  463. usecnt--;
  464. ast_mutex_unlock(&usecnt_lock);
  465. needhangup = 0;
  466. needanswer = 0;
  467. if (hookstate) {
  468. res = 2;
  469. write(sndcmd[1], &res, sizeof(res));
  470. }
  471. return 0;
  472. }
  473. #if 0
  474. static int soundcard_writeframe(short *data)
  475. {
  476. /* Write an exactly FRAME_SIZE sized of frame */
  477. static int bufcnt = 0;
  478. static short buffer[FRAME_SIZE * MAX_BUFFER_SIZE * 5];
  479. struct audio_buf_info info;
  480. int res;
  481. int fd = sounddev;
  482. static int warned=0;
  483. if (ioctl(fd, SNDCTL_DSP_GETOSPACE, &info)) {
  484. if (!warned)
  485. ast_log(LOG_WARNING, "Error reading output space\n");
  486. bufcnt = buffersize;
  487. warned++;
  488. }
  489. if ((info.fragments >= buffersize * 5) && (bufcnt == buffersize)) {
  490. /* We've run out of stuff, buffer again */
  491. bufcnt = 0;
  492. }
  493. if (bufcnt == buffersize) {
  494. /* Write sample immediately */
  495. res = write(fd, ((void *)data), FRAME_SIZE * 2);
  496. } else {
  497. /* Copy the data into our buffer */
  498. res = FRAME_SIZE * 2;
  499. memcpy(buffer + (bufcnt * FRAME_SIZE), data, FRAME_SIZE * 2);
  500. bufcnt++;
  501. if (bufcnt == buffersize) {
  502. res = write(fd, ((void *)buffer), FRAME_SIZE * 2 * buffersize);
  503. }
  504. }
  505. return res;
  506. }
  507. #endif
  508. static int alsa_write(struct ast_channel *chan, struct ast_frame *f)
  509. {
  510. int res;
  511. static char sizbuf[8000];
  512. static int sizpos = 0;
  513. int len = sizpos;
  514. int pos;
  515. //size_t frames = 0;
  516. snd_pcm_state_t state;
  517. /* Immediately return if no sound is enabled */
  518. if (nosound)
  519. return 0;
  520. /* Stop any currently playing sound */
  521. if (cursound != -1) {
  522. snd_pcm_drop(alsa.ocard);
  523. snd_pcm_prepare(alsa.ocard);
  524. cursound = -1;
  525. }
  526. /* We have to digest the frame in 160-byte portions */
  527. if (f->datalen > sizeof(sizbuf) - sizpos) {
  528. ast_log(LOG_WARNING, "Frame too large\n");
  529. return -1;
  530. }
  531. memcpy(sizbuf + sizpos, f->data, f->datalen);
  532. len += f->datalen;
  533. pos = 0;
  534. #ifdef ALSA_MONITOR
  535. alsa_monitor_write(sizbuf, len);
  536. #endif
  537. state = snd_pcm_state(alsa.ocard);
  538. if (state == SND_PCM_STATE_XRUN) {
  539. snd_pcm_prepare(alsa.ocard);
  540. }
  541. res = snd_pcm_writei(alsa.ocard, sizbuf, len/2);
  542. if (res == -EPIPE) {
  543. #if DEBUG
  544. ast_log(LOG_DEBUG, "XRUN write\n");
  545. #endif
  546. snd_pcm_prepare(alsa.ocard);
  547. res = snd_pcm_writei(alsa.ocard, sizbuf, len/2);
  548. if (res != len/2) {
  549. ast_log(LOG_ERROR, "Write error: %s\n", snd_strerror(res));
  550. return -1;
  551. } else if (res < 0) {
  552. ast_log(LOG_ERROR, "Write error %s\n", snd_strerror(res));
  553. return -1;
  554. }
  555. } else {
  556. if (res == -ESTRPIPE) {
  557. ast_log(LOG_ERROR, "You've got some big problems\n");
  558. }
  559. }
  560. return 0;
  561. }
  562. static struct ast_frame *alsa_read(struct ast_channel *chan)
  563. {
  564. static struct ast_frame f;
  565. static short __buf[FRAME_SIZE + AST_FRIENDLY_OFFSET/2];
  566. short *buf;
  567. static int readpos = 0;
  568. static int left = FRAME_SIZE;
  569. int res;
  570. int b;
  571. int nonull=0;
  572. snd_pcm_state_t state;
  573. int r = 0;
  574. int off = 0;
  575. /* Acknowledge any pending cmd */
  576. res = read(cmd[0], &b, sizeof(b));
  577. if (res > 0)
  578. nonull = 1;
  579. f.frametype = AST_FRAME_NULL;
  580. f.subclass = 0;
  581. f.samples = 0;
  582. f.datalen = 0;
  583. f.data = NULL;
  584. f.offset = 0;
  585. f.src = type;
  586. f.mallocd = 0;
  587. if (needringing) {
  588. f.frametype = AST_FRAME_CONTROL;
  589. f.subclass = AST_CONTROL_RINGING;
  590. needringing = 0;
  591. return &f;
  592. }
  593. if (needhangup) {
  594. needhangup = 0;
  595. return NULL;
  596. }
  597. if (strlen(text2send)) {
  598. f.frametype = AST_FRAME_TEXT;
  599. f.subclass = 0;
  600. f.data = text2send;
  601. f.datalen = strlen(text2send);
  602. strcpy(text2send,"");
  603. return &f;
  604. }
  605. if (strlen(digits)) {
  606. f.frametype = AST_FRAME_DTMF;
  607. f.subclass = digits[0];
  608. for (res=0;res<strlen(digits);res++)
  609. digits[res] = digits[res + 1];
  610. return &f;
  611. }
  612. if (needanswer) {
  613. needanswer = 0;
  614. f.frametype = AST_FRAME_CONTROL;
  615. f.subclass = AST_CONTROL_ANSWER;
  616. ast_setstate(chan, AST_STATE_UP);
  617. return &f;
  618. }
  619. if (nonull)
  620. return &f;
  621. state = snd_pcm_state(alsa.ocard);
  622. if (state == SND_PCM_STATE_XRUN) {
  623. snd_pcm_prepare(alsa.ocard);
  624. }
  625. buf = __buf + AST_FRIENDLY_OFFSET/2;
  626. r = snd_pcm_readi(alsa.icard, buf + readpos, left);
  627. if (r == -EPIPE) {
  628. #if DEBUG
  629. ast_log(LOG_ERROR, "XRUN read\n");
  630. #endif
  631. snd_pcm_prepare(alsa.icard);
  632. } else if (r == -ESTRPIPE) {
  633. ast_log(LOG_ERROR, "-ESTRPIPE\n");
  634. snd_pcm_prepare(alsa.icard);
  635. } else if (r < 0) {
  636. ast_log(LOG_ERROR, "Read error: %s\n", snd_strerror(r));
  637. return NULL;
  638. } else if (r >= 0) {
  639. off -= r;
  640. }
  641. /* Update positions */
  642. readpos += r;
  643. left -= r;
  644. if (readpos >= FRAME_SIZE) {
  645. /* A real frame */
  646. readpos = 0;
  647. left = FRAME_SIZE;
  648. if (chan->_state != AST_STATE_UP) {
  649. /* Don't transmit unless it's up */
  650. return &f;
  651. }
  652. f.frametype = AST_FRAME_VOICE;
  653. f.subclass = AST_FORMAT_SLINEAR;
  654. f.samples = FRAME_SIZE;
  655. f.datalen = FRAME_SIZE * 2;
  656. f.data = buf;
  657. f.offset = AST_FRIENDLY_OFFSET;
  658. f.src = type;
  659. f.mallocd = 0;
  660. #ifdef ALSA_MONITOR
  661. alsa_monitor_read((char *)buf, FRAME_SIZE * 2);
  662. #endif
  663. #if 0
  664. { static int fd = -1;
  665. if (fd < 0)
  666. fd = open("output.raw", O_RDWR | O_TRUNC | O_CREAT);
  667. write(fd, f.data, f.datalen);
  668. }
  669. #endif
  670. }
  671. return &f;
  672. }
  673. static int alsa_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
  674. {
  675. struct chan_alsa_pvt *p = newchan->pvt->pvt;
  676. p->owner = newchan;
  677. return 0;
  678. }
  679. static int alsa_indicate(struct ast_channel *chan, int cond)
  680. {
  681. int res;
  682. switch(cond) {
  683. case AST_CONTROL_BUSY:
  684. res = 1;
  685. break;
  686. case AST_CONTROL_CONGESTION:
  687. res = 2;
  688. break;
  689. case AST_CONTROL_RINGING:
  690. res = 0;
  691. break;
  692. default:
  693. ast_log(LOG_WARNING, "Don't know how to display condition %d on %s\n", cond, chan->name);
  694. return -1;
  695. }
  696. if (res > -1) {
  697. write(sndcmd[1], &res, sizeof(res));
  698. }
  699. return 0;
  700. }
  701. static struct ast_channel *alsa_new(struct chan_alsa_pvt *p, int state)
  702. {
  703. struct ast_channel *tmp;
  704. tmp = ast_channel_alloc(1);
  705. if (tmp) {
  706. snprintf(tmp->name, sizeof(tmp->name), "ALSA/%s", indevname);
  707. tmp->type = type;
  708. tmp->fds[0] = readdev;
  709. tmp->fds[1] = cmd[0];
  710. tmp->nativeformats = AST_FORMAT_SLINEAR;
  711. tmp->pvt->pvt = p;
  712. tmp->pvt->send_digit = alsa_digit;
  713. tmp->pvt->send_text = alsa_text;
  714. tmp->pvt->hangup = alsa_hangup;
  715. tmp->pvt->answer = alsa_answer;
  716. tmp->pvt->read = alsa_read;
  717. tmp->pvt->call = alsa_call;
  718. tmp->pvt->write = alsa_write;
  719. tmp->pvt->indicate = alsa_indicate;
  720. tmp->pvt->fixup = alsa_fixup;
  721. if (strlen(p->context))
  722. strncpy(tmp->context, p->context, sizeof(tmp->context)-1);
  723. if (strlen(p->exten))
  724. strncpy(tmp->exten, p->exten, sizeof(tmp->exten)-1);
  725. if (strlen(language))
  726. strncpy(tmp->language, language, sizeof(tmp->language)-1);
  727. p->owner = tmp;
  728. ast_setstate(tmp, state);
  729. ast_mutex_lock(&usecnt_lock);
  730. usecnt++;
  731. ast_mutex_unlock(&usecnt_lock);
  732. ast_update_use_count();
  733. if (state != AST_STATE_DOWN) {
  734. if (ast_pbx_start(tmp)) {
  735. ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
  736. ast_hangup(tmp);
  737. tmp = NULL;
  738. }
  739. }
  740. }
  741. return tmp;
  742. }
  743. static struct ast_channel *alsa_request(char *type, int format, void *data)
  744. {
  745. int oldformat = format;
  746. struct ast_channel *tmp;
  747. format &= AST_FORMAT_SLINEAR;
  748. if (!format) {
  749. ast_log(LOG_NOTICE, "Asked to get a channel of format '%d'\n", oldformat);
  750. return NULL;
  751. }
  752. if (alsa.owner) {
  753. ast_log(LOG_NOTICE, "Already have a call on the ALSA channel\n");
  754. return NULL;
  755. }
  756. tmp= alsa_new(&alsa, AST_STATE_DOWN);
  757. if (!tmp) {
  758. ast_log(LOG_WARNING, "Unable to create new ALSA channel\n");
  759. }
  760. return tmp;
  761. }
  762. static int console_autoanswer(int fd, int argc, char *argv[])
  763. {
  764. if ((argc != 1) && (argc != 2))
  765. return RESULT_SHOWUSAGE;
  766. if (argc == 1) {
  767. ast_cli(fd, "Auto answer is %s.\n", autoanswer ? "on" : "off");
  768. return RESULT_SUCCESS;
  769. } else {
  770. if (!strcasecmp(argv[1], "on"))
  771. autoanswer = -1;
  772. else if (!strcasecmp(argv[1], "off"))
  773. autoanswer = 0;
  774. else
  775. return RESULT_SHOWUSAGE;
  776. }
  777. return RESULT_SUCCESS;
  778. }
  779. static char *autoanswer_complete(char *line, char *word, int pos, int state)
  780. {
  781. #ifndef MIN
  782. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  783. #endif
  784. switch(state) {
  785. case 0:
  786. if (strlen(word) && !strncasecmp(word, "on", MIN(strlen(word), 2)))
  787. return strdup("on");
  788. case 1:
  789. if (strlen(word) && !strncasecmp(word, "off", MIN(strlen(word), 3)))
  790. return strdup("off");
  791. default:
  792. return NULL;
  793. }
  794. return NULL;
  795. }
  796. static char autoanswer_usage[] =
  797. "Usage: autoanswer [on|off]\n"
  798. " Enables or disables autoanswer feature. If used without\n"
  799. " argument, displays the current on/off status of autoanswer.\n"
  800. " The default value of autoanswer is in 'alsa.conf'.\n";
  801. static int console_answer(int fd, int argc, char *argv[])
  802. {
  803. if (argc != 1)
  804. return RESULT_SHOWUSAGE;
  805. if (!alsa.owner) {
  806. ast_cli(fd, "No one is calling us\n");
  807. return RESULT_FAILURE;
  808. }
  809. hookstate = 1;
  810. cursound = -1;
  811. needanswer++;
  812. answer_sound();
  813. return RESULT_SUCCESS;
  814. }
  815. static char sendtext_usage[] =
  816. "Usage: send text <message>\n"
  817. " Sends a text message for display on the remote terminal.\n";
  818. static int console_sendtext(int fd, int argc, char *argv[])
  819. {
  820. int tmparg = 2;
  821. if (argc < 2)
  822. return RESULT_SHOWUSAGE;
  823. if (!alsa.owner) {
  824. ast_cli(fd, "No one is calling us\n");
  825. return RESULT_FAILURE;
  826. }
  827. if (strlen(text2send))
  828. ast_cli(fd, "Warning: message already waiting to be sent, overwriting\n");
  829. strcpy(text2send, "");
  830. while(tmparg <= argc) {
  831. strncat(text2send, argv[tmparg++], sizeof(text2send) - strlen(text2send));
  832. strncat(text2send, " ", sizeof(text2send) - strlen(text2send));
  833. }
  834. needanswer++;
  835. return RESULT_SUCCESS;
  836. }
  837. static char answer_usage[] =
  838. "Usage: answer\n"
  839. " Answers an incoming call on the console (ALSA) channel.\n";
  840. static int console_hangup(int fd, int argc, char *argv[])
  841. {
  842. if (argc != 1)
  843. return RESULT_SHOWUSAGE;
  844. cursound = -1;
  845. if (!alsa.owner && !hookstate) {
  846. ast_cli(fd, "No call to hangup up\n");
  847. return RESULT_FAILURE;
  848. }
  849. hookstate = 0;
  850. if (alsa.owner) {
  851. ast_queue_hangup(alsa.owner, 1);
  852. }
  853. return RESULT_SUCCESS;
  854. }
  855. static char hangup_usage[] =
  856. "Usage: hangup\n"
  857. " Hangs up any call currently placed on the console.\n";
  858. static int console_dial(int fd, int argc, char *argv[])
  859. {
  860. char tmp[256], *tmp2;
  861. char *mye, *myc;
  862. int b = 0;
  863. if ((argc != 1) && (argc != 2))
  864. return RESULT_SHOWUSAGE;
  865. if (alsa.owner) {
  866. if (argc == 2) {
  867. strncat(digits, argv[1], sizeof(digits) - strlen(digits));
  868. /* Wake up the polling thread */
  869. write(cmd[1], &b, sizeof(b));
  870. } else {
  871. ast_cli(fd, "You're already in a call. You can use this only to dial digits until you hangup\n");
  872. return RESULT_FAILURE;
  873. }
  874. return RESULT_SUCCESS;
  875. }
  876. mye = exten;
  877. myc = context;
  878. if (argc == 2) {
  879. char *stringp=NULL;
  880. strncpy(tmp, argv[1], sizeof(tmp)-1);
  881. stringp=tmp;
  882. strsep(&stringp, "@");
  883. tmp2 = strsep(&stringp, "@");
  884. if (strlen(tmp))
  885. mye = tmp;
  886. if (tmp2 && strlen(tmp2))
  887. myc = tmp2;
  888. }
  889. if (ast_exists_extension(NULL, myc, mye, 1, NULL)) {
  890. strncpy(alsa.exten, mye, sizeof(alsa.exten)-1);
  891. strncpy(alsa.context, myc, sizeof(alsa.context)-1);
  892. hookstate = 1;
  893. alsa_new(&alsa, AST_STATE_RINGING);
  894. } else
  895. ast_cli(fd, "No such extension '%s' in context '%s'\n", mye, myc);
  896. return RESULT_SUCCESS;
  897. }
  898. static char dial_usage[] =
  899. "Usage: dial [extension[@context]]\n"
  900. " Dials a given extensison (";
  901. static struct ast_cli_entry myclis[] = {
  902. { { "answer", NULL }, console_answer, "Answer an incoming console call", answer_usage },
  903. { { "hangup", NULL }, console_hangup, "Hangup a call on the console", hangup_usage },
  904. { { "dial", NULL }, console_dial, "Dial an extension on the console", dial_usage },
  905. { { "send", "text", NULL }, console_sendtext, "Send text to the remote device", sendtext_usage },
  906. { { "autoanswer", NULL }, console_autoanswer, "Sets/displays autoanswer", autoanswer_usage, autoanswer_complete }
  907. };
  908. int load_module()
  909. {
  910. int res;
  911. int x;
  912. int flags;
  913. struct ast_config *cfg;
  914. struct ast_variable *v;
  915. res = pipe(cmd);
  916. res = pipe(sndcmd);
  917. if (res) {
  918. ast_log(LOG_ERROR, "Unable to create pipe\n");
  919. return -1;
  920. }
  921. flags = fcntl(cmd[0], F_GETFL);
  922. fcntl(cmd[0], F_SETFL, flags | O_NONBLOCK);
  923. flags = fcntl(cmd[1], F_GETFL);
  924. fcntl(cmd[1], F_SETFL, flags | O_NONBLOCK);
  925. res = soundcard_init();
  926. if (res < 0) {
  927. close(cmd[1]);
  928. close(cmd[0]);
  929. if (option_verbose > 1) {
  930. ast_verbose(VERBOSE_PREFIX_2 "No sound card detected -- console channel will be unavailable\n");
  931. ast_verbose(VERBOSE_PREFIX_2 "Turn off ALSA support by adding 'noload=chan_alsa.so' in /etc/asterisk/modules.conf\n");
  932. }
  933. return 0;
  934. }
  935. #if 0
  936. if (!full_duplex)
  937. ast_log(LOG_WARNING, "XXX I don't work right with non-full duplex sound cards XXX\n");
  938. #endif
  939. res = ast_channel_register(type, tdesc, AST_FORMAT_SLINEAR, alsa_request);
  940. if (res < 0) {
  941. ast_log(LOG_ERROR, "Unable to register channel class '%s'\n", type);
  942. return -1;
  943. }
  944. for (x=0;x<sizeof(myclis)/sizeof(struct ast_cli_entry); x++)
  945. ast_cli_register(myclis + x);
  946. if ((cfg = ast_load(config))) {
  947. v = ast_variable_browse(cfg, "general");
  948. while(v) {
  949. if (!strcasecmp(v->name, "autoanswer"))
  950. autoanswer = ast_true(v->value);
  951. else if (!strcasecmp(v->name, "silencesuppression"))
  952. silencesuppression = ast_true(v->value);
  953. else if (!strcasecmp(v->name, "silencethreshold"))
  954. silencethreshold = atoi(v->value);
  955. else if (!strcasecmp(v->name, "context"))
  956. strncpy(context, v->value, sizeof(context)-1);
  957. else if (!strcasecmp(v->name, "language"))
  958. strncpy(language, v->value, sizeof(language)-1);
  959. else if (!strcasecmp(v->name, "extension"))
  960. strncpy(exten, v->value, sizeof(exten)-1);
  961. else if (!strcasecmp(v->name, "input_device"))
  962. strncpy(indevname, v->value, sizeof(indevname)-1);
  963. else if (!strcasecmp(v->name, "output_device"))
  964. strncpy(outdevname, v->value, sizeof(outdevname)-1);
  965. v=v->next;
  966. }
  967. ast_destroy(cfg);
  968. }
  969. pthread_create(&sthread, NULL, sound_thread, NULL);
  970. #ifdef ALSA_MONITOR
  971. if (alsa_monitor_start()) {
  972. ast_log(LOG_ERROR, "Problem starting Monitoring\n");
  973. }
  974. #endif
  975. return 0;
  976. }
  977. int unload_module()
  978. {
  979. int x;
  980. for (x=0;x<sizeof(myclis)/sizeof(struct ast_cli_entry); x++)
  981. ast_cli_unregister(myclis + x);
  982. close(readdev);
  983. close(writedev);
  984. if (cmd[0] > 0) {
  985. close(cmd[0]);
  986. close(cmd[1]);
  987. }
  988. if (sndcmd[0] > 0) {
  989. close(sndcmd[0]);
  990. close(sndcmd[1]);
  991. }
  992. if (alsa.owner)
  993. ast_softhangup(alsa.owner, AST_SOFTHANGUP_APPUNLOAD);
  994. if (alsa.owner)
  995. return -1;
  996. return 0;
  997. }
  998. char *description()
  999. {
  1000. return desc;
  1001. }
  1002. int usecount()
  1003. {
  1004. int res;
  1005. ast_mutex_lock(&usecnt_lock);
  1006. res = usecnt;
  1007. ast_mutex_unlock(&usecnt_lock);
  1008. return res;
  1009. }
  1010. char *key()
  1011. {
  1012. return ASTERISK_GPL_KEY;
  1013. }