Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

5599 linhas
165KB

  1. /* Audio hardware handlers (OSS, ALSA, Sun, Windows, Mac OSX, Jack, HPUX, NetBSD, OpenBSD, pulseaudio, portaudio)
  2. *
  3. * In many cases, only callback driven transfers are supported, so ideally we'd have:
  4. * int mus_audio_playback(caller_data, start_func, fill_func, end_func)
  5. * returns error indication or MUS_NO_ERROR
  6. * calls start_func at startup: void start(caller_data, ...)?
  7. * each times it needs a bufferfull, calls fill_func: bool fill(caller_data, void *buf, buf_size_in_samples, buf_data_type)
  8. * perhaps returns false to signal normal quit?
  9. * at end (either via fill or some interrupt), calls end(caller_data, ...)?
  10. */
  11. /*
  12. * layout of this file:
  13. * error handlers
  14. * OSS
  15. * ALSA
  16. * Sun
  17. * Windows 95/98
  18. * OSX
  19. * JACK
  20. * HPUX
  21. * NetBSD/OpenBSD
  22. * PulseAudio (in progress?)
  23. * PortAudio
  24. */
  25. /*
  26. * int mus_audio_open_output(int dev, int srate, int chans, mus_sample_t samp_type, int size)
  27. * int mus_audio_open_input(int dev, int srate, int chans, mus_sample_t samp_type, int size)
  28. * int mus_audio_write(int line, char *buf, int bytes)
  29. * int mus_audio_close(int line)
  30. * int mus_audio_read(int line, char *buf, int bytes)
  31. * int mus_audio_initialize(void) does whatever is needed to get set up
  32. * char *mus_audio_moniker(void) returns some brief description of the overall audio setup (don't free return string).
  33. */
  34. #include "mus-config.h"
  35. #if USE_SND && __APPLE__ && USE_MOTIF
  36. #undef USE_MOTIF
  37. #define USE_NO_GUI 1
  38. /* Xt's Boolean (/usr/include/X11/Intrinsic.h = char) collides with MacTypes.h Boolean, (actually,
  39. * unsigned char in /Developer/SDKs/MacOSX10.4u.sdk/System/Library/Frameworks/CoreFoundation.framework/Versions/A/Headers/CFBase.h)
  40. * but we want snd.h for other stuff, so, if Motif is in use, don't load its headers at this time
  41. * perhaps we could use the -funsigned-char switch in gcc
  42. */
  43. #endif
  44. #if USE_SND && __APPLE__ && HAVE_RUBY
  45. /* if using Ruby, OpenTransport.h T_* definitions collide with Ruby's -- it isn't needed here, so... */
  46. #define REDEFINE_HAVE_RUBY 1
  47. #undef HAVE_RUBY
  48. #endif
  49. #if USE_SND
  50. #include "snd.h"
  51. #else
  52. #define PRINT_BUFFER_SIZE 512
  53. #define LABEL_BUFFER_SIZE 64
  54. #endif
  55. #if USE_SND && __APPLE__
  56. #define USE_MOTIF 1
  57. #undef USE_NO_GUI
  58. #if REDEFINE_HAVE_RUBY
  59. #define HAVE_RUBY 1
  60. #endif
  61. #endif
  62. #include <math.h>
  63. #include <stdio.h>
  64. #include <fcntl.h>
  65. #include <errno.h>
  66. #include <stdlib.h>
  67. #ifndef _MSC_VER
  68. #include <unistd.h>
  69. #endif
  70. #include <string.h>
  71. #ifdef __APPLE__
  72. #include <CoreServices/CoreServices.h>
  73. #include <CoreAudio/CoreAudio.h>
  74. /* these pull in stdbool.h apparently, so they have to precede sndlib.h */
  75. #endif
  76. /* #define HAVE_JACK_IN_LINUX (MUS_JACK && __linux__) */
  77. /* using JACK on GNU/linux, GNU/kFreeBSD and GNU/Hurd is all the same */
  78. #if ((defined __linux__) || ((defined __FreeBSD_kernel__) && (defined __GLIBC__)) || (defined __GNU__))
  79. #define HAVE_JACK_IN_LINUX MUS_JACK
  80. #else
  81. #define HAVE_JACK_IN_LINUX 0
  82. #endif
  83. #include "_sndlib.h"
  84. #include "sndlib-strings.h"
  85. #if WITH_AUDIO
  86. enum {MUS_AUDIO_IGNORED, MUS_AUDIO_DUPLEX_DEFAULT, MUS_AUDIO_LINE_OUT,
  87. MUS_AUDIO_LINE_IN, MUS_AUDIO_MICROPHONE, MUS_AUDIO_SPEAKERS, MUS_AUDIO_DIGITAL_OUT,
  88. MUS_AUDIO_DAC_OUT, MUS_AUDIO_MIXER, MUS_AUDIO_AUX_OUTPUT
  89. };
  90. #define mus_standard_error(Error_Type, Error_Message) \
  91. mus_print("%s\n [%s[%d] %s]", Error_Message, __FILE__, __LINE__, __func__)
  92. #define mus_standard_io_error(Error_Type, IO_Func, IO_Name) \
  93. mus_print("%s %s: %s\n [%s[%d] %s]", IO_Func, IO_Name, strerror(errno), __FILE__, __LINE__, __func__)
  94. static char *version_name = NULL;
  95. static bool audio_initialized = false;
  96. /* ------------------------------- OSS ----------------------------------------- */
  97. /* Thanks to Yair K. for OSS v4 changes. 22-Jan-08 */
  98. #if (HAVE_OSS || HAVE_ALSA || HAVE_JACK_IN_LINUX)
  99. /* actually it's not impossible that someday we'll have ALSA but not OSS... */
  100. #define AUDIO_OK 1
  101. #include <sys/ioctl.h>
  102. #include <sys/soundcard.h>
  103. #if ((SOUND_VERSION > 360) && (defined(OSS_SYSINFO)))
  104. #define NEW_OSS 1
  105. #endif
  106. #define MUS_OSS_WRITE_RATE SNDCTL_DSP_SPEED
  107. #define MUS_OSS_WRITE_CHANNELS SNDCTL_DSP_CHANNELS
  108. #define MUS_OSS_SET_FORMAT SNDCTL_DSP_SETFMT
  109. #define MUS_OSS_GET_FORMATS SNDCTL_DSP_GETFMTS
  110. #define DAC_NAME "/dev/dsp"
  111. #define MIXER_NAME "/dev/mixer"
  112. /* some programs use /dev/audio */
  113. /* there can be more than one sound card installed, and a card can be handled through
  114. * more than one /dev/dsp device, so we can't use a global dac device here.
  115. * The caller has to keep track of the various cards (via AUDIO_SYSTEM) --
  116. * I toyed with embedding all that in mus_audio_open_output and mus_audio_write, but
  117. * decided it's better to keep them explicit -- the caller may want entirely
  118. * different (non-synchronous) streams going to the various cards. This same
  119. * code (AUDIO_SYSTEM(n)->devn) should work in Windoze (see below), and
  120. * might work on the Mac -- something for a rainy day...
  121. */
  122. #define return_error_exit(Message_Type, Audio_Line, Ur_Message) \
  123. do { \
  124. char *Message; Message = Ur_Message; \
  125. if (Audio_Line != -1) \
  126. linux_audio_close(Audio_Line); \
  127. if ((Message) && (strlen(Message) > 0)) \
  128. { \
  129. mus_print("%s\n [%s[%d] %s]", \
  130. Message, \
  131. __FILE__, __LINE__, __func__); \
  132. free(Message); \
  133. } \
  134. else mus_print("%s\n [%s[%d] %s]", \
  135. mus_error_type_to_string(Message_Type), \
  136. __FILE__, __LINE__, __func__); \
  137. return(MUS_ERROR); \
  138. } while (false)
  139. static int FRAGMENTS = 4;
  140. static int FRAGMENT_SIZE = 12;
  141. static bool fragments_locked = false;
  142. /* defaults here are FRAGMENTS 16 and FRAGMENT_SIZE 12; these values however
  143. * cause about a .5 second delay, which is not acceptable in "real-time" situations.
  144. *
  145. * this changed 22-May-01: these are causing more trouble than they're worth
  146. */
  147. static void oss_mus_oss_set_buffers(int num, int size) {FRAGMENTS = num; FRAGMENT_SIZE = size; fragments_locked = true;}
  148. #define MAX_SOUNDCARDS 8
  149. #define MAX_DSPS 8
  150. #define MAX_MIXERS 8
  151. /* there can be (apparently) any number of mixers and dsps per soundcard, but 8 is enough! */
  152. static int *audio_fd = NULL;
  153. static int *audio_open_ctr = NULL;
  154. static int *audio_dsp = NULL;
  155. static int *audio_mixer = NULL;
  156. static int *audio_mode = NULL;
  157. static int sound_cards = 0;
  158. #ifdef NEW_OSS
  159. static int new_oss_running = 0;
  160. #endif
  161. static char *dev_name = NULL;
  162. static char *oss_mus_audio_moniker(void)
  163. {
  164. if (version_name == NULL) version_name = (char *)calloc(LABEL_BUFFER_SIZE, sizeof(char));
  165. if (SOUND_VERSION < 361)
  166. {
  167. char version[LABEL_BUFFER_SIZE];
  168. snprintf(version, LABEL_BUFFER_SIZE, "%d", SOUND_VERSION);
  169. snprintf(version_name, LABEL_BUFFER_SIZE, "OSS %c.%c.%c", version[0], version[1], version[2]);
  170. }
  171. else
  172. snprintf(version_name, LABEL_BUFFER_SIZE, "OSS %x.%x.%x",
  173. (SOUND_VERSION >> 16) & 0xff,
  174. (SOUND_VERSION >> 8) & 0xff,
  175. SOUND_VERSION & 0xff);
  176. return(version_name);
  177. }
  178. static char *dac_name(int sys, int offset)
  179. {
  180. if ((sys < sound_cards) && (audio_mixer[sys] >= -1))
  181. {
  182. snprintf(dev_name, LABEL_BUFFER_SIZE, "%s%d", DAC_NAME, audio_dsp[sys] + offset);
  183. return(dev_name);
  184. }
  185. return((char *)DAC_NAME);
  186. }
  187. #define MIXER_SIZE SOUND_MIXER_NRDEVICES
  188. static int **mixer_state = NULL;
  189. static int *init_srate = NULL, *init_chans = NULL, *init_format = NULL;
  190. static int oss_mus_audio_initialize(void)
  191. {
  192. /* here we need to set up the map of /dev/dsp and /dev/mixer to a given system */
  193. /* since this info is not passed to us by OSS, we have to work at it... */
  194. /* for the time being, I'll ignore auxiliary dsp and mixer ports (each is a special case) */
  195. int amp, old_mixer_amp, old_dsp_amp, new_mixer_amp;
  196. int devmask;
  197. #ifdef NEW_OSS
  198. int status, ignored;
  199. oss_sysinfo sysinfo;
  200. static mixer_info mixinfo;
  201. int sysinfo_ok = 0;
  202. #endif
  203. if (!audio_initialized)
  204. {
  205. int i, num_mixers, num_dsps, nmix, ndsp, err = 0, fd = -1, responsive_field;
  206. audio_initialized = true;
  207. audio_fd = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
  208. audio_open_ctr = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
  209. audio_dsp = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
  210. audio_mixer = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
  211. audio_mode = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
  212. dev_name = (char *)calloc(LABEL_BUFFER_SIZE, sizeof(char));
  213. init_srate = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
  214. init_chans = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
  215. init_format = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
  216. mixer_state = (int **)calloc(MAX_SOUNDCARDS, sizeof(int *));
  217. for (i = 0; i < MAX_SOUNDCARDS; i++) mixer_state[i] = (int *)calloc(MIXER_SIZE, sizeof(int));
  218. for (i = 0; i < MAX_SOUNDCARDS; i++)
  219. {
  220. audio_fd[i] = -1;
  221. audio_open_ctr[i] = 0;
  222. audio_dsp[i] = -1;
  223. audio_mixer[i] = -1;
  224. }
  225. num_mixers = MAX_MIXERS;
  226. num_dsps = MAX_DSPS;
  227. #ifdef NEW_OSS
  228. fd = open(DAC_NAME, O_WRONLY | O_NONBLOCK, 0);
  229. if (fd == -1) fd = open(MIXER_NAME, O_RDONLY | O_NONBLOCK, 0);
  230. if (fd != -1)
  231. {
  232. status = ioctl(fd, OSS_GETVERSION, &ignored);
  233. new_oss_running = (status == 0);
  234. if (new_oss_running)
  235. {
  236. status = ioctl(fd, OSS_SYSINFO, &sysinfo);
  237. sysinfo_ok = (status == 0);
  238. }
  239. if ((new_oss_running) && (sysinfo_ok))
  240. {
  241. num_mixers = sysinfo.nummixers;
  242. num_dsps = sysinfo.numaudios;
  243. }
  244. close(fd);
  245. }
  246. #endif
  247. /* need to get which /dev/dsp lines match which /dev/mixer lines,
  248. * find out how many separate systems (soundcards) are available,
  249. * fill the audio_dsp and audio_mixer arrays with the system-related numbers,
  250. * since we have no way to tell from OSS info which mixers/dsps are the
  251. * main ones, we'll do some messing aound to try to deduce this info.
  252. * for example, SB uses two dsp ports and two mixers per card, whereas
  253. * Ensoniq uses 2 dsps and 1 mixer.
  254. *
  255. * the data we are gathering here:
  256. * int audio_dsp[MAX_SOUNDCARDS] -> main_dsp_port[n] (-1 => no such system dsp)
  257. * int audio_mixer[MAX_SOUNDCARDS] -> main_mixer_port[n]
  258. * int sound_cards = 0 -> usable systems
  259. * all auxiliary ports are currently ignored (SB equalizer, etc)
  260. */
  261. sound_cards = 0;
  262. ndsp = 0;
  263. nmix = 0;
  264. while ((nmix < num_mixers) &&
  265. (ndsp < num_dsps))
  266. {
  267. char dname[LABEL_BUFFER_SIZE];
  268. int md;
  269. /* for each mixer, find associated main dsp (assumed to be first in /dev/dsp ordering) */
  270. /* if mixer's dsp overlaps or we run out of dsps first, ignore it (aux mixer) */
  271. /* our by-guess-or-by-gosh method here is to try to open the mixer.
  272. * if that fails, quit (if very first, try at least to get the dsp setup)
  273. * find volume field, if none, go on, else read current volume
  274. * open next unchecked dsp, try to set volume, read current, if different we found a match -- set and go on.
  275. * if no change, move to next dsp and try again, if no more dsps, quit (checking for null case as before)
  276. */
  277. snprintf(dname, LABEL_BUFFER_SIZE, "%s%d", MIXER_NAME, nmix);
  278. md = open(dname, O_RDWR, 0);
  279. if (md == -1)
  280. {
  281. if (errno == EBUSY)
  282. {
  283. mus_print("%s is busy: can't access it [%s[%d] %s]",
  284. dname,
  285. __FILE__, __LINE__, __func__);
  286. nmix++;
  287. continue;
  288. }
  289. else break;
  290. }
  291. snprintf(dname, LABEL_BUFFER_SIZE, "%s%d", DAC_NAME, ndsp);
  292. fd = open(dname, O_RDWR | O_NONBLOCK, 0);
  293. if (fd == -1) fd = open(dname, O_RDONLY | O_NONBLOCK, 0);
  294. if (fd == -1) fd = open(dname, O_WRONLY | O_NONBLOCK, 0); /* some output devices need this */
  295. if (fd == -1)
  296. {
  297. close(md);
  298. if (errno == EBUSY) /* in linux /usr/include/asm-generic/errno-base.h */
  299. {
  300. fprintf(stderr, "%s is busy: can't access it\n", dname);
  301. ndsp++;
  302. continue;
  303. }
  304. else
  305. {
  306. if ((errno != ENXIO) && (errno != ENODEV) && (errno != ENOENT))
  307. fprintf(stderr, "%s: %s! ", dname, strerror(errno));
  308. break;
  309. }
  310. }
  311. #ifdef NEW_OSS
  312. status = ioctl(md, SOUND_MIXER_INFO, &mixinfo);
  313. #endif
  314. err = ioctl(md, SOUND_MIXER_READ_DEVMASK, &devmask);
  315. responsive_field = SOUND_MIXER_VOLUME;
  316. for (i = 0; i < SOUND_MIXER_NRDEVICES; i++)
  317. if ((1 << i) & devmask)
  318. {
  319. responsive_field = i;
  320. break;
  321. }
  322. if (!err)
  323. {
  324. err = ioctl(md, MIXER_READ(responsive_field), &old_mixer_amp);
  325. if (!err)
  326. {
  327. err = ioctl(fd, MIXER_READ(responsive_field), &old_dsp_amp);
  328. if ((!err) && (old_dsp_amp == old_mixer_amp))
  329. {
  330. if (old_mixer_amp == 0) amp = 50; else amp = 0; /* 0..100 */
  331. err = ioctl(fd, MIXER_WRITE(responsive_field), &amp);
  332. if (!err)
  333. {
  334. err = ioctl(md, MIXER_READ(responsive_field), &new_mixer_amp);
  335. if (!err)
  336. {
  337. if (new_mixer_amp == amp)
  338. {
  339. /* found one! */
  340. audio_dsp[sound_cards] = ndsp; ndsp++;
  341. audio_mixer[sound_cards] = nmix; nmix++;
  342. sound_cards++;
  343. }
  344. else ndsp++;
  345. err = ioctl(fd, MIXER_WRITE(responsive_field), &old_dsp_amp);
  346. }
  347. else nmix++;
  348. }
  349. else ndsp++;
  350. }
  351. else ndsp++;
  352. }
  353. else nmix++;
  354. }
  355. else nmix++;
  356. close(fd);
  357. close(md);
  358. }
  359. if (sound_cards == 0)
  360. {
  361. fd = open(DAC_NAME, O_WRONLY | O_NONBLOCK, 0);
  362. if (fd != -1)
  363. {
  364. sound_cards = 1;
  365. audio_dsp[0] = 0;
  366. audio_mixer[0] = -2; /* hmmm -- need a way to see /dev/dsp as lonely outpost */
  367. close(fd);
  368. fd = open(MIXER_NAME, O_RDONLY | O_NONBLOCK, 0);
  369. if (fd == -1)
  370. audio_mixer[0] = -3;
  371. else close(fd);
  372. }
  373. }
  374. }
  375. return(MUS_NO_ERROR);
  376. }
  377. static int linux_audio_open(const char *pathname, int flags, mode_t mode, int system)
  378. {
  379. /* sometimes this is simply searching for a device (so failure is not a mus_error) */
  380. if (audio_fd[system] == -1)
  381. {
  382. audio_fd[system] = open(pathname, flags, mode);
  383. audio_open_ctr[system] = 0;
  384. }
  385. else audio_open_ctr[system]++;
  386. return(audio_fd[system]);
  387. }
  388. static int linux_audio_open_with_error(const char *pathname, int flags, mode_t mode, int system)
  389. {
  390. int fd;
  391. static bool already_warned = false;
  392. if ((system < 0) ||
  393. (system >= MAX_SOUNDCARDS))
  394. return(-1);
  395. fd = linux_audio_open(pathname, flags, mode, system);
  396. if ((fd == -1) &&
  397. (!already_warned))
  398. {
  399. already_warned = true;
  400. mus_standard_io_error(MUS_AUDIO_CANT_OPEN,
  401. ((mode == O_RDONLY) ? "open read" :
  402. (mode == O_WRONLY) ? "open write" : "open read/write"),
  403. pathname);
  404. }
  405. return(fd);
  406. }
  407. static int find_system(int line)
  408. {
  409. int i;
  410. for (i = 0; i < sound_cards; i++)
  411. if (line == audio_fd[i])
  412. return(i);
  413. return(MUS_ERROR);
  414. }
  415. static int linux_audio_close(int fd)
  416. {
  417. if (fd != -1)
  418. {
  419. int err = 0, sys;
  420. sys = find_system(fd);
  421. if (sys != -1)
  422. {
  423. if (audio_open_ctr[sys] > 0)
  424. audio_open_ctr[sys]--;
  425. else
  426. {
  427. err = close(fd);
  428. audio_open_ctr[sys] = 0;
  429. audio_fd[sys] = -1;
  430. }
  431. }
  432. else err = close(fd);
  433. if (err) return_error_exit(MUS_AUDIO_CANT_CLOSE, -1,
  434. mus_format("close %d failed: %s",
  435. fd, strerror(errno)));
  436. }
  437. /* is this an error? */
  438. return(MUS_NO_ERROR);
  439. }
  440. static int to_oss_sample_type(mus_sample_t snd_format)
  441. {
  442. switch (snd_format)
  443. {
  444. case MUS_BYTE: return(AFMT_S8); break;
  445. case MUS_BSHORT: return(AFMT_S16_BE); break;
  446. case MUS_UBYTE: return(AFMT_U8); break;
  447. case MUS_MULAW: return(AFMT_MU_LAW); break;
  448. case MUS_ALAW: return(AFMT_A_LAW); break;
  449. case MUS_LSHORT: return(AFMT_S16_LE); break;
  450. case MUS_UBSHORT: return(AFMT_U16_BE); break;
  451. case MUS_ULSHORT: return(AFMT_U16_LE); break;
  452. #ifdef NEW_OSS
  453. case MUS_LINT: return(AFMT_S32_LE); break;
  454. case MUS_BINT: return(AFMT_S32_BE); break;
  455. #endif
  456. default: break;
  457. }
  458. return(MUS_ERROR);
  459. }
  460. static bool fragment_set_failed = false;
  461. static int oss_mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
  462. {
  463. int oss_sample_type, buffer_info, audio_out = -1, sys, dev;
  464. char *dev_name;
  465. #ifndef NEW_OSS
  466. int stereo;
  467. #endif
  468. sys = MUS_AUDIO_SYSTEM(ur_dev);
  469. dev = MUS_AUDIO_DEVICE(ur_dev);
  470. oss_sample_type = to_oss_sample_type(samp_type);
  471. if (oss_sample_type == MUS_ERROR)
  472. return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, -1,
  473. mus_format("sample type %d (%s) not available",
  474. samp_type,
  475. mus_sample_type_name(samp_type)));
  476. if (dev == MUS_AUDIO_DEFAULT)
  477. audio_out = linux_audio_open_with_error(dev_name = dac_name(sys, 0),
  478. O_WRONLY, 0, sys);
  479. else audio_out = linux_audio_open_with_error(dev_name = dac_name(sys, (dev == MUS_AUDIO_AUX_OUTPUT) ? 1 : 0),
  480. O_RDWR, 0, sys);
  481. if (audio_out == -1) return(MUS_ERROR);
  482. /* ioctl(audio_out, SNDCTL_DSP_RESET, 0); */ /* causes clicks */
  483. if ((fragments_locked) &&
  484. (!(fragment_set_failed)) &&
  485. ((dev == MUS_AUDIO_DUPLEX_DEFAULT) ||
  486. (size != 0))) /* only set if user has previously called set_oss_buffers */
  487. {
  488. buffer_info = (FRAGMENTS << 16) | (FRAGMENT_SIZE);
  489. if (ioctl(audio_out, SNDCTL_DSP_SETFRAGMENT, &buffer_info) == -1)
  490. {
  491. /* older Linuces (or OSS's?) refuse to handle the fragment reset if O_RDWR used --
  492. * someone at OSS forgot to update the version number when this was fixed, so
  493. * I have no way to get around this except to try and retry...
  494. */
  495. linux_audio_close(audio_out);
  496. audio_out = linux_audio_open_with_error(dev_name = dac_name(sys, (dev == MUS_AUDIO_AUX_OUTPUT) ? 1 : 0),
  497. O_WRONLY, 0, sys);
  498. if (audio_out == -1) return(MUS_ERROR);
  499. buffer_info = (FRAGMENTS << 16) | (FRAGMENT_SIZE);
  500. if (ioctl(audio_out, SNDCTL_DSP_SETFRAGMENT, &buffer_info) == -1)
  501. {
  502. char *tmp;
  503. tmp = mus_format("can't set %s fragments to: %d x %d",
  504. dev_name, FRAGMENTS, FRAGMENT_SIZE); /* not an error if ALSA OSS-emulation */
  505. fprintf(stderr, "%s\n", tmp);
  506. fragment_set_failed = true;
  507. free(tmp);
  508. }
  509. }
  510. }
  511. if ((ioctl(audio_out, MUS_OSS_SET_FORMAT, &oss_sample_type) == -1) ||
  512. (oss_sample_type != to_oss_sample_type(samp_type)))
  513. return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, audio_out,
  514. mus_format("sample type %d (%s) not available on %s",
  515. samp_type,
  516. mus_sample_type_name(samp_type),
  517. dev_name));
  518. #ifdef NEW_OSS
  519. if (ioctl(audio_out, MUS_OSS_WRITE_CHANNELS, &chans) == -1)
  520. return_error_exit(MUS_AUDIO_CHANNELS_NOT_AVAILABLE, audio_out,
  521. mus_format("can't get %d channels on %s",
  522. chans, dev_name));
  523. #else
  524. if (chans == 2) stereo = 1; else stereo = 0;
  525. if ((ioctl(audio_out, SNDCTL_DSP_STEREO, &stereo) == -1) ||
  526. ((chans == 2) && (stereo == 0)))
  527. return_error_exit(MUS_AUDIO_CHANNELS_NOT_AVAILABLE, audio_out,
  528. mus_format("can't get %d channels on %s",
  529. chans, dev_name));
  530. #endif
  531. if (ioctl(audio_out, MUS_OSS_WRITE_RATE, &srate) == -1)
  532. return_error_exit(MUS_AUDIO_SRATE_NOT_AVAILABLE, audio_out,
  533. mus_format("can't set srate of %s to %d",
  534. dev_name, srate));
  535. /* http://www.4front-tech.com/pguide/audio.html says this order has to be followed */
  536. return(audio_out);
  537. }
  538. static int oss_mus_audio_write(int line, char *buf, int bytes)
  539. {
  540. int err;
  541. if (line < 0) return(-1);
  542. errno = 0;
  543. err = write(line, buf, bytes);
  544. if (err != bytes)
  545. {
  546. if (errno != 0)
  547. return_error_exit(MUS_AUDIO_WRITE_ERROR, -1,
  548. mus_format("write error: %s", strerror(errno)));
  549. else return_error_exit(MUS_AUDIO_WRITE_ERROR, -1,
  550. mus_format("wrote %d bytes of requested %d", err, bytes));
  551. }
  552. return(MUS_NO_ERROR);
  553. }
  554. static int oss_mus_audio_close(int line)
  555. {
  556. return(linux_audio_close(line));
  557. }
  558. static int oss_mus_audio_read(int line, char *buf, int bytes)
  559. {
  560. int err;
  561. if (line < 0) return(-1);
  562. errno = 0;
  563. err = read(line, buf, bytes);
  564. if (err != bytes)
  565. {
  566. if (errno != 0)
  567. return_error_exit(MUS_AUDIO_READ_ERROR, -1,
  568. mus_format("read error: %s", strerror(errno)));
  569. else return_error_exit(MUS_AUDIO_READ_ERROR, -1,
  570. mus_format("read %d bytes of requested %d", err, bytes));
  571. }
  572. return(MUS_NO_ERROR);
  573. }
  574. static char *oss_unsrc(int srcbit)
  575. {
  576. if (srcbit == 0)
  577. return(mus_strdup("none"));
  578. else
  579. {
  580. bool need_and = false;
  581. char *buf;
  582. buf = (char *)calloc(PRINT_BUFFER_SIZE, sizeof(char));
  583. if (srcbit & SOUND_MASK_MIC) {need_and = true; strcat(buf, "mic");}
  584. if (srcbit & SOUND_MASK_LINE) {if (need_and) strcat(buf, " and "); need_and = true; strcat(buf, "line in");}
  585. if (srcbit & SOUND_MASK_CD) {if (need_and) strcat(buf, " and "); strcat(buf, "cd");}
  586. return(buf);
  587. }
  588. }
  589. static int oss_mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int requested_size)
  590. {
  591. /* dev can be MUS_AUDIO_DEFAULT or MUS_AUDIO_DUPLEX_DEFAULT as well as the obvious others */
  592. int audio_fd = -1, oss_sample_type, buffer_info, sys, dev, srcbit, cursrc, err;
  593. char *dev_name;
  594. #ifndef NEW_OSS
  595. int stereo;
  596. #endif
  597. sys = MUS_AUDIO_SYSTEM(ur_dev);
  598. dev = MUS_AUDIO_DEVICE(ur_dev);
  599. oss_sample_type = to_oss_sample_type(samp_type);
  600. if (oss_sample_type == MUS_ERROR)
  601. return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, -1,
  602. mus_format("sample type %d (%s) not available",
  603. samp_type,
  604. mus_sample_type_name(samp_type)));
  605. if (((dev == MUS_AUDIO_DEFAULT) || (dev == MUS_AUDIO_DUPLEX_DEFAULT)) && (sys == 0))
  606. audio_fd = linux_audio_open(dev_name = dac_name(sys, 0),
  607. O_RDWR, 0, sys);
  608. else audio_fd = linux_audio_open(dev_name = dac_name(sys, 0), O_RDONLY, 0, sys);
  609. if (audio_fd == -1)
  610. {
  611. if (dev == MUS_AUDIO_DUPLEX_DEFAULT)
  612. return_error_exit(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, -1,
  613. mus_format("can't open %s: %s",
  614. dev_name, strerror(errno)));
  615. if ((audio_fd = linux_audio_open(dev_name = dac_name(sys, 0), O_RDONLY, 0, sys)) == -1)
  616. {
  617. if ((errno == EACCES) || (errno == ENOENT))
  618. return_error_exit(MUS_AUDIO_NO_READ_PERMISSION, -1,
  619. mus_format("can't open %s: %s\n to get input in Linux, we need read permission on /dev/dsp",
  620. dev_name,
  621. strerror(errno)));
  622. else return_error_exit(MUS_AUDIO_NO_INPUT_AVAILABLE, -1,
  623. mus_format("can't open %s: %s",
  624. dev_name,
  625. strerror(errno)));
  626. }
  627. }
  628. #ifdef SNDCTL_DSP_SETDUPLEX
  629. else
  630. ioctl(audio_fd, SNDCTL_DSP_SETDUPLEX, &err); /* not always a no-op! */
  631. #endif
  632. /* need to make sure the desired recording source is active -- does this actually have any effect? */
  633. switch (dev)
  634. {
  635. case MUS_AUDIO_MICROPHONE: srcbit = SOUND_MASK_MIC; break;
  636. case MUS_AUDIO_LINE_IN: srcbit = SOUND_MASK_LINE; break;
  637. case MUS_AUDIO_DUPLEX_DEFAULT:
  638. case MUS_AUDIO_DEFAULT: srcbit = SOUND_MASK_LINE | SOUND_MASK_MIC; break;
  639. default: srcbit = 0; break;
  640. }
  641. ioctl(audio_fd, MIXER_READ(SOUND_MIXER_RECSRC), &cursrc);
  642. srcbit = (srcbit | cursrc);
  643. ioctl(audio_fd, MIXER_WRITE(SOUND_MIXER_RECSRC), &srcbit);
  644. ioctl(audio_fd, MIXER_READ(SOUND_MIXER_RECSRC), &cursrc);
  645. if (cursrc != srcbit)
  646. {
  647. char *str1, *str2;
  648. str1 = oss_unsrc(srcbit);
  649. str2 = oss_unsrc(cursrc);
  650. mus_print("weird: tried to set recorder source to %s, but got %s?", str1, str2);
  651. free(str1);
  652. free(str2);
  653. }
  654. if ((fragments_locked) && (requested_size != 0))
  655. {
  656. buffer_info = (FRAGMENTS << 16) | (FRAGMENT_SIZE);
  657. ioctl(audio_fd, SNDCTL_DSP_SETFRAGMENT, &buffer_info);
  658. }
  659. if ((ioctl(audio_fd, MUS_OSS_SET_FORMAT, &oss_sample_type) == -1) ||
  660. (oss_sample_type != to_oss_sample_type(samp_type)))
  661. return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, audio_fd,
  662. mus_format("can't set %s sample type to %d (%s)",
  663. dev_name, samp_type,
  664. mus_sample_type_name(samp_type)));
  665. #ifdef NEW_OSS
  666. if (ioctl(audio_fd, MUS_OSS_WRITE_CHANNELS, &chans) == -1)
  667. return_error_exit(MUS_AUDIO_CHANNELS_NOT_AVAILABLE, audio_fd,
  668. mus_format("can't get %d channels on %s",
  669. chans, dev_name));
  670. #else
  671. if (chans == 2) stereo = 1; else stereo = 0;
  672. if ((ioctl(audio_fd, SNDCTL_DSP_STEREO, &stereo) == -1) ||
  673. ((chans == 2) && (stereo == 0)))
  674. return_error_exit(MUS_AUDIO_CHANNELS_NOT_AVAILABLE, audio_fd,
  675. mus_format("can't get %d channels on %s",
  676. chans, dev_name));
  677. #endif
  678. if (ioctl(audio_fd, MUS_OSS_WRITE_RATE, &srate) == -1)
  679. return_error_exit(MUS_AUDIO_SRATE_NOT_AVAILABLE, audio_fd,
  680. mus_format("can't set srate to %d on %s",
  681. srate, dev_name));
  682. return(audio_fd);
  683. }
  684. #if (!HAVE_ALSA)
  685. static int oss_sample_types(int ur_dev, mus_sample_t *val)
  686. {
  687. int fd, samp_types = 0, sys, ind;
  688. sys = MUS_AUDIO_SYSTEM(ur_dev);
  689. /* dev = MUS_AUDIO_DEVICE(ur_dev); */
  690. fd = open(dac_name(sys, 0), O_WRONLY, 0);
  691. if (fd == -1) fd = open(DAC_NAME, O_WRONLY, 0);
  692. if (fd == -1)
  693. {
  694. return_error_exit(MUS_AUDIO_CANT_OPEN, -1,
  695. mus_format("can't open %s: %s",
  696. DAC_NAME, strerror(errno)));
  697. return(MUS_ERROR);
  698. }
  699. ioctl(fd, MUS_OSS_GET_FORMATS, &samp_types);
  700. ind = 1;
  701. if (samp_types & (to_oss_sample_type(MUS_BSHORT))) val[ind++] = MUS_BSHORT;
  702. if (samp_types & (to_oss_sample_type(MUS_LSHORT))) val[ind++] = MUS_LSHORT;
  703. if (samp_types & (to_oss_sample_type(MUS_MULAW))) val[ind++] = MUS_MULAW;
  704. if (samp_types & (to_oss_sample_type(MUS_ALAW))) val[ind++] = MUS_ALAW;
  705. if (samp_types & (to_oss_sample_type(MUS_BYTE))) val[ind++] = MUS_BYTE;
  706. if (samp_types & (to_oss_sample_type(MUS_UBYTE))) val[ind++] = MUS_UBYTE;
  707. if (samp_types & (to_oss_sample_type(MUS_UBSHORT))) val[ind++] = MUS_UBSHORT;
  708. if (samp_types & (to_oss_sample_type(MUS_ULSHORT))) val[ind++] = MUS_ULSHORT;
  709. val[0] = (mus_sample_t)(ind - 1);
  710. return(MUS_NO_ERROR);
  711. }
  712. #endif
  713. /* ------------------------------- ALSA, OSS, Jack-in-Linux ----------------------------------- */
  714. static int api = MUS_ALSA_API;
  715. int mus_audio_api(void) {return(api);}
  716. /* hopefully first call to sndlib will be this... */
  717. static int probe_api(void);
  718. static int (*vect_mus_audio_initialize)(void);
  719. /* FIXME: add a suitable default for all other vectors
  720. so that a call happening before mus_audio_initialize
  721. can be detected */
  722. /* I don't think this is necessary -- documentation discusses this
  723. * (mus_sound_initialize calls mus_audio_initialize)
  724. */
  725. /* vectors for the rest of the sndlib api */
  726. static void (*vect_mus_oss_set_buffers)(int num, int size);
  727. static char* (*vect_mus_audio_moniker)(void);
  728. static int (*vect_mus_audio_open_output)(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size);
  729. static int (*vect_mus_audio_open_input)(int ur_dev, int srate, int chans, mus_sample_t samp_type, int requested_size);
  730. static int (*vect_mus_audio_write)(int id, char *buf, int bytes);
  731. static int (*vect_mus_audio_read)(int id, char *buf, int bytes);
  732. static int (*vect_mus_audio_close)(int id);
  733. /* vectors for the rest of the sndlib api */
  734. int mus_audio_initialize(void)
  735. {
  736. return(probe_api());
  737. }
  738. void mus_oss_set_buffers(int num, int size)
  739. {
  740. vect_mus_oss_set_buffers(num, size);
  741. }
  742. #if HAVE_ALSA
  743. static char* alsa_mus_audio_moniker(void);
  744. #endif
  745. char* mus_audio_moniker(void)
  746. {
  747. #if (HAVE_OSS && HAVE_ALSA)
  748. char *both_names;
  749. both_names = (char *)calloc(PRINT_BUFFER_SIZE, sizeof(char));
  750. /* need to be careful here since these use the same constant buffer */
  751. strcpy(both_names, oss_mus_audio_moniker());
  752. strcat(both_names, ", ");
  753. strcat(both_names, alsa_mus_audio_moniker());
  754. return(both_names); /* tiny memory leak ... */
  755. #else
  756. return(vect_mus_audio_moniker());
  757. #endif
  758. }
  759. int mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
  760. {
  761. return(vect_mus_audio_open_output(ur_dev, srate, chans, samp_type, size));
  762. }
  763. int mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int requested_size)
  764. {
  765. return(vect_mus_audio_open_input(ur_dev, srate, chans, samp_type, requested_size));
  766. }
  767. int mus_audio_write(int id, char *buf, int bytes)
  768. {
  769. return(vect_mus_audio_write(id, buf, bytes));
  770. }
  771. int mus_audio_read(int id, char *buf, int bytes)
  772. {
  773. return(vect_mus_audio_read(id, buf, bytes));
  774. }
  775. int mus_audio_close(int id)
  776. {
  777. return(vect_mus_audio_close(id));
  778. }
  779. #if HAVE_JACK_IN_LINUX
  780. static int jack_mus_audio_initialize(void);
  781. #endif
  782. #if (!HAVE_ALSA)
  783. static int probe_api(void)
  784. {
  785. #if HAVE_JACK_IN_LINUX
  786. {
  787. int jackprobe = jack_mus_audio_initialize();
  788. if (jackprobe == MUS_ERROR)
  789. {
  790. #endif
  791. /* go for the oss api */
  792. api = MUS_OSS_API;
  793. vect_mus_audio_initialize = oss_mus_audio_initialize;
  794. vect_mus_oss_set_buffers = oss_mus_oss_set_buffers;
  795. vect_mus_audio_moniker = oss_mus_audio_moniker;
  796. vect_mus_audio_open_output = oss_mus_audio_open_output;
  797. vect_mus_audio_open_input = oss_mus_audio_open_input;
  798. vect_mus_audio_write = oss_mus_audio_write;
  799. vect_mus_audio_read = oss_mus_audio_read;
  800. vect_mus_audio_close = oss_mus_audio_close;
  801. return(vect_mus_audio_initialize());
  802. #if HAVE_JACK_IN_LINUX
  803. }
  804. return(jackprobe);
  805. }
  806. #endif
  807. }
  808. #endif
  809. #endif
  810. /* ------------------------------- ALSA ----------------------------------------- */
  811. /*
  812. * Changed the names of the environment variables to use MUS, not SNDLIB.
  813. * reformatted and reorganized to be like the rest of the code
  814. * changed default device to "default"
  815. * -- Bill 3-Feb-06
  816. *
  817. * error handling (mus_error) changed by Bill 14-Nov-02
  818. * 0.5 support removed by Bill 24-Mar-02
  819. *
  820. * changed for 0.9.x api by Fernando Lopez-Lezcano <nando@ccrma.stanford.edu>
  821. *
  822. * sndlib "exports" only one soundcard with two directions (if they are available),
  823. * and only deals with the alsa library pcm's. It does not scan for available
  824. * cards and devices at the hardware level. Which device it uses can be defined by:
  825. *
  826. * - setting variables in the environment (searched for in the following order):
  827. * MUS_ALSA_PLAYBACK_DEVICE
  828. * defines the name of the playback device
  829. * MUS_ALSA_CAPTURE_DEVICE
  830. * defines the name of the capture device
  831. * MUS_ALSA_DEVICE
  832. * defines the name of the playback and capture device
  833. * use the first two if the playback and capture devices are different or the
  834. * third if they are the same.
  835. * - if no variables are found in the environment sndlib tries to probe for a
  836. * default device named "sndlib" (in alsa 0.9 devices are configured in
  837. * /usr/share/alsa/alsa.conf or in ~/.asoundrc)
  838. * - if "sndlib" is not a valid device "hw:0,0" was used [but now it looks for "default"] (which by default should
  839. * point to the first device of the first card
  840. *
  841. * Some default settings are controllable through the environment as well:
  842. * MUS_ALSA_BUFFER_SIZE = size of each buffer in frames
  843. * MUS_ALSA_BUFFERS = number of buffers
  844. *
  845. * changed 18-Sep-00 by Bill: new error handling: old mus_audio_error folded into
  846. * mus_error; mus_error itself should be used only for "real" errors -- things
  847. * that can cause a throw (a kind of global jump elsewhere); use mus_print for informational
  848. * stuff -- in Snd, mus_print will also save everything printed in the error dialog.
  849. * In a few cases, I tried to fix the code to unwind before mus_error, and in others
  850. * I've changed mus_error to mus_print, but some of these may be mistaken.
  851. * Look for ?? below for areas where I'm not sure I rewrote code correctly.
  852. *
  853. * changed for 0.6.x api by Paul Barton-Davis, pbd@op.net
  854. *
  855. * changed for 0.5.x api by Fernando Lopez-Lezcano, nando@ccrma.stanford.edu
  856. * 04-10-2000:
  857. * based on original 0.4.x code by Paul Barton-Davis (not much left of it :-)
  858. * also Bill's code and Jaroslav Kysela (aplay.c and friends)
  859. *
  860. * Changes:
  861. * 04/25/2000: finished major rework, snd-dac now automatically decides which
  862. * device or devices it uses for playback. Multiple device use is
  863. * for now restricted to only two at most (more changes in Bill's
  864. * needed to be able to support more). Four channel playback in
  865. * Ensoniq AudioPCI and relatives possible (with proper settings
  866. * of the mixer) as well as using two separate cards.
  867. * 04/11/2000: added reporting of alsa sound formats
  868. */
  869. #if HAVE_ALSA
  870. #if (!HAVE_OSS)
  871. #define AUDIO_OK 1
  872. #endif
  873. #include <sys/ioctl.h>
  874. #if HAVE_ALSA
  875. #include <alsa/asoundlib.h>
  876. #else
  877. #include <sys/asoundlib.h>
  878. #endif
  879. #if SND_LIB_VERSION < ((0<<16)|(6<<8)|(0))
  880. #error ALSA version is too old -- audio.c needs 0.9 or later
  881. #endif
  882. /* prototypes for the alsa sndlib functions */
  883. static int alsa_mus_audio_initialize(void);
  884. static void alsa_mus_oss_set_buffers(int num, int size);
  885. static int alsa_mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size);
  886. static int alsa_mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int requested_size);
  887. static int alsa_mus_audio_write(int id, char *buf, int bytes);
  888. static int alsa_mus_audio_read(int id, char *buf, int bytes);
  889. static int alsa_mus_audio_close(int id);
  890. /* decide which api to activate */
  891. static int probe_api(void)
  892. {
  893. #if HAVE_JACK_IN_LINUX
  894. int jackprobe;
  895. jackprobe = jack_mus_audio_initialize();
  896. if (jackprobe == MUS_ERROR)
  897. {
  898. #endif
  899. int card = -1;
  900. if ((snd_card_next(&card) >= 0) && (card >= 0))
  901. {
  902. /* the alsa library has detected one or more cards */
  903. api = MUS_ALSA_API;
  904. vect_mus_audio_initialize = alsa_mus_audio_initialize;
  905. vect_mus_oss_set_buffers = alsa_mus_oss_set_buffers;
  906. vect_mus_audio_moniker = alsa_mus_audio_moniker;
  907. vect_mus_audio_open_output = alsa_mus_audio_open_output;
  908. vect_mus_audio_open_input = alsa_mus_audio_open_input;
  909. vect_mus_audio_write = alsa_mus_audio_write;
  910. vect_mus_audio_read = alsa_mus_audio_read;
  911. vect_mus_audio_close = alsa_mus_audio_close;
  912. }
  913. else
  914. {
  915. /* go for the oss api */
  916. api = MUS_OSS_API;
  917. vect_mus_audio_initialize = oss_mus_audio_initialize;
  918. vect_mus_oss_set_buffers = oss_mus_oss_set_buffers;
  919. vect_mus_audio_moniker = oss_mus_audio_moniker;
  920. vect_mus_audio_open_output = oss_mus_audio_open_output;
  921. vect_mus_audio_open_input = oss_mus_audio_open_input;
  922. vect_mus_audio_write = oss_mus_audio_write;
  923. vect_mus_audio_read = oss_mus_audio_read;
  924. vect_mus_audio_close = oss_mus_audio_close;
  925. }
  926. /* will the _real_ mus_audio_initialize please stand up? */
  927. return(vect_mus_audio_initialize());
  928. #if HAVE_JACK_IN_LINUX
  929. }
  930. return(jackprobe);
  931. #endif
  932. }
  933. /* convert a sndlib sample type to an alsa sample type */
  934. static snd_pcm_format_t to_alsa_format(mus_sample_t snd_format)
  935. {
  936. switch (snd_format)
  937. {
  938. case MUS_BYTE: return(SND_PCM_FORMAT_S8);
  939. case MUS_UBYTE: return(SND_PCM_FORMAT_U8);
  940. case MUS_MULAW: return(SND_PCM_FORMAT_MU_LAW);
  941. case MUS_ALAW: return(SND_PCM_FORMAT_A_LAW);
  942. case MUS_BSHORT: return(SND_PCM_FORMAT_S16_BE);
  943. case MUS_LSHORT: return(SND_PCM_FORMAT_S16_LE);
  944. case MUS_UBSHORT: return(SND_PCM_FORMAT_U16_BE);
  945. case MUS_ULSHORT: return(SND_PCM_FORMAT_U16_LE);
  946. case MUS_B24INT: return(SND_PCM_FORMAT_S24_BE);
  947. case MUS_L24INT: return(SND_PCM_FORMAT_S24_LE);
  948. case MUS_BINT: return(SND_PCM_FORMAT_S32_BE);
  949. case MUS_LINT: return(SND_PCM_FORMAT_S32_LE);
  950. case MUS_BINTN: return(SND_PCM_FORMAT_S32_BE);
  951. case MUS_LINTN: return(SND_PCM_FORMAT_S32_LE);
  952. case MUS_BFLOAT: return(SND_PCM_FORMAT_FLOAT_BE);
  953. case MUS_LFLOAT: return(SND_PCM_FORMAT_FLOAT_LE);
  954. case MUS_BDOUBLE: return(SND_PCM_FORMAT_FLOAT64_BE);
  955. case MUS_LDOUBLE: return(SND_PCM_FORMAT_FLOAT64_LE);
  956. default: break;
  957. }
  958. return((snd_pcm_format_t)MUS_ERROR);
  959. }
  960. /* FIXME: this is not taking yet into account the
  961. * number of bits that a given alsa format is actually
  962. * using...
  963. */
  964. static mus_sample_t to_mus_sample_type(int alsa_format)
  965. {
  966. /* alsa format definitions from asoundlib.h (0.9 cvs 6/27/2001) */
  967. switch (alsa_format)
  968. {
  969. case SND_PCM_FORMAT_S8: return(MUS_BYTE);
  970. case SND_PCM_FORMAT_U8: return(MUS_UBYTE);
  971. case SND_PCM_FORMAT_S16_LE: return(MUS_LSHORT);
  972. case SND_PCM_FORMAT_S16_BE: return(MUS_BSHORT);
  973. case SND_PCM_FORMAT_U16_LE: return(MUS_ULSHORT);
  974. case SND_PCM_FORMAT_U16_BE: return(MUS_UBSHORT);
  975. case SND_PCM_FORMAT_S24_LE: return(MUS_L24INT);
  976. case SND_PCM_FORMAT_S24_BE: return(MUS_B24INT);
  977. case SND_PCM_FORMAT_S32_LE: return(MUS_LINTN); /* 32bit normalized plays 24bit and 16bit files with same amplitude bound (for 24 bit cards) */
  978. case SND_PCM_FORMAT_S32_BE: return(MUS_BINTN);
  979. case SND_PCM_FORMAT_FLOAT_LE: return(MUS_LFLOAT);
  980. case SND_PCM_FORMAT_FLOAT_BE: return(MUS_BFLOAT);
  981. case SND_PCM_FORMAT_FLOAT64_LE: return(MUS_LDOUBLE);
  982. case SND_PCM_FORMAT_FLOAT64_BE: return(MUS_BDOUBLE);
  983. case SND_PCM_FORMAT_MU_LAW: return(MUS_MULAW);
  984. case SND_PCM_FORMAT_A_LAW: return(MUS_ALAW);
  985. /* formats with no translation in snd */
  986. case SND_PCM_FORMAT_U24_LE:
  987. case SND_PCM_FORMAT_U24_BE:
  988. case SND_PCM_FORMAT_U32_LE:
  989. case SND_PCM_FORMAT_U32_BE:
  990. case SND_PCM_FORMAT_IEC958_SUBFRAME_LE:
  991. case SND_PCM_FORMAT_IEC958_SUBFRAME_BE:
  992. case SND_PCM_FORMAT_IMA_ADPCM:
  993. case SND_PCM_FORMAT_MPEG:
  994. case SND_PCM_FORMAT_GSM:
  995. case SND_PCM_FORMAT_SPECIAL:
  996. default:
  997. return(MUS_UNKNOWN_SAMPLE);
  998. }
  999. }
  1000. /* convert a sndlib device into an alsa device number and channel
  1001. * [has to be coordinated with following function!]
  1002. */
  1003. /* very simplistic approach, device mapping should also depend
  1004. * on which card we're dealing with, digital i/o devices should
  1005. * be identified as such and so on
  1006. */
  1007. /* NOTE: in the Delta1010 digital i/o is just a pair of channels
  1008. * in the 10 channel playback frame or 12 channel capture frame,
  1009. * how do we specify that???
  1010. */
  1011. static int to_alsa_device(int dev, int *adev, snd_pcm_stream_t *achan)
  1012. {
  1013. switch (dev)
  1014. {
  1015. /* default values are a problem because the concept does
  1016. * not imply a direction (playback or capture). This works
  1017. * fine as long as both directions of a device are symetric,
  1018. * the Midiman 1010, for example, has 10 channel frames for
  1019. * playback and 12 channel frames for capture and breaks
  1020. * the recorder (probes the default, defaults to output,
  1021. * uses the values for input).
  1022. */
  1023. case MUS_AUDIO_DEFAULT:
  1024. case MUS_AUDIO_DUPLEX_DEFAULT:
  1025. case MUS_AUDIO_LINE_OUT:
  1026. /* analog output */
  1027. (*adev) = 0;
  1028. (*achan) = SND_PCM_STREAM_PLAYBACK;
  1029. break;
  1030. case MUS_AUDIO_AUX_OUTPUT:
  1031. /* extra analog output */
  1032. (*adev) = 1;
  1033. (*achan) = SND_PCM_STREAM_PLAYBACK;
  1034. break;
  1035. case MUS_AUDIO_DAC_OUT:
  1036. /* analog outputs */
  1037. (*adev) = 2;
  1038. (*achan) = SND_PCM_STREAM_PLAYBACK;
  1039. break;
  1040. case MUS_AUDIO_MICROPHONE:
  1041. case MUS_AUDIO_LINE_IN:
  1042. /* analog input */
  1043. (*adev) = 0;
  1044. (*achan) = SND_PCM_STREAM_CAPTURE;
  1045. break;
  1046. default:
  1047. return(MUS_ERROR);
  1048. break;
  1049. }
  1050. return(0);
  1051. }
  1052. /* convert an alsa device into a sndlib device
  1053. * [has to be coordinated with previous function!]
  1054. *
  1055. * naming here is pretty much arbitrary. We have to have
  1056. * a bidirectional mapping between sndlib devices and
  1057. * alsa devices and that's just not possible (I think).
  1058. * This stopgap mapping ignores digital input and output
  1059. * devices - how to differentiate them in alsa?
  1060. */
  1061. static int to_sndlib_device(int dev, int channel)
  1062. {
  1063. switch (channel)
  1064. {
  1065. case SND_PCM_STREAM_PLAYBACK:
  1066. switch (dev)
  1067. {
  1068. /* works only for the first three outputs */
  1069. case 0: return(MUS_AUDIO_LINE_OUT);
  1070. case 1: return(MUS_AUDIO_AUX_OUTPUT);
  1071. case 2: return(MUS_AUDIO_DAC_OUT);
  1072. default:
  1073. return(MUS_ERROR);
  1074. }
  1075. case SND_PCM_STREAM_CAPTURE:
  1076. switch (dev)
  1077. {
  1078. case 0: return(MUS_AUDIO_LINE_IN);
  1079. default:
  1080. return(MUS_ERROR);
  1081. }
  1082. break;
  1083. }
  1084. return(MUS_ERROR);
  1085. }
  1086. static int alsa_mus_error(int type, char *message)
  1087. {
  1088. if (message)
  1089. {
  1090. mus_print("%s", message);
  1091. free(message);
  1092. }
  1093. return(MUS_ERROR);
  1094. }
  1095. /* dump current hardware and software configuration */
  1096. static void alsa_dump_configuration(char *name, snd_pcm_hw_params_t *hw_params, snd_pcm_sw_params_t *sw_params)
  1097. {
  1098. int err;
  1099. char *str;
  1100. snd_output_t *buf;
  1101. #if (SND_LIB_MAJOR == 0) || ((SND_LIB_MAJOR == 1) && (SND_LIB_MINOR == 0) && (SND_LIB_SUBMINOR < 8))
  1102. return; /* avoid Alsa bug */
  1103. #endif
  1104. err = snd_output_buffer_open(&buf);
  1105. if (err < 0)
  1106. mus_print("could not open dump buffer: %s", snd_strerror(err));
  1107. else
  1108. {
  1109. size_t len;
  1110. if (hw_params)
  1111. {
  1112. snd_output_puts(buf, "hw_params status of ");
  1113. snd_output_puts(buf, name);
  1114. snd_output_puts(buf, "\n");
  1115. err = snd_pcm_hw_params_dump(hw_params, buf);
  1116. if (err < 0)
  1117. mus_print("snd_pcm_hw_params_dump: %s", snd_strerror(err));
  1118. }
  1119. if (sw_params)
  1120. {
  1121. snd_output_puts(buf, "sw_params status of ");
  1122. snd_output_puts(buf, name);
  1123. snd_output_puts(buf, "\n");
  1124. err = snd_pcm_sw_params_dump(sw_params, buf);
  1125. if (err < 0)
  1126. mus_print("snd_pcm_hw_params_dump: %s", snd_strerror(err));
  1127. }
  1128. snd_output_putc(buf, '\0');
  1129. len = snd_output_buffer_string(buf, &str);
  1130. if (len > 1)
  1131. mus_print("status of %s\n%s", name, str);
  1132. snd_output_close(buf);
  1133. }
  1134. }
  1135. /* get hardware params for a pcm */
  1136. static snd_pcm_hw_params_t *alsa_get_hardware_params(const char *name, snd_pcm_stream_t stream, int mode)
  1137. {
  1138. int err;
  1139. snd_pcm_t *handle;
  1140. if ((err = snd_pcm_open(&handle, name, stream, mode | SND_PCM_NONBLOCK)) != 0)
  1141. {
  1142. alsa_mus_error(MUS_AUDIO_CANT_OPEN,
  1143. mus_format("open pcm %s for stream %d: %s",
  1144. name, stream, snd_strerror(err)));
  1145. return(NULL);
  1146. }
  1147. else
  1148. {
  1149. snd_pcm_hw_params_t *params;
  1150. params = (snd_pcm_hw_params_t *)calloc(1, snd_pcm_hw_params_sizeof());
  1151. if (params == NULL)
  1152. {
  1153. snd_pcm_close(handle);
  1154. alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE,
  1155. mus_format("could not allocate memory for hardware params"));
  1156. }
  1157. else
  1158. {
  1159. err = snd_pcm_hw_params_any(handle, params);
  1160. if (err < 0)
  1161. {
  1162. snd_pcm_close(handle);
  1163. alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE,
  1164. mus_format("snd_pcm_hw_params_any: pcm %s, stream %d, error: %s",
  1165. name, stream, snd_strerror(err)));
  1166. }
  1167. else
  1168. {
  1169. snd_pcm_close(handle);
  1170. return(params);
  1171. }
  1172. }
  1173. }
  1174. return(NULL);
  1175. }
  1176. /* allocate software params structure */
  1177. static snd_pcm_sw_params_t *alsa_get_software_params(void)
  1178. {
  1179. snd_pcm_sw_params_t *params = NULL;
  1180. params = (snd_pcm_sw_params_t *)calloc(1, snd_pcm_sw_params_sizeof());
  1181. if (params == NULL)
  1182. {
  1183. alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE,
  1184. mus_format("could not allocate memory for software params"));
  1185. }
  1186. return(params);
  1187. }
  1188. /* probe a device name against the list of available pcm devices */
  1189. static bool alsa_probe_device_name(const char *name)
  1190. {
  1191. snd_config_t *conf;
  1192. snd_config_iterator_t pos, next;
  1193. int err;
  1194. err = snd_config_update();
  1195. if (err < 0)
  1196. {
  1197. mus_print("snd_config_update: %s", snd_strerror(err));
  1198. return(false);
  1199. }
  1200. err = snd_config_search(snd_config, "pcm", &conf);
  1201. if (err < 0)
  1202. {
  1203. mus_print("snd_config_search: %s", snd_strerror(err));
  1204. return(false);
  1205. }
  1206. snd_config_for_each(pos, next, conf)
  1207. {
  1208. snd_config_t *c = snd_config_iterator_entry(pos);
  1209. const char *id;
  1210. int err = snd_config_get_id(c, &id);
  1211. if (err == 0) {
  1212. int result = strncmp(name, id, strlen(id));
  1213. if (result == 0 &&
  1214. (name[strlen(id)] == '\0' || name[strlen(id)] == ':'))
  1215. {
  1216. return(true);
  1217. }
  1218. }
  1219. }
  1220. return(false);
  1221. }
  1222. /* check a device name against the list of available pcm devices */
  1223. static int alsa_check_device_name(const char *name)
  1224. {
  1225. if (!alsa_probe_device_name(name))
  1226. {
  1227. return(alsa_mus_error(MUS_AUDIO_CANT_READ,
  1228. mus_format("alsa could not find device \"%s\" in configuration",
  1229. name)));
  1230. }
  1231. return(MUS_NO_ERROR);
  1232. }
  1233. /* set scheduling priority to SCHED_FIFO
  1234. * this will only work if the program that uses sndlib is run as root or is suid root
  1235. */
  1236. /* whether we want to trace calls
  1237. *
  1238. * set to "1" to print function trace information in the
  1239. * snd error window
  1240. */
  1241. static int alsa_trace = 0;
  1242. /* this should go away as it is oss specific */
  1243. static int fragment_size = 512;
  1244. static int fragments = 4;
  1245. static void alsa_mus_oss_set_buffers(int num, int size)
  1246. {
  1247. fragments = num;
  1248. fragment_size = size;
  1249. }
  1250. /* total number of soundcards in our setup, set by initialize_audio */
  1251. /* static int sound_cards = 0; */
  1252. /* return the number of cards that are available */
  1253. /* return the type of driver we're dealing with */
  1254. static char *alsa_mus_audio_moniker(void)
  1255. {
  1256. if (version_name == NULL) version_name = (char *)calloc(LABEL_BUFFER_SIZE, sizeof(char));
  1257. snprintf(version_name, LABEL_BUFFER_SIZE, "ALSA %s", SND_LIB_VERSION_STR);
  1258. return(version_name);
  1259. }
  1260. /* handles for both directions of the virtual device */
  1261. static snd_pcm_t *handles[2] = {NULL, NULL};
  1262. /* hardware and software parameter sctructure pointers */
  1263. static snd_pcm_hw_params_t *alsa_hw_params[2] = {NULL, NULL}; /* avoid bogus free */
  1264. static snd_pcm_sw_params_t *alsa_sw_params[2] = {NULL, NULL};
  1265. /* some defaults */
  1266. static int alsa_open_mode = SND_PCM_ASYNC;
  1267. static int alsa_buffers = 3;
  1268. /* size of buffer in number of samples per channel,
  1269. * at 44100 approximately 5.9mSecs
  1270. */
  1271. static int alsa_samples_per_channel = 1024;
  1272. static snd_pcm_access_t alsa_interleave = SND_PCM_ACCESS_RW_INTERLEAVED;
  1273. static int alsa_max_capture_channels = 32;
  1274. /* first default name for pcm configuration */
  1275. static char *alsa_sndlib_device_name = (char *)"sndlib";
  1276. /* second default for playback and capture: hardware pcm, first card, first device */
  1277. /* pcms used by sndlib, playback and capture */
  1278. static char *alsa_playback_device_name = NULL;
  1279. static char *alsa_capture_device_name = NULL;
  1280. /* -------- tie these names into scheme/ruby -------- */
  1281. static int alsa_get_max_buffers(void)
  1282. {
  1283. unsigned int max_periods = 0, max_rec_periods = 0;
  1284. int dir = 0;
  1285. if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK])
  1286. snd_pcm_hw_params_get_periods_max(alsa_hw_params[SND_PCM_STREAM_PLAYBACK], &max_periods, &dir);
  1287. if (alsa_hw_params[SND_PCM_STREAM_CAPTURE])
  1288. {
  1289. snd_pcm_hw_params_get_periods_max(alsa_hw_params[SND_PCM_STREAM_CAPTURE], &max_rec_periods, &dir);
  1290. if (max_periods > max_rec_periods)
  1291. max_periods = max_rec_periods;
  1292. }
  1293. return(max_periods);
  1294. }
  1295. static int alsa_get_min_buffers(void)
  1296. {
  1297. unsigned int min_periods = 0, min_rec_periods = 0;
  1298. int dir = 0;
  1299. if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK])
  1300. snd_pcm_hw_params_get_periods_min(alsa_hw_params[SND_PCM_STREAM_PLAYBACK], &min_periods, &dir);
  1301. if (alsa_hw_params[SND_PCM_STREAM_CAPTURE])
  1302. {
  1303. snd_pcm_hw_params_get_periods_min(alsa_hw_params[SND_PCM_STREAM_CAPTURE], &min_rec_periods, &dir);
  1304. if (min_periods < min_rec_periods)
  1305. min_periods = min_rec_periods;
  1306. }
  1307. return(min_periods);
  1308. }
  1309. static int alsa_clamp_buffers(int bufs)
  1310. {
  1311. int minb, maxb;
  1312. minb = alsa_get_min_buffers();
  1313. maxb = alsa_get_max_buffers();
  1314. if (bufs > maxb)
  1315. bufs = maxb;
  1316. if (bufs < minb)
  1317. bufs = minb;
  1318. return(bufs);
  1319. }
  1320. static snd_pcm_uframes_t alsa_get_min_buffer_size(void)
  1321. {
  1322. snd_pcm_uframes_t min_buffer_size = 0, min_rec_buffer_size = 0;
  1323. if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK])
  1324. snd_pcm_hw_params_get_buffer_size_min(alsa_hw_params[SND_PCM_STREAM_PLAYBACK], &min_buffer_size);
  1325. if (alsa_hw_params[SND_PCM_STREAM_CAPTURE])
  1326. {
  1327. snd_pcm_hw_params_get_buffer_size_min(alsa_hw_params[SND_PCM_STREAM_CAPTURE], &min_rec_buffer_size);
  1328. if (min_buffer_size < min_rec_buffer_size)
  1329. min_buffer_size = min_rec_buffer_size;
  1330. }
  1331. return(min_buffer_size);
  1332. }
  1333. static snd_pcm_uframes_t alsa_get_max_buffer_size(void)
  1334. {
  1335. snd_pcm_uframes_t max_buffer_size = 0, max_rec_buffer_size = 0;
  1336. if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK])
  1337. snd_pcm_hw_params_get_buffer_size_max(alsa_hw_params[SND_PCM_STREAM_PLAYBACK], &max_buffer_size);
  1338. if (alsa_hw_params[SND_PCM_STREAM_CAPTURE])
  1339. {
  1340. snd_pcm_hw_params_get_buffer_size_max(alsa_hw_params[SND_PCM_STREAM_CAPTURE], &max_rec_buffer_size);
  1341. if (max_buffer_size > max_rec_buffer_size)
  1342. max_buffer_size = max_rec_buffer_size;
  1343. }
  1344. return(max_buffer_size);
  1345. }
  1346. static snd_pcm_uframes_t alsa_clamp_buffer_size(snd_pcm_uframes_t buf_size)
  1347. {
  1348. snd_pcm_uframes_t minb, maxb;
  1349. minb = alsa_get_min_buffer_size();
  1350. maxb = alsa_get_max_buffer_size();
  1351. if (buf_size > maxb)
  1352. buf_size = maxb;
  1353. if (buf_size < minb)
  1354. buf_size = minb;
  1355. return(buf_size);
  1356. }
  1357. static bool alsa_set_playback_parameters(void)
  1358. {
  1359. /* playback stream parameters */
  1360. if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK]) free(alsa_hw_params[SND_PCM_STREAM_PLAYBACK]);
  1361. alsa_hw_params[SND_PCM_STREAM_PLAYBACK] = alsa_get_hardware_params(alsa_playback_device_name, SND_PCM_STREAM_PLAYBACK, alsa_open_mode);
  1362. if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK])
  1363. {
  1364. snd_pcm_uframes_t size;
  1365. int old_buffers;
  1366. old_buffers = alsa_buffers;
  1367. if (alsa_sw_params[SND_PCM_STREAM_PLAYBACK]) free(alsa_sw_params[SND_PCM_STREAM_PLAYBACK]);
  1368. alsa_sw_params[SND_PCM_STREAM_PLAYBACK] = alsa_get_software_params();
  1369. sound_cards = 1;
  1370. alsa_buffers = alsa_clamp_buffers(alsa_buffers);
  1371. if (alsa_buffers <= 0)
  1372. {
  1373. alsa_buffers = old_buffers;
  1374. return(false);
  1375. }
  1376. size = alsa_clamp_buffer_size((snd_pcm_uframes_t)(alsa_samples_per_channel * alsa_buffers));
  1377. if (size <= 0) return(false);
  1378. alsa_samples_per_channel = size / alsa_buffers;
  1379. }
  1380. return(alsa_hw_params[SND_PCM_STREAM_PLAYBACK] && alsa_sw_params[SND_PCM_STREAM_PLAYBACK]);
  1381. }
  1382. static bool alsa_set_capture_parameters(void)
  1383. {
  1384. /* capture stream parameters */
  1385. if (alsa_hw_params[SND_PCM_STREAM_CAPTURE]) free(alsa_hw_params[SND_PCM_STREAM_CAPTURE]);
  1386. alsa_hw_params[SND_PCM_STREAM_CAPTURE] = alsa_get_hardware_params(alsa_capture_device_name, SND_PCM_STREAM_CAPTURE, alsa_open_mode);
  1387. if (alsa_hw_params[SND_PCM_STREAM_CAPTURE])
  1388. {
  1389. snd_pcm_uframes_t size;
  1390. int old_buffers;
  1391. old_buffers = alsa_buffers;
  1392. if (alsa_sw_params[SND_PCM_STREAM_CAPTURE]) free(alsa_sw_params[SND_PCM_STREAM_CAPTURE]);
  1393. alsa_sw_params[SND_PCM_STREAM_CAPTURE] = alsa_get_software_params();
  1394. sound_cards = 1;
  1395. alsa_buffers = alsa_clamp_buffers(alsa_buffers);
  1396. if (alsa_buffers <= 0)
  1397. {
  1398. alsa_buffers = old_buffers;
  1399. return(false);
  1400. }
  1401. size = alsa_clamp_buffer_size((snd_pcm_uframes_t)(alsa_samples_per_channel * alsa_buffers));
  1402. if (size <= 0) return(false);
  1403. alsa_samples_per_channel = size / alsa_buffers;
  1404. }
  1405. return(alsa_hw_params[SND_PCM_STREAM_CAPTURE] && alsa_sw_params[SND_PCM_STREAM_CAPTURE]);
  1406. }
  1407. char *mus_alsa_playback_device(void) {return(alsa_playback_device_name);}
  1408. char *mus_alsa_set_playback_device(const char *name)
  1409. {
  1410. if (alsa_check_device_name(name) == MUS_NO_ERROR)
  1411. {
  1412. char *old_name = alsa_playback_device_name;
  1413. alsa_playback_device_name = mus_strdup(name);
  1414. if (!alsa_set_playback_parameters())
  1415. {
  1416. alsa_playback_device_name = old_name; /* try to back out of the mistake */
  1417. alsa_set_playback_parameters();
  1418. }
  1419. }
  1420. return(alsa_playback_device_name);
  1421. }
  1422. char *mus_alsa_capture_device(void) {return(alsa_capture_device_name);}
  1423. char *mus_alsa_set_capture_device(const char *name)
  1424. {
  1425. if (alsa_check_device_name(name) == MUS_NO_ERROR)
  1426. {
  1427. char *old_name = alsa_capture_device_name;
  1428. alsa_capture_device_name = mus_strdup(name);
  1429. if (!alsa_set_capture_parameters())
  1430. {
  1431. alsa_capture_device_name = old_name;
  1432. alsa_set_capture_parameters();
  1433. }
  1434. }
  1435. return(alsa_capture_device_name);
  1436. }
  1437. char *mus_alsa_device(void) {return(alsa_sndlib_device_name);}
  1438. char *mus_alsa_set_device(const char *name)
  1439. {
  1440. if (alsa_check_device_name(name) == MUS_NO_ERROR)
  1441. {
  1442. alsa_sndlib_device_name = mus_strdup(name);
  1443. mus_alsa_set_playback_device(name);
  1444. mus_alsa_set_capture_device(name);
  1445. }
  1446. return(alsa_sndlib_device_name);
  1447. }
  1448. int mus_alsa_buffer_size(void) {return(alsa_samples_per_channel);}
  1449. int mus_alsa_set_buffer_size(int size)
  1450. {
  1451. snd_pcm_uframes_t bsize;
  1452. if (alsa_buffers == 0) alsa_buffers = 1;
  1453. if (size > 0)
  1454. {
  1455. bsize = alsa_clamp_buffer_size((snd_pcm_uframes_t)(size * alsa_buffers));
  1456. alsa_samples_per_channel = bsize / alsa_buffers;
  1457. }
  1458. return(alsa_samples_per_channel);
  1459. }
  1460. int mus_alsa_buffers(void) {return(alsa_buffers);}
  1461. int mus_alsa_set_buffers(int num)
  1462. {
  1463. snd_pcm_uframes_t size;
  1464. if (num > 0)
  1465. {
  1466. alsa_buffers = alsa_clamp_buffers(num);
  1467. if (alsa_buffers > 0)
  1468. {
  1469. size = alsa_clamp_buffer_size((snd_pcm_uframes_t)(alsa_samples_per_channel * alsa_buffers));
  1470. alsa_samples_per_channel = size / alsa_buffers;
  1471. }
  1472. }
  1473. return(alsa_buffers);
  1474. }
  1475. static bool alsa_squelch_warning = false;
  1476. bool mus_alsa_squelch_warning(void) {return(alsa_squelch_warning);}
  1477. bool mus_alsa_set_squelch_warning(bool val)
  1478. {
  1479. alsa_squelch_warning = val;
  1480. return(val);
  1481. }
  1482. /* get a device name from the environment */
  1483. static char *alsa_get_device_from_env(const char *name)
  1484. {
  1485. char *string = getenv(name);
  1486. if (string)
  1487. if (alsa_check_device_name(string) == MUS_NO_ERROR)
  1488. return(string);
  1489. return(NULL);
  1490. }
  1491. /* get an integer from the environment */
  1492. static int alsa_get_int_from_env(const char *name, int *value, int min, int max)
  1493. {
  1494. char *string = getenv(name);
  1495. if (string)
  1496. {
  1497. char *end;
  1498. long int result = strtol(string, &end, 10);
  1499. if (((min != -1) && (max != -1)) &&
  1500. (result < min || result > max))
  1501. {
  1502. return(alsa_mus_error(MUS_AUDIO_CANT_READ,
  1503. mus_format("%s ignored: out of range, value=%d, min=%d, max=%d",
  1504. name, (int)result, min, max)));
  1505. }
  1506. else
  1507. {
  1508. if (errno == ERANGE)
  1509. {
  1510. return(alsa_mus_error(MUS_AUDIO_CANT_READ,
  1511. mus_format("%s ignored: strlol conversion out of range",
  1512. name)));
  1513. }
  1514. else
  1515. {
  1516. if ((*string != '\0') && (*end == '\0'))
  1517. {
  1518. *value = (int)result;
  1519. return(MUS_NO_ERROR);
  1520. }
  1521. else
  1522. {
  1523. return(alsa_mus_error(MUS_AUDIO_CANT_READ,
  1524. mus_format("%s ignored: value is \"%s\", not an integer",
  1525. name, string)));
  1526. }
  1527. }
  1528. }
  1529. }
  1530. return(MUS_ERROR);
  1531. }
  1532. /* initialize the audio subsystem */
  1533. /* define environment variable names */
  1534. #define MUS_ALSA_PLAYBACK_DEVICE_ENV_NAME "MUS_ALSA_PLAYBACK_DEVICE"
  1535. #define MUS_ALSA_CAPTURE_DEVICE_ENV_NAME "MUS_ALSA_CAPTURE_DEVICE"
  1536. #define MUS_ALSA_DEVICE_ENV_NAME "MUS_ALSA_DEVICE"
  1537. #define MUS_ALSA_BUFFERS_ENV_NAME "MUS_ALSA_BUFFERS"
  1538. #define MUS_ALSA_BUFFER_SIZE_ENV_NAME "MUS_ALSA_BUFFER_SIZE"
  1539. #define MUS_ALSA_TRACE_ENV_NAME "MUS_ALSA_TRACE"
  1540. static int alsa_mus_audio_initialize(void)
  1541. {
  1542. char *name = NULL;
  1543. char *pname;
  1544. char *cname;
  1545. int value = 0, alsa_buffer_size = 0;
  1546. if (audio_initialized)
  1547. return(0);
  1548. sound_cards = 0;
  1549. /* get trace flag from environment */
  1550. if (alsa_get_int_from_env(MUS_ALSA_TRACE_ENV_NAME, &value, 0, 1) == MUS_NO_ERROR)
  1551. alsa_trace = value;
  1552. /* try to get device names from environment */
  1553. pname = alsa_get_device_from_env(MUS_ALSA_PLAYBACK_DEVICE_ENV_NAME);
  1554. if ((pname) && (alsa_probe_device_name(pname)))
  1555. alsa_playback_device_name = pname;
  1556. cname = alsa_get_device_from_env(MUS_ALSA_CAPTURE_DEVICE_ENV_NAME);
  1557. if ((cname) && (alsa_probe_device_name(cname)))
  1558. alsa_capture_device_name = cname;
  1559. name = alsa_get_device_from_env(MUS_ALSA_DEVICE_ENV_NAME);
  1560. if ((name) && (alsa_probe_device_name(name)))
  1561. {
  1562. if (!alsa_playback_device_name)
  1563. alsa_playback_device_name = name;
  1564. if (!alsa_capture_device_name)
  1565. alsa_capture_device_name = name;
  1566. alsa_sndlib_device_name = name;
  1567. }
  1568. /* now check that we have a plausible name */
  1569. if (!alsa_probe_device_name(alsa_sndlib_device_name))
  1570. {
  1571. alsa_sndlib_device_name = (char *)"default";
  1572. if (!alsa_probe_device_name(alsa_sndlib_device_name))
  1573. {
  1574. alsa_sndlib_device_name = (char *)"plughw:0";
  1575. if (!alsa_probe_device_name(alsa_sndlib_device_name))
  1576. alsa_sndlib_device_name = (char *)"hw:0";
  1577. }
  1578. }
  1579. /* if no device name set yet, try for special sndlib name first */
  1580. if (!alsa_playback_device_name)
  1581. {
  1582. if (alsa_probe_device_name(alsa_sndlib_device_name))
  1583. alsa_playback_device_name = alsa_sndlib_device_name;
  1584. else alsa_playback_device_name = (char *)"hw:0";
  1585. }
  1586. if (!alsa_capture_device_name)
  1587. {
  1588. if (alsa_probe_device_name(alsa_sndlib_device_name))
  1589. alsa_capture_device_name = alsa_sndlib_device_name;
  1590. else alsa_capture_device_name = (char *)"hw:0";
  1591. }
  1592. alsa_get_int_from_env(MUS_ALSA_BUFFERS_ENV_NAME, &alsa_buffers, -1, -1);
  1593. alsa_get_int_from_env(MUS_ALSA_BUFFER_SIZE_ENV_NAME, &alsa_buffer_size, -1, -1);
  1594. if ((alsa_buffer_size > 0) && (alsa_buffers > 0))
  1595. alsa_samples_per_channel = alsa_buffer_size / alsa_buffers;
  1596. if (!alsa_set_playback_parameters())
  1597. {
  1598. /* somehow we got a device that passed muster with alsa_probe_device_name, but doesn't return hw params! */
  1599. alsa_playback_device_name = (char *)"plughw:0";
  1600. if (!alsa_set_playback_parameters())
  1601. {
  1602. alsa_playback_device_name = (char *)"hw:0";
  1603. if (!alsa_set_playback_parameters())
  1604. return(MUS_ERROR);
  1605. }
  1606. }
  1607. if (!alsa_set_capture_parameters())
  1608. {
  1609. alsa_capture_device_name = (char *)"plughw:0";
  1610. if (!alsa_set_capture_parameters())
  1611. {
  1612. alsa_capture_device_name = (char *)"hw:0";
  1613. if (!alsa_set_capture_parameters())
  1614. return(MUS_ERROR);
  1615. }
  1616. }
  1617. if ((!alsa_hw_params[SND_PCM_STREAM_CAPTURE]) ||
  1618. (!alsa_hw_params[SND_PCM_STREAM_PLAYBACK]))
  1619. return(MUS_ERROR);
  1620. audio_initialized = true;
  1621. return(0);
  1622. }
  1623. /* open an input or output stream */
  1624. static int alsa_audio_open(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
  1625. {
  1626. int device, alsa_device;
  1627. snd_pcm_format_t alsa_format;
  1628. snd_pcm_stream_t alsa_stream;
  1629. char *alsa_name;
  1630. int frames, periods;
  1631. int err;
  1632. snd_pcm_t *handle;
  1633. snd_pcm_hw_params_t *hw_params = NULL;
  1634. snd_pcm_sw_params_t *sw_params = NULL;
  1635. if ((!audio_initialized) &&
  1636. (mus_audio_initialize() != MUS_NO_ERROR))
  1637. return(MUS_ERROR);
  1638. if (chans <= 0) return(MUS_ERROR);
  1639. if (alsa_trace)
  1640. mus_print("%s: %x rate=%d, chans=%d, format=%d:%s, size=%d",
  1641. __func__, ur_dev, srate, chans, samp_type,
  1642. mus_sample_type_to_string(samp_type), size);
  1643. /* card = MUS_AUDIO_SYSTEM(ur_dev); */
  1644. device = MUS_AUDIO_DEVICE(ur_dev);
  1645. if ((err = to_alsa_device(device, &alsa_device, &alsa_stream)) < 0)
  1646. {
  1647. return(alsa_mus_error(MUS_AUDIO_DEVICE_NOT_AVAILABLE,
  1648. mus_format("%s: cannot translate device %d to alsa",
  1649. snd_strerror(err), device)));
  1650. }
  1651. if ((alsa_format = to_alsa_format(samp_type)) == (snd_pcm_format_t)MUS_ERROR)
  1652. {
  1653. return(alsa_mus_error(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE,
  1654. mus_format("could not change %s<%d> to alsa format",
  1655. mus_sample_type_to_string(samp_type), samp_type)));
  1656. }
  1657. alsa_name = (alsa_stream == SND_PCM_STREAM_PLAYBACK) ? alsa_playback_device_name : alsa_capture_device_name;
  1658. if ((err = snd_pcm_open(&handle, alsa_name, alsa_stream, alsa_open_mode)) != 0)
  1659. {
  1660. /* snd_pcm_close(handle); */
  1661. /* this segfaults in some versions of ALSA */
  1662. return(alsa_mus_error(MUS_AUDIO_CANT_OPEN,
  1663. mus_format("open pcm %s stream %s: %s",
  1664. alsa_name, snd_pcm_stream_name(alsa_stream),
  1665. snd_strerror(err))));
  1666. }
  1667. handles[alsa_stream] = handle;
  1668. hw_params = alsa_hw_params[alsa_stream];
  1669. sw_params = alsa_sw_params[alsa_stream];
  1670. if ((err = snd_pcm_hw_params_any(handle, hw_params)) < 0)
  1671. {
  1672. snd_pcm_close(handle);
  1673. handles[alsa_stream] = NULL;
  1674. alsa_dump_configuration(alsa_name, hw_params, sw_params);
  1675. return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE,
  1676. mus_format("%s: no parameter configurations available for %s",
  1677. snd_strerror(err), alsa_name)));
  1678. }
  1679. err = snd_pcm_hw_params_set_access(handle, hw_params, alsa_interleave);
  1680. if (err < 0)
  1681. {
  1682. snd_pcm_close(handle);
  1683. handles[alsa_stream] = NULL;
  1684. alsa_dump_configuration(alsa_name, hw_params, sw_params);
  1685. return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE,
  1686. mus_format("%s: %s: access type %s not available",
  1687. snd_strerror(err), alsa_name, snd_pcm_access_name(alsa_interleave))));
  1688. }
  1689. periods = alsa_buffers;
  1690. err = snd_pcm_hw_params_set_periods(handle, hw_params, periods, 0);
  1691. if (err < 0)
  1692. {
  1693. unsigned int minp, maxp;
  1694. int dir;
  1695. snd_pcm_hw_params_get_periods_min(hw_params, &minp, &dir);
  1696. snd_pcm_hw_params_get_periods_max(hw_params, &maxp, &dir);
  1697. snd_pcm_close(handle);
  1698. handles[alsa_stream] = NULL;
  1699. alsa_dump_configuration(alsa_name, hw_params, sw_params);
  1700. return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE,
  1701. mus_format("%s: %s: cannot set number of periods to %d, min is %d, max is %d",
  1702. snd_strerror(err), alsa_name, periods, (int)minp, (int)maxp)));
  1703. }
  1704. frames = size / chans / mus_bytes_per_sample(samp_type);
  1705. err = snd_pcm_hw_params_set_buffer_size(handle, hw_params, frames * periods);
  1706. if (err < 0)
  1707. {
  1708. snd_pcm_uframes_t minp, maxp;
  1709. snd_pcm_hw_params_get_buffer_size_min(hw_params, &minp);
  1710. snd_pcm_hw_params_get_buffer_size_max(hw_params, &maxp);
  1711. snd_pcm_close(handle);
  1712. handles[alsa_stream] = NULL;
  1713. alsa_dump_configuration(alsa_name, hw_params, sw_params);
  1714. return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE,
  1715. mus_format("%s: %s: cannot set buffer size to %d periods of %d frames; \
  1716. total requested buffer size is %d frames, minimum allowed is %d, maximum is %d",
  1717. snd_strerror(err), alsa_name, periods, frames, periods * frames, (int)minp, (int)maxp)));
  1718. }
  1719. err = snd_pcm_hw_params_set_format(handle, hw_params, alsa_format);
  1720. if (err < 0)
  1721. {
  1722. snd_pcm_close(handle);
  1723. handles[alsa_stream] = NULL;
  1724. alsa_dump_configuration(alsa_name, hw_params, sw_params);
  1725. return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE,
  1726. mus_format("%s: %s: cannot set format to %s",
  1727. snd_strerror(err), alsa_name, snd_pcm_format_name(alsa_format))));
  1728. }
  1729. err = snd_pcm_hw_params_set_channels(handle, hw_params, chans);
  1730. if (err < 0)
  1731. {
  1732. snd_pcm_close(handle);
  1733. handles[alsa_stream] = NULL;
  1734. alsa_dump_configuration(alsa_name, hw_params, sw_params);
  1735. return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE,
  1736. mus_format("%s: %s: cannot set channels to %d",
  1737. snd_strerror(err), alsa_name, chans)));
  1738. }
  1739. {
  1740. unsigned int new_rate;
  1741. new_rate = srate;
  1742. /* r is unsigned int so it can't be negative */
  1743. err = snd_pcm_hw_params_set_rate_near(handle, hw_params, &new_rate, 0);
  1744. if ((new_rate != (unsigned int)srate) && (!alsa_squelch_warning))
  1745. {
  1746. mus_print("%s: could not set rate to exactly %d, set to %d instead",
  1747. alsa_name, srate, new_rate);
  1748. }
  1749. }
  1750. err = snd_pcm_hw_params(handle, hw_params);
  1751. if (err < 0)
  1752. {
  1753. snd_pcm_close(handle);
  1754. handles[alsa_stream] = NULL;
  1755. alsa_dump_configuration(alsa_name, hw_params, sw_params);
  1756. return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE,
  1757. mus_format("%s: cannot set hardware parameters for %s",
  1758. snd_strerror(err), alsa_name)));
  1759. }
  1760. snd_pcm_sw_params_current(handle, sw_params);
  1761. err = snd_pcm_sw_params(handle, sw_params);
  1762. if (err < 0)
  1763. {
  1764. snd_pcm_close(handle);
  1765. handles[alsa_stream] = NULL;
  1766. alsa_dump_configuration(alsa_name, hw_params, sw_params);
  1767. return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE,
  1768. mus_format("%s: cannot set software parameters for %s",
  1769. snd_strerror(err), alsa_name)));
  1770. }
  1771. /* for now the id for the stream is the direction identifier, that is
  1772. not a problem because we only advertise one card with two devices */
  1773. return(alsa_stream);
  1774. }
  1775. /* sndlib support for opening output devices */
  1776. static int alsa_mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
  1777. {
  1778. return(alsa_audio_open(ur_dev, srate, chans, samp_type, size));
  1779. }
  1780. /* sndlib support for opening input devices */
  1781. static int alsa_mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
  1782. {
  1783. return(alsa_audio_open(ur_dev, srate, chans, samp_type, size));
  1784. }
  1785. /* sndlib support for closing a device */
  1786. /* to force it to stop, snd_pcm_drop */
  1787. static bool xrun_warned = false;
  1788. static int alsa_mus_audio_close(int id)
  1789. {
  1790. xrun_warned = false;
  1791. if (id == MUS_ERROR) return(MUS_ERROR);
  1792. if (alsa_trace) mus_print( "%s: %d", __func__, id);
  1793. if (handles[id])
  1794. {
  1795. int err;
  1796. err = snd_pcm_drain(handles[id]);
  1797. if (err != 0)
  1798. mus_print("snd_pcm_drain: %s", snd_strerror(err));
  1799. err = snd_pcm_close(handles[id]);
  1800. if (err != 0)
  1801. return(alsa_mus_error(MUS_AUDIO_CANT_CLOSE,
  1802. mus_format("snd_pcm_close: %s",
  1803. snd_strerror(err))));
  1804. handles[id] = NULL;
  1805. }
  1806. return(MUS_NO_ERROR);
  1807. }
  1808. /* recover from underruns or overruns */
  1809. static int recover_from_xrun(int id)
  1810. {
  1811. int err;
  1812. snd_pcm_status_t *status;
  1813. snd_pcm_state_t state;
  1814. snd_pcm_status_alloca(&status);
  1815. err = snd_pcm_status(handles[id], status);
  1816. if (err < 0)
  1817. {
  1818. mus_print("%s: snd_pcm_status: %s", __func__, snd_strerror(err));
  1819. return(MUS_ERROR);
  1820. }
  1821. state = snd_pcm_status_get_state(status);
  1822. if (state == SND_PCM_STATE_XRUN)
  1823. {
  1824. if (!xrun_warned)
  1825. {
  1826. xrun_warned = true;
  1827. mus_print("[under|over]run detected");
  1828. }
  1829. err = snd_pcm_prepare(handles[id]);
  1830. if (err < 0)
  1831. mus_print("snd_pcm_prepare: %s", snd_strerror(err));
  1832. else return(MUS_NO_ERROR);
  1833. }
  1834. else mus_print("%s: error, current state is %s", __func__, snd_pcm_state_name(state));
  1835. return(MUS_ERROR);
  1836. }
  1837. /* sndlib support for writing a buffer to an output device */
  1838. static int alsa_mus_audio_write(int id, char *buf, int bytes)
  1839. {
  1840. snd_pcm_sframes_t status;
  1841. ssize_t frames;
  1842. if (id == MUS_ERROR) return(MUS_ERROR);
  1843. frames = snd_pcm_bytes_to_frames(handles[id], bytes);
  1844. status = snd_pcm_writei(handles[id], buf, frames);
  1845. if ((status == -EAGAIN) ||
  1846. ((status >= 0) && (status < frames)))
  1847. snd_pcm_wait(handles[id], 1000);
  1848. else
  1849. {
  1850. if (status == -EPIPE)
  1851. return(recover_from_xrun(id));
  1852. else
  1853. {
  1854. if (status < 0)
  1855. {
  1856. mus_print("snd_pcm_writei: %s", snd_strerror(status));
  1857. return(MUS_ERROR);
  1858. }
  1859. }
  1860. }
  1861. return(MUS_NO_ERROR);
  1862. }
  1863. /* sndlib support for reading a buffer from an input device */
  1864. static int alsa_mus_audio_read(int id, char *buf, int bytes)
  1865. {
  1866. snd_pcm_sframes_t status;
  1867. ssize_t frames;
  1868. if (id == MUS_ERROR) return(MUS_ERROR);
  1869. frames = snd_pcm_bytes_to_frames(handles[id], bytes);
  1870. status = snd_pcm_readi(handles[id], buf, frames);
  1871. if ((status == -EAGAIN) ||
  1872. ((status >= 0) && (status < frames)))
  1873. snd_pcm_wait(handles[id], 1000);
  1874. else
  1875. {
  1876. if (status == -EPIPE)
  1877. return(recover_from_xrun(id));
  1878. else
  1879. {
  1880. if (status < 0)
  1881. {
  1882. mus_print("snd_pcm_readi: %s", snd_strerror(status));
  1883. return(MUS_ERROR);
  1884. }
  1885. }
  1886. }
  1887. return(MUS_NO_ERROR);
  1888. }
  1889. /* read state of the audio hardware */
  1890. static int alsa_chans(int ur_dev, int *info)
  1891. {
  1892. int card;
  1893. int device;
  1894. int alsa_device = 0;
  1895. snd_pcm_stream_t alsa_stream = SND_PCM_STREAM_PLAYBACK;
  1896. if ((!audio_initialized) &&
  1897. (mus_audio_initialize() != MUS_NO_ERROR))
  1898. return(MUS_ERROR);
  1899. card = MUS_AUDIO_SYSTEM(ur_dev);
  1900. device = MUS_AUDIO_DEVICE(ur_dev);
  1901. to_alsa_device(device, &alsa_device, &alsa_stream);
  1902. if (card > 0 || alsa_device > 0)
  1903. return(alsa_mus_error(MUS_AUDIO_CANT_READ, NULL));
  1904. if ((alsa_stream == SND_PCM_STREAM_CAPTURE) &&
  1905. (alsa_capture_device_name) &&
  1906. (strcmp(alsa_capture_device_name, "default") == 0))
  1907. {
  1908. if (info)
  1909. info[0] = 2;
  1910. else return(2);
  1911. }
  1912. {
  1913. unsigned int max_channels = 0;
  1914. snd_pcm_hw_params_get_channels_max(alsa_hw_params[alsa_stream], &max_channels);
  1915. if ((alsa_stream == SND_PCM_STREAM_CAPTURE) &&
  1916. (max_channels > (unsigned int)alsa_max_capture_channels))
  1917. {
  1918. /* limit number of capture channels to a reasonable maximum, if the user
  1919. specifies a plug pcm as the capture pcm then the returned number of channels
  1920. would be MAXINT (or whatever the name is for a really big number). At this
  1921. point there is no support in the alsa api to distinguish between default
  1922. parameters or those that have been set by a user on purpose, of for querying
  1923. the hardware pcm device that is hidden by the plug device to see what is the
  1924. real number of channels for the device we are dealing with. We could also try
  1925. to flag this as an error to the user and exit the program */
  1926. max_channels = alsa_max_capture_channels;
  1927. }
  1928. if (info)
  1929. {
  1930. unsigned int tmp = 0;
  1931. info[0] = max_channels;
  1932. snd_pcm_hw_params_get_channels_min(alsa_hw_params[alsa_stream], &tmp);
  1933. info[1] = tmp;
  1934. info[2] = max_channels;
  1935. }
  1936. return(max_channels);
  1937. }
  1938. }
  1939. static int alsa_sample_types(int ur_dev, int chan, mus_sample_t *val)
  1940. {
  1941. int card;
  1942. int device;
  1943. int alsa_device = 0;
  1944. snd_pcm_stream_t alsa_stream = SND_PCM_STREAM_PLAYBACK;
  1945. if ((!audio_initialized) &&
  1946. (mus_audio_initialize() != MUS_NO_ERROR))
  1947. return(MUS_ERROR);
  1948. card = MUS_AUDIO_SYSTEM(ur_dev);
  1949. device = MUS_AUDIO_DEVICE(ur_dev);
  1950. to_alsa_device(device, &alsa_device, &alsa_stream);
  1951. if (card > 0 || alsa_device > 0)
  1952. return(alsa_mus_error(MUS_AUDIO_CANT_READ, NULL));
  1953. {
  1954. int f, format;
  1955. snd_pcm_format_mask_t *mask;
  1956. snd_pcm_format_mask_alloca(&mask);
  1957. snd_pcm_hw_params_get_format_mask(alsa_hw_params[alsa_stream], mask);
  1958. for (format = 0, f = 1; format < SND_PCM_FORMAT_LAST; format++)
  1959. {
  1960. int err;
  1961. err = snd_pcm_format_mask_test(mask, (snd_pcm_format_t)format);
  1962. if (err > 0)
  1963. {
  1964. if ((f < chan) &&
  1965. (to_mus_sample_type(format) != MUS_UNKNOWN_SAMPLE))
  1966. val[f++] = to_mus_sample_type(format);
  1967. }
  1968. }
  1969. val[0] = (mus_sample_t)(f - 1);
  1970. }
  1971. return(MUS_NO_ERROR);
  1972. }
  1973. #endif /* HAVE_ALSA */
  1974. /* -------------------------------- SUN -------------------------------- */
  1975. /*
  1976. * Thanks to Seppo Ingalsuo for several bugfixes.
  1977. * record case improved after perusal of Snack 1.6/src/jkAudio_sun.c
  1978. */
  1979. /* apparently input other than 8000 is 16-bit, 8000 is (?) mulaw */
  1980. #if (defined(__sun) || defined(__SVR4)) && (!(defined(AUDIO_OK)))
  1981. #define AUDIO_OK 1
  1982. #include <sys/types.h>
  1983. #ifdef SUNOS
  1984. #include <stropts.h>
  1985. #endif
  1986. #include <sys/filio.h>
  1987. #ifdef SUNOS
  1988. #include <sun/audioio.h>
  1989. #else
  1990. #include <sys/audioio.h>
  1991. #endif
  1992. #include <sys/mixer.h>
  1993. int mus_audio_initialize(void) {return(MUS_NO_ERROR);}
  1994. #define DAC_NAME "/dev/audio"
  1995. #define AUDIODEV_ENV "AUDIODEV"
  1996. #define return_error_exit(Error_Type, Audio_Line, Ur_Error_Message) \
  1997. do { char *Error_Message; Error_Message = Ur_Error_Message; \
  1998. if (Audio_Line != -1) close(Audio_Line); \
  1999. if (Error_Message) \
  2000. {mus_standard_error(Error_Type, Error_Message); free(Error_Message);} \
  2001. else mus_standard_error(Error_Type, mus_error_type_to_string(Error_Type)); \
  2002. return(MUS_ERROR); \
  2003. } while (false)
  2004. char *mus_audio_moniker(void)
  2005. {
  2006. #ifndef AUDIO_DEV_AMD
  2007. struct audio_device ad;
  2008. #else
  2009. int ad;
  2010. #endif
  2011. int audio_fd, err;
  2012. char *dev_name;
  2013. if (getenv(AUDIODEV_ENV) != NULL)
  2014. dev_name = getenv(AUDIODEV_ENV);
  2015. else dev_name = (char *)DAC_NAME;
  2016. audio_fd = open(dev_name, O_RDONLY | O_NONBLOCK, 0);
  2017. if (audio_fd == -1)
  2018. {
  2019. audio_fd = open("/dev/audioctl", O_RDONLY | O_NONBLOCK, 0);
  2020. if (audio_fd == -1) return("sun probably");
  2021. }
  2022. err = ioctl(audio_fd, AUDIO_GETDEV, &ad);
  2023. if (err == -1)
  2024. {
  2025. close(audio_fd);
  2026. return("sun?");
  2027. }
  2028. mus_audio_close(audio_fd);
  2029. if (version_name == NULL) version_name = (char *)calloc(PRINT_BUFFER_SIZE, sizeof(char));
  2030. #ifndef AUDIO_DEV_AMD
  2031. snprintf(version_name, LABEL_BUFFER_SIZE, "audio: %s (%s)", ad.name, ad.version);
  2032. #else
  2033. switch (ad)
  2034. {
  2035. case AUDIO_DEV_AMD: snprintf(version_name, LABEL_BUFFER_SIZE, "audio: amd"); break;
  2036. #ifdef AUDIO_DEV_CS4231
  2037. case AUDIO_DEV_CS4231: snprintf(version_name, LABEL_BUFFER_SIZE, "audio: cs4231"); break;
  2038. #endif
  2039. case AUDIO_DEV_SPEAKERBOX: snprintf(version_name, LABEL_BUFFER_SIZE, "audio: speakerbox"); break;
  2040. case AUDIO_DEV_CODEC: snprintf(version_name, LABEL_BUFFER_SIZE, "audio: codec"); break;
  2041. default: snprintf(version_name, LABEL_BUFFER_SIZE, "audio: unknown"); break;
  2042. }
  2043. #endif
  2044. return(version_name);
  2045. }
  2046. static int to_sun_sample_type(mus_sample_t samp_type)
  2047. {
  2048. switch (samp_type)
  2049. {
  2050. #if MUS_LITTLE_ENDIAN
  2051. case MUS_LSHORT: /* Solaris on Intel? */
  2052. #else
  2053. case MUS_BSHORT:
  2054. #endif
  2055. return(AUDIO_ENCODING_LINEAR);
  2056. break;
  2057. case MUS_BYTE:
  2058. #if defined(AUDIO_ENCODING_LINEAR8)
  2059. return(AUDIO_ENCODING_LINEAR8); break;
  2060. #else
  2061. return(AUDIO_ENCODING_LINEAR);
  2062. break;
  2063. #endif
  2064. case MUS_MULAW: return(AUDIO_ENCODING_ULAW); break;
  2065. case MUS_ALAW: return(AUDIO_ENCODING_ALAW); break;
  2066. /* there's also AUDIO_ENCODING_DVI */
  2067. default: break;
  2068. }
  2069. return(MUS_ERROR);
  2070. }
  2071. int mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
  2072. {
  2073. struct audio_info info;
  2074. char *dev_name;
  2075. int encode, bits, dev;
  2076. int audio_fd, err;
  2077. dev = MUS_AUDIO_DEVICE(ur_dev);
  2078. encode = to_sun_sample_type(samp_type);
  2079. if (encode == MUS_ERROR)
  2080. return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, -1,
  2081. mus_format("sample type %d (%s) not available",
  2082. samp_type,
  2083. mus_sample_type_name(samp_type)));
  2084. if (getenv(AUDIODEV_ENV) != NULL)
  2085. dev_name = getenv(AUDIODEV_ENV);
  2086. else dev_name = (char *)DAC_NAME;
  2087. if (dev != MUS_AUDIO_DUPLEX_DEFAULT)
  2088. audio_fd = open(dev_name, O_WRONLY, 0);
  2089. else audio_fd = open(dev_name, O_RDWR, 0);
  2090. if (audio_fd == -1)
  2091. return_error_exit(MUS_AUDIO_CANT_OPEN, -1,
  2092. mus_format("can't open output %s: %s",
  2093. dev_name, strerror(errno)));
  2094. AUDIO_INITINFO(&info);
  2095. if (dev == MUS_AUDIO_LINE_OUT)
  2096. info.play.port = AUDIO_LINE_OUT;
  2097. else
  2098. {
  2099. if (dev == MUS_AUDIO_SPEAKERS)
  2100. /* OR may not be available */
  2101. info.play.port = AUDIO_SPEAKER | AUDIO_HEADPHONE;
  2102. else
  2103. info.play.port = AUDIO_SPEAKER;
  2104. }
  2105. info.play.sample_rate = srate;
  2106. info.play.channels = chans;
  2107. bits = 8 * mus_bytes_per_sample(samp_type);
  2108. info.play.precision = bits;
  2109. info.play.encoding = encode;
  2110. err = ioctl(audio_fd, AUDIO_SETINFO, &info);
  2111. if (err == -1)
  2112. {
  2113. ioctl(audio_fd, AUDIO_GETINFO, &info);
  2114. if ((int)info.play.channels != chans)
  2115. return_error_exit(MUS_AUDIO_CHANNELS_NOT_AVAILABLE, audio_fd,
  2116. mus_format("can't set output %s channels to %d",
  2117. dev_name, chans));
  2118. if (((int)info.play.precision != bits) ||
  2119. ((int)info.play.encoding != encode))
  2120. return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, audio_fd,
  2121. mus_format("can't set output %s sample type to %d bits, %d encode (%s)",
  2122. dev_name,
  2123. bits, encode,
  2124. mus_sample_type_name(samp_type)));
  2125. if ((int)info.play.sample_rate != srate)
  2126. return_error_exit(MUS_AUDIO_CHANNELS_NOT_AVAILABLE, audio_fd,
  2127. mus_format("can't set output %s srate to %d",
  2128. dev_name, srate));
  2129. }
  2130. /* man audio sez the play.buffer_size field is not currently supported */
  2131. /* but since the default buffer size is 8180! we need ioctl(audio_fd, I_SETSIG, ...) */
  2132. #ifdef SUNOS
  2133. ioctl(audio_fd, I_FLUSH, FLUSHR);
  2134. #endif
  2135. return(audio_fd);
  2136. }
  2137. int mus_audio_write(int line, char *buf, int bytes)
  2138. {
  2139. if (write(line, buf, bytes) != bytes)
  2140. return_error_exit(MUS_AUDIO_WRITE_ERROR, -1,
  2141. mus_format("write error: %s", strerror(errno)));
  2142. return(MUS_NO_ERROR);
  2143. }
  2144. int mus_audio_close(int line)
  2145. {
  2146. write(line, (char *)NULL, 0);
  2147. close(line);
  2148. return(MUS_NO_ERROR);
  2149. }
  2150. int mus_audio_read(int line, char *buf, int bytes)
  2151. {
  2152. int total = 0;
  2153. char *curbuf;
  2154. /* ioctl(line, AUDIO_DRAIN, NULL) */
  2155. /* this seems to return 8-12 bytes fewer than requested -- perverse! */
  2156. /* should I buffer data internally? */
  2157. /* apparently we need to loop here ... */
  2158. curbuf = buf;
  2159. while (total < bytes)
  2160. {
  2161. int bytes_available;
  2162. ioctl(line, FIONREAD, &bytes_available);
  2163. if (bytes_available > 0)
  2164. {
  2165. int bytes_read;
  2166. if ((total + bytes_available) > bytes) bytes_available = bytes - total;
  2167. bytes_read = read(line, curbuf, bytes_available);
  2168. if (bytes_read > 0)
  2169. {
  2170. total += bytes_read;
  2171. curbuf = (char *)(buf + total);
  2172. }
  2173. /* else return anyway?? */
  2174. }
  2175. }
  2176. return(MUS_NO_ERROR);
  2177. }
  2178. int mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
  2179. {
  2180. struct audio_info info;
  2181. int indev, encode, bits, dev, audio_fd, err;
  2182. char *dev_name;
  2183. dev = MUS_AUDIO_DEVICE(ur_dev);
  2184. encode = to_sun_sample_type(samp_type);
  2185. bits = 8 * mus_bytes_per_sample(samp_type);
  2186. if (encode == -1)
  2187. return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, -1,
  2188. mus_format("sample type %d bits, %d encode (%s) not available",
  2189. bits, encode,
  2190. mus_sample_type_name(samp_type)));
  2191. if (getenv(AUDIODEV_ENV) != NULL)
  2192. dev_name = getenv(AUDIODEV_ENV);
  2193. else dev_name = (char *)DAC_NAME;
  2194. if (dev != MUS_AUDIO_DUPLEX_DEFAULT)
  2195. audio_fd = open(dev_name, O_RDONLY, 0);
  2196. else audio_fd = open(dev_name, O_RDWR, 0);
  2197. if (audio_fd == -1)
  2198. return_error_exit(MUS_AUDIO_CANT_OPEN, -1,
  2199. mus_format("can't open input %s: %s",
  2200. dev_name, strerror(errno)));
  2201. AUDIO_INITINFO(&info);
  2202. /* ioctl(audio_fd, AUDIO_GETINFO, &info); */
  2203. info.record.sample_rate = srate;
  2204. info.record.channels = chans;
  2205. err = ioctl(audio_fd, AUDIO_SETINFO, &info);
  2206. if (err == -1)
  2207. return_error_exit(MUS_AUDIO_CANT_OPEN, audio_fd,
  2208. mus_format("can't set srate %d and chans %d for input %s",
  2209. srate, chans,
  2210. dev_name));
  2211. ioctl(audio_fd, AUDIO_GETINFO, &info);
  2212. if (info.record.sample_rate != (unsigned int)srate)
  2213. mus_print("%s[%d]: sampling rate: %d != %d\n",
  2214. __FILE__, __LINE__,
  2215. info.record.sample_rate, srate);
  2216. if (info.record.channels != (unsigned int)chans)
  2217. mus_print("%s[%d]: channels: %d != %d\n",
  2218. __FILE__, __LINE__,
  2219. info.record.channels, chans);
  2220. info.record.precision = bits; /* was play, changed 10-Jul-03 thanks to Jürgen Keil */
  2221. info.record.encoding = encode;
  2222. err = ioctl(audio_fd, AUDIO_SETINFO, &info);
  2223. if (err == -1)
  2224. return_error_exit(MUS_AUDIO_CANT_OPEN, audio_fd,
  2225. mus_format("can't set bits %d, encode %d (sample type %s) for input %s",
  2226. bits, encode, mus_sample_type_name(samp_type),
  2227. dev_name));
  2228. ioctl(audio_fd, AUDIO_GETINFO, &info);
  2229. /* these cannot be OR'd */
  2230. if (dev == MUS_AUDIO_LINE_IN)
  2231. indev = AUDIO_LINE_IN;
  2232. else indev = AUDIO_MICROPHONE;
  2233. info.record.port = indev;
  2234. err = ioctl(audio_fd, AUDIO_SETINFO, &info);
  2235. if (err == -1)
  2236. return_error_exit(MUS_AUDIO_CANT_WRITE, audio_fd,
  2237. mus_format("can't set record.port to %d for %s",
  2238. indev, dev_name));
  2239. err = ioctl(audio_fd, AUDIO_GETINFO, &info);
  2240. if (err == -1)
  2241. return_error_exit(MUS_AUDIO_CANT_READ, audio_fd,
  2242. mus_format("can't getinfo on input %s (line: %d)",
  2243. dev_name,
  2244. audio_fd));
  2245. else
  2246. {
  2247. if ((int)info.record.port != indev)
  2248. return_error_exit(MUS_AUDIO_DEVICE_NOT_AVAILABLE, audio_fd,
  2249. mus_format("confusion in record.port: %d != %d (%s)",
  2250. (int)info.record.port, indev,
  2251. dev_name));
  2252. if ((int)info.record.channels != chans)
  2253. return_error_exit(MUS_AUDIO_CHANNELS_NOT_AVAILABLE, audio_fd,
  2254. mus_format("confusion in record.channels: %d != %d (%s)",
  2255. (int)info.record.channels, chans,
  2256. dev_name));
  2257. if (((int)info.record.precision != bits) ||
  2258. ((int)info.record.encoding != encode))
  2259. return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, audio_fd,
  2260. mus_format("confusion in record.precision|encoding: %d != %d or %d != %d (%s)",
  2261. (int)info.record.precision, bits,
  2262. (int)info.record.encoding, encode,
  2263. dev_name));
  2264. }
  2265. /* this may be a bad idea */
  2266. info.record.buffer_size = size;
  2267. err = ioctl(audio_fd, AUDIO_SETINFO, &info);
  2268. if (err == -1)
  2269. return_error_exit(MUS_AUDIO_CANT_WRITE, audio_fd,
  2270. mus_format("can't set buffer size to %d on input %s",
  2271. size,
  2272. dev_name));
  2273. return(audio_fd);
  2274. }
  2275. #if 0
  2276. /* pause can be implemented with play.pause and record.pause */
  2277. static const char *sun_sample_type_name(mus_sample_t samp_type)
  2278. {
  2279. switch (samp_type)
  2280. {
  2281. #ifdef AUDIO_ENCODING_ALAW
  2282. case AUDIO_ENCODING_ALAW: return("alaw"); break;
  2283. #endif
  2284. #ifdef AUDIO_ENCODING_ULAW
  2285. case AUDIO_ENCODING_ULAW: return("ulaw"); break;
  2286. #endif
  2287. #ifdef AUDIO_ENCODING_DVI
  2288. case AUDIO_ENCODING_DVI: return("dvi adpcm"); break;
  2289. #endif
  2290. #ifdef AUDIO_ENCODING_LINEAR8
  2291. case AUDIO_ENCODING_LINEAR8: return("linear"); break;
  2292. #else
  2293. #ifdef AUDIO_ENCODING_PCM8
  2294. case AUDIO_ENCODING_PCM8: return("linear"); break;
  2295. #endif
  2296. #endif
  2297. #ifdef AUDIO_ENCODING_LINEAR
  2298. case AUDIO_ENCODING_LINEAR: return("linear"); break;
  2299. #else
  2300. #ifdef AUDIO_ENCODING_PCM16
  2301. case AUDIO_ENCODING_PCM16: return("linear"); break;
  2302. #endif
  2303. #endif
  2304. #ifdef AUDIO_ENCODING_NONE
  2305. case AUDIO_ENCODING_NONE: return("not audio"); break; /* dbri interface configured for something else */
  2306. #endif
  2307. }
  2308. return("unknown");
  2309. }
  2310. static const char *sun_in_device_name(int dev)
  2311. {
  2312. if (dev == AUDIO_MICROPHONE) return("microphone");
  2313. if (dev == AUDIO_LINE_IN) return("line in");
  2314. if (dev == AUDIO_INTERNAL_CD_IN) return("cd");
  2315. if (dev == (AUDIO_MICROPHONE | AUDIO_LINE_IN)) return("microphone + line in");
  2316. if (dev == (AUDIO_MICROPHONE | AUDIO_LINE_IN | AUDIO_INTERNAL_CD_IN)) return("microphone + line in + cd");
  2317. if (dev == (AUDIO_MICROPHONE | AUDIO_INTERNAL_CD_IN)) return("microphone + cd");
  2318. if (dev == (AUDIO_LINE_IN | AUDIO_INTERNAL_CD_IN)) return("line in + cd");
  2319. return("unknown");
  2320. }
  2321. static const char *sun_out_device_name(int dev)
  2322. {
  2323. if (dev == AUDIO_SPEAKER) return("speakers");
  2324. if (dev == AUDIO_LINE_OUT) return("line out");
  2325. if (dev == AUDIO_HEADPHONE) return("headphones");
  2326. if (dev == (AUDIO_SPEAKER | AUDIO_LINE_OUT)) return("speakers + line out");
  2327. if (dev == (AUDIO_SPEAKER | AUDIO_LINE_OUT | AUDIO_HEADPHONE)) return("speakers + line out + headphones");
  2328. if (dev == (AUDIO_SPEAKER | AUDIO_HEADPHONE)) return("speakers + headphones");
  2329. if (dev == (AUDIO_LINE_OUT | AUDIO_HEADPHONE)) return("line out + headphones");
  2330. return("unknown");
  2331. }
  2332. static char *sun_vol_name = NULL;
  2333. static char *sun_volume_name(float vol, int balance, int chans)
  2334. {
  2335. if (sun_vol_name == NULL) sun_vol_name = (char *)calloc(LABEL_BUFFER_SIZE, sizeof(char));
  2336. if (chans != 2)
  2337. snprintf(sun_vol_name, LABEL_BUFFER_SIZE, "%.3f", vol);
  2338. else
  2339. {
  2340. snprintf(sun_vol_name, LABEL_BUFFER_SIZE, "%.3f %.3f",
  2341. vol * (float)(AUDIO_RIGHT_BALANCE - balance) / (float)AUDIO_RIGHT_BALANCE,
  2342. vol * (float)balance / (float)AUDIO_RIGHT_BALANCE);
  2343. }
  2344. return(sun_vol_name);
  2345. }
  2346. #endif
  2347. #endif
  2348. /* ------------------------------- WINDOZE ----------------------------------------- */
  2349. #if defined(_MSC_VER) && (!(defined(__CYGWIN__)))
  2350. #define AUDIO_OK 1
  2351. #include <windows.h>
  2352. #include <mmsystem.h>
  2353. #define BUFFER_FILLED 1
  2354. #define BUFFER_EMPTY 2
  2355. #define OUTPUT_LINE 1
  2356. #define INPUT_LINE 2
  2357. #define SOUND_UNREADY 0
  2358. #define SOUND_INITIALIZED 1
  2359. #define SOUND_RUNNING 2
  2360. static int buffer_size = 1024;
  2361. static int db_state[2];
  2362. static int sound_state = 0;
  2363. static int current_chans = 1;
  2364. static int current_datum_size = 2;
  2365. static int current_buf = 0;
  2366. WAVEHDR wh[2];
  2367. HWAVEOUT fd;
  2368. HWAVEIN record_fd;
  2369. WAVEHDR rec_wh;
  2370. static int rec_state = SOUND_UNREADY;
  2371. static MMRESULT win_in_err = 0, win_out_err = 0;
  2372. static char errstr[128], getstr[128];
  2373. static char *win_err_buf = NULL;
  2374. static mus_print_handler_t *old_handler;
  2375. static void win_mus_print(char *msg)
  2376. {
  2377. if ((win_in_err == 0) && (win_out_err == 0))
  2378. (*old_handler)(msg);
  2379. else
  2380. {
  2381. if (win_in_err)
  2382. waveInGetErrorText(win_in_err, getstr, PRINT_BUFFER_SIZE);
  2383. else waveOutGetErrorText(win_out_err, getstr, PRINT_BUFFER_SIZE);
  2384. snprintf(errstr, PRINT_BUFFER_SIZE, "%s [%s]", msg, getstr);
  2385. (*old_handler)(errstr);
  2386. }
  2387. }
  2388. static void start_win_print(void)
  2389. {
  2390. if (old_handler != win_mus_print)
  2391. old_handler = mus_print_set_handler(win_mus_print);
  2392. }
  2393. static void end_win_print(void)
  2394. {
  2395. if (old_handler == win_mus_print)
  2396. mus_print_set_handler(NULL);
  2397. else mus_print_set_handler(old_handler);
  2398. }
  2399. #define return_error_exit(Error_Type, Ur_Error_Message) \
  2400. do { char *Error_Message; Error_Message = Ur_Error_Message; \
  2401. if (Error_Message) \
  2402. {mus_standard_error(Error_Type, Error_Message); free(Error_Message);} \
  2403. else mus_standard_error(Error_Type, mus_error_type_to_string(Error_Type)); \
  2404. end_win_print(); \
  2405. return(MUS_ERROR); \
  2406. } while (false)
  2407. DWORD CALLBACK next_buffer(HWAVEOUT w, UINT msg, DWORD user_data, DWORD p1, DWORD p2)
  2408. {
  2409. if (msg == WOM_DONE)
  2410. {
  2411. db_state[current_buf] = BUFFER_EMPTY;
  2412. }
  2413. return(0);
  2414. }
  2415. int mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
  2416. {
  2417. WAVEFORMATEX wf;
  2418. int dev;
  2419. start_win_print();
  2420. dev = MUS_AUDIO_DEVICE(ur_dev);
  2421. wf.nChannels = chans;
  2422. current_chans = chans;
  2423. wf.wFormatTag = WAVE_FORMAT_PCM;
  2424. wf.cbSize = 0;
  2425. if (samp_type == MUS_UBYTE)
  2426. {
  2427. wf.wBitsPerSample = 8;
  2428. current_datum_size = 1;
  2429. }
  2430. else
  2431. {
  2432. wf.wBitsPerSample = 16;
  2433. current_datum_size = 2;
  2434. }
  2435. wf.nSamplesPerSec = srate;
  2436. wf.nBlockAlign = chans * current_datum_size;
  2437. wf.nAvgBytesPerSec = wf.nBlockAlign * wf.nSamplesPerSec;
  2438. #if _MSC_VER
  2439. win_out_err = waveOutOpen(&fd, WAVE_MAPPER, &wf, (DWORD (*)(HWAVEOUT,UINT,DWORD,DWORD,DWORD))next_buffer, 0, CALLBACK_FUNCTION);
  2440. #else
  2441. win_out_err = waveOutOpen(&fd, WAVE_MAPPER, &wf, (DWORD)next_buffer, 0, CALLBACK_FUNCTION);
  2442. #endif
  2443. /* 0 here = user_data above, other case = WAVE_FORMAT_QUERY */
  2444. if (win_out_err)
  2445. return_error_exit(MUS_AUDIO_DEVICE_NOT_AVAILABLE,
  2446. mus_format("can't open %d", dev));
  2447. waveOutPause(fd);
  2448. if (size <= 0)
  2449. buffer_size = 1024;
  2450. else buffer_size = size;
  2451. wh[0].dwBufferLength = buffer_size * current_datum_size;
  2452. wh[0].dwFlags = 0;
  2453. wh[0].dwLoops = 0;
  2454. wh[0].lpData = (char *)calloc(wh[0].dwBufferLength, sizeof(char));
  2455. if ((wh[0].lpData) == 0)
  2456. {
  2457. waveOutClose(fd);
  2458. return_error_exit(MUS_AUDIO_SIZE_NOT_AVAILABLE,
  2459. mus_format("can't allocate buffer size %d for output %d", buffer_size, dev));
  2460. }
  2461. win_out_err = waveOutPrepareHeader(fd, &(wh[0]), sizeof(WAVEHDR));
  2462. if (win_out_err)
  2463. {
  2464. free(wh[0].lpData);
  2465. waveOutClose(fd);
  2466. return_error_exit(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE,
  2467. mus_format("can't setup output 'header' for %d", dev));
  2468. }
  2469. db_state[0] = BUFFER_EMPTY;
  2470. wh[1].dwBufferLength = buffer_size * current_datum_size;
  2471. wh[1].dwFlags = 0;
  2472. wh[1].dwLoops = 0;
  2473. wh[1].lpData = (char *)calloc(wh[0].dwBufferLength, sizeof(char));
  2474. if ((wh[1].lpData) == 0)
  2475. {
  2476. free(wh[0].lpData);
  2477. waveOutClose(fd);
  2478. return_error_exit(MUS_AUDIO_SIZE_NOT_AVAILABLE,
  2479. mus_format("can't allocate buffer size %d for output %d", buffer_size, dev));
  2480. }
  2481. win_out_err = waveOutPrepareHeader(fd, &(wh[1]), sizeof(WAVEHDR));
  2482. if (win_out_err)
  2483. {
  2484. waveOutUnprepareHeader(fd, &(wh[0]), sizeof(WAVEHDR));
  2485. free(wh[0].lpData);
  2486. free(wh[1].lpData);
  2487. waveOutClose(fd);
  2488. return_error_exit(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE,
  2489. mus_format("can't setup output 'header' for %d", dev));
  2490. }
  2491. db_state[1] = BUFFER_EMPTY;
  2492. sound_state = SOUND_INITIALIZED;
  2493. current_buf = 0;
  2494. end_win_print();
  2495. return(OUTPUT_LINE);
  2496. }
  2497. static MMRESULT fill_buffer(int dbi, char *inbuf, int instart, int bytes)
  2498. {
  2499. int i, j;
  2500. win_out_err = 0;
  2501. if (sound_state == SOUND_UNREADY) return(0);
  2502. for (i = instart, j = 0; j < bytes; j++, i++)
  2503. wh[dbi].lpData[j] = inbuf[i];
  2504. wh[dbi].dwBufferLength = bytes;
  2505. db_state[dbi] = BUFFER_FILLED;
  2506. if ((sound_state == SOUND_INITIALIZED) &&
  2507. (dbi == 1))
  2508. {
  2509. sound_state = SOUND_RUNNING;
  2510. win_out_err = waveOutRestart(fd);
  2511. }
  2512. return(win_out_err);
  2513. }
  2514. static void wait_for_empty_buffer(int buf)
  2515. {
  2516. while (db_state[buf] != BUFFER_EMPTY)
  2517. {
  2518. Sleep(1); /* in millisecs, so even this may be too much if buf = 256 bytes */
  2519. }
  2520. }
  2521. int mus_audio_write(int line, char *buf, int bytes)
  2522. {
  2523. int leftover, start;
  2524. start_win_print();
  2525. if (line != OUTPUT_LINE)
  2526. return_error_exit(MUS_AUDIO_CANT_WRITE,
  2527. mus_format("write error: line %d != %d?",
  2528. line, OUTPUT_LINE));
  2529. win_out_err = 0;
  2530. leftover = bytes;
  2531. start = 0;
  2532. if (sound_state == SOUND_UNREADY)
  2533. {
  2534. end_win_print();
  2535. return(MUS_NO_ERROR);
  2536. }
  2537. while (leftover > 0)
  2538. {
  2539. int lim;
  2540. lim = leftover;
  2541. if (lim > buffer_size) lim = buffer_size;
  2542. leftover -= lim;
  2543. wait_for_empty_buffer(current_buf);
  2544. win_out_err = fill_buffer(current_buf, buf, start, lim);
  2545. if (win_out_err)
  2546. return_error_exit(MUS_AUDIO_CANT_WRITE,
  2547. mus_format("write error on %d",
  2548. line));
  2549. win_out_err = waveOutWrite(fd, &wh[current_buf], sizeof(WAVEHDR));
  2550. if (win_out_err)
  2551. return_error_exit(MUS_AUDIO_CANT_WRITE,
  2552. mus_format("write error on %d",
  2553. line));
  2554. start += lim;
  2555. current_buf++;
  2556. if (current_buf > 1) current_buf = 0;
  2557. }
  2558. return(MUS_NO_ERROR);
  2559. }
  2560. static float unlog(unsigned short val)
  2561. {
  2562. /* 1.0 linear is 0xffff, rest is said to be "logarithmic", whatever that really means here */
  2563. if (val == 0) return(0.0);
  2564. return((float)val / 65536.0);
  2565. /* return(pow(2.0, amp) - 1.0); */ /* doc seems to be bogus */
  2566. }
  2567. static char *mixer_status_name(int status)
  2568. {
  2569. switch (status)
  2570. {
  2571. case MIXERLINE_LINEF_ACTIVE: return(", (active)"); break;
  2572. case MIXERLINE_LINEF_DISCONNECTED: return(", (disconnected)"); break;
  2573. case MIXERLINE_LINEF_SOURCE: return(", (source)"); break;
  2574. default: return(""); break;
  2575. }
  2576. }
  2577. static char *mixer_target_name(int type)
  2578. {
  2579. switch (type)
  2580. {
  2581. case MIXERLINE_TARGETTYPE_UNDEFINED: return("undefined"); break;
  2582. case MIXERLINE_TARGETTYPE_WAVEOUT: return("output"); break;
  2583. case MIXERLINE_TARGETTYPE_WAVEIN: return("input"); break;
  2584. case MIXERLINE_TARGETTYPE_MIDIOUT: return("midi output"); break;
  2585. case MIXERLINE_TARGETTYPE_MIDIIN: return("midi input"); break;
  2586. case MIXERLINE_TARGETTYPE_AUX: return("aux"); break;
  2587. default: return(""); break;
  2588. }
  2589. }
  2590. static char *mixer_component_name(int type)
  2591. {
  2592. switch (type)
  2593. {
  2594. case MIXERLINE_COMPONENTTYPE_DST_UNDEFINED: return("undefined"); break;
  2595. case MIXERLINE_COMPONENTTYPE_DST_DIGITAL: return("digital"); break;
  2596. case MIXERLINE_COMPONENTTYPE_DST_LINE: return("line"); break;
  2597. case MIXERLINE_COMPONENTTYPE_DST_MONITOR: return("monitor"); break;
  2598. case MIXERLINE_COMPONENTTYPE_DST_SPEAKERS: return("speakers"); break;
  2599. case MIXERLINE_COMPONENTTYPE_DST_HEADPHONES: return("headphones"); break;
  2600. case MIXERLINE_COMPONENTTYPE_DST_TELEPHONE: return("telephone"); break;
  2601. case MIXERLINE_COMPONENTTYPE_DST_WAVEIN: return("wave in"); break;
  2602. case MIXERLINE_COMPONENTTYPE_DST_VOICEIN: return("voice in"); break;
  2603. case MIXERLINE_COMPONENTTYPE_SRC_UNDEFINED: return("undefined"); break;
  2604. case MIXERLINE_COMPONENTTYPE_SRC_DIGITAL: return("digital"); break;
  2605. case MIXERLINE_COMPONENTTYPE_SRC_LINE: return("line"); break;
  2606. case MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE: return("mic"); break;
  2607. case MIXERLINE_COMPONENTTYPE_SRC_SYNTHESIZER: return("synth"); break;
  2608. case MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC: return("CD"); break;
  2609. case MIXERLINE_COMPONENTTYPE_SRC_TELEPHONE: return("telephone"); break;
  2610. case MIXERLINE_COMPONENTTYPE_SRC_PCSPEAKER: return("speaker"); break;
  2611. case MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT: return("wave out"); break;
  2612. case MIXERLINE_COMPONENTTYPE_SRC_AUXILIARY: return("aux"); break;
  2613. case MIXERLINE_COMPONENTTYPE_SRC_ANALOG: return("analog"); break;
  2614. default: return(""); break;
  2615. }
  2616. }
  2617. char *mus_audio_moniker(void) {return("MS audio");} /* version number of some sort? */
  2618. int mus_audio_initialize(void)
  2619. {
  2620. return(MUS_NO_ERROR);
  2621. }
  2622. int mus_audio_close(int line)
  2623. {
  2624. win_out_err = 0;
  2625. win_in_err = 0;
  2626. if (line == OUTPUT_LINE)
  2627. {
  2628. /* fill with a few zeros, wait for empty flag */
  2629. if (sound_state != SOUND_UNREADY)
  2630. {
  2631. int i;
  2632. wait_for_empty_buffer(current_buf);
  2633. for (i = 0; i < 128; i++) wh[current_buf].lpData[i] = 0;
  2634. wait_for_empty_buffer(current_buf);
  2635. win_out_err = waveOutClose(fd);
  2636. i = 0;
  2637. while (win_out_err == WAVERR_STILLPLAYING)
  2638. {
  2639. Sleep(1);
  2640. win_out_err = waveOutClose(fd);
  2641. i++;
  2642. if (i > 1024) break;
  2643. }
  2644. db_state[0] = BUFFER_EMPTY;
  2645. db_state[1] = BUFFER_EMPTY;
  2646. sound_state = SOUND_UNREADY;
  2647. waveOutUnprepareHeader(fd, &(wh[0]), sizeof(WAVEHDR));
  2648. waveOutUnprepareHeader(fd, &(wh[1]), sizeof(WAVEHDR));
  2649. free(wh[0].lpData);
  2650. free(wh[1].lpData);
  2651. if (win_out_err)
  2652. return_error_exit(MUS_AUDIO_CANT_CLOSE,
  2653. mus_format("close failed on %d",
  2654. line));
  2655. }
  2656. }
  2657. else
  2658. {
  2659. if (line == INPUT_LINE)
  2660. {
  2661. if (rec_state != SOUND_UNREADY)
  2662. {
  2663. waveInReset(record_fd);
  2664. waveInClose(record_fd);
  2665. waveInUnprepareHeader(record_fd, &rec_wh, sizeof(WAVEHDR));
  2666. if (rec_wh.lpData)
  2667. {
  2668. free(rec_wh.lpData);
  2669. rec_wh.lpData = NULL;
  2670. }
  2671. rec_state = SOUND_UNREADY;
  2672. }
  2673. }
  2674. else
  2675. return_error_exit(MUS_AUDIO_CANT_CLOSE,
  2676. mus_format("can't close unrecognized line %d",
  2677. line));
  2678. }
  2679. return(MUS_NO_ERROR);
  2680. }
  2681. /*
  2682. * waveInAddBuffer sends buffer to get data
  2683. * MM_WIM_DATA lParam->WAVEHDR dwBytesRecorded =>how much data actually in buffer
  2684. */
  2685. static int current_record_chans = 0, current_record_datum_size = 0;
  2686. DWORD CALLBACK next_input_buffer(HWAVEIN w, UINT msg, DWORD user_data, DWORD p1, DWORD p2)
  2687. {
  2688. if (msg == WIM_DATA)
  2689. {
  2690. /* grab data */
  2691. /* p1->dwBytesRecorded */
  2692. }
  2693. return(0);
  2694. }
  2695. int mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
  2696. {
  2697. WAVEFORMATEX wf;
  2698. int dev;
  2699. win_in_err = 0;
  2700. dev = MUS_AUDIO_DEVICE(ur_dev);
  2701. wf.nChannels = chans;
  2702. current_record_chans = chans;
  2703. wf.wFormatTag = WAVE_FORMAT_PCM;
  2704. wf.cbSize = 0;
  2705. if (samp_type == MUS_UBYTE)
  2706. {
  2707. wf.wBitsPerSample = 8;
  2708. current_record_datum_size = 1;
  2709. }
  2710. else
  2711. {
  2712. wf.wBitsPerSample = 16;
  2713. current_record_datum_size = 2;
  2714. }
  2715. wf.nSamplesPerSec = srate;
  2716. wf.nBlockAlign = chans * current_datum_size;
  2717. wf.nAvgBytesPerSec = wf.nBlockAlign * wf.nSamplesPerSec;
  2718. rec_wh.dwBufferLength = size * current_record_datum_size;
  2719. rec_wh.dwFlags = 0;
  2720. rec_wh.dwLoops = 0;
  2721. rec_wh.lpData = (char *)calloc(rec_wh.dwBufferLength, sizeof(char));
  2722. if ((rec_wh.lpData) == 0)
  2723. return_error_exit(MUS_AUDIO_SIZE_NOT_AVAILABLE,
  2724. mus_format("can't allocated %d bytes for input buffer of %d", size, dev));
  2725. #if _MSC_VER
  2726. win_in_err = waveInOpen(&record_fd, WAVE_MAPPER, &wf, (DWORD (*)(HWAVEIN,UINT,DWORD,DWORD,DWORD))next_input_buffer, 0, CALLBACK_FUNCTION);
  2727. /* why isn't the simple cast (DWORD) correct here as below? -- the docs say the 4th arg's type is DWORD */
  2728. #else
  2729. win_in_err = waveInOpen(&record_fd, WAVE_MAPPER, &wf, (DWORD)next_input_buffer, 0, CALLBACK_FUNCTION);
  2730. #endif
  2731. if (win_in_err)
  2732. {
  2733. free(rec_wh.lpData);
  2734. return_error_exit(MUS_AUDIO_DEVICE_NOT_AVAILABLE,
  2735. mus_format("can't open input device %d", dev));
  2736. }
  2737. win_in_err = waveInPrepareHeader(record_fd, &(rec_wh), sizeof(WAVEHDR));
  2738. if (win_in_err)
  2739. {
  2740. free(rec_wh.lpData);
  2741. waveInClose(record_fd);
  2742. return_error_exit(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE,
  2743. mus_format("can't prepare input 'header' for %d", dev));
  2744. }
  2745. return(MUS_NO_ERROR);
  2746. }
  2747. int mus_audio_read(int line, char *buf, int bytes)
  2748. {
  2749. win_in_err = 0;
  2750. return(MUS_ERROR);
  2751. }
  2752. #endif
  2753. /* ------------------------------- Mac OSX ----------------------------------------- */
  2754. /* this code based primarily on the CoreAudio headers and portaudio pa_mac_core.c,
  2755. * and to a much lesser extent, coreaudio.pdf and the HAL/Daisy examples.
  2756. */
  2757. #ifdef __APPLE__
  2758. #define AUDIO_OK 1
  2759. #include <AvailabilityMacros.h>
  2760. #define HAVE_AUDIODEVICEDESTROYIOPROCID (defined(MAC_OS_X_VERSION_10_5))
  2761. /*
  2762. #include <CoreServices/CoreServices.h>
  2763. #include <CoreAudio/CoreAudio.h>
  2764. */
  2765. /* ./System/Library/Frameworks/CoreAudio.framework/Headers/CoreAudio.h */
  2766. static const char* osx_error(OSStatus err)
  2767. {
  2768. if (err == noErr) return("no error");
  2769. switch (err)
  2770. {
  2771. case kAudioHardwareNoError: return("no error"); break;
  2772. case kAudioHardwareUnspecifiedError: return("unspecified audio hardware error"); break;
  2773. case kAudioHardwareNotRunningError: return("audio hardware not running"); break;
  2774. case kAudioHardwareUnknownPropertyError: return("unknown property"); break;
  2775. case kAudioHardwareBadPropertySizeError: return("bad property"); break;
  2776. case kAudioHardwareBadDeviceError: return("bad device"); break;
  2777. case kAudioHardwareBadStreamError: return("bad stream"); break;
  2778. case kAudioHardwareIllegalOperationError: return("illegal operation"); break;
  2779. case kAudioDeviceUnsupportedFormatError: return("unsupported sample type"); break;
  2780. case kAudioDevicePermissionsError: return("device permissions error"); break;
  2781. }
  2782. return("unknown error");
  2783. }
  2784. #define MAX_BUFS 4
  2785. static char **bufs = NULL;
  2786. static unsigned int in_buf = 0, out_buf = 0;
  2787. static OSStatus writer(AudioDeviceID inDevice,
  2788. const AudioTimeStamp *inNow,
  2789. const AudioBufferList *InputData, const AudioTimeStamp *InputTime,
  2790. AudioBufferList *OutputData, const AudioTimeStamp *OutputTime,
  2791. void *appGlobals)
  2792. {
  2793. AudioBuffer abuf;
  2794. char *aplbuf, *sndbuf;
  2795. abuf = OutputData->mBuffers[0];
  2796. aplbuf = (char *)(abuf.mData);
  2797. sndbuf = bufs[out_buf];
  2798. memmove((void *)aplbuf, (void *)sndbuf, abuf.mDataByteSize);
  2799. out_buf++;
  2800. if (out_buf >= MAX_BUFS) out_buf = 0;
  2801. return(noErr);
  2802. }
  2803. static OSStatus reader(AudioDeviceID inDevice,
  2804. const AudioTimeStamp *inNow,
  2805. const AudioBufferList *InputData, const AudioTimeStamp *InputTime,
  2806. AudioBufferList *OutputData, const AudioTimeStamp *OutputTime,
  2807. void *appGlobals)
  2808. {
  2809. AudioBuffer abuf;
  2810. char *aplbuf, *sndbuf;
  2811. abuf = InputData->mBuffers[0];
  2812. aplbuf = (char *)(abuf.mData);
  2813. sndbuf = bufs[out_buf];
  2814. memmove((void *)sndbuf, (void *)aplbuf, abuf.mDataByteSize);
  2815. out_buf++;
  2816. if (out_buf >= MAX_BUFS) out_buf = 0;
  2817. return(noErr);
  2818. }
  2819. static AudioDeviceID device = kAudioDeviceUnknown;
  2820. static bool writing = false, open_for_input = false;
  2821. #if HAVE_AUDIODEVICEDESTROYIOPROCID
  2822. static AudioDeviceIOProcID read_procId, write_procId;
  2823. #endif
  2824. int mus_audio_close(int line)
  2825. {
  2826. OSStatus err = noErr;
  2827. UInt32 sizeof_running;
  2828. UInt32 running;
  2829. if (open_for_input)
  2830. {
  2831. in_buf = 0;
  2832. err = AudioDeviceStop(device, (AudioDeviceIOProc)reader);
  2833. if (err == noErr)
  2834. #if HAVE_AUDIODEVICEDESTROYIOPROCID
  2835. err = AudioDeviceDestroyIOProcID(device, read_procId);
  2836. #else
  2837. err = AudioDeviceRemoveIOProc(device, (AudioDeviceIOProc)reader);
  2838. #endif
  2839. }
  2840. else
  2841. {
  2842. if ((in_buf > 0) && (!writing))
  2843. {
  2844. /* short enough sound that we never got started? */
  2845. #if HAVE_AUDIODEVICEDESTROYIOPROCID
  2846. err = AudioDeviceCreateIOProcID(device, (AudioDeviceIOProc)writer, NULL, &write_procId);
  2847. #else
  2848. err = AudioDeviceAddIOProc(device, (AudioDeviceIOProc)writer, NULL);
  2849. #endif
  2850. if (err == noErr)
  2851. err = AudioDeviceStart(device, (AudioDeviceIOProc)writer); /* writer will be called right away */
  2852. if (err == noErr)
  2853. writing = true;
  2854. }
  2855. if (writing)
  2856. {
  2857. /* send out waiting buffers */
  2858. sizeof_running = sizeof(UInt32);
  2859. while (in_buf == out_buf)
  2860. {
  2861. /* err = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyDeviceIsRunning, &sizeof_running, &running); */
  2862. {
  2863. AudioObjectPropertyAddress device_address = { kAudioDevicePropertyDeviceIsRunning,
  2864. kAudioDevicePropertyScopeOutput,
  2865. kAudioObjectPropertyElementMaster };
  2866. err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_running, &running);
  2867. }
  2868. }
  2869. while (in_buf != out_buf)
  2870. {
  2871. /* err = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyDeviceIsRunning, &sizeof_running, &running); */
  2872. {
  2873. AudioObjectPropertyAddress device_address = { kAudioDevicePropertyDeviceIsRunning,
  2874. kAudioDevicePropertyScopeOutput,
  2875. kAudioObjectPropertyElementMaster };
  2876. err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_running, &running);
  2877. }
  2878. }
  2879. in_buf = 0;
  2880. err = AudioDeviceStop(device, (AudioDeviceIOProc)writer);
  2881. if (err == noErr)
  2882. #if HAVE_AUDIODEVICEDESTROYIOPROCID
  2883. err = AudioDeviceDestroyIOProcID(device, write_procId);
  2884. #else
  2885. err = AudioDeviceRemoveIOProc(device, (AudioDeviceIOProc)writer);
  2886. #endif
  2887. writing = false;
  2888. }
  2889. }
  2890. device = kAudioDeviceUnknown;
  2891. if (err == noErr)
  2892. return(MUS_NO_ERROR);
  2893. return(MUS_ERROR);
  2894. }
  2895. typedef enum {CONVERT_NOT, CONVERT_COPY, CONVERT_SKIP, CONVERT_COPY_AND_SKIP, CONVERT_SKIP_N, CONVERT_COPY_AND_SKIP_N} audio_convert_t;
  2896. static audio_convert_t conversion_choice = CONVERT_NOT;
  2897. static float conversion_multiplier = 1.0;
  2898. static int dac_out_chans, dac_out_srate;
  2899. static int incoming_out_chans = 1, incoming_out_srate = 44100;
  2900. static unsigned int fill_point = 0;
  2901. static unsigned int bufsize = 0, current_bufsize = 0;
  2902. static bool match_dac_to_sound = true;
  2903. bool mus_audio_output_properties_mutable(bool mut)
  2904. {
  2905. match_dac_to_sound = mut;
  2906. return(mut);
  2907. }
  2908. /* I'm getting bogus buffer sizes from the audio conversion stuff from Apple,
  2909. * and I think AudioConvert doesn't handle cases like 4->6 chans correctly
  2910. * so, I'll just do the conversions myself -- there is little need here
  2911. * for non-integer srate conversion anyway, and the rest is trivial.
  2912. */
  2913. int mus_audio_open_output(int dev, int srate, int chans, mus_sample_t samp_type, int size)
  2914. {
  2915. OSStatus err = noErr;
  2916. UInt32 sizeof_device, sizeof_format, sizeof_bufsize;
  2917. AudioStreamBasicDescription device_desc;
  2918. device = 0;
  2919. sizeof_device = sizeof(AudioDeviceID);
  2920. sizeof_bufsize = sizeof(unsigned int);
  2921. /* err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &sizeof_device, (void *)(&device)); */
  2922. {
  2923. AudioObjectPropertyAddress device_address = { kAudioHardwarePropertyDefaultOutputDevice,
  2924. kAudioObjectPropertyScopeGlobal,
  2925. kAudioObjectPropertyElementMaster };
  2926. err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &device_address, 0, NULL, &sizeof_device, &device);
  2927. }
  2928. bufsize = 4096;
  2929. if (err == noErr)
  2930. {
  2931. /* err = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyBufferSize, &sizeof_bufsize, &bufsize); */
  2932. {
  2933. AudioObjectPropertyAddress device_address = { kAudioDevicePropertyBufferSize,
  2934. kAudioDevicePropertyScopeOutput,
  2935. kAudioObjectPropertyElementMaster };
  2936. err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_bufsize, &bufsize);
  2937. }
  2938. }
  2939. if (err != noErr)
  2940. {
  2941. fprintf(stderr, "open audio output err: %d %s\n", (int)err, osx_error(err));
  2942. return(MUS_ERROR);
  2943. }
  2944. sizeof_format = sizeof(AudioStreamBasicDescription);
  2945. /* err = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyStreamFormat, &sizeof_format, &device_desc); */
  2946. {
  2947. AudioObjectPropertyAddress device_address = { kAudioDevicePropertyStreamFormat,
  2948. kAudioDevicePropertyScopeOutput,
  2949. kAudioObjectPropertyElementMaster };
  2950. err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_format, &device_desc);
  2951. }
  2952. if (err != noErr)
  2953. {
  2954. fprintf(stderr, "open audio output (get device format) err: %d %s\n", (int)err, osx_error(err));
  2955. return(MUS_ERROR);
  2956. }
  2957. if (match_dac_to_sound)
  2958. {
  2959. /* now check for srate/chan mismatches and so on */
  2960. /* current DAC state: device_desc.mChannelsPerFrame, (int)(device_desc.mSampleRate) */
  2961. /* apparently get stream format can return noErr but chans == 0?? */
  2962. if (((int)device_desc.mChannelsPerFrame != chans) ||
  2963. ((int)(device_desc.mSampleRate) != srate))
  2964. {
  2965. /* try to match DAC settings to current sound */
  2966. device_desc.mChannelsPerFrame = chans;
  2967. device_desc.mSampleRate = srate;
  2968. device_desc.mBytesPerPacket = chans * 4; /* assume 1 frame/packet and float32 data */
  2969. device_desc.mBytesPerFrame = chans * 4;
  2970. sizeof_format = sizeof(AudioStreamBasicDescription);
  2971. /* err = AudioDeviceSetProperty(device, 0, 0, false, kAudioDevicePropertyStreamFormat, sizeof_format, &device_desc); */
  2972. {
  2973. AudioObjectPropertyAddress device_address = { kAudioDevicePropertyStreamFormat,
  2974. kAudioDevicePropertyScopeOutput,
  2975. kAudioObjectPropertyElementMaster };
  2976. err = AudioObjectSetPropertyData(device, &device_address, 0, NULL, sizeof_format, &device_desc);
  2977. }
  2978. /* this error is bogus in some cases -- other audio systems just ignore it,
  2979. * but in my case (a standard MacIntel with no special audio hardware), if I leave
  2980. * this block out, the sound is played back at the wrong rate, and the volume
  2981. * of outa is set to 0.0??
  2982. */
  2983. if (err != noErr)
  2984. {
  2985. /* it must have failed for some reason -- look for closest match available */
  2986. /* if srate = 22050 try 44100, if chans = 1 try 2 */
  2987. /* the "get closest match" business appears to be completely bogus... */
  2988. device_desc.mChannelsPerFrame = (chans == 1) ? 2 : chans;
  2989. device_desc.mSampleRate = (srate == 22050) ? 44100 : srate;
  2990. device_desc.mBytesPerPacket = device_desc.mChannelsPerFrame * 4; /* assume 1 frame/packet and float32 data */
  2991. device_desc.mBytesPerFrame = device_desc.mChannelsPerFrame * 4;
  2992. sizeof_format = sizeof(AudioStreamBasicDescription);
  2993. /* err = AudioDeviceSetProperty(device, 0, 0, false, kAudioDevicePropertyStreamFormat, sizeof_format, &device_desc); */
  2994. {
  2995. AudioObjectPropertyAddress device_address = { kAudioDevicePropertyStreamFormat,
  2996. kAudioDevicePropertyScopeOutput,
  2997. kAudioObjectPropertyElementMaster };
  2998. err = AudioObjectSetPropertyData(device, &device_address, 0, NULL, sizeof_format, &device_desc);
  2999. }
  3000. if (err != noErr)
  3001. {
  3002. sizeof_format = sizeof(AudioStreamBasicDescription);
  3003. /* err = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyStreamFormatMatch, &sizeof_format, &device_desc); */
  3004. {
  3005. AudioObjectPropertyAddress device_address = { kAudioDevicePropertyStreamFormatMatch,
  3006. kAudioDevicePropertyScopeOutput,
  3007. kAudioObjectPropertyElementMaster };
  3008. err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_format, &device_desc);
  3009. }
  3010. if (err == noErr)
  3011. {
  3012. /* match suggests: device_desc.mChannelsPerFrame, (int)(device_desc.mSampleRate) */
  3013. /* try to set DAC to reflect that match */
  3014. /* a bug here in emagic 2|6 -- we can get 6 channel match, but then can't set it?? */
  3015. sizeof_format = sizeof(AudioStreamBasicDescription);
  3016. /* err = AudioDeviceSetProperty(device, 0, 0, false, kAudioDevicePropertyStreamFormat, sizeof_format, &device_desc); */
  3017. {
  3018. AudioObjectPropertyAddress device_address = { kAudioDevicePropertyStreamFormat,
  3019. kAudioDevicePropertyScopeOutput,
  3020. kAudioObjectPropertyElementMaster };
  3021. err = AudioObjectSetPropertyData(device, &device_address, 0, NULL, sizeof_format, &device_desc);
  3022. }
  3023. if (err != noErr)
  3024. {
  3025. /* no luck -- get current DAC settings at least */
  3026. sizeof_format = sizeof(AudioStreamBasicDescription);
  3027. /* AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyStreamFormat, &sizeof_format, &device_desc); */
  3028. {
  3029. AudioObjectPropertyAddress device_address = { kAudioDevicePropertyStreamFormat,
  3030. kAudioDevicePropertyScopeOutput,
  3031. kAudioObjectPropertyElementMaster };
  3032. err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_format, &device_desc);
  3033. }
  3034. }
  3035. }
  3036. }
  3037. else
  3038. {
  3039. /* nothing matches? -- get current DAC settings */
  3040. sizeof_format = sizeof(AudioStreamBasicDescription);
  3041. /* AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyStreamFormat, &sizeof_format, &device_desc); */
  3042. {
  3043. AudioObjectPropertyAddress device_address = { kAudioDevicePropertyStreamFormat,
  3044. kAudioDevicePropertyScopeOutput,
  3045. kAudioObjectPropertyElementMaster };
  3046. err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_format, &device_desc);
  3047. }
  3048. }
  3049. }
  3050. }
  3051. } /* end mismatch check */
  3052. /* now DAC claims it is ready for device_desc.mChannelsPerFrame, (int)(device_desc.mSampleRate) */
  3053. dac_out_chans = device_desc.mChannelsPerFrame; /* use better variable names */
  3054. dac_out_srate = (int)(device_desc.mSampleRate);
  3055. open_for_input = false;
  3056. if ((bufs == NULL) || (bufsize > current_bufsize))
  3057. {
  3058. int i;
  3059. if (bufs)
  3060. {
  3061. for (i = 0; i < MAX_BUFS; i++) free(bufs[i]);
  3062. free(bufs);
  3063. }
  3064. bufs = (char **)calloc(MAX_BUFS, sizeof(char *));
  3065. for (i = 0; i < MAX_BUFS; i++)
  3066. bufs[i] = (char *)calloc(bufsize, sizeof(char));
  3067. current_bufsize = bufsize;
  3068. }
  3069. in_buf = 0;
  3070. out_buf = 0;
  3071. fill_point = 0;
  3072. if (!match_dac_to_sound)
  3073. {
  3074. incoming_out_srate = dac_out_srate;
  3075. incoming_out_chans = dac_out_chans;
  3076. conversion_choice = CONVERT_NOT;
  3077. conversion_multiplier = 1.0;
  3078. return(MUS_NO_ERROR);
  3079. }
  3080. incoming_out_srate = srate;
  3081. incoming_out_chans = chans;
  3082. if (incoming_out_chans == dac_out_chans)
  3083. {
  3084. if (incoming_out_srate == dac_out_srate)
  3085. {
  3086. conversion_choice = CONVERT_NOT;
  3087. conversion_multiplier = 1.0;
  3088. }
  3089. else
  3090. {
  3091. /* here we don't get very fancy -- assume dac/2=in */
  3092. conversion_choice = CONVERT_COPY;
  3093. conversion_multiplier = 2.0;
  3094. }
  3095. }
  3096. else
  3097. {
  3098. if (incoming_out_srate == dac_out_srate)
  3099. {
  3100. if ((dac_out_chans == 2) && (incoming_out_chans == 1)) /* the usual case */
  3101. {
  3102. conversion_choice = CONVERT_SKIP;
  3103. conversion_multiplier = 2.0;
  3104. }
  3105. else
  3106. {
  3107. conversion_choice = CONVERT_SKIP_N;
  3108. conversion_multiplier = ((float)dac_out_chans / (float)incoming_out_chans);
  3109. }
  3110. }
  3111. else
  3112. {
  3113. if ((dac_out_chans == 2) && (incoming_out_chans == 1)) /* the usual case */
  3114. {
  3115. conversion_choice = CONVERT_COPY_AND_SKIP;
  3116. conversion_multiplier = 4.0;
  3117. }
  3118. else
  3119. {
  3120. conversion_choice = CONVERT_COPY_AND_SKIP_N;
  3121. conversion_multiplier = ((float)dac_out_chans / (float)incoming_out_chans) * 2;
  3122. }
  3123. }
  3124. }
  3125. return(MUS_NO_ERROR);
  3126. }
  3127. static void convert_incoming(char *to_buf, int fill_point, int lim, char *buf)
  3128. {
  3129. int i, j, k, jc, kc, ic;
  3130. switch (conversion_choice)
  3131. {
  3132. case CONVERT_NOT:
  3133. /* no conversion needed */
  3134. for (i = 0; i < lim; i++)
  3135. to_buf[i + fill_point] = buf[i];
  3136. break;
  3137. case CONVERT_COPY:
  3138. /* copy sample to mimic lower srate */
  3139. for (i = 0, j = fill_point; i < lim; i += 8, j += 16)
  3140. for (k = 0; k < 8; k++)
  3141. {
  3142. to_buf[j + k] = buf[i + k];
  3143. to_buf[j + k + 8] = buf[i + k];
  3144. }
  3145. break;
  3146. case CONVERT_SKIP:
  3147. /* skip sample for empty chan */
  3148. for (i = 0, j = fill_point; i < lim; i += 4, j += 8)
  3149. for (k = 0; k < 4; k++)
  3150. {
  3151. to_buf[j + k] = buf[i + k];
  3152. to_buf[j + k + 4] = 0;
  3153. }
  3154. break;
  3155. case CONVERT_SKIP_N:
  3156. /* copy incoming_out_chans then skip up to dac_out_chans */
  3157. jc = dac_out_chans * 4;
  3158. ic = incoming_out_chans * 4;
  3159. for (i = 0, j = fill_point; i < lim; i += ic, j += jc)
  3160. {
  3161. for (k = 0; k < ic; k++) to_buf[j + k] = buf[i + k];
  3162. for (k = ic; k < jc; k++) to_buf[j + k] = 0;
  3163. }
  3164. break;
  3165. case CONVERT_COPY_AND_SKIP:
  3166. for (i = 0, j = fill_point; i < lim; i += 4, j += 16)
  3167. for (k = 0; k < 4; k++)
  3168. {
  3169. to_buf[j + k] = buf[i + k];
  3170. to_buf[j + k + 4] = 0;
  3171. to_buf[j + k + 8] = buf[i + k];
  3172. to_buf[j + k + 12] = 0;
  3173. }
  3174. break;
  3175. case CONVERT_COPY_AND_SKIP_N:
  3176. /* copy for each active chan, skip rest */
  3177. jc = dac_out_chans * 8;
  3178. ic = incoming_out_chans * 4;
  3179. kc = dac_out_chans * 4;
  3180. for (i = 0, j = fill_point; i < lim; i += ic, j += jc)
  3181. {
  3182. for (k = 0; k < ic; k++)
  3183. {
  3184. to_buf[j + k] = buf[i + k];
  3185. to_buf[j + k + kc] = buf[i + k];
  3186. }
  3187. for (k = ic; k < kc; k++)
  3188. {
  3189. to_buf[j + k] = 0;
  3190. to_buf[j + k + kc] = 0;
  3191. }
  3192. }
  3193. break;
  3194. }
  3195. }
  3196. int mus_audio_write(int line, char *buf, int bytes)
  3197. {
  3198. OSStatus err = noErr;
  3199. unsigned int lim, out_bytes;
  3200. UInt32 sizeof_running;
  3201. UInt32 running;
  3202. char *to_buf;
  3203. to_buf = bufs[in_buf];
  3204. out_bytes = (unsigned int)(bytes * conversion_multiplier);
  3205. if ((fill_point + out_bytes) > bufsize)
  3206. out_bytes = bufsize - fill_point;
  3207. lim = (unsigned int)(out_bytes / conversion_multiplier);
  3208. if (!writing)
  3209. {
  3210. convert_incoming(to_buf, fill_point, lim, buf);
  3211. fill_point += out_bytes;
  3212. if (fill_point >= bufsize)
  3213. {
  3214. in_buf++;
  3215. fill_point = 0;
  3216. if (in_buf == MAX_BUFS)
  3217. {
  3218. in_buf = 0;
  3219. #if HAVE_AUDIODEVICEDESTROYIOPROCID
  3220. err = AudioDeviceCreateIOProcID(device, (AudioDeviceIOProc)writer, NULL, &write_procId);
  3221. #else
  3222. err = AudioDeviceAddIOProc(device, (AudioDeviceIOProc)writer, NULL);
  3223. #endif
  3224. if (err == noErr)
  3225. err = AudioDeviceStart(device, (AudioDeviceIOProc)writer); /* writer will be called right away */
  3226. if (err == noErr)
  3227. {
  3228. writing = true;
  3229. return(MUS_NO_ERROR);
  3230. }
  3231. else return(MUS_ERROR);
  3232. }
  3233. }
  3234. return(MUS_NO_ERROR);
  3235. }
  3236. if ((fill_point == 0) && (in_buf == out_buf))
  3237. {
  3238. unsigned int bp;
  3239. bp = out_buf;
  3240. sizeof_running = sizeof(UInt32);
  3241. while (bp == out_buf)
  3242. {
  3243. /* i.e. just kill time without hanging */
  3244. /* err = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyDeviceIsRunning, &sizeof_running, &running); */
  3245. {
  3246. AudioObjectPropertyAddress device_address = { kAudioDevicePropertyDeviceIsRunning,
  3247. kAudioDevicePropertyScopeOutput,
  3248. kAudioObjectPropertyElementMaster };
  3249. err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_running, &running);
  3250. }
  3251. /* usleep(10); */
  3252. }
  3253. }
  3254. to_buf = bufs[in_buf];
  3255. if (fill_point == 0) memset((void *)to_buf, 0, bufsize);
  3256. convert_incoming(to_buf, fill_point, lim, buf);
  3257. fill_point += out_bytes;
  3258. if (fill_point >= bufsize)
  3259. {
  3260. in_buf++;
  3261. fill_point = 0;
  3262. if (in_buf >= MAX_BUFS) in_buf = 0;
  3263. }
  3264. return(MUS_NO_ERROR);
  3265. }
  3266. int mus_audio_open_input(int dev, int srate, int chans, mus_sample_t samp_type, int size)
  3267. {
  3268. OSStatus err = noErr;
  3269. UInt32 sizeof_device;
  3270. UInt32 sizeof_bufsize;
  3271. sizeof_device = sizeof(AudioDeviceID);
  3272. sizeof_bufsize = sizeof(unsigned int);
  3273. device = 0;
  3274. /* err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &sizeof_device, (void *)(&device)); */
  3275. {
  3276. AudioObjectPropertyAddress device_address = { kAudioHardwarePropertyDefaultInputDevice,
  3277. kAudioObjectPropertyScopeGlobal,
  3278. kAudioObjectPropertyElementMaster };
  3279. err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &device_address, 0, NULL, &sizeof_device, &device);
  3280. }
  3281. bufsize = 4096;
  3282. if (err == noErr)
  3283. {
  3284. /* err = AudioDeviceGetProperty(device, 0, true, kAudioDevicePropertyBufferSize, &sizeof_bufsize, &bufsize); */
  3285. {
  3286. AudioObjectPropertyAddress device_address = { kAudioDevicePropertyBufferSize,
  3287. kAudioDevicePropertyScopeInput,
  3288. kAudioObjectPropertyElementMaster };
  3289. err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_bufsize, &bufsize);
  3290. }
  3291. }
  3292. if (err != noErr)
  3293. {
  3294. fprintf(stderr, "open audio input err: %d %s\n", (int)err, osx_error(err));
  3295. return(MUS_ERROR);
  3296. }
  3297. open_for_input = true;
  3298. /* assume for now that recorder (higher level) will enforce match */
  3299. if ((bufs == NULL) || (bufsize > current_bufsize))
  3300. {
  3301. int i;
  3302. if (bufs)
  3303. {
  3304. for (i = 0; i < MAX_BUFS; i++) free(bufs[i]);
  3305. free(bufs);
  3306. }
  3307. bufs = (char **)calloc(MAX_BUFS, sizeof(char *));
  3308. for (i = 0; i < MAX_BUFS; i++)
  3309. bufs[i] = (char *)calloc(bufsize, sizeof(char));
  3310. current_bufsize = bufsize;
  3311. }
  3312. in_buf = 0;
  3313. out_buf = 0;
  3314. fill_point = 0;
  3315. incoming_out_srate = srate;
  3316. incoming_out_chans = chans;
  3317. #if HAVE_AUDIODEVICEDESTROYIOPROCID
  3318. err = AudioDeviceCreateIOProcID(device, (AudioDeviceIOProc)reader, NULL, &read_procId);
  3319. #else
  3320. err = AudioDeviceAddIOProc(device, (AudioDeviceIOProc)reader, NULL);
  3321. #endif
  3322. if (err == noErr)
  3323. err = AudioDeviceStart(device, (AudioDeviceIOProc)reader);
  3324. if (err != noErr)
  3325. {
  3326. fprintf(stderr, "add open audio input err: %d %s\n", (int)err, osx_error(err));
  3327. return(MUS_ERROR);
  3328. }
  3329. return(MUS_NO_ERROR);
  3330. }
  3331. int mus_audio_read(int line, char *buf, int bytes)
  3332. {
  3333. OSStatus err = noErr;
  3334. UInt32 sizeof_running;
  3335. UInt32 running;
  3336. char *to_buf;
  3337. if (in_buf == out_buf)
  3338. {
  3339. unsigned int bp;
  3340. bp = out_buf;
  3341. sizeof_running = sizeof(UInt32);
  3342. while (bp == out_buf)
  3343. {
  3344. /* err = AudioDeviceGetProperty(device, 0, true, kAudioDevicePropertyDeviceIsRunning, &sizeof_running, &running); */
  3345. {
  3346. AudioObjectPropertyAddress device_address = { kAudioDevicePropertyDeviceIsRunning,
  3347. kAudioDevicePropertyScopeInput,
  3348. kAudioObjectPropertyElementMaster };
  3349. err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_running, &running);
  3350. }
  3351. if (err != noErr)
  3352. fprintf(stderr, "wait err: %s ", osx_error(err));
  3353. }
  3354. }
  3355. to_buf = bufs[in_buf];
  3356. if (bytes <= (int)bufsize)
  3357. memmove((void *)buf, (void *)to_buf, bytes);
  3358. else memmove((void *)buf, (void *)to_buf, bufsize);
  3359. in_buf++;
  3360. if (in_buf >= MAX_BUFS) in_buf = 0;
  3361. return(MUS_ERROR);
  3362. }
  3363. int mus_audio_initialize(void) {return(MUS_NO_ERROR);}
  3364. char *mus_audio_moniker(void) {return((char *)"Mac OSX audio");}
  3365. #endif
  3366. /* ------------------------------- JACK ----------------------------------------- */
  3367. /* Kjetil S. Matheussen. k.s.matheussen@notam02.no */
  3368. /* Based on code from ceres. */
  3369. #if MUS_JACK
  3370. #define AUDIO_OK 1
  3371. #include <pthread.h>
  3372. #include <jack/jack.h>
  3373. #include <samplerate.h>
  3374. #include <sys/mman.h>
  3375. #include <signal.h>
  3376. #if MUS_LITTLE_ENDIAN
  3377. # define MUS_COMP_SHORT MUS_LSHORT
  3378. # define MUS_COMP_FLOAT MUS_LFLOAT
  3379. #else
  3380. # define MUS_COMP_SHORT MUS_BSHORT
  3381. # define MUS_COMP_FLOAT MUS_BFLOAT
  3382. #endif
  3383. #define SRC_QUALITY SRC_SINC_BEST_QUALITY
  3384. #if defined(__i386__) || defined(__x86_64)
  3385. static inline void __attribute__ ((__unused__)) atomic_add(volatile int* __mem, int __val)
  3386. {
  3387. __asm__ __volatile__ ("lock; addl %1,%0"
  3388. : "=m" (*__mem) : "ir" (__val), "m" (*__mem));
  3389. }
  3390. #elif defined(__powerpc__) || defined(__ppc__)
  3391. #ifdef __PPC405__
  3392. #define _STWCX "sync \n\tstwcx. "
  3393. #else
  3394. #define _STWCX "stwcx. "
  3395. #endif
  3396. static inline void __attribute__ ((__unused__)) atomic_add(volatile int* __mem, int __val)
  3397. {
  3398. int __tmp;
  3399. __asm__ __volatile__ (
  3400. "/* Inline atomic add */\n"
  3401. "0:\t"
  3402. "lwarx %0,0,%2 \n\t"
  3403. "add%I3 %0,%0,%3 \n\t"
  3404. _STWCX " %0,0,%2 \n\t"
  3405. "bne- 0b \n\t"
  3406. "/* End atomic add */"
  3407. : "=&b"(__tmp), "=m" (*__mem)
  3408. : "r" (__mem), "Ir"(__val), "m" (*__mem)
  3409. : "cr0");
  3410. }
  3411. #else
  3412. #error "Seems like an unsupported hardware for jack. Please contact k.s.matheussen@notam02.no"
  3413. #endif
  3414. /*************/
  3415. /* Jack Part */
  3416. /*************/
  3417. #define SNDJACK_BUFFERSIZE 32768
  3418. typedef jack_default_audio_sample_t sample_t;
  3419. typedef jack_nframes_t nframes_t;
  3420. struct SndjackChannel{
  3421. jack_port_t *port;
  3422. sample_t *buffer;
  3423. };
  3424. static jack_client_t *sndjack_client = NULL;
  3425. /*************************/
  3426. /* Variables for reading */
  3427. /*************************/
  3428. static int sndjack_num_read_channels_allocated=0;
  3429. static int sndjack_num_read_channels_inuse=0;
  3430. static struct SndjackChannel *sndjack_read_channels=NULL;
  3431. static pthread_cond_t sndjack_read_cond= PTHREAD_COND_INITIALIZER;
  3432. static pthread_mutex_t sndjack_read_mutex= PTHREAD_MUTEX_INITIALIZER;
  3433. static int sj_r_buffersize=0;
  3434. static int sj_r_writeplace=0;
  3435. static int sj_r_readplace=0;
  3436. static int sj_r_unread=0;
  3437. static int sj_r_xrun=0;
  3438. static int sj_r_totalxrun=0;
  3439. /*************************/
  3440. /* Variables for writing */
  3441. /*************************/
  3442. static pthread_cond_t sndjack_cond= PTHREAD_COND_INITIALIZER;
  3443. static pthread_mutex_t sndjack_mutex= PTHREAD_MUTEX_INITIALIZER;
  3444. enum{SJ_STOPPED,SJ_RUNNING,SJ_ABOUTTOSTOP};
  3445. // Variables for the ringbuffer:
  3446. static int sj_writeplace=0;
  3447. static int sj_readplace=0;
  3448. static int sj_unread=0;
  3449. static int sj_buffersize;
  3450. static int sj_jackbuffersize; // number of frames sent to sndjack_process.
  3451. static int sj_totalxrun=0;
  3452. static int sj_xrun=0;
  3453. static int sj_status=SJ_STOPPED;
  3454. static int sndjack_num_channels_allocated=0;
  3455. static int sndjack_num_channels_inuse=0;
  3456. static struct SndjackChannel *sndjack_channels=NULL;
  3457. static int sndjack_read_format;
  3458. static SRC_STATE **sndjack_srcstates;
  3459. static double sndjack_srcratio=1.0;
  3460. static int jack_mus_watchdog_counter=0;
  3461. #define SJ_MAX(a,b) (((a)>(b))?(a):(b))
  3462. static void sndjack_read_process(jack_nframes_t nframes){
  3463. int i,ch;
  3464. sample_t *out[sndjack_num_channels_allocated];
  3465. if (sndjack_num_read_channels_inuse==0) return;
  3466. for (ch=0;ch<sndjack_num_read_channels_allocated;ch++){
  3467. out[ch]=(sample_t*)jack_port_get_buffer(sndjack_read_channels[ch].port,nframes);
  3468. }
  3469. for (i=0;i<nframes;i++){
  3470. if (sj_r_unread==sj_buffersize){
  3471. sj_r_xrun+=nframes-i;
  3472. goto exit;
  3473. }
  3474. for (ch=0;ch<sndjack_num_read_channels_inuse;ch++)
  3475. sndjack_read_channels[ch].buffer[sj_r_writeplace]=out[ch][i];
  3476. atomic_add(&sj_r_unread,1);
  3477. sj_r_writeplace++;
  3478. if (sj_r_writeplace==sj_r_buffersize)
  3479. sj_r_writeplace=0;
  3480. }
  3481. exit:
  3482. pthread_cond_broadcast(&sndjack_read_cond);
  3483. }
  3484. static void sndjack_write_process(jack_nframes_t nframes){
  3485. int ch,i;
  3486. sample_t *out[sndjack_num_channels_allocated];
  3487. for (ch=0;ch<sndjack_num_channels_allocated;ch++){
  3488. out[ch]=(sample_t*)jack_port_get_buffer(sndjack_channels[ch].port,nframes);
  3489. }
  3490. if (sj_status==SJ_STOPPED){
  3491. for (ch=0;ch<sndjack_num_channels_allocated;ch++){
  3492. memset(out[ch],0,nframes*sizeof(sample_t));
  3493. }
  3494. }else{
  3495. // First null out unused channels, if any.
  3496. if (sndjack_num_channels_inuse==1 && sndjack_num_channels_allocated>=2){
  3497. for (ch=2;ch<sndjack_num_channels_allocated;ch++){
  3498. memset(out[ch],0,nframes*sizeof(sample_t));
  3499. }
  3500. }else{
  3501. for (ch=sndjack_num_channels_inuse;ch<sndjack_num_channels_allocated;ch++){
  3502. memset(out[ch],0,nframes*sizeof(sample_t));
  3503. }
  3504. }
  3505. for (i=0;i<nframes;i++){
  3506. if (sj_unread==0){
  3507. if (sj_status==SJ_RUNNING)
  3508. sj_xrun+=nframes-i;
  3509. for (;i<nframes;i++){
  3510. for (ch=0;ch<sndjack_num_channels_inuse;ch++){
  3511. out[ch][i]=0.0f;
  3512. }
  3513. }
  3514. break;
  3515. }
  3516. if (sndjack_num_channels_inuse==1 && sndjack_num_channels_allocated>=2){
  3517. for (ch=0;ch<2;ch++){
  3518. out[ch][i]=sndjack_channels[0].buffer[sj_readplace];
  3519. }
  3520. }else{
  3521. for (ch=0;ch<sndjack_num_channels_inuse;ch++){
  3522. out[ch][i]=sndjack_channels[ch].buffer[sj_readplace];
  3523. }
  3524. }
  3525. atomic_add(&sj_unread,-1);
  3526. sj_readplace++;
  3527. if (sj_readplace==sj_buffersize)
  3528. sj_readplace=0;
  3529. }
  3530. pthread_cond_broadcast(&sndjack_cond);
  3531. if (sj_status==SJ_ABOUTTOSTOP && sj_unread==0)
  3532. sj_status=SJ_STOPPED;
  3533. }
  3534. }
  3535. static int sndjack_process(jack_nframes_t nframes, void *arg){
  3536. sndjack_read_process(nframes);
  3537. sndjack_write_process(nframes);
  3538. return 0;
  3539. }
  3540. static int sndjack_read(void *buf,int bytes,int chs){
  3541. int i,ch;
  3542. int nframes=bytes /
  3543. sndjack_read_format==MUS_COMP_FLOAT ? sizeof(float) :
  3544. sndjack_read_format==MUS_COMP_SHORT ? sizeof(short) :
  3545. 1;
  3546. float *buf_f=(float *)buf;
  3547. short *buf_s=(short *)buf;
  3548. char *buf_c=(char *)buf;
  3549. for (i=0;i<nframes;i++){
  3550. while(sj_r_unread==0){
  3551. pthread_cond_wait(&sndjack_read_cond,&sndjack_read_mutex);
  3552. jack_mus_watchdog_counter++;
  3553. }
  3554. if (sj_r_xrun>0){
  3555. sj_r_totalxrun+=sj_r_xrun;
  3556. sj_r_xrun=0;
  3557. return -1;
  3558. }
  3559. for (ch=0;ch<chs;ch++){
  3560. switch (sndjack_read_format){
  3561. case MUS_BYTE:
  3562. buf_c[i*chs+ch]=sndjack_read_channels[ch].buffer[sj_r_readplace] * 127.9f;
  3563. break;
  3564. case MUS_COMP_SHORT:
  3565. buf_s[i*chs+ch]=sndjack_read_channels[ch].buffer[sj_r_readplace] * 32767.9f;
  3566. break;
  3567. case MUS_COMP_FLOAT:
  3568. buf_f[i*chs+ch]=sndjack_read_channels[ch].buffer[sj_r_readplace];
  3569. break;
  3570. }}
  3571. atomic_add(&sj_r_unread,-1);
  3572. sj_r_readplace++;
  3573. if (sj_r_readplace==sj_r_buffersize)
  3574. sj_r_readplace=0;
  3575. }
  3576. return 0;
  3577. }
  3578. static void sndjack_write(sample_t **buf,int nframes,int latencyframes,int chs){
  3579. int ch;
  3580. int i;
  3581. if (sj_xrun>0){
  3582. if (sj_status==SJ_RUNNING){
  3583. printf("Warning. %d frames delayed.\n",sj_xrun);
  3584. sj_totalxrun+=sj_xrun;
  3585. }
  3586. sj_xrun=0;
  3587. }
  3588. for (i=0;i<nframes;i++){
  3589. while(
  3590. sj_status==SJ_RUNNING
  3591. && (sj_unread==sj_buffersize
  3592. || sj_unread >= SJ_MAX(sj_jackbuffersize*2, latencyframes))
  3593. )
  3594. {
  3595. jack_mus_watchdog_counter++;
  3596. pthread_cond_wait(&sndjack_cond,&sndjack_mutex);
  3597. }
  3598. for (ch=0;ch<chs;ch++)
  3599. sndjack_channels[ch].buffer[sj_writeplace]=buf[ch][i];
  3600. atomic_add(&sj_unread,1);
  3601. sj_writeplace++;
  3602. if (sj_writeplace==sj_buffersize)
  3603. sj_writeplace=0;
  3604. }
  3605. if (sj_status==SJ_STOPPED)
  3606. if (sj_unread>=sj_jackbuffersize)
  3607. sj_status=SJ_RUNNING;
  3608. }
  3609. static int sndjack_buffersizecallback(jack_nframes_t nframes, void *arg){
  3610. sj_jackbuffersize=nframes;
  3611. return 0;
  3612. }
  3613. static int sndjack_getnumoutchannels(void){
  3614. char *a=getenv("SNDLIB_NUM_JACK_CHANNELS");
  3615. if (a!=NULL){
  3616. int num_ch=atoi(a);
  3617. return
  3618. (num_ch<=0 || num_ch > 100000)
  3619. ? 2
  3620. : num_ch;
  3621. }else{
  3622. int lokke=0;
  3623. const char **ports=jack_get_ports(sndjack_client,NULL,NULL,JackPortIsPhysical|JackPortIsInput);
  3624. while(ports!=NULL && ports[lokke]!=NULL){
  3625. lokke++;
  3626. }
  3627. if (lokke<2) return 2;
  3628. return lokke;
  3629. }
  3630. }
  3631. static int sndjack_getnuminchannels(void){
  3632. char *a=getenv("SNDLIB_NUM_JACK_CHANNELS");
  3633. if (a!=NULL){
  3634. int num_ch=atoi(a);
  3635. return
  3636. (num_ch<=0 || num_ch > 100000)
  3637. ? 2
  3638. : num_ch;
  3639. }else{
  3640. int lokke=0;
  3641. const char **ports=jack_get_ports(sndjack_client,NULL,NULL,JackPortIsPhysical|JackPortIsOutput);
  3642. while(ports!=NULL && ports[lokke]!=NULL){
  3643. lokke++;
  3644. }
  3645. if (lokke<2) return 2;
  3646. return lokke;
  3647. }
  3648. }
  3649. static int sndjack_init(void){
  3650. int ch;
  3651. int numch;
  3652. int num=0;
  3653. {
  3654. jack_status_t status;
  3655. sndjack_client=jack_client_open("sndlib",JackNoStartServer,&status,NULL);
  3656. if (sndjack_client == NULL) {
  3657. #if 0
  3658. fprintf (stderr, "jack_client_open() failed, "
  3659. "status = 0x%2.0x\n", status);
  3660. if (status & JackServerFailed) {
  3661. fprintf (stderr, "Unable to connect to JACK server\n");
  3662. }
  3663. #endif
  3664. return -1;
  3665. }
  3666. }
  3667. pthread_mutex_init(&sndjack_mutex,NULL);
  3668. pthread_cond_init(&sndjack_cond,NULL);
  3669. pthread_mutex_init(&sndjack_read_mutex,NULL);
  3670. pthread_cond_init(&sndjack_read_cond,NULL);
  3671. jack_set_process_callback(sndjack_client,sndjack_process,NULL);
  3672. sndjack_num_channels_allocated = numch = sndjack_getnumoutchannels();
  3673. sndjack_num_read_channels_allocated = sndjack_getnuminchannels();
  3674. sndjack_channels=(struct SndjackChannel *)calloc(sizeof(struct SndjackChannel),numch);
  3675. sndjack_read_channels=(struct SndjackChannel *)calloc(sizeof(struct SndjackChannel),sndjack_num_read_channels_allocated);
  3676. for (ch=0;ch<numch;ch++){
  3677. sndjack_channels[ch].buffer=(sample_t *)calloc(sizeof(sample_t),SNDJACK_BUFFERSIZE);
  3678. }
  3679. for (ch=0;ch<sndjack_num_read_channels_allocated;ch++){
  3680. sndjack_read_channels[ch].buffer=(sample_t *)calloc(sizeof(sample_t),SNDJACK_BUFFERSIZE);
  3681. }
  3682. sj_buffersize=SNDJACK_BUFFERSIZE;
  3683. for (ch=0;ch<numch;ch++){
  3684. char temp[500];
  3685. snprintf(temp, 500, "out_%d",ch+1);
  3686. if ((sndjack_channels[ch].port=jack_port_register(
  3687. sndjack_client,
  3688. mus_strdup(temp),
  3689. JACK_DEFAULT_AUDIO_TYPE,
  3690. JackPortIsOutput,
  3691. 0
  3692. ))==NULL)
  3693. {
  3694. fprintf(stderr, "Error. Could not register jack port.\n");
  3695. goto failed_register;
  3696. }
  3697. }
  3698. for (ch=0;ch<sndjack_num_read_channels_allocated;ch++){
  3699. char temp[500];
  3700. snprintf(temp, 500, "in_%d",ch+1);
  3701. if ((sndjack_read_channels[ch].port=jack_port_register(
  3702. sndjack_client,
  3703. mus_strdup(temp),
  3704. JACK_DEFAULT_AUDIO_TYPE,
  3705. JackPortIsInput,
  3706. 0
  3707. ))==NULL)
  3708. {
  3709. fprintf(stderr, "Error. Could not register jack port.\n");
  3710. goto failed_register;
  3711. }
  3712. }
  3713. sj_jackbuffersize=jack_get_buffer_size(sndjack_client);
  3714. jack_set_buffer_size_callback(sndjack_client,sndjack_buffersizecallback,NULL);
  3715. if (jack_activate (sndjack_client)) {
  3716. fprintf (stderr, "Error. Cannot activate jack client.\n");
  3717. goto failed_activate;
  3718. }
  3719. if (getenv("SNDLIB_JACK_DONT_AUTOCONNECT")==NULL){
  3720. const char **outportnames=jack_get_ports(sndjack_client,NULL,NULL,JackPortIsPhysical|JackPortIsInput);
  3721. for (ch=0;outportnames && outportnames[ch]!=NULL && ch<numch;ch++){
  3722. if (
  3723. jack_connect(
  3724. sndjack_client,
  3725. jack_port_name(sndjack_channels[ch].port),
  3726. outportnames[ch]
  3727. )
  3728. )
  3729. {
  3730. printf ("Warning. Cannot connect jack output port %d: \"%s\".\n",ch,outportnames[ch]);
  3731. }
  3732. }
  3733. const char **inportnames=jack_get_ports(sndjack_client,NULL,NULL,JackPortIsPhysical|JackPortIsOutput);
  3734. for (ch=0;inportnames && inportnames[ch]!=NULL && ch<numch;ch++){
  3735. if (
  3736. jack_connect(
  3737. sndjack_client,
  3738. inportnames[ch],
  3739. jack_port_name(sndjack_read_channels[ch].port)
  3740. )
  3741. )
  3742. {
  3743. printf ("Warning. Cannot connect jack input port %d: \"%s\".\n",ch,inportnames[ch]);
  3744. }
  3745. }
  3746. }
  3747. return 0;
  3748. // failed_connect:
  3749. failed_activate:
  3750. jack_deactivate(sndjack_client);
  3751. failed_register:
  3752. jack_client_close(sndjack_client);
  3753. sndjack_client=NULL;
  3754. return -1;
  3755. }
  3756. static void sndjack_cleanup(void){
  3757. int ch;
  3758. for (ch=0;ch<sndjack_num_channels_allocated;ch++){
  3759. src_delete(sndjack_srcstates[ch]);
  3760. }
  3761. jack_deactivate(sndjack_client);
  3762. jack_client_close(sndjack_client);
  3763. }
  3764. /***************/
  3765. /* Sndlib Part */
  3766. /***************/
  3767. static int sndjack_format;
  3768. static sample_t **sndjack_buffer;
  3769. static sample_t *sndjack_srcbuffer;
  3770. static int sndjack_dev;
  3771. static int sndjack_read_dev;
  3772. /* prototypes for the jack sndlib functions */
  3773. static int jack_mus_audio_initialize(void);
  3774. static void jack_mus_oss_set_buffers(int num, int size);
  3775. static char* jack_mus_audio_moniker(void);
  3776. static int jack_mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size);
  3777. static int jack_mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int requested_size);
  3778. static int jack_mus_audio_write(int id, char *buf, int bytes);
  3779. static int jack_mus_audio_read(int id, char *buf, int bytes);
  3780. static int jack_mus_audio_close(int id);
  3781. #if (!HAVE_JACK_IN_LINUX) // Ie. Not using Linux.
  3782. int mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
  3783. {
  3784. return(jack_mus_audio_open_output(ur_dev, srate, chans, samp_type, size));
  3785. }
  3786. int mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int requested_size)
  3787. {
  3788. return(jack_mus_audio_open_input(ur_dev, srate, chans, samp_type, requested_size));
  3789. }
  3790. int mus_audio_write(int id, char *buf, int bytes)
  3791. {
  3792. return(jack_mus_audio_write(id, buf, bytes));
  3793. }
  3794. int mus_audio_read(int id, char *buf, int bytes)
  3795. {
  3796. return(jack_mus_audio_read(id, buf, bytes));
  3797. }
  3798. int mus_audio_close(int id)
  3799. {
  3800. return(jack_mus_audio_close(id));
  3801. }
  3802. int mus_audio_initialize(void){
  3803. return jack_mus_audio_initialize();
  3804. }
  3805. char* mus_audio_moniker(void)
  3806. {
  3807. return(jack_mus_audio_moniker());
  3808. }
  3809. #endif
  3810. static int jack_mus_audio_initialize(void) {
  3811. int ch;
  3812. if (audio_initialized){
  3813. return MUS_NO_ERROR;
  3814. }
  3815. if (sndjack_init()!=0)
  3816. return MUS_ERROR;
  3817. sndjack_buffer=(sample_t **)calloc(sizeof(sample_t*),sndjack_num_channels_allocated);
  3818. for (ch=0;ch<sndjack_num_channels_allocated;ch++)
  3819. sndjack_buffer[ch]=(sample_t *)calloc(sizeof(sample_t),SNDJACK_BUFFERSIZE);
  3820. sndjack_srcbuffer=(sample_t *)calloc(sizeof(sample_t),SNDJACK_BUFFERSIZE);
  3821. sndjack_srcstates=(SRC_STATE **)calloc(sizeof(SRC_STATE*),sndjack_num_channels_allocated);
  3822. for (ch=0;ch<sndjack_num_channels_allocated;ch++){
  3823. sndjack_srcstates[ch]=src_new(SRC_QUALITY,1,NULL);
  3824. }
  3825. atexit(sndjack_cleanup);
  3826. api = MUS_JACK_API;
  3827. vect_mus_audio_initialize = jack_mus_audio_initialize;
  3828. vect_mus_oss_set_buffers = jack_mus_oss_set_buffers;
  3829. vect_mus_audio_moniker = jack_mus_audio_moniker;
  3830. vect_mus_audio_open_output = jack_mus_audio_open_output;
  3831. vect_mus_audio_open_input = jack_mus_audio_open_input;
  3832. vect_mus_audio_write = jack_mus_audio_write;
  3833. vect_mus_audio_read = jack_mus_audio_read;
  3834. vect_mus_audio_close = jack_mus_audio_close;
  3835. audio_initialized = true;
  3836. #if 0
  3837. /* Locking all future memory shouldn't be that necessary, and might even freeze the machine in certain situations. */
  3838. /* So remove MCL_FUTURE from the mlockall call. (No. We can't do that. It can screw up code using the realtime extension. -Kjetil.*/
  3839. munlockall();
  3840. //mlockall(MCL_CURRENT);
  3841. // Instead we just do this: (which is not enough, but maybe better than nothing)
  3842. {
  3843. mlock(sndjack_channels,sizeof(struct SndjackChannel)*sndjack_num_channels_allocated);
  3844. mlock(sndjack_read_channels,sizeof(struct SndjackChannel)*sndjack_num_read_channels_allocated);
  3845. for (ch=0;ch<numch;ch++){
  3846. mlock(sndjack_channels[ch].buffer,sizeof(sample_t)*SNDJACK_BUFFERSIZE);
  3847. }
  3848. for (ch=0;ch<sndjack_num_read_channels_allocated;ch++){
  3849. mlock(sndjack_read_channels[ch].buffer,sizeof(sample_t)*SNDJACK_BUFFERSIZE);
  3850. }
  3851. }
  3852. #endif
  3853. return MUS_NO_ERROR;
  3854. }
  3855. // ??
  3856. static void jack_mus_oss_set_buffers(int num, int size){
  3857. }
  3858. static int jack_mus_isrunning=0;
  3859. static pid_t jack_mus_player_pid;
  3860. static pthread_t jack_mus_watchdog_thread;
  3861. static void *jack_mus_audio_watchdog(void *arg){
  3862. #if MUS_JACK
  3863. struct sched_param par;
  3864. par.sched_priority = sched_get_priority_max(SCHED_RR);
  3865. if (sched_setscheduler(0,SCHED_RR,&par)==-1){
  3866. fprintf(stderr, "SNDLIB: Unable to set SCHED_RR realtime priority for the watchdog thread. No watchdog.\n");
  3867. goto exit;
  3868. }
  3869. for (;;){
  3870. int last=jack_mus_watchdog_counter;
  3871. sleep(1);
  3872. if (jack_mus_isrunning && jack_mus_watchdog_counter<last+10){
  3873. struct sched_param par;
  3874. fprintf(stderr, "SNDLIB: Setting player to non-realtime for 2 seconds.\n");
  3875. par.sched_priority = 0;
  3876. if (sched_setscheduler(jack_mus_player_pid,SCHED_OTHER,&par)==-1){
  3877. fprintf(stderr, "SNDLIB: Unable to set non-realtime priority. Must kill player thread. Sorry!\n");
  3878. while(1){
  3879. kill(jack_mus_player_pid,SIGKILL);
  3880. sleep(2);
  3881. }
  3882. }
  3883. sleep(2);
  3884. if (jack_mus_isrunning){
  3885. par.sched_priority = sched_get_priority_min(SCHED_RR)+1;
  3886. if (sched_setscheduler(jack_mus_player_pid,SCHED_RR,&par)==-1){
  3887. fprintf(stderr, "SNDLIB: Could not set back to realtime priority...\n");
  3888. }else
  3889. fprintf(stderr, "SNDLIB: Play thread set back to realtime priority.\n");
  3890. }
  3891. }
  3892. }
  3893. exit:
  3894. fprintf(stderr, "SNDLIB: Watchdog exiting\n");
  3895. #endif
  3896. return NULL;
  3897. }
  3898. static void jack_mus_audio_set_realtime(void){
  3899. #if HAVE_JACK_IN_LINUX
  3900. struct sched_param par;
  3901. static int watchdog_started=0;
  3902. jack_mus_player_pid=getpid();
  3903. if (watchdog_started==0){
  3904. if (pthread_create(&jack_mus_watchdog_thread,NULL,jack_mus_audio_watchdog,NULL)!=0){
  3905. fprintf(stderr, "Could not create watchdog. Not running realtime\n");
  3906. return;
  3907. }
  3908. watchdog_started=1;
  3909. }
  3910. jack_mus_isrunning=1;
  3911. par.sched_priority = sched_get_priority_min(SCHED_RR)+1;
  3912. if (sched_setscheduler(0,SCHED_RR,&par)==-1){
  3913. fprintf(stderr, "SNDLIB: Unable to set SCHED_RR realtime priority for the player thread.\n");
  3914. }{
  3915. //fprintf(stderr, "Set realtime priority\n");
  3916. }
  3917. #endif
  3918. }
  3919. static void jack_mus_audio_set_non_realtime(void){
  3920. #if HAVE_JACK_IN_LINUX
  3921. struct sched_param par;
  3922. par.sched_priority = 0;
  3923. sched_setscheduler(0,SCHED_OTHER,&par);
  3924. //fprintf(stderr, "Set non-realtime priority\n");
  3925. jack_mus_isrunning=0;
  3926. #endif
  3927. }
  3928. int jack_mus_audio_open_output(int dev, int srate, int chans, mus_sample_t samp_type, int size){
  3929. if (sndjack_client==NULL){
  3930. if (jack_mus_audio_initialize()==MUS_ERROR)
  3931. return MUS_ERROR;
  3932. }
  3933. if (sndjack_num_channels_allocated<chans){
  3934. printf("Error. Can not play back %d channels. (Only %d)\n",chans,sndjack_num_channels_allocated);
  3935. return MUS_ERROR;
  3936. }
  3937. if (samp_type!=MUS_BYTE && samp_type!=MUS_COMP_SHORT && samp_type!=MUS_COMP_FLOAT){
  3938. printf("Error, unable to handle sample type %s.\n",mus_sample_type_to_string(samp_type));
  3939. return MUS_ERROR;
  3940. }
  3941. while(sj_status!=SJ_STOPPED) usleep(5);
  3942. sj_unread=0;
  3943. sj_writeplace=0;
  3944. sj_readplace=0;
  3945. if (srate!=jack_get_sample_rate(sndjack_client)){
  3946. int lokke;
  3947. //printf("Warning, sample-rate differs between snd and jack. Sound will not be played correctly! %d/%d\n",srate,jack_get_sample_rate(sndjack_client));
  3948. sndjack_srcratio=(double)jack_get_sample_rate(sndjack_client)/(double)srate;
  3949. for (lokke=0;lokke<chans;lokke++){
  3950. src_reset(sndjack_srcstates[lokke]);
  3951. }
  3952. }else{
  3953. sndjack_srcratio=1.0;
  3954. }
  3955. sndjack_format=samp_type;
  3956. sndjack_num_channels_inuse=chans;
  3957. sndjack_dev=dev;
  3958. jack_mus_audio_set_realtime();
  3959. return(MUS_NO_ERROR);
  3960. }
  3961. #define MUS_BYTE_TO_SAMPLE(n) (((mus_float_t)(n) / (mus_float_t)(1 << 7)))
  3962. static int sndjack_from_byte(int ch,int chs,char *buf,float *out,int bytes){
  3963. int i;
  3964. int len=bytes/chs;
  3965. if (len>SNDJACK_BUFFERSIZE) return -1;
  3966. for (i=0;i<len;i++){
  3967. out[i]=MUS_BYTE_TO_SAMPLE(buf[i*chs+ch]);
  3968. }
  3969. return len;
  3970. }
  3971. static int sndjack_from_short(int ch,int chs,short *buf,float *out,int bytes){
  3972. int i;
  3973. int len=bytes/(sizeof(short)*chs);
  3974. if (len>SNDJACK_BUFFERSIZE) return -1;
  3975. for (i=0;i<len;i++){
  3976. out[i]=(float)buf[i*chs+ch]/32768.1f;
  3977. }
  3978. return len;
  3979. }
  3980. static int sndjack_from_float(int ch,int chs,float *buf,float *out,int bytes){
  3981. int i;
  3982. int len=bytes/(sizeof(float)*chs);
  3983. if (len>SNDJACK_BUFFERSIZE) return -1;
  3984. for (i=0;i<len;i++){
  3985. out[i]=buf[i*chs+ch];
  3986. }
  3987. return len;
  3988. }
  3989. int jack_mus_audio_write(int line, char *buf, int bytes){
  3990. int i;
  3991. int ch;
  3992. int outlen=0;
  3993. for (ch=0;ch<sndjack_num_channels_inuse;ch++){
  3994. int len = 0;
  3995. float *buf2=sndjack_srcratio==1.0?sndjack_buffer[ch]:sndjack_srcbuffer;
  3996. switch (sndjack_format){
  3997. case MUS_BYTE:
  3998. len=sndjack_from_byte(ch,sndjack_num_channels_inuse,buf,buf2,bytes);
  3999. break;
  4000. case MUS_COMP_SHORT:
  4001. len=sndjack_from_short(ch,sndjack_num_channels_inuse,(short *)buf,buf2,bytes);
  4002. break;
  4003. case MUS_COMP_FLOAT:
  4004. len=sndjack_from_float(ch,sndjack_num_channels_inuse,(float *)buf,buf2,bytes);
  4005. break;
  4006. }
  4007. if (len<0){
  4008. printf("Errur. Input buffer to large for mus_audio_write.\n");
  4009. return MUS_ERROR;
  4010. }
  4011. if (sndjack_srcratio!=1.0){
  4012. SRC_DATA src_data={
  4013. buf2,sndjack_buffer[ch],
  4014. len,SNDJACK_BUFFERSIZE,
  4015. 0,0,
  4016. 0,
  4017. sndjack_srcratio
  4018. };
  4019. int res=src_process(sndjack_srcstates[ch],&src_data);
  4020. if (res!=0){
  4021. printf("Error while resampling. (%s)\n",src_strerror(res));
  4022. return MUS_ERROR;
  4023. }
  4024. if (src_data.input_frames!=len){
  4025. printf("Unsuccessfull resampling: Should have used %d bytes, used %ld.",len,(long int)(src_data.input_frames));
  4026. return MUS_ERROR;
  4027. }
  4028. if (ch>0 && src_data.output_frames_gen!=outlen){
  4029. printf("Error, src_process did not output the same number of frames as previous resampled channel (%ld/%d).\n"
  4030. "Please report this problem to k.s.matheussen@notam02.no. Thanks!\n",(long int)(src_data.output_frames_gen),outlen);
  4031. return MUS_ERROR;
  4032. }
  4033. outlen=src_data.output_frames_gen;
  4034. }else{
  4035. outlen=len;
  4036. }
  4037. }
  4038. sndjack_write(sndjack_buffer,outlen,outlen*2,sndjack_num_channels_inuse);
  4039. return MUS_NO_ERROR;
  4040. }
  4041. int jack_mus_audio_close(int line)
  4042. {
  4043. jack_mus_audio_set_non_realtime();
  4044. if (line==sndjack_dev){
  4045. sj_status=SJ_ABOUTTOSTOP;
  4046. sndjack_num_channels_inuse=0;
  4047. }
  4048. return MUS_NO_ERROR;
  4049. }
  4050. int jack_mus_audio_open_input(int dev, int srate, int chans, mus_sample_t samp_type, int size){
  4051. if (sndjack_client==NULL){
  4052. if (jack_mus_audio_initialize()==MUS_ERROR)
  4053. return MUS_ERROR;
  4054. }
  4055. if (sndjack_num_read_channels_allocated<chans){
  4056. printf("Error. Can not record %d channels. (Only %d)\n",chans,sndjack_num_read_channels_allocated);
  4057. return MUS_ERROR;
  4058. }
  4059. printf("dev: %d\n" ,dev);
  4060. if (samp_type!=MUS_BYTE && samp_type!=MUS_COMP_SHORT && samp_type!=MUS_COMP_FLOAT){
  4061. printf("Error, unable to handle format %s.\n",mus_sample_type_to_string(samp_type));
  4062. return MUS_ERROR;
  4063. }
  4064. if (srate!=jack_get_sample_rate(sndjack_client)){
  4065. printf("Warning, jacks samplerate is %d (and not %d), and the recording will use this samplerate too.\n",jack_get_sample_rate(sndjack_client),srate);
  4066. }
  4067. sndjack_read_format=samp_type;
  4068. sndjack_num_read_channels_inuse=chans;
  4069. sndjack_read_dev=dev;
  4070. return(MUS_NO_ERROR);
  4071. }
  4072. int jack_mus_audio_read(int line, char *buf, int bytes){
  4073. if (sndjack_read(buf,bytes,sndjack_num_read_channels_inuse)==-1)
  4074. return(MUS_ERROR);
  4075. return MUS_NO_ERROR;
  4076. }
  4077. char *jack_mus_audio_moniker(void)
  4078. {
  4079. return((char *)"Jack");
  4080. }
  4081. #endif
  4082. /* ------------------------------- HPUX ----------------------------------------- */
  4083. /* if this is basically the same as the Sun case with different macro names,
  4084. * then it could perhaps be updated to match the new Sun version above --
  4085. * Sun version changed 28-Jan-99
  4086. */
  4087. #if defined(__hpux) && (!(defined(AUDIO_OK)))
  4088. #define AUDIO_OK 1
  4089. #include <sys/audio.h>
  4090. #define return_error_exit(Error_Type, Audio_Line, Ur_Error_Message) \
  4091. do { char *Error_Message; Error_Message = Ur_Error_Message; \
  4092. if (Audio_Line != -1) close(Audio_Line); \
  4093. if (Error_Message) \
  4094. {mus_standard_error(Error_Type, Error_Message); free(Error_Message);} \
  4095. else mus_standard_error(Error_Type, mus_error_type_to_string(Error_Type)); \
  4096. return(MUS_ERROR); \
  4097. } while (false)
  4098. char *mus_audio_moniker(void)
  4099. {
  4100. return("HPUX audio");
  4101. }
  4102. int mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
  4103. {
  4104. int fd, i, dev;
  4105. struct audio_describe desc;
  4106. dev = MUS_AUDIO_DEVICE(ur_dev);
  4107. fd = open("/dev/audio", O_RDWR);
  4108. if (fd == -1)
  4109. return_error_exit(MUS_AUDIO_CANT_OPEN, -1,
  4110. mus_format("can't open /dev/audio for output: %s",
  4111. strerror(errno)));
  4112. ioctl(fd, AUDIO_SET_CHANNELS, chans);
  4113. if (dev == MUS_AUDIO_SPEAKERS)
  4114. ioctl(fd, AUDIO_SET_OUTPUT, AUDIO_OUT_SPEAKER);
  4115. else
  4116. if (dev == MUS_AUDIO_LINE_OUT)
  4117. ioctl(fd, AUDIO_SET_OUTPUT, AUDIO_OUT_LINE);
  4118. else ioctl(fd, AUDIO_SET_OUTPUT, AUDIO_OUT_HEADPHONE);
  4119. if (samp_type == MUS_BSHORT)
  4120. ioctl(fd, AUDIO_SET_SAMPLE_TYPE, AUDIO_FORMAT_LINEAR16BIT);
  4121. else
  4122. {
  4123. if (samp_type == MUS_MULAW)
  4124. ioctl(fd, AUDIO_SET_SAMPLE_TYPE, AUDIO_FORMAT_ULAW);
  4125. else
  4126. {
  4127. if (samp_type == MUS_ALAW)
  4128. ioctl(fd, AUDIO_SET_SAMPLE_TYPE, AUDIO_FORMAT_ALAW);
  4129. else
  4130. return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, fd,
  4131. mus_format("can't set output sample type to %d (%s) for %d",
  4132. samp_type, mus_sample_type_to_string(samp_type),
  4133. dev));
  4134. }
  4135. }
  4136. ioctl(fd, AUDIO_DESCRIBE, &desc);
  4137. for (i = 0; i < desc.nrates; i++)
  4138. if (srate == desc.sample_rate[i])
  4139. break;
  4140. if (i == desc.nrates)
  4141. return_error_exit(SRATE_NOT_AVAILABLE, fd,
  4142. mus_format("can't set srate to %d on %d",
  4143. srate, dev));
  4144. ioctl(fd, AUDIO_SET_SAMPLE_RATE, srate);
  4145. return(fd);
  4146. }
  4147. int mus_audio_write(int line, char *buf, int bytes)
  4148. {
  4149. write(line, buf, bytes);
  4150. return(MUS_NO_ERROR);
  4151. }
  4152. int mus_audio_close(int line)
  4153. {
  4154. close(line);
  4155. return(MUS_NO_ERROR);
  4156. }
  4157. int mus_audio_initialize(void)
  4158. {
  4159. return(MUS_NO_ERROR);
  4160. }
  4161. /* struct audio_status status_b;
  4162. * ioctl(devAudio, AUDIO_GET_STATUS, &status_b)
  4163. * not_busy = (status_b.transmit_status == AUDIO_DONE);
  4164. */
  4165. int mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
  4166. {
  4167. int fd, i, dev;
  4168. struct audio_describe desc;
  4169. dev = MUS_AUDIO_DEVICE(ur_dev);
  4170. fd = open("/dev/audio", O_RDWR);
  4171. if (fd == -1)
  4172. return_error_exit(MUS_AUDIO_CANT_OPEN, NULL,
  4173. mus_format("can't open /dev/audio for input: %s",
  4174. strerror(errno)));
  4175. ioctl(fd, AUDIO_SET_CHANNELS, chans);
  4176. if (dev == MUS_AUDIO_MICROPHONE)
  4177. ioctl(fd, AUDIO_SET_INPUT, AUDIO_IN_MIKE);
  4178. else ioctl(fd, AUDIO_SET_INPUT, AUDIO_IN_LINE);
  4179. if (samp_type == MUS_BSHORT)
  4180. ioctl(fd, AUDIO_SET_SAMPLE_TYPE, AUDIO_FORMAT_LINEAR16BIT);
  4181. else
  4182. {
  4183. if (samp_type == MUS_MULAW)
  4184. ioctl(fd, AUDIO_SET_SAMPLE_TYPE, AUDIO_FORMAT_ULAW);
  4185. else
  4186. {
  4187. if (samp_type == MUS_ALAW)
  4188. ioctl(fd, AUDIO_SET_SAMPLE_TYPE, AUDIO_FORMAT_ALAW);
  4189. else
  4190. return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, fd,
  4191. mus_format("can't set input sample type to %d (%s) on %d",
  4192. samp_type, mus_sample_type_to_string(samp_type),
  4193. dev));
  4194. }
  4195. }
  4196. ioctl(fd, AUDIO_DESCRIBE, &desc);
  4197. for (i = 0; i < desc.nrates; i++)
  4198. if (srate == desc.sample_rate[i])
  4199. break;
  4200. if (i == desc.nrates)
  4201. return_error_exit(MUS_AUDIO_SRATE_NOT_AVAILABLE, fd,
  4202. mus_format("can't set srate to %d on %d",
  4203. srate, dev));
  4204. ioctl(fd, AUDIO_SET_SAMPLE_RATE, srate);
  4205. return(fd);
  4206. }
  4207. int mus_audio_read(int line, char *buf, int bytes)
  4208. {
  4209. read(line, buf, bytes);
  4210. return(MUS_NO_ERROR);
  4211. }
  4212. #endif
  4213. /* ------------------------------- NETBSD/OpenBSD ----------------------------------------- */
  4214. #if (__NetBSD__ || __OpenBSD__) && (!(defined(AUDIO_OK)))
  4215. #define AUDIO_OK 1
  4216. /* started from Xanim a long time ago..., bugfixes from Thomas Klausner 30-Jul-05, worked into better shape Aug-05 */
  4217. #include <fcntl.h>
  4218. #include <sys/audioio.h>
  4219. #include <sys/ioctl.h>
  4220. #include <sys/param.h>
  4221. #define return_error_exit(Error_Type, Audio_Line, Ur_Error_Message) \
  4222. do { char *Error_Message; Error_Message = Ur_Error_Message; \
  4223. if (Audio_Line != -1) close(Audio_Line); \
  4224. if (Error_Message) \
  4225. {mus_standard_error(Error_Type, Error_Message); free(Error_Message);} \
  4226. else mus_standard_error(Error_Type, mus_error_type_to_string(Error_Type)); \
  4227. return(MUS_ERROR); \
  4228. } while (false)
  4229. static mus_sample_t bsd_format_to_sndlib(int encoding)
  4230. {
  4231. switch (encoding)
  4232. {
  4233. case AUDIO_ENCODING_ULAW: return(MUS_MULAW); break;
  4234. case AUDIO_ENCODING_ALAW: return(MUS_ALAW); break;
  4235. case AUDIO_ENCODING_LINEAR: return(MUS_BSHORT); break; /* "sun compatible" so probably big-endian? */
  4236. case AUDIO_ENCODING_SLINEAR:
  4237. case AUDIO_ENCODING_LINEAR8: return(MUS_BYTE); break;
  4238. case AUDIO_ENCODING_SLINEAR_LE: return(MUS_LSHORT); break;
  4239. case AUDIO_ENCODING_SLINEAR_BE: return(MUS_BSHORT); break;
  4240. case AUDIO_ENCODING_ULINEAR_LE: return(MUS_ULSHORT); break;
  4241. case AUDIO_ENCODING_ULINEAR_BE: return(MUS_UBSHORT); break;
  4242. case AUDIO_ENCODING_ULINEAR: return(MUS_UBYTE); break;
  4243. case AUDIO_ENCODING_NONE:
  4244. case AUDIO_ENCODING_ADPCM:
  4245. default: return(MUS_UNKNOWN_SAMPLE); break;
  4246. }
  4247. return(MUS_UNKNOWN_SAMPLE);
  4248. }
  4249. static int sndlib_format_to_bsd(mus_sample_t encoding)
  4250. {
  4251. switch (encoding)
  4252. {
  4253. case MUS_MULAW: return(AUDIO_ENCODING_ULAW); break;
  4254. case MUS_ALAW: return(AUDIO_ENCODING_ALAW); break;
  4255. case MUS_BYTE: return(AUDIO_ENCODING_SLINEAR); break;
  4256. case MUS_LSHORT: return(AUDIO_ENCODING_SLINEAR_LE); break;
  4257. case MUS_BSHORT: return(AUDIO_ENCODING_SLINEAR_BE); break;
  4258. case MUS_ULSHORT: return(AUDIO_ENCODING_ULINEAR_LE); break;
  4259. case MUS_UBSHORT: return(AUDIO_ENCODING_ULINEAR_BE); break;
  4260. case MUS_UBYTE: return(AUDIO_ENCODING_ULINEAR); break;
  4261. default: break;
  4262. }
  4263. return(AUDIO_ENCODING_NONE);
  4264. }
  4265. int mus_audio_initialize(void)
  4266. {
  4267. return(MUS_NO_ERROR);
  4268. }
  4269. char *mus_audio_moniker(void)
  4270. {
  4271. #if __NetBSD__
  4272. return((char *)"NetBSD audio");
  4273. #else
  4274. return((char *)"OpenBSD audio");
  4275. #endif
  4276. }
  4277. static int cur_chans = 1, cur_srate = 22050;
  4278. int mus_audio_write(int line, char *buf, int bytes)
  4279. {
  4280. #if defined(__NetBSD__) && (__NetBSD_Version__ >= 700000000)
  4281. if (write(line, buf, bytes) != bytes)
  4282. return_error_exit(MUS_AUDIO_WRITE_ERROR, line,
  4283. mus_format("write error: %s", strerror(errno)));
  4284. #else
  4285. /* trouble... AUDIO_WSEEK always returns 0, no way to tell that I'm about to
  4286. * hit "hiwat", but when I do, it hangs. Can't use AUDIO_DRAIN --
  4287. * it introduces interruptions. Not sure what to do...
  4288. */
  4289. int b = 0;
  4290. b = write(line, buf, bytes);
  4291. usleep(10000);
  4292. if ((b != bytes) && (b > 0)) /* b <= 0 presumably some sort of error, and we want to avoid infinite recursion below */
  4293. {
  4294. /* hangs at close if we don't handle this somehow */
  4295. if ((cur_chans == 1) || (cur_srate == 22050))
  4296. sleep(1);
  4297. else usleep(10000);
  4298. mus_audio_write(line, (char *)(buf + b), bytes - b);
  4299. }
  4300. #endif
  4301. return(MUS_NO_ERROR);
  4302. }
  4303. /* from Mike Scholz, 11-Feb-16 (edited):
  4304. * On Netbsd sound output with Snd and Sndplay stops before the sound is really at the end.
  4305. * [In audioplay] after the read-write loop they call ioctl(fd, AUDIO_DRAIN, NULL).
  4306. * Before closing sound output they call ioctl(fd, AUDIO_FLUSH, NULL) (like in audio.c),
  4307. * and in addition ioctl(fd, AUDIO_SETINFO, &info). The latter requires that
  4308. * audio_info_t a_info be a global variable. The AUDIO_DRAIN call has been in their
  4309. * sources since version 1.1 of /usr/src/usr.bin/audio/play/play.c from March 1999.
  4310. */
  4311. static audio_info_t a_info;
  4312. int mus_audio_close(int line)
  4313. {
  4314. ioctl(line, AUDIO_DRAIN, NULL);
  4315. ioctl(line, AUDIO_FLUSH, NULL);
  4316. ioctl(line, AUDIO_SETINFO, &a_info);
  4317. close(line);
  4318. return(MUS_NO_ERROR);
  4319. }
  4320. static int netbsd_default_outputs = (AUDIO_HEADPHONE | AUDIO_LINE_OUT | AUDIO_SPEAKER);
  4321. int mus_audio_open_output(int dev, int srate, int chans, mus_sample_t samp_type, int size)
  4322. {
  4323. int line, encode;
  4324. line = open("/dev/sound", O_WRONLY); /* /dev/audio assumes mono 8-bit mulaw */
  4325. if (line == -1)
  4326. {
  4327. if (errno == EBUSY)
  4328. return(mus_error(MUS_AUDIO_CANT_OPEN, NULL));
  4329. else return(mus_error(MUS_AUDIO_DEVICE_NOT_AVAILABLE, NULL));
  4330. }
  4331. AUDIO_INITINFO(&a_info);
  4332. /* a_info.blocksize = size; */
  4333. encode = sndlib_format_to_bsd(samp_type);
  4334. if (encode == AUDIO_ENCODING_NONE)
  4335. return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, -1,
  4336. mus_format("sample type %d (%s) not available",
  4337. samp_type,
  4338. mus_sample_type_name(samp_type)));
  4339. a_info.play.encoding = encode;
  4340. a_info.mode = AUMODE_PLAY | AUMODE_PLAY_ALL;
  4341. a_info.play.precision = mus_bytes_per_sample(samp_type) * 8;
  4342. a_info.play.sample_rate = srate;
  4343. if (dev == MUS_AUDIO_LINE_OUT)
  4344. a_info.play.port = AUDIO_LINE_OUT;
  4345. else
  4346. {
  4347. if (dev == MUS_AUDIO_SPEAKERS)
  4348. a_info.play.port = AUDIO_SPEAKER | (netbsd_default_outputs & AUDIO_HEADPHONE);
  4349. else a_info.play.port = netbsd_default_outputs;
  4350. }
  4351. a_info.play.channels = chans;
  4352. ioctl(line, AUDIO_SETINFO, &a_info);
  4353. /* actually doesn't set the "ports" field -- always 0 */
  4354. ioctl(line, AUDIO_GETINFO, &a_info);
  4355. if ((int)(a_info.play.sample_rate) != srate)
  4356. mus_print("srate: %d -> %d\n", srate, a_info.play.sample_rate);
  4357. if ((int)(a_info.play.encoding) != sndlib_format_to_bsd(samp_type))
  4358. mus_print("encoding: %d -> %d\n", sndlib_format_to_bsd(samp_type), a_info.play.encoding);
  4359. if ((int)(a_info.play.channels) != chans)
  4360. mus_print("chans: %d -> %d\n", chans, a_info.play.channels);
  4361. cur_chans = chans;
  4362. cur_srate = srate;
  4363. return(line);
  4364. }
  4365. int mus_audio_read(int line, char *buf, int bytes)
  4366. {
  4367. read(line, buf, bytes);
  4368. return(MUS_NO_ERROR);
  4369. }
  4370. static int netbsd_sample_types(int ur_dev, mus_sample_t *val)
  4371. {
  4372. int i, audio_fd, err, dev;
  4373. audio_info_t info;
  4374. audio_encoding_t e_info;
  4375. dev = MUS_AUDIO_DEVICE(ur_dev);
  4376. AUDIO_INITINFO(&info);
  4377. audio_fd = open("/dev/sound", O_RDONLY | O_NONBLOCK, 0);
  4378. if (audio_fd == -1)
  4379. return_error_exit(MUS_AUDIO_CANT_READ, -1, mus_format("can't open /dev/sound: %s", strerror(errno)));
  4380. err = ioctl(audio_fd, AUDIO_GETINFO, &info);
  4381. if (err == -1)
  4382. {
  4383. close(audio_fd);
  4384. return_error_exit(MUS_AUDIO_CANT_READ, audio_fd, mus_format("can't get dac info"));
  4385. }
  4386. for (i = 0; ; i++)
  4387. {
  4388. e_info.index = i;
  4389. err = ioctl(audio_fd, AUDIO_GETENC, &e_info);
  4390. if (err != 0) break;
  4391. val[i + 1] = bsd_format_to_sndlib(e_info.encoding);
  4392. }
  4393. val[0] = (mus_sample_t)i;
  4394. close(audio_fd);
  4395. return(MUS_NO_ERROR);
  4396. }
  4397. int mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
  4398. {
  4399. audio_info_t info;
  4400. int encode, bits, dev, audio_fd, err;
  4401. dev = MUS_AUDIO_DEVICE(ur_dev);
  4402. encode = sndlib_format_to_bsd(samp_type);
  4403. bits = 8 * mus_bytes_per_sample(samp_type);
  4404. if (encode == AUDIO_ENCODING_NONE)
  4405. return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, -1,
  4406. mus_format("sample type %s not available for recording",
  4407. mus_sample_type_name(samp_type)));
  4408. if (dev != MUS_AUDIO_DUPLEX_DEFAULT)
  4409. audio_fd = open("/dev/sound", O_RDONLY, 0);
  4410. else audio_fd = open("/dev/sound", O_RDWR, 0);
  4411. if (audio_fd == -1)
  4412. return_error_exit(MUS_AUDIO_CANT_OPEN, -1,
  4413. mus_format("can't open /dev/sound: %s",
  4414. strerror(errno)));
  4415. AUDIO_INITINFO(&info);
  4416. info.record.sample_rate = srate;
  4417. info.record.channels = chans;
  4418. info.record.precision = bits;
  4419. info.record.encoding = encode;
  4420. info.record.port = AUDIO_MICROPHONE;
  4421. err = ioctl(audio_fd, AUDIO_SETINFO, &info);
  4422. if (err == -1)
  4423. return_error_exit(MUS_AUDIO_CANT_WRITE, audio_fd,
  4424. mus_format("can't set up for recording"));
  4425. return(audio_fd);
  4426. }
  4427. #endif
  4428. /* -------------------------------- PULSEAUDIO -------------------------------- */
  4429. #if defined(MUS_PULSEAUDIO) && (!(defined(AUDIO_OK)))
  4430. #define AUDIO_OK 1
  4431. /* this code compiles/loads, but I don't know if it works -- paplay itself
  4432. * doesn't work on my machine due to either a libtool/dlopen mismatch
  4433. * or some problem with "pulse-rt".
  4434. */
  4435. #include <pulse/simple.h>
  4436. #include <pulse/error.h>
  4437. #include <pulse/gccmacro.h>
  4438. static int sndlib_to_pa_format(mus_sample_t samp_type)
  4439. {
  4440. switch (samp_type)
  4441. {
  4442. case MUS_BYTE: return(PA_SAMPLE_U8);
  4443. case MUS_LSHORT: return(PA_SAMPLE_S16LE);
  4444. case MUS_BSHORT: return(PA_SAMPLE_S16BE);
  4445. case MUS_LINT: return(PA_SAMPLE_S32LE);
  4446. case MUS_BINT: return(PA_SAMPLE_S32BE);
  4447. case MUS_LFLOAT: return(PA_SAMPLE_FLOAT32LE);
  4448. case MUS_BFLOAT: return(PA_SAMPLE_FLOAT32BE);
  4449. case MUS_ALAW: return(PA_SAMPLE_ALAW);
  4450. case MUS_MULAW: return(PA_SAMPLE_ULAW);
  4451. default:
  4452. fprintf(stderr, "unsupported sample type: %d\n", samp_type);
  4453. return(0);
  4454. break;
  4455. }
  4456. }
  4457. static pa_simple *pa_out = NULL, *pa_in = NULL;
  4458. int mus_audio_open_output(int dev, int srate, int chans, mus_sample_t samp_type, int size)
  4459. {
  4460. pa_sample_spec spec = {0};
  4461. int error;
  4462. spec.format = sndlib_to_pa_format(samp_type);
  4463. spec.rate = srate;
  4464. spec.channels = chans;
  4465. pa_out = pa_simple_new(NULL, "snd", PA_STREAM_PLAYBACK, NULL, "playback", &spec, NULL, NULL, &error);
  4466. if (!pa_out)
  4467. {
  4468. fprintf(stderr, "can't play: %s\n", pa_strerror(error));
  4469. return(MUS_ERROR);
  4470. }
  4471. return(0);
  4472. }
  4473. int mus_audio_open_input(int dev, int srate, int chans, mus_sample_t samp_type, int size)
  4474. {
  4475. return(MUS_ERROR);
  4476. }
  4477. int mus_audio_write(int line, char *buf, int bytes)
  4478. {
  4479. int error;
  4480. pa_simple_write(pa_out, (unsigned char *)buf, (size_t)bytes, &error);
  4481. }
  4482. int mus_audio_close(int line)
  4483. {
  4484. int error;
  4485. pa_simple_drain(pa_out, &error);
  4486. pa_simple_free(pa_out);
  4487. pa_out = NULL;
  4488. }
  4489. int mus_audio_read(int line, char *buf, int bytes)
  4490. {
  4491. return(MUS_ERROR);
  4492. }
  4493. int mus_audio_initialize(void)
  4494. {
  4495. return(MUS_ERROR);
  4496. }
  4497. char *mus_audio_moniker(void)
  4498. {
  4499. return(mus_format("pulseaudio %s", pa_get_library_version()));
  4500. }
  4501. #endif
  4502. /* -------------------------------- PORTAUDIO -------------------------------- */
  4503. #if defined(MUS_PORTAUDIO) && (!(defined(AUDIO_OK)))
  4504. #define AUDIO_OK 1
  4505. #include <portaudio.h>
  4506. #define PA_OUT_STREAM 0
  4507. #define PA_IN_STREAM 1
  4508. static unsigned long sndlib_to_portaudio_format(mus_sample_t samp_type)
  4509. {
  4510. switch (samp_type)
  4511. {
  4512. case MUS_BYTE: return(paInt8);
  4513. case MUS_LSHORT: return(paInt16);
  4514. case MUS_BSHORT: return(paInt16);
  4515. case MUS_LINT: return(paInt32);
  4516. case MUS_BINT: return(paInt32);
  4517. case MUS_LFLOAT: return(paFloat32);
  4518. case MUS_BFLOAT: return(paFloat32);
  4519. default: break;
  4520. }
  4521. return(paInt16);
  4522. }
  4523. static PaStream *out_stream = NULL;
  4524. int mus_audio_open_output(int dev, int srate, int chans, mus_sample_t samp_type, int size)
  4525. {
  4526. PaStreamParameters output_pars;
  4527. PaError err;
  4528. output_pars.device = Pa_GetDefaultOutputDevice();
  4529. output_pars.channelCount = chans;
  4530. output_pars.sampleFormat = sndlib_to_portaudio_format(samp_type);
  4531. output_pars.suggestedLatency = Pa_GetDeviceInfo(output_pars.device)->defaultHighOutputLatency;
  4532. output_pars.hostApiSpecificStreamInfo = NULL;
  4533. err = Pa_OpenStream(&out_stream, NULL, &output_pars, srate, 1024, paClipOff, NULL, NULL); /* 1024 = frames [dac_size] but can we use "size"? */
  4534. if (err == paNoError)
  4535. err = Pa_StartStream(out_stream);
  4536. if (err != paNoError)
  4537. {
  4538. fprintf(stderr, "portaudio open output: %s\n", Pa_GetErrorText(err));
  4539. return(MUS_ERROR);
  4540. }
  4541. return(PA_OUT_STREAM);
  4542. }
  4543. static PaStream *in_stream = NULL;
  4544. int mus_audio_open_input(int dev, int srate, int chans, mus_sample_t samp_type, int size)
  4545. {
  4546. PaStreamParameters input_pars;
  4547. PaError err;
  4548. input_pars.device = Pa_GetDefaultInputDevice();
  4549. input_pars.channelCount = chans;
  4550. input_pars.sampleFormat = sndlib_to_portaudio_format(samp_type);
  4551. input_pars.suggestedLatency = Pa_GetDeviceInfo(input_pars.device)->defaultHighInputLatency;
  4552. input_pars.hostApiSpecificStreamInfo = NULL;
  4553. err = Pa_OpenStream(&in_stream, &input_pars, NULL, srate, 1024, paClipOff, NULL, NULL);
  4554. if (err == paNoError)
  4555. err = Pa_StartStream(in_stream);
  4556. if (err != paNoError)
  4557. {
  4558. fprintf(stderr, "portaudio open input: %s\n", Pa_GetErrorText(err));
  4559. return(MUS_ERROR);
  4560. }
  4561. return(MUS_NO_ERROR);
  4562. }
  4563. int mus_audio_write(int line, char *buf, int bytes)
  4564. {
  4565. PaError err;
  4566. err = Pa_WriteStream(out_stream, buf, 1024);
  4567. if (err != paNoError)
  4568. {
  4569. fprintf(stderr, "portaudio write: %s\n", Pa_GetErrorText(err));
  4570. return(MUS_ERROR);
  4571. }
  4572. return(MUS_NO_ERROR);
  4573. }
  4574. int mus_audio_close(int line)
  4575. {
  4576. PaError err;
  4577. if (line == PA_IN_STREAM)
  4578. err = Pa_CloseStream(in_stream);
  4579. else err = Pa_CloseStream(out_stream);
  4580. if (err != paNoError)
  4581. {
  4582. fprintf(stderr, "portaudio close: %s\n", Pa_GetErrorText(err));
  4583. return(MUS_ERROR);
  4584. }
  4585. return(MUS_NO_ERROR);
  4586. }
  4587. int mus_audio_read(int line, char *buf, int bytes)
  4588. {
  4589. PaError err;
  4590. err = Pa_ReadStream(in_stream, buf, 1024);
  4591. if (err != paNoError)
  4592. {
  4593. fprintf(stderr, "portaudio read: %s\n", Pa_GetErrorText(err));
  4594. return(MUS_ERROR);
  4595. }
  4596. return(MUS_NO_ERROR);
  4597. }
  4598. static bool portaudio_initialized = false;
  4599. int mus_audio_initialize(void)
  4600. {
  4601. PaError err;
  4602. if (portaudio_initialized) return(MUS_NO_ERROR);
  4603. portaudio_initialized = true;
  4604. err = Pa_Initialize();
  4605. if (err == paNoError)
  4606. return(MUS_NO_ERROR);
  4607. fprintf(stderr, "portaudio initialize: %s\n", Pa_GetErrorText(err));
  4608. return(MUS_ERROR);
  4609. }
  4610. char *mus_audio_moniker(void)
  4611. {
  4612. return((char *)Pa_GetVersionText());
  4613. }
  4614. #endif
  4615. /* ------------------------------- STUBS ----------------------------------------- */
  4616. #ifndef AUDIO_OK
  4617. int mus_audio_open_output(int dev, int srate, int chans, mus_sample_t samp_type, int size) {return(MUS_ERROR);}
  4618. int mus_audio_open_input(int dev, int srate, int chans, mus_sample_t samp_type, int size) {return(MUS_ERROR);}
  4619. int mus_audio_write(int line, char *buf, int bytes) {return(MUS_ERROR);}
  4620. int mus_audio_close(int line) {return(MUS_ERROR);}
  4621. int mus_audio_read(int line, char *buf, int bytes) {return(MUS_ERROR);}
  4622. int mus_audio_initialize(void) {return(MUS_ERROR);}
  4623. char *mus_audio_moniker(void) {return((char *)"no audio support");}
  4624. #endif
  4625. /* for CLM */
  4626. void mus_reset_audio_c(void)
  4627. {
  4628. audio_initialized = false;
  4629. version_name = NULL;
  4630. }
  4631. #if HAVE_ALSA || HAVE_OSS
  4632. void mus_audio_alsa_channel_info(int dev, int *info);
  4633. void mus_audio_alsa_channel_info(int dev, int *info)
  4634. {
  4635. #if MUS_JACK
  4636. if (api == MUS_JACK_API)
  4637. {
  4638. info[0] = sndjack_num_channels_allocated;
  4639. return;
  4640. }
  4641. #endif
  4642. #if HAVE_ALSA
  4643. if (api == MUS_ALSA_API)
  4644. {
  4645. alsa_chans(dev, info);
  4646. return;
  4647. }
  4648. #endif
  4649. #if HAVE_OSS
  4650. info[0] = 2;
  4651. #endif
  4652. }
  4653. int mus_audio_alsa_samples_per_channel(int dev);
  4654. int mus_audio_alsa_samples_per_channel(int dev)
  4655. {
  4656. #if HAVE_ALSA
  4657. return(alsa_samples_per_channel);
  4658. #else
  4659. return(1024);
  4660. #endif
  4661. }
  4662. void mus_audio_alsa_device_list(int ur_dev, int chan, int *val);
  4663. void mus_audio_alsa_device_list(int ur_dev, int chan, int *val)
  4664. {
  4665. #if HAVE_ALSA
  4666. int i = 1;
  4667. if (!audio_initialized) mus_audio_initialize();
  4668. if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK])
  4669. val[i++] = to_sndlib_device(0, SND_PCM_STREAM_PLAYBACK);
  4670. if (alsa_hw_params[SND_PCM_STREAM_CAPTURE])
  4671. val[i++] = to_sndlib_device(0, SND_PCM_STREAM_CAPTURE);
  4672. val[0] = (i - 1);
  4673. #endif
  4674. }
  4675. #define MUS_AUDIO_DIRECTION_PLAYBACK 0
  4676. #define MUS_AUDIO_DIRECTION_RECORD 1
  4677. int mus_audio_alsa_device_direction(int dev);
  4678. int mus_audio_alsa_device_direction(int dev)
  4679. {
  4680. #if HAVE_OSS
  4681. switch (MUS_AUDIO_DEVICE(dev))
  4682. {
  4683. case MUS_AUDIO_DIGITAL_OUT: case MUS_AUDIO_LINE_OUT: case MUS_AUDIO_DEFAULT:
  4684. case MUS_AUDIO_SPEAKERS: case MUS_AUDIO_MIXER:
  4685. case MUS_AUDIO_AUX_OUTPUT: case MUS_AUDIO_DAC_OUT:
  4686. return(MUS_AUDIO_DIRECTION_PLAYBACK);
  4687. default:
  4688. return(MUS_AUDIO_DIRECTION_RECORD);
  4689. }
  4690. #else
  4691. {
  4692. int card, device, alsa_device = 0;
  4693. snd_pcm_stream_t alsa_stream = SND_PCM_STREAM_PLAYBACK;
  4694. if ((!audio_initialized) &&
  4695. (mus_audio_initialize() != MUS_NO_ERROR))
  4696. return(MUS_ERROR);
  4697. card = MUS_AUDIO_SYSTEM(dev);
  4698. device = MUS_AUDIO_DEVICE(dev);
  4699. to_alsa_device(device, &alsa_device, &alsa_stream);
  4700. if (card > 0 || alsa_device > 0)
  4701. return(alsa_mus_error(MUS_AUDIO_CANT_READ, NULL));
  4702. return(alsa_stream);
  4703. }
  4704. #endif
  4705. }
  4706. #endif
  4707. int mus_audio_device_channels(int dev)
  4708. {
  4709. #if MUS_JACK
  4710. if (api == MUS_JACK_API)
  4711. {
  4712. return(sndjack_num_channels_allocated);
  4713. }
  4714. #endif
  4715. #if HAVE_ALSA
  4716. if (api == MUS_ALSA_API)
  4717. {
  4718. return(alsa_chans(dev, NULL));
  4719. }
  4720. #endif
  4721. return(2); /* netbsd hpux sun mac and oss with quibbles */
  4722. }
  4723. mus_sample_t mus_audio_compatible_sample_type(int dev) /* snd-dac and sndplay */
  4724. {
  4725. #if HAVE_ALSA
  4726. if (api == MUS_ALSA_API)
  4727. {
  4728. int err;
  4729. mus_sample_t ival[32];
  4730. err = alsa_sample_types(dev, 32, ival);
  4731. if (err != MUS_ERROR)
  4732. {
  4733. int i;
  4734. for (i = 1; i <= (int)(ival[0]); i++)
  4735. if (ival[i] == MUS_AUDIO_COMPATIBLE_SAMPLE_TYPE)
  4736. return(MUS_AUDIO_COMPATIBLE_SAMPLE_TYPE);
  4737. for (i = 1; i <= (int)(ival[0]); i++)
  4738. if ((ival[i] == MUS_BINT) || (ival[i] == MUS_LINT) ||
  4739. (ival[i] == MUS_BFLOAT) || (ival[i] == MUS_LFLOAT) ||
  4740. (ival[i] == MUS_BSHORT) || (ival[i] == MUS_LSHORT))
  4741. return(ival[i]);
  4742. for (i = 1; i <= (int)(ival[0]); i++)
  4743. if ((ival[i] == MUS_MULAW) || (ival[i] == MUS_ALAW) ||
  4744. (ival[i] == MUS_UBYTE) || (ival[i] == MUS_BYTE))
  4745. return(ival[i]);
  4746. return(ival[1]);
  4747. }
  4748. }
  4749. #endif
  4750. #if MUS_JACK
  4751. if (api == MUS_JACK_API)
  4752. return(MUS_COMP_FLOAT);
  4753. #endif
  4754. return(MUS_AUDIO_COMPATIBLE_SAMPLE_TYPE);
  4755. }
  4756. static mus_sample_t look_for_sample_type (mus_sample_t *mixer_vals, mus_sample_t samp_type)
  4757. {
  4758. int i, lim;
  4759. lim = mixer_vals[0];
  4760. for (i = 1; i <= lim; i++)
  4761. if (mixer_vals[i] == samp_type)
  4762. return(samp_type);
  4763. return(MUS_UNKNOWN_SAMPLE);
  4764. }
  4765. mus_sample_t mus_audio_device_sample_type(int dev) /* snd-dac */
  4766. {
  4767. mus_sample_t mixer_vals[16];
  4768. mus_sample_t samp_type;
  4769. /* we return the new sample type, so mixer_vals is just a local collector of possible sample types */
  4770. mixer_vals[0] = MUS_UNKNOWN_SAMPLE;
  4771. #if (!WITH_AUDIO)
  4772. return(MUS_AUDIO_COMPATIBLE_SAMPLE_TYPE);
  4773. #endif
  4774. #if HAVE_OSS
  4775. if (api == MUS_OSS_API)
  4776. oss_sample_types(dev, mixer_vals);
  4777. #endif
  4778. #if HAVE_ALSA
  4779. if (api == MUS_ALSA_API)
  4780. alsa_sample_types(dev, 16, mixer_vals);
  4781. #endif
  4782. #if MUS_JACK
  4783. if (api == MUS_JACK_API)
  4784. {
  4785. mixer_vals[0] = (mus_sample_t)1;
  4786. mixer_vals[1] = MUS_COMP_FLOAT;
  4787. }
  4788. #endif
  4789. #if HAVE_SUN
  4790. mixer_vals[0] = (mus_sample_t)2;
  4791. mixer_vals[1] = MUS_LSHORT;
  4792. mixer_vals[2] = MUS_MULAW;
  4793. #endif
  4794. #if __APPLE__
  4795. mixer_vals[0] = (mus_sample_t)1;
  4796. #if MUS_LITTLE_ENDIAN
  4797. mixer_vals[1] = MUS_LFLOAT;
  4798. #else
  4799. mixer_vals[1] = MUS_BFLOAT;
  4800. #endif
  4801. #endif
  4802. #if __NetBSD__ || __OpenBSD__
  4803. netbsd_sample_types(dev, mixer_vals);
  4804. #endif
  4805. samp_type = look_for_sample_type(mixer_vals, MUS_AUDIO_COMPATIBLE_SAMPLE_TYPE);
  4806. if (samp_type != MUS_UNKNOWN_SAMPLE)
  4807. return(samp_type);
  4808. #if MUS_LITTLE_ENDIAN
  4809. samp_type = look_for_sample_type(mixer_vals, MUS_LFLOAT);
  4810. if (samp_type == MUS_UNKNOWN_SAMPLE)
  4811. {
  4812. samp_type = look_for_sample_type(mixer_vals, MUS_LSHORT);
  4813. if (samp_type == MUS_UNKNOWN_SAMPLE)
  4814. samp_type = mixer_vals[1];
  4815. }
  4816. #else
  4817. samp_type = look_for_sample_type(mixer_vals, MUS_BFLOAT);
  4818. if (samp_type == MUS_UNKNOWN_SAMPLE)
  4819. {
  4820. samp_type = look_for_sample_type(mixer_vals, MUS_BSHORT);
  4821. if (samp_type == MUS_UNKNOWN_SAMPLE)
  4822. samp_type = mixer_vals[1];
  4823. }
  4824. #endif
  4825. return(samp_type);
  4826. }
  4827. #else
  4828. /* not WITH_AUDIO */
  4829. int mus_audio_open_output(int dev, int srate, int chans, mus_sample_t samp_type, int size) {return(-1);}
  4830. int mus_audio_open_input(int dev, int srate, int chans, mus_sample_t samp_type, int size) {return(-1);}
  4831. int mus_audio_write(int line, char *buf, int bytes) {return(-1);}
  4832. int mus_audio_close(int line) {return(-1);}
  4833. int mus_audio_read(int line, char *buf, int bytes) {return(-1);}
  4834. int mus_audio_initialize(void) {return(-1);}
  4835. char *mus_audio_moniker(void) {return((char *)"no audio support");}
  4836. void mus_reset_audio_c(void) {}
  4837. int mus_audio_device_channels(int dev) {return(0);}
  4838. mus_sample_t mus_audio_compatible_sample_type(int dev) {return(MUS_UNKNOWN_SAMPLE);}
  4839. mus_sample_t mus_audio_device_sample_type(int dev) {return(MUS_UNKNOWN_SAMPLE);}
  4840. #if __APPLE__
  4841. bool mus_audio_output_properties_mutable(bool mut) {return(false);}
  4842. #endif
  4843. #endif