chan_alsa.c 28 KB

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