audio.c 168 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/* Audio hardware handlers (OSS, ALSA, Sun, Windows, Mac OSX, Jack, HPUX, NetBSD, OpenBSD, pulseaudio, portaudio) 
 *
 * In many cases, only callback driven transfers are supported, so ideally we'd have:
 * int mus_audio_playback(caller_data, start_func, fill_func, end_func)
 *   returns error indication or MUS_NO_ERROR
 *   calls start_func at startup: void start(caller_data, ...)?
 *   each times it needs a bufferfull, calls fill_func: bool fill(caller_data, void *buf, buf_size_in_samples, buf_data_type)
 *     perhaps returns false to signal normal quit?
 *   at end (either via fill or some interrupt), calls end(caller_data, ...)?
 */
11 12 13 14

/*
 * layout of this file:
 *    error handlers
15
 *    OSS
16
 *    ALSA
17
 *    Sun
18 19 20 21
 *    Windows 95/98
 *    OSX
 *    JACK
 *    HPUX
22 23
 *    OpenBSD
 *    NetBSD
24
 *    PulseAudio (in progress?)
25
 *    PortAudio
26 27 28
 */

/*
29 30
 * int mus_audio_open_output(int dev, int srate, int chans, mus_sample_t samp_type, int size)
 * int mus_audio_open_input(int dev, int srate, int chans, mus_sample_t samp_type, int size)
31 32 33 34 35 36 37
 * int mus_audio_write(int line, char *buf, int bytes)
 * int mus_audio_close(int line)
 * int mus_audio_read(int line, char *buf, int bytes)
 * int mus_audio_initialize(void) does whatever is needed to get set up
 * char *mus_audio_moniker(void) returns some brief description of the overall audio setup (don't free return string).
 */

38
#include "mus-config.h"
39

40
#if USE_SND && __APPLE__ && USE_MOTIF
41 42 43 44 45 46 47 48 49
  #undef USE_MOTIF
  #define USE_NO_GUI 1
  /* Xt's Boolean (/usr/include/X11/Intrinsic.h = char) collides with MacTypes.h Boolean, (actually,
   *   unsigned char in /Developer/SDKs/MacOSX10.4u.sdk/System/Library/Frameworks/CoreFoundation.framework/Versions/A/Headers/CFBase.h)
   *   but we want snd.h for other stuff, so, if Motif is in use, don't load its headers at this time
   *   perhaps we could use the -funsigned-char switch in gcc
   */
#endif

50
#if USE_SND && __APPLE__ && HAVE_RUBY
51 52 53 54 55 56 57 58 59 60 61 62
  /* if using Ruby, OpenTransport.h T_* definitions collide with Ruby's -- it isn't needed here, so... */
  #define REDEFINE_HAVE_RUBY 1
  #undef HAVE_RUBY
#endif

#if USE_SND
  #include "snd.h"
#else
  #define PRINT_BUFFER_SIZE 512
  #define LABEL_BUFFER_SIZE 64
#endif

63
#if USE_SND && __APPLE__
64 65 66 67 68 69 70 71 72
  #define USE_MOTIF 1
  #undef USE_NO_GUI
  #if REDEFINE_HAVE_RUBY
    #define HAVE_RUBY 1
  #endif
#endif

#include <math.h>
#include <stdio.h>
73
#include <fcntl.h>
74 75
#include <errno.h>
#include <stdlib.h>
76 77
#ifndef _MSC_VER
  #include <unistd.h>
78
#endif
79
#include <string.h>
80

81
#ifdef __APPLE__
82 83 84 85 86
#include <CoreServices/CoreServices.h>
#include <CoreAudio/CoreAudio.h>
/* these pull in stdbool.h apparently, so they have to precede sndlib.h */
#endif

87 88 89 90 91 92 93
/* #define HAVE_JACK_IN_LINUX (MUS_JACK && __linux__) */
/* using JACK on GNU/linux, GNU/kFreeBSD and GNU/Hurd is all the same */
#if ((defined __linux__) || ((defined __FreeBSD_kernel__) && (defined __GLIBC__)) || (defined __GNU__))
  #define HAVE_JACK_IN_LINUX MUS_JACK
#else
  #define HAVE_JACK_IN_LINUX 0
#endif
94

95 96 97
#include "_sndlib.h"
#include "sndlib-strings.h"

98 99 100
#if WITH_AUDIO

enum {MUS_AUDIO_IGNORED, MUS_AUDIO_DUPLEX_DEFAULT, MUS_AUDIO_LINE_OUT,
101 102 103 104 105
      MUS_AUDIO_LINE_IN, MUS_AUDIO_MICROPHONE, MUS_AUDIO_SPEAKERS, MUS_AUDIO_DIGITAL_OUT,
      MUS_AUDIO_DAC_OUT, MUS_AUDIO_MIXER, MUS_AUDIO_AUX_OUTPUT
};


106 107
#define mus_standard_error(Error_Type, Error_Message) \
  mus_print("%s\n  [%s[%d] %s]", Error_Message, __FILE__, __LINE__, __func__)
108

109 110
#define mus_standard_io_error(Error_Type, IO_Func, IO_Name) \
  mus_print("%s %s: %s\n  [%s[%d] %s]", IO_Func, IO_Name, strerror(errno), __FILE__, __LINE__, __func__)
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127


static char *version_name = NULL;
static bool audio_initialized = false;




/* ------------------------------- OSS ----------------------------------------- */

/* Thanks to Yair K. for OSS v4 changes.  22-Jan-08 */

#if (HAVE_OSS || HAVE_ALSA || HAVE_JACK_IN_LINUX)
/* actually it's not impossible that someday we'll have ALSA but not OSS... */
#define AUDIO_OK 1

#include <sys/ioctl.h>
128
#include <sys/soundcard.h>
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149

#if ((SOUND_VERSION > 360) && (defined(OSS_SYSINFO)))
  #define NEW_OSS 1
#endif

#define MUS_OSS_WRITE_RATE     SNDCTL_DSP_SPEED
#define MUS_OSS_WRITE_CHANNELS SNDCTL_DSP_CHANNELS
#define MUS_OSS_SET_FORMAT     SNDCTL_DSP_SETFMT
#define MUS_OSS_GET_FORMATS    SNDCTL_DSP_GETFMTS

#define DAC_NAME "/dev/dsp"
#define MIXER_NAME "/dev/mixer"
/* some programs use /dev/audio */

/* there can be more than one sound card installed, and a card can be handled through
 * more than one /dev/dsp device, so we can't use a global dac device here.
 * The caller has to keep track of the various cards (via AUDIO_SYSTEM) --
 * I toyed with embedding all that in mus_audio_open_output and mus_audio_write, but
 * decided it's better to keep them explicit -- the caller may want entirely
 * different (non-synchronous) streams going to the various cards.  This same
 * code (AUDIO_SYSTEM(n)->devn) should work in Windoze (see below), and
150
 * might work on the Mac -- something for a rainy day...
151 152
 */

153
#define return_error_exit(Message_Type, Audio_Line, Ur_Message) \
154 155 156 157 158 159 160 161
  do { \
       char *Message; Message = Ur_Message; \
       if (Audio_Line != -1) \
          linux_audio_close(Audio_Line); \
       if ((Message) && (strlen(Message) > 0)) \
         { \
           mus_print("%s\n  [%s[%d] %s]", \
                     Message, \
162
                     __FILE__, __LINE__, __func__); \
163 164 165 166
           free(Message); \
         } \
       else mus_print("%s\n  [%s[%d] %s]", \
                      mus_error_type_to_string(Message_Type), \
167
                      __FILE__, __LINE__, __func__); \
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
       return(MUS_ERROR); \
     } while (false)

static int FRAGMENTS = 4;
static int FRAGMENT_SIZE = 12;
static bool fragments_locked = false;

/* defaults here are FRAGMENTS 16 and FRAGMENT_SIZE 12; these values however
 * cause about a .5 second delay, which is not acceptable in "real-time" situations.
 *
 * this changed 22-May-01: these are causing more trouble than they're worth
 */

static void oss_mus_oss_set_buffers(int num, int size) {FRAGMENTS = num; FRAGMENT_SIZE = size; fragments_locked = true;}

#define MAX_SOUNDCARDS 8
#define MAX_DSPS 8
#define MAX_MIXERS 8
/* there can be (apparently) any number of mixers and dsps per soundcard, but 8 is enough! */

static int *audio_fd = NULL; 
static int *audio_open_ctr = NULL; 
static int *audio_dsp = NULL; 
static int *audio_mixer = NULL; 
static int *audio_mode = NULL; 

static int sound_cards = 0;
195 196 197
#ifdef NEW_OSS
  static int new_oss_running = 0;
#endif
198 199 200 201
static char *dev_name = NULL;

static char *oss_mus_audio_moniker(void)
{
202
  if (!version_name) version_name = (char *)calloc(LABEL_BUFFER_SIZE, sizeof(char));
203 204
  if (SOUND_VERSION < 361)
    {
205 206 207
      char version[LABEL_BUFFER_SIZE];
      snprintf(version, LABEL_BUFFER_SIZE, "%d", SOUND_VERSION);
      snprintf(version_name, LABEL_BUFFER_SIZE, "OSS %c.%c.%c", version[0], version[1], version[2]);
208 209
    }
  else
210
    snprintf(version_name, LABEL_BUFFER_SIZE, "OSS %x.%x.%x", 
211 212 213 214 215 216 217 218 219 220
		 (SOUND_VERSION >> 16) & 0xff, 
		 (SOUND_VERSION >> 8) & 0xff, 
		 SOUND_VERSION & 0xff);
  return(version_name);
}

static char *dac_name(int sys, int offset)
{
  if ((sys < sound_cards) && (audio_mixer[sys] >= -1))
    {
221
      snprintf(dev_name, LABEL_BUFFER_SIZE, "%s%d", DAC_NAME, audio_dsp[sys] + offset);
222 223 224 225 226 227 228 229 230 231 232 233 234 235
      return(dev_name);
    }
  return((char *)DAC_NAME);
}

#define MIXER_SIZE SOUND_MIXER_NRDEVICES
static int **mixer_state = NULL;
static int *init_srate = NULL, *init_chans = NULL, *init_format = NULL;

static int oss_mus_audio_initialize(void) 
{
  /* here we need to set up the map of /dev/dsp and /dev/mixer to a given system */
  /* since this info is not passed to us by OSS, we have to work at it... */
  /* for the time being, I'll ignore auxiliary dsp and mixer ports (each is a special case) */
236
  int amp, old_mixer_amp, old_dsp_amp, new_mixer_amp;
237 238 239 240 241 242 243 244 245
  int devmask;
#ifdef NEW_OSS
  int status, ignored;
  oss_sysinfo sysinfo;
  static mixer_info mixinfo;
  int sysinfo_ok = 0;
#endif
  if (!audio_initialized)
    {
246
      int i, num_mixers, num_dsps, nmix, ndsp, err = 0, fd = -1, responsive_field;
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
      audio_initialized = true;
      audio_fd = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
      audio_open_ctr = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
      audio_dsp = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
      audio_mixer = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
      audio_mode = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
      dev_name = (char *)calloc(LABEL_BUFFER_SIZE, sizeof(char));
      init_srate = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
      init_chans = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
      init_format = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
      mixer_state = (int **)calloc(MAX_SOUNDCARDS, sizeof(int *));
      for (i = 0; i < MAX_SOUNDCARDS; i++) mixer_state[i] = (int *)calloc(MIXER_SIZE, sizeof(int));
      for (i = 0; i < MAX_SOUNDCARDS; i++)
	{
	  audio_fd[i] = -1;
	  audio_open_ctr[i] = 0;
	  audio_dsp[i] = -1;
	  audio_mixer[i] = -1;
	}

      num_mixers = MAX_MIXERS;
      num_dsps = MAX_DSPS;
#ifdef NEW_OSS
      fd = open(DAC_NAME, O_WRONLY | O_NONBLOCK, 0);
      if (fd == -1) fd = open(MIXER_NAME, O_RDONLY | O_NONBLOCK, 0);
      if (fd != -1)
	{
	  status = ioctl(fd, OSS_GETVERSION, &ignored);
	  new_oss_running = (status == 0);
	  if (new_oss_running)
	    {
	      status = ioctl(fd, OSS_SYSINFO, &sysinfo);
	      sysinfo_ok = (status == 0);
	    }
	  if ((new_oss_running) && (sysinfo_ok))
	    {
	      num_mixers = sysinfo.nummixers;
	      num_dsps = sysinfo.numaudios;
	    }
	  close(fd);
	}
#endif

      /* need to get which /dev/dsp lines match which /dev/mixer lines,
       *   find out how many separate systems (soundcards) are available,
       *   fill the audio_dsp and audio_mixer arrays with the system-related numbers,
       * since we have no way to tell from OSS info which mixers/dsps are the
       *   main ones, we'll do some messing aound to try to deduce this info.
       * for example, SB uses two dsp ports and two mixers per card, whereas
       *  Ensoniq uses 2 dsps and 1 mixer.
       * 
       * the data we are gathering here:
299 300
       *   int audio_dsp[MAX_SOUNDCARDS] -> main_dsp_port[n] (-1 => no such system dsp)
       *   int audio_mixer[MAX_SOUNDCARDS] -> main_mixer_port[n]
301 302 303 304 305 306 307 308 309
       *   int sound_cards = 0 -> usable systems
       * all auxiliary ports are currently ignored (SB equalizer, etc)
       */
      sound_cards = 0;
      ndsp = 0;
      nmix = 0;
      while ((nmix < num_mixers) && 
	     (ndsp < num_dsps))
	{
310 311
	  char dname[LABEL_BUFFER_SIZE];
	  int md;
312 313 314 315 316 317 318 319
	  /* for each mixer, find associated main dsp (assumed to be first in /dev/dsp ordering) */
	  /*   if mixer's dsp overlaps or we run out of dsps first, ignore it (aux mixer) */
	  /* our by-guess-or-by-gosh method here is to try to open the mixer.
	   *   if that fails, quit (if very first, try at least to get the dsp setup)
	   *   find volume field, if none, go on, else read current volume
	   *   open next unchecked dsp, try to set volume, read current, if different we found a match -- set and go on.
	   *     if no change, move to next dsp and try again, if no more dsps, quit (checking for null case as before)
	   */
320
	  snprintf(dname, LABEL_BUFFER_SIZE, "%s%d", MIXER_NAME, nmix);
321 322 323 324 325 326 327
	  md = open(dname, O_RDWR, 0);
	  if (md == -1)
	    {
	      if (errno == EBUSY) 
		{
		  mus_print("%s is busy: can't access it [%s[%d] %s]", 
			    dname,
328
			    __FILE__, __LINE__, __func__); 
329 330 331 332 333
		  nmix++;
		  continue;
		}
	      else break;
	    }
334
	  snprintf(dname, LABEL_BUFFER_SIZE, "%s%d", DAC_NAME, ndsp);
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
	  fd = open(dname, O_RDWR | O_NONBLOCK, 0);
	  if (fd == -1) fd = open(dname, O_RDONLY | O_NONBLOCK, 0);
 	  if (fd == -1) fd = open(dname, O_WRONLY | O_NONBLOCK, 0); /* some output devices need this */
	  if (fd == -1)
	    {
	      close(md); 
	      if (errno == EBUSY) /* in linux /usr/include/asm-generic/errno-base.h */
		{
		  fprintf(stderr, "%s is busy: can't access it\n", dname); 
		  ndsp++;
		  continue;
		}
	      else 
		{
		  if ((errno != ENXIO) && (errno != ENODEV) && (errno != ENOENT))
		    fprintf(stderr, "%s: %s! ", dname, strerror(errno));
		  break;
		}
	    }
#ifdef NEW_OSS				  
	  status = ioctl(md, SOUND_MIXER_INFO, &mixinfo);
#endif
	  err = ioctl(md, SOUND_MIXER_READ_DEVMASK, &devmask);
	  responsive_field = SOUND_MIXER_VOLUME;
	  for (i = 0; i < SOUND_MIXER_NRDEVICES; i++)
	    if ((1 << i) & devmask)
	      {
		responsive_field = i;
		break;
	      }
	  if (!err)
	    {
	      err = ioctl(md, MIXER_READ(responsive_field), &old_mixer_amp);
	      if (!err)
		{
		  err = ioctl(fd, MIXER_READ(responsive_field), &old_dsp_amp);
		  if ((!err) && (old_dsp_amp == old_mixer_amp))
		    {
		      if (old_mixer_amp == 0) amp = 50; else amp = 0; /* 0..100 */
		      err = ioctl(fd, MIXER_WRITE(responsive_field), &amp);
		      if (!err)
			{
			  err = ioctl(md, MIXER_READ(responsive_field), &new_mixer_amp);
			  if (!err)
			    {
			      if (new_mixer_amp == amp)
				{
				  /* found one! */
				  audio_dsp[sound_cards] = ndsp; ndsp++;
				  audio_mixer[sound_cards] = nmix; nmix++;
				  sound_cards++;
				}
			      else ndsp++;
			      err = ioctl(fd, MIXER_WRITE(responsive_field), &old_dsp_amp);
			    }
			  else nmix++;
			}
		      else ndsp++;
		    }
		  else ndsp++;
		}
	      else nmix++;
	    }
	  else nmix++;
	  close(fd);
	  close(md);
	}
      if (sound_cards == 0)
	{
 	  fd = open(DAC_NAME, O_WRONLY | O_NONBLOCK, 0);
	  if (fd != -1)
	    {
	      sound_cards = 1;
	      audio_dsp[0] = 0;
	      audio_mixer[0] = -2; /* hmmm -- need a way to see /dev/dsp as lonely outpost */
	      close(fd);
 	      fd = open(MIXER_NAME, O_RDONLY | O_NONBLOCK, 0);
	      if (fd == -1)
		audio_mixer[0] = -3;
	      else close(fd);
	    }
	}
    }
  return(MUS_NO_ERROR);
}

static int linux_audio_open(const char *pathname, int flags, mode_t mode, int system)
{
  /* sometimes this is simply searching for a device (so failure is not a mus_error) */
  if (audio_fd[system] == -1) 
    {
      audio_fd[system] = open(pathname, flags, mode);
      audio_open_ctr[system] = 0;
    }
  else audio_open_ctr[system]++;
  return(audio_fd[system]);
}

static int linux_audio_open_with_error(const char *pathname, int flags, mode_t mode, int system)
{
  int fd;
  static bool already_warned = false;
  if ((system < 0) ||
      (system >= MAX_SOUNDCARDS))
    return(-1);

  fd = linux_audio_open(pathname, flags, mode, system);
  if ((fd == -1) &&
      (!already_warned))
    {
      already_warned = true;
446
      mus_standard_io_error(MUS_AUDIO_CANT_OPEN,
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
			    ((mode == O_RDONLY) ? "open read" : 
			     (mode == O_WRONLY) ? "open write" : "open read/write"),
			    pathname);
    }
  return(fd);
}

static int find_system(int line)
{
  int i;
  for (i = 0; i < sound_cards; i++)
    if (line == audio_fd[i])
      return(i);
  return(MUS_ERROR);
}

static int linux_audio_close(int fd)
{
  if (fd != -1)
    {
      int err = 0, sys;
      sys = find_system(fd);
      if (sys != -1)
	{
	  if (audio_open_ctr[sys] > 0) 
	    audio_open_ctr[sys]--;
	  else 
	    {
	      err = close(fd);
	      audio_open_ctr[sys] = 0;
	      audio_fd[sys] = -1;
	    }
	}
      else err = close(fd);
481
      if (err) return_error_exit(MUS_AUDIO_CANT_CLOSE, -1,
482 483 484 485 486 487 488
				 mus_format("close %d failed: %s",
					    fd, strerror(errno)));
    }
  /* is this an error? */
  return(MUS_NO_ERROR);
}

489
static int to_oss_sample_type(mus_sample_t snd_format)
490 491 492
{
  switch (snd_format)
    {
493 494 495 496 497 498 499 500
    case MUS_BYTE:    return(AFMT_S8);     
    case MUS_BSHORT:  return(AFMT_S16_BE); 
    case MUS_UBYTE:   return(AFMT_U8);     
    case MUS_MULAW:   return(AFMT_MU_LAW); 
    case MUS_ALAW:    return(AFMT_A_LAW);  
    case MUS_LSHORT:  return(AFMT_S16_LE); 
    case MUS_UBSHORT: return(AFMT_U16_BE); 
    case MUS_ULSHORT: return(AFMT_U16_LE); 
501
#ifdef NEW_OSS
502 503
    case MUS_LINT:    return(AFMT_S32_LE); 
    case MUS_BINT:    return(AFMT_S32_BE); 
504
#endif
505
    default: break;
506 507 508 509 510 511
    }
  return(MUS_ERROR);
}

static bool fragment_set_failed = false;

512
static int oss_mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
513
{
514
  int oss_sample_type, buffer_info, audio_out = -1, sys, dev;
515 516 517 518 519 520
  char *dev_name;
#ifndef NEW_OSS
  int stereo;
#endif
  sys = MUS_AUDIO_SYSTEM(ur_dev);
  dev = MUS_AUDIO_DEVICE(ur_dev);
521 522 523 524 525 526
  oss_sample_type = to_oss_sample_type(samp_type); 
  if (oss_sample_type == MUS_ERROR) 
    return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, -1,
		      mus_format("sample type %d (%s) not available",
				 samp_type, 
				 mus_sample_type_name(samp_type)));
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563

  if (dev == MUS_AUDIO_DEFAULT)
    audio_out = linux_audio_open_with_error(dev_name = dac_name(sys, 0), 
					    O_WRONLY, 0, sys);
  else audio_out = linux_audio_open_with_error(dev_name = dac_name(sys, (dev == MUS_AUDIO_AUX_OUTPUT) ? 1 : 0), 
					       O_RDWR, 0, sys);
  if (audio_out == -1) return(MUS_ERROR);

  /* ioctl(audio_out, SNDCTL_DSP_RESET, 0); */ /* causes clicks */
  if ((fragments_locked) && 
      (!(fragment_set_failed)) &&
      ((dev == MUS_AUDIO_DUPLEX_DEFAULT) || 
       (size != 0))) /* only set if user has previously called set_oss_buffers */
    {
      buffer_info = (FRAGMENTS << 16) | (FRAGMENT_SIZE);
      if (ioctl(audio_out, SNDCTL_DSP_SETFRAGMENT, &buffer_info) == -1)
        {
          /* older Linuces (or OSS's?) refuse to handle the fragment reset if O_RDWR used --
           * someone at OSS forgot to update the version number when this was fixed, so
           * I have no way to get around this except to try and retry...
           */
          linux_audio_close(audio_out);
          audio_out = linux_audio_open_with_error(dev_name = dac_name(sys, (dev == MUS_AUDIO_AUX_OUTPUT) ? 1 : 0), 
						  O_WRONLY, 0, sys);
	  if (audio_out == -1) return(MUS_ERROR);
          buffer_info = (FRAGMENTS << 16) | (FRAGMENT_SIZE);
          if (ioctl(audio_out, SNDCTL_DSP_SETFRAGMENT, &buffer_info) == -1) 
	    {
	      char *tmp;
	      tmp = mus_format("can't set %s fragments to: %d x %d",
			       dev_name, FRAGMENTS, FRAGMENT_SIZE); /* not an error if ALSA OSS-emulation */
	      fprintf(stderr, "%s\n", tmp);
	      fragment_set_failed = true;
	      free(tmp);
	    }
        }
    }
564 565 566 567 568 569
  if ((ioctl(audio_out, MUS_OSS_SET_FORMAT, &oss_sample_type) == -1) || 
      (oss_sample_type != to_oss_sample_type(samp_type)))
    return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, audio_out,
		      mus_format("sample type %d (%s) not available on %s",
				 samp_type, 
				 mus_sample_type_name(samp_type), 
570 571 572
				 dev_name));
#ifdef NEW_OSS
  if (ioctl(audio_out, MUS_OSS_WRITE_CHANNELS, &chans) == -1) 
573
    return_error_exit(MUS_AUDIO_CHANNELS_NOT_AVAILABLE, audio_out,
574 575 576 577 578 579
		      mus_format("can't get %d channels on %s",
				 chans, dev_name));
#else
  if (chans == 2) stereo = 1; else stereo = 0;
  if ((ioctl(audio_out, SNDCTL_DSP_STEREO, &stereo) == -1) || 
      ((chans == 2) && (stereo == 0)))
580
    return_error_exit(MUS_AUDIO_CHANNELS_NOT_AVAILABLE, audio_out,
581 582 583 584
		      mus_format("can't get %d channels on %s",
				 chans, dev_name));
#endif
  if (ioctl(audio_out, MUS_OSS_WRITE_RATE, &srate) == -1) 
585
    return_error_exit(MUS_AUDIO_SRATE_NOT_AVAILABLE, audio_out,
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
		      mus_format("can't set srate of %s to %d",
				 dev_name, srate));
  /* http://www.4front-tech.com/pguide/audio.html says this order has to be followed */
  return(audio_out);
}

static int oss_mus_audio_write(int line, char *buf, int bytes)
{
  int err;
  if (line < 0) return(-1);
  errno = 0;
  err = write(line, buf, bytes);
  if (err != bytes)
    {
      if (errno != 0)
601
	return_error_exit(MUS_AUDIO_WRITE_ERROR, -1,
602
			  mus_format("write error: %s", strerror(errno)));
603
      else return_error_exit(MUS_AUDIO_WRITE_ERROR, -1,
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
			     mus_format("wrote %d bytes of requested %d", err, bytes));
    }
  return(MUS_NO_ERROR);
}

static int oss_mus_audio_close(int line)
{
  return(linux_audio_close(line));
}

static int oss_mus_audio_read(int line, char *buf, int bytes)
{
  int err;
  if (line < 0) return(-1);
  errno = 0;
  err = read(line, buf, bytes);
  if (err != bytes) 
    {
      if (errno != 0)
623
	return_error_exit(MUS_AUDIO_READ_ERROR, -1,
624
			  mus_format("read error: %s", strerror(errno)));
625
      else return_error_exit(MUS_AUDIO_READ_ERROR, -1,
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
			     mus_format("read %d bytes of requested %d", err, bytes));
    }
  return(MUS_NO_ERROR);
}

static char *oss_unsrc(int srcbit)
{
  if (srcbit == 0)
    return(mus_strdup("none"));
  else
    {
      bool need_and = false;
      char *buf;
      buf = (char *)calloc(PRINT_BUFFER_SIZE, sizeof(char));
      if (srcbit & SOUND_MASK_MIC) {need_and = true; strcat(buf, "mic");}
      if (srcbit & SOUND_MASK_LINE) {if (need_and) strcat(buf, " and "); need_and = true; strcat(buf, "line in");}
642
      if (srcbit & SOUND_MASK_CD) {if (need_and) strcat(buf, " and "); strcat(buf, "cd");}
643 644 645 646
      return(buf);
    }
}

647

648
static int oss_mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int requested_size)
649 650
{
  /* dev can be MUS_AUDIO_DEFAULT or MUS_AUDIO_DUPLEX_DEFAULT as well as the obvious others */
651
  int audio_fd = -1, oss_sample_type, buffer_info, sys, dev, srcbit, cursrc, err;
652 653 654 655 656 657
  char *dev_name;
#ifndef NEW_OSS
  int stereo;
#endif
  sys = MUS_AUDIO_SYSTEM(ur_dev);
  dev = MUS_AUDIO_DEVICE(ur_dev);
658 659 660 661 662 663
  oss_sample_type = to_oss_sample_type(samp_type);
  if (oss_sample_type == MUS_ERROR)
    return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, -1,
		      mus_format("sample type %d (%s) not available",
				 samp_type, 
				 mus_sample_type_name(samp_type)));
664 665 666 667

  if (((dev == MUS_AUDIO_DEFAULT) || (dev == MUS_AUDIO_DUPLEX_DEFAULT)) && (sys == 0))
    audio_fd = linux_audio_open(dev_name = dac_name(sys, 0), 
				O_RDWR, 0, sys);
668
  else audio_fd = linux_audio_open(dev_name = dac_name(sys, 0), O_RDONLY, 0, sys);
669 670 671
  if (audio_fd == -1)
    {
      if (dev == MUS_AUDIO_DUPLEX_DEFAULT)
672 673 674
	return_error_exit(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, -1,
		       mus_format("can't open %s: %s",
				  dev_name, strerror(errno)));
675
      if ((audio_fd = linux_audio_open(dev_name = dac_name(sys, 0), O_RDONLY, 0, sys)) == -1)
676 677
        {
          if ((errno == EACCES) || (errno == ENOENT))
678 679
	    return_error_exit(MUS_AUDIO_NO_READ_PERMISSION, -1,
			      mus_format("can't open %s: %s\n  to get input in Linux, we need read permission on /dev/dsp",
680 681
					 dev_name, 
					 strerror(errno)));
682 683
          else return_error_exit(MUS_AUDIO_NO_INPUT_AVAILABLE, -1,
				 mus_format("can't open %s: %s",
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
					    dev_name, 
					    strerror(errno)));
        }
    }
#ifdef SNDCTL_DSP_SETDUPLEX
  else 
    ioctl(audio_fd, SNDCTL_DSP_SETDUPLEX, &err); /* not always a no-op! */
#endif
  /* need to make sure the desired recording source is active -- does this actually have any effect? */
  switch (dev)
    {
    case MUS_AUDIO_MICROPHONE: srcbit = SOUND_MASK_MIC;                   break;
    case MUS_AUDIO_LINE_IN:    srcbit = SOUND_MASK_LINE;                  break;
    case MUS_AUDIO_DUPLEX_DEFAULT: 
    case MUS_AUDIO_DEFAULT:    srcbit = SOUND_MASK_LINE | SOUND_MASK_MIC; break;
    default:                   srcbit = 0;                                break;
700

701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
    }
  ioctl(audio_fd, MIXER_READ(SOUND_MIXER_RECSRC), &cursrc);
  srcbit = (srcbit | cursrc);
  ioctl(audio_fd, MIXER_WRITE(SOUND_MIXER_RECSRC), &srcbit);
  ioctl(audio_fd, MIXER_READ(SOUND_MIXER_RECSRC), &cursrc);
  if (cursrc != srcbit)
    {
      char *str1, *str2;
      str1 = oss_unsrc(srcbit);
      str2 = oss_unsrc(cursrc);
      mus_print("weird: tried to set recorder source to %s, but got %s?", str1, str2);
      free(str1);
      free(str2);
    }
  if ((fragments_locked) && (requested_size != 0))
    {
      buffer_info = (FRAGMENTS << 16) | (FRAGMENT_SIZE);
      ioctl(audio_fd, SNDCTL_DSP_SETFRAGMENT, &buffer_info);
    }
720 721 722 723 724 725
  if ((ioctl(audio_fd, MUS_OSS_SET_FORMAT, &oss_sample_type) == -1) ||
      (oss_sample_type != to_oss_sample_type(samp_type)))
    return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, audio_fd,
		      mus_format("can't set %s sample type to %d (%s)",
				 dev_name, samp_type, 
				 mus_sample_type_name(samp_type)));
726 727
#ifdef NEW_OSS
  if (ioctl(audio_fd, MUS_OSS_WRITE_CHANNELS, &chans) == -1) 
728
    return_error_exit(MUS_AUDIO_CHANNELS_NOT_AVAILABLE, audio_fd,
729 730 731 732 733 734
		      mus_format("can't get %d channels on %s",
				 chans, dev_name));
#else
  if (chans == 2) stereo = 1; else stereo = 0;
  if ((ioctl(audio_fd, SNDCTL_DSP_STEREO, &stereo) == -1) || 
      ((chans == 2) && (stereo == 0))) 
735 736 737
    return_error_exit(MUS_AUDIO_CHANNELS_NOT_AVAILABLE, audio_fd,
		      mus_format("can't get %d channels on %s",
				 chans, dev_name));
738 739
#endif
  if (ioctl(audio_fd, MUS_OSS_WRITE_RATE, &srate) == -1) 
740 741 742
    return_error_exit(MUS_AUDIO_SRATE_NOT_AVAILABLE, audio_fd,
		      mus_format("can't set srate to %d on %s",
				 srate, dev_name));
743 744 745 746
  return(audio_fd);
}


747
#if (!HAVE_ALSA) && (!HAVE_JACK_IN_LINUX)
748
static int oss_sample_types(int ur_dev, mus_sample_t *val)
749
{
750
  int fd, samp_types = 0, sys, ind;
751

752
  sys = MUS_AUDIO_SYSTEM(ur_dev);
753
  /* dev = MUS_AUDIO_DEVICE(ur_dev); */
754 755 756 757

  fd = open(dac_name(sys, 0), O_WRONLY, 0);
  if (fd == -1) fd = open(DAC_NAME, O_WRONLY, 0);
  if (fd == -1) 
758
    {
759
      return_error_exit(MUS_AUDIO_CANT_OPEN, -1,
760 761 762
			mus_format("can't open %s: %s",
				   DAC_NAME, strerror(errno)));
      return(MUS_ERROR);
763
    }
764
  
765
  ioctl(fd, MUS_OSS_GET_FORMATS, &samp_types);
766
  ind = 1;
767 768 769 770 771 772 773 774 775
  if (samp_types & (to_oss_sample_type(MUS_BSHORT)))  val[ind++] = MUS_BSHORT;
  if (samp_types & (to_oss_sample_type(MUS_LSHORT)))  val[ind++] = MUS_LSHORT;
  if (samp_types & (to_oss_sample_type(MUS_MULAW)))   val[ind++] = MUS_MULAW;
  if (samp_types & (to_oss_sample_type(MUS_ALAW)))    val[ind++] = MUS_ALAW;
  if (samp_types & (to_oss_sample_type(MUS_BYTE)))    val[ind++] = MUS_BYTE;
  if (samp_types & (to_oss_sample_type(MUS_UBYTE)))   val[ind++] = MUS_UBYTE;
  if (samp_types & (to_oss_sample_type(MUS_UBSHORT))) val[ind++] = MUS_UBSHORT;
  if (samp_types & (to_oss_sample_type(MUS_ULSHORT))) val[ind++] = MUS_ULSHORT;
  val[0] = (mus_sample_t)(ind - 1);
776 777
  return(MUS_NO_ERROR);
}
778
#endif
779

780

781 782


783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
/* ------------------------------- ALSA, OSS, Jack-in-Linux ----------------------------------- */

static int api = MUS_ALSA_API;
int mus_audio_api(void) {return(api);}

/* hopefully first call to sndlib will be this... */
static int probe_api(void);
static int (*vect_mus_audio_initialize)(void);

/* FIXME: add a suitable default for all other vectors
   so that a call happening before mus_audio_initialize
   can be detected */
/* I don't think this is necessary -- documentation discusses this
 * (mus_sound_initialize calls mus_audio_initialize)
 */

/* vectors for the rest of the sndlib api */
static void  (*vect_mus_oss_set_buffers)(int num, int size);
static char* (*vect_mus_audio_moniker)(void);
802 803
static int   (*vect_mus_audio_open_output)(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size);
static int   (*vect_mus_audio_open_input)(int ur_dev, int srate, int chans, mus_sample_t samp_type, int requested_size);
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
static int   (*vect_mus_audio_write)(int id, char *buf, int bytes);
static int   (*vect_mus_audio_read)(int id, char *buf, int bytes);
static int   (*vect_mus_audio_close)(int id);

/* vectors for the rest of the sndlib api */
int mus_audio_initialize(void) 
{
  return(probe_api());
}

void mus_oss_set_buffers(int num, int size) 
{
  vect_mus_oss_set_buffers(num, size);
}

#if HAVE_ALSA 
static char* alsa_mus_audio_moniker(void);
#endif

char* mus_audio_moniker(void) 
{
#if (HAVE_OSS && HAVE_ALSA)
  char *both_names;
  both_names = (char *)calloc(PRINT_BUFFER_SIZE, sizeof(char));
  /* need to be careful here since these use the same constant buffer */
  strcpy(both_names, oss_mus_audio_moniker());
  strcat(both_names, ", ");
  strcat(both_names, alsa_mus_audio_moniker());
  return(both_names); /* tiny memory leak ... */
#else
  return(vect_mus_audio_moniker());
#endif
}

838
int mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size) 
839
{
840
  return(vect_mus_audio_open_output(ur_dev, srate, chans, samp_type, size));
841 842
}

843
int mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int requested_size) 
844
{
845
  return(vect_mus_audio_open_input(ur_dev, srate, chans, samp_type, requested_size));
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
}

int mus_audio_write(int id, char *buf, int bytes) 
{
  return(vect_mus_audio_write(id, buf, bytes));
}

int mus_audio_read(int id, char *buf, int bytes) 
{
  return(vect_mus_audio_read(id, buf, bytes));
}

int mus_audio_close(int id) 
{
  return(vect_mus_audio_close(id));
}

#if HAVE_JACK_IN_LINUX
  static int jack_mus_audio_initialize(void);
#endif

#if (!HAVE_ALSA)
static int probe_api(void) 
{
#if HAVE_JACK_IN_LINUX
  {
    int jackprobe = jack_mus_audio_initialize();
    if (jackprobe == MUS_ERROR)
      {
#endif
  /* go for the oss api */
  api = MUS_OSS_API;
  vect_mus_audio_initialize = oss_mus_audio_initialize;
  vect_mus_oss_set_buffers = oss_mus_oss_set_buffers;
  vect_mus_audio_moniker = oss_mus_audio_moniker;
  vect_mus_audio_open_output = oss_mus_audio_open_output;
  vect_mus_audio_open_input = oss_mus_audio_open_input;
  vect_mus_audio_write = oss_mus_audio_write;
  vect_mus_audio_read = oss_mus_audio_read;
  vect_mus_audio_close = oss_mus_audio_close;
  return(vect_mus_audio_initialize());
#if HAVE_JACK_IN_LINUX
      }
    return(jackprobe);
  }
#endif
}
#endif

#endif


/* ------------------------------- ALSA ----------------------------------------- */
/*
900
 * Changed the names of the environment variables to use MUS, not SNDLIB.
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
 * reformatted and reorganized to be like the rest of the code
 * changed default device to "default"
 *    -- Bill 3-Feb-06
 *
 * error handling (mus_error) changed by Bill 14-Nov-02
 * 0.5 support removed by Bill 24-Mar-02
 *
 * changed for 0.9.x api by Fernando Lopez-Lezcano <nando@ccrma.stanford.edu>
 *
 *  sndlib "exports" only one soundcard with two directions (if they are available),
 *  and only deals with the alsa library pcm's. It does not scan for available
 *  cards and devices at the hardware level. Which device it uses can be defined by:
 *
 *  - setting variables in the environment (searched for in the following order):
 *    MUS_ALSA_PLAYBACK_DEVICE
 *       defines the name of the playback device
 *    MUS_ALSA_CAPTURE_DEVICE
 *       defines the name of the capture device
 *    MUS_ALSA_DEVICE
 *       defines the name of the playback and capture device
 *    use the first two if the playback and capture devices are different or the
 *    third if they are the same. 
 *  - if no variables are found in the environment sndlib tries to probe for a
 *    default device named "sndlib" (in alsa 0.9 devices are configured in 
 *    /usr/share/alsa/alsa.conf or in ~/.asoundrc)
 *  - if "sndlib" is not a valid device "hw:0,0" was used [but now it looks for "default"] (which by default should
 *    point to the first device of the first card
 *
 *  Some default settings are controllable through the environment as well:
 *    MUS_ALSA_BUFFER_SIZE = size of each buffer in frames
 *    MUS_ALSA_BUFFERS = number of buffers
 *
 * changed 18-Sep-00 by Bill: new error handling: old mus_audio_error folded into
 *  mus_error; mus_error itself should be used only for "real" errors -- things
 *  that can cause a throw (a kind of global jump elsewhere); use mus_print for informational
 *  stuff -- in Snd, mus_print will also save everything printed in the error dialog.
 *  In a few cases, I tried to fix the code to unwind before mus_error, and in others
 *  I've changed mus_error to mus_print, but some of these may be mistaken.
 *  Look for ?? below for areas where I'm not sure I rewrote code correctly.
 *
 * changed for 0.6.x api by Paul Barton-Davis, pbd@op.net
 *
 * changed for 0.5.x api by Fernando Lopez-Lezcano, nando@ccrma.stanford.edu
 *   04-10-2000:
 *     based on original 0.4.x code by Paul Barton-Davis (not much left of it :-)
 *     also Bill's code and Jaroslav Kysela (aplay.c and friends)
 *
 * Changes:
 * 04/25/2000: finished major rework, snd-dac now automatically decides which
 *             device or devices it uses for playback. Multiple device use is
 *             for now restricted to only two at most (more changes in Bill's
 *             needed to be able to support more). Four channel playback in 
 *             Ensoniq AudioPCI and relatives possible (with proper settings
 *             of the mixer) as well as using two separate cards. 
 * 04/11/2000: added reporting of alsa sound formats
*/

#if HAVE_ALSA

#if (!HAVE_OSS)
#define AUDIO_OK 1
#endif

#include <sys/ioctl.h>

966
#if HAVE_ALSA
967 968 969 970 971 972 973 974 975 976 977 978
  #include <alsa/asoundlib.h>
#else
  #include <sys/asoundlib.h>
#endif

#if SND_LIB_VERSION < ((0<<16)|(6<<8)|(0))
  #error ALSA version is too old -- audio.c needs 0.9 or later
#endif

/* prototypes for the alsa sndlib functions */
static int   alsa_mus_audio_initialize(void);
static void  alsa_mus_oss_set_buffers(int num, int size);
979 980
static int   alsa_mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size);
static int   alsa_mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int requested_size);
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
static int   alsa_mus_audio_write(int id, char *buf, int bytes);
static int   alsa_mus_audio_read(int id, char *buf, int bytes);
static int   alsa_mus_audio_close(int id);

/* decide which api to activate */

static int probe_api(void) 
{
#if HAVE_JACK_IN_LINUX
  int jackprobe;
  jackprobe = jack_mus_audio_initialize();
  if (jackprobe == MUS_ERROR)
    {
#endif
    int card = -1;
    if ((snd_card_next(&card) >= 0) && (card >= 0))
      {
	/* the alsa library has detected one or more cards */
	api = MUS_ALSA_API;
	vect_mus_audio_initialize = alsa_mus_audio_initialize;
	vect_mus_oss_set_buffers = alsa_mus_oss_set_buffers;
	vect_mus_audio_moniker = alsa_mus_audio_moniker;
	vect_mus_audio_open_output = alsa_mus_audio_open_output;
	vect_mus_audio_open_input = alsa_mus_audio_open_input;
	vect_mus_audio_write = alsa_mus_audio_write;
	vect_mus_audio_read = alsa_mus_audio_read;
	vect_mus_audio_close = alsa_mus_audio_close;
      } 
    else 
      {
	/* go for the oss api */
        api = MUS_OSS_API;
	vect_mus_audio_initialize = oss_mus_audio_initialize;
	vect_mus_oss_set_buffers = oss_mus_oss_set_buffers;
	vect_mus_audio_moniker = oss_mus_audio_moniker;
	vect_mus_audio_open_output = oss_mus_audio_open_output;
	vect_mus_audio_open_input = oss_mus_audio_open_input;
	vect_mus_audio_write = oss_mus_audio_write;
	vect_mus_audio_read = oss_mus_audio_read;
	vect_mus_audio_close = oss_mus_audio_close;
      }
    /* will the _real_ mus_audio_initialize please stand up? */
    return(vect_mus_audio_initialize());
#if HAVE_JACK_IN_LINUX
    }
  return(jackprobe);
#endif
}

1030
/* convert a sndlib sample type to an alsa sample type */
1031

1032
static snd_pcm_format_t to_alsa_format(mus_sample_t snd_format)
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
{
  switch (snd_format) 
    {
    case MUS_BYTE:     return(SND_PCM_FORMAT_S8); 
    case MUS_UBYTE:    return(SND_PCM_FORMAT_U8); 
    case MUS_MULAW:    return(SND_PCM_FORMAT_MU_LAW); 
    case MUS_ALAW:     return(SND_PCM_FORMAT_A_LAW); 
    case MUS_BSHORT:   return(SND_PCM_FORMAT_S16_BE); 
    case MUS_LSHORT:   return(SND_PCM_FORMAT_S16_LE); 
    case MUS_UBSHORT:  return(SND_PCM_FORMAT_U16_BE); 
    case MUS_ULSHORT:  return(SND_PCM_FORMAT_U16_LE); 
    case MUS_B24INT:   return(SND_PCM_FORMAT_S24_BE); 
    case MUS_L24INT:   return(SND_PCM_FORMAT_S24_LE); 
    case MUS_BINT:     return(SND_PCM_FORMAT_S32_BE); 
    case MUS_LINT:     return(SND_PCM_FORMAT_S32_LE); 
    case MUS_BINTN:    return(SND_PCM_FORMAT_S32_BE); 
    case MUS_LINTN:    return(SND_PCM_FORMAT_S32_LE); 
    case MUS_BFLOAT:   return(SND_PCM_FORMAT_FLOAT_BE); 
    case MUS_LFLOAT:   return(SND_PCM_FORMAT_FLOAT_LE); 
    case MUS_BDOUBLE:  return(SND_PCM_FORMAT_FLOAT64_BE); 
    case MUS_LDOUBLE:  return(SND_PCM_FORMAT_FLOAT64_LE); 
1054
    default: break;
1055 1056 1057 1058 1059 1060 1061 1062 1063
    }
  return((snd_pcm_format_t)MUS_ERROR);
}

/* FIXME: this is not taking yet into account the 
 * number of bits that a given alsa format is actually
 * using... 
 */

1064
static mus_sample_t to_mus_sample_type(int alsa_format) 
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
{
  /* alsa format definitions from asoundlib.h (0.9 cvs 6/27/2001) */
  switch (alsa_format)
    {
    case SND_PCM_FORMAT_S8:         return(MUS_BYTE);
    case SND_PCM_FORMAT_U8:         return(MUS_UBYTE);
    case SND_PCM_FORMAT_S16_LE:     return(MUS_LSHORT);
    case SND_PCM_FORMAT_S16_BE:     return(MUS_BSHORT);
    case SND_PCM_FORMAT_U16_LE:     return(MUS_ULSHORT);
    case SND_PCM_FORMAT_U16_BE:     return(MUS_UBSHORT);
    case SND_PCM_FORMAT_S24_LE:     return(MUS_L24INT);
    case SND_PCM_FORMAT_S24_BE:     return(MUS_B24INT);
    case SND_PCM_FORMAT_S32_LE:     return(MUS_LINTN); /* 32bit normalized plays 24bit and 16bit files with same amplitude bound (for 24 bit cards) */
    case SND_PCM_FORMAT_S32_BE:     return(MUS_BINTN);
    case SND_PCM_FORMAT_FLOAT_LE:   return(MUS_LFLOAT);
    case SND_PCM_FORMAT_FLOAT_BE:   return(MUS_BFLOAT);
    case SND_PCM_FORMAT_FLOAT64_LE: return(MUS_LDOUBLE);
    case SND_PCM_FORMAT_FLOAT64_BE: return(MUS_BDOUBLE);
    case SND_PCM_FORMAT_MU_LAW:     return(MUS_MULAW);
    case SND_PCM_FORMAT_A_LAW:      return(MUS_ALAW);
    /* formats with no translation in snd */
    case SND_PCM_FORMAT_U24_LE:
    case SND_PCM_FORMAT_U24_BE:
    case SND_PCM_FORMAT_U32_LE:
    case SND_PCM_FORMAT_U32_BE:
    case SND_PCM_FORMAT_IEC958_SUBFRAME_LE:
    case SND_PCM_FORMAT_IEC958_SUBFRAME_BE:
    case SND_PCM_FORMAT_IMA_ADPCM:
    case SND_PCM_FORMAT_MPEG:
    case SND_PCM_FORMAT_GSM:
    case SND_PCM_FORMAT_SPECIAL:
    default:
1097
      return(MUS_UNKNOWN_SAMPLE);
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
    }
}

/* convert a sndlib device into an alsa device number and channel
 * [has to be coordinated with following function!] 
 */

/* very simplistic approach, device mapping should also depend
 * on which card we're dealing with, digital i/o devices should
 * be identified as such and so on 
 */

/* NOTE: in the Delta1010 digital i/o is just a pair of channels
 * in the 10 channel playback frame or 12 channel capture frame,
 * how do we specify that???
 */

static int to_alsa_device(int dev, int *adev, snd_pcm_stream_t *achan)
{
  switch (dev) 
    {
      /* default values are a problem because the concept does
       * not imply a direction (playback or capture). This works
       * fine as long as both directions of a device are symetric,
       * the Midiman 1010, for example, has 10 channel frames for
       * playback and 12 channel frames for capture and breaks 
       * the recorder (probes the default, defaults to output, 
       * uses the values for input). 
       */
    case MUS_AUDIO_DEFAULT:
    case MUS_AUDIO_DUPLEX_DEFAULT:
    case MUS_AUDIO_LINE_OUT:
      /* analog output */
      (*adev) = 0;
      (*achan) = SND_PCM_STREAM_PLAYBACK;
      break;
1134

1135 1136 1137 1138 1139
    case MUS_AUDIO_AUX_OUTPUT:
      /* extra analog output */
      (*adev) = 1;
      (*achan) = SND_PCM_STREAM_PLAYBACK;
      break;
1140

1141 1142 1143 1144 1145
    case MUS_AUDIO_DAC_OUT:
      /* analog outputs */
      (*adev) = 2;
      (*achan) = SND_PCM_STREAM_PLAYBACK;
      break;
1146

1147 1148 1149 1150 1151 1152
    case MUS_AUDIO_MICROPHONE:
    case MUS_AUDIO_LINE_IN:
      /* analog input */
      (*adev) = 0;
      (*achan) = SND_PCM_STREAM_CAPTURE;
      break;
1153

1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
    default:
      return(MUS_ERROR);
      break;
    }
  return(0);
}

/* convert an alsa device into a sndlib device 
 * [has to be coordinated with previous function!] 
 *
 * naming here is pretty much arbitrary. We have to have
 * a bidirectional mapping between sndlib devices and
 * alsa devices and that's just not possible (I think). 
 * This stopgap mapping ignores digital input and output
 * devices - how to differentiate them in alsa?
 */

static int to_sndlib_device(int dev, int channel) 
{
  switch (channel) 
    {
    case SND_PCM_STREAM_PLAYBACK:
      switch (dev) 
	{
	  /* works only for the first three outputs */
	case 0: return(MUS_AUDIO_LINE_OUT);
	case 1: return(MUS_AUDIO_AUX_OUTPUT);
	case 2: return(MUS_AUDIO_DAC_OUT);
	default:
	  return(MUS_ERROR);
	}
    case SND_PCM_STREAM_CAPTURE:
      switch (dev) 
	{
	case 0: return(MUS_AUDIO_LINE_IN);
	default:
	  return(MUS_ERROR);
	}
      break;
    }
  return(MUS_ERROR);
}


static int alsa_mus_error(int type, char *message)
{
  if (message)
    {
1202
      mus_print("%s", message);
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
      free(message);
    }
  return(MUS_ERROR);
}


/* dump current hardware and software configuration */

static void alsa_dump_configuration(char *name, snd_pcm_hw_params_t *hw_params, snd_pcm_sw_params_t *sw_params)
{
  int err; 
  char *str;
  snd_output_t *buf;

#if (SND_LIB_MAJOR == 0) || ((SND_LIB_MAJOR == 1) && (SND_LIB_MINOR == 0) && (SND_LIB_SUBMINOR < 8))
  return; /* avoid Alsa bug */
#endif

  err = snd_output_buffer_open(&buf);
  if (err < 0) 
1223
    mus_print("could not open dump buffer: %s", snd_strerror(err));
1224 1225
  else 
    {
1226
      size_t len;
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
      if (hw_params) 
	{
	  snd_output_puts(buf, "hw_params status of ");
	  snd_output_puts(buf, name);
	  snd_output_puts(buf, "\n");
	  err = snd_pcm_hw_params_dump(hw_params, buf);
	  if (err < 0) 
	    mus_print("snd_pcm_hw_params_dump: %s", snd_strerror(err));
	}
      if (sw_params) 
	{
	  snd_output_puts(buf, "sw_params status of ");
	  snd_output_puts(buf, name);
	  snd_output_puts(buf, "\n");
	  err = snd_pcm_sw_params_dump(sw_params, buf);
	  if (err < 0) 
	    mus_print("snd_pcm_hw_params_dump: %s", snd_strerror(err));
	}
      snd_output_putc(buf, '\0');
      len = snd_output_buffer_string(buf, &str);
      if (len > 1) 
	mus_print("status of %s\n%s", name, str);
      snd_output_close(buf);
    }
}

/* get hardware params for a pcm */

static snd_pcm_hw_params_t *alsa_get_hardware_params(const char *name, snd_pcm_stream_t stream, int mode)
{
  int err;
  snd_pcm_t *handle;
  if ((err = snd_pcm_open(&handle, name, stream, mode | SND_PCM_NONBLOCK)) != 0) 
    {
      alsa_mus_error(MUS_AUDIO_CANT_OPEN, 
		     mus_format("open pcm %s for stream %d: %s",
				name, stream, snd_strerror(err)));
      return(NULL);
    }
  else 
    {
      snd_pcm_hw_params_t *params;
      params = (snd_pcm_hw_params_t *)calloc(1, snd_pcm_hw_params_sizeof());
1270
      if (!params) 
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
	{
	  snd_pcm_close(handle);
	  alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			 mus_format("could not allocate memory for hardware params"));
	} 
      else 
	{
	  err = snd_pcm_hw_params_any(handle, params);
	  if (err < 0) 
	    {
	      snd_pcm_close(handle);
	      alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			     mus_format("snd_pcm_hw_params_any: pcm %s, stream %d, error: %s",
					name, stream, snd_strerror(err)));
	    } 
	  else 
	    {
	      snd_pcm_close(handle);
	      return(params);
	    }
	}
    }
  return(NULL);
}

/* allocate software params structure */

static snd_pcm_sw_params_t *alsa_get_software_params(void)
{
  snd_pcm_sw_params_t *params = NULL;
  params = (snd_pcm_sw_params_t *)calloc(1, snd_pcm_sw_params_sizeof());
1302
  if (!params) 
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
    {
      alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
		     mus_format("could not allocate memory for software params"));
    } 
  return(params);
}

/* probe a device name against the list of available pcm devices */

static bool alsa_probe_device_name(const char *name)
{
  snd_config_t *conf;
  snd_config_iterator_t pos, next;
  int err;
  
  err = snd_config_update();
  if (err < 0) 
    {
      mus_print("snd_config_update: %s", snd_strerror(err));
      return(false);
    }

  err = snd_config_search(snd_config, "pcm", &conf);
  if (err < 0) 
    {
      mus_print("snd_config_search: %s", snd_strerror(err));
      return(false);
    }

  snd_config_for_each(pos, next, conf) 
    {
      snd_config_t *c = snd_config_iterator_entry(pos);
      const char *id;
      int err = snd_config_get_id(c, &id);
      if (err == 0) {
	int result = strncmp(name, id, strlen(id));
	if (result == 0 &&
	    (name[strlen(id)] == '\0' || name[strlen(id)] == ':')) 
	  {
	    return(true);
	  }
      }
    }
  return(false);
}

/* check a device name against the list of available pcm devices */

static int alsa_check_device_name(const char *name)
{
  if (!alsa_probe_device_name(name)) 
    {
      return(alsa_mus_error(MUS_AUDIO_CANT_READ, 
			    mus_format("alsa could not find device \"%s\" in configuration", 
				       name)));
    } 
  return(MUS_NO_ERROR);
}


/* set scheduling priority to SCHED_FIFO 
 * this will only work if the program that uses sndlib is run as root or is suid root 
 */

/* whether we want to trace calls 
 *
 * set to "1" to print function trace information in the 
 * snd error window
 */

static int alsa_trace = 0;

/* this should go away as it is oss specific */

static int fragment_size = 512; 
static int fragments = 4;

static void alsa_mus_oss_set_buffers(int num, int size) 
{
  fragments = num; 
  fragment_size = size; 
}

/* total number of soundcards in our setup, set by initialize_audio */

/* static int sound_cards = 0; */

/* return the number of cards that are available */

/* return the type of driver we're dealing with */

static char *alsa_mus_audio_moniker(void)
{
1396
  if (!version_name) version_name = (char *)calloc(LABEL_BUFFER_SIZE, sizeof(char));
1397
  snprintf(version_name, LABEL_BUFFER_SIZE, "ALSA %s", SND_LIB_VERSION_STR);
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
  return(version_name);
}

/* handles for both directions of the virtual device */

static snd_pcm_t *handles[2] = {NULL, NULL};

/* hardware and software parameter sctructure pointers */

static snd_pcm_hw_params_t *alsa_hw_params[2] = {NULL, NULL}; /* avoid bogus free */
static snd_pcm_sw_params_t *alsa_sw_params[2] = {NULL, NULL};

/* some defaults */

static int alsa_open_mode = SND_PCM_ASYNC;
static int alsa_buffers = 3;
/* size of buffer in number of samples per channel, 
 * at 44100 approximately 5.9mSecs
 */
static int alsa_samples_per_channel = 1024;
static snd_pcm_access_t alsa_interleave = SND_PCM_ACCESS_RW_INTERLEAVED;
static int alsa_max_capture_channels = 32;

/* first default name for pcm configuration */

static char *alsa_sndlib_device_name = (char *)"sndlib";

/* second default for playback and capture: hardware pcm, first card, first device */
/* pcms used by sndlib, playback and capture */

static char *alsa_playback_device_name = NULL;
static char *alsa_capture_device_name = NULL;


1432

1433 1434 1435 1436
/* -------- tie these names into scheme/ruby -------- */

static int alsa_get_max_buffers(void)
{
1437
  uint32_t max_periods = 0, max_rec_periods = 0;
1438
  int dir = 0;
1439

1440
  if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK])
1441 1442
    snd_pcm_hw_params_get_periods_max(alsa_hw_params[SND_PCM_STREAM_PLAYBACK], &max_periods, &dir);

1443 1444 1445
  if (alsa_hw_params[SND_PCM_STREAM_CAPTURE]) 
    {
      snd_pcm_hw_params_get_periods_max(alsa_hw_params[SND_PCM_STREAM_CAPTURE], &max_rec_periods, &dir);
1446

1447 1448 1449 1450 1451 1452 1453 1454
      if (max_periods > max_rec_periods) 
	max_periods = max_rec_periods;
    }
  return(max_periods);
}

static int alsa_get_min_buffers(void)
{
1455
  uint32_t min_periods = 0, min_rec_periods = 0;
1456 1457
  int dir = 0;
  if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK])
1458 1459
    snd_pcm_hw_params_get_periods_min(alsa_hw_params[SND_PCM_STREAM_PLAYBACK], &min_periods, &dir);

1460 1461 1462
  if (alsa_hw_params[SND_PCM_STREAM_CAPTURE]) 
    {
      snd_pcm_hw_params_get_periods_min(alsa_hw_params[SND_PCM_STREAM_CAPTURE], &min_rec_periods, &dir);
1463

1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
      if (min_periods < min_rec_periods) 
	min_periods = min_rec_periods;
    }
  return(min_periods);
}

static int alsa_clamp_buffers(int bufs)
{
  int minb, maxb;
  minb = alsa_get_min_buffers();
  maxb = alsa_get_max_buffers();
  if (bufs > maxb)
    bufs = maxb;
  if (bufs < minb)
    bufs = minb;
  return(bufs);
}

static snd_pcm_uframes_t alsa_get_min_buffer_size(void)
{
  snd_pcm_uframes_t min_buffer_size = 0, min_rec_buffer_size = 0;
  if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK])
1486 1487
    snd_pcm_hw_params_get_buffer_size_min(alsa_hw_params[SND_PCM_STREAM_PLAYBACK], &min_buffer_size);

1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
  if (alsa_hw_params[SND_PCM_STREAM_CAPTURE]) 
    {
      snd_pcm_hw_params_get_buffer_size_min(alsa_hw_params[SND_PCM_STREAM_CAPTURE], &min_rec_buffer_size);
      if (min_buffer_size < min_rec_buffer_size) 
	min_buffer_size = min_rec_buffer_size;
    }
  return(min_buffer_size);
}

static snd_pcm_uframes_t alsa_get_max_buffer_size(void)
{
  snd_pcm_uframes_t max_buffer_size = 0, max_rec_buffer_size = 0;
  if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK])
1501 1502
    snd_pcm_hw_params_get_buffer_size_max(alsa_hw_params[SND_PCM_STREAM_PLAYBACK], &max_buffer_size);

1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
  if (alsa_hw_params[SND_PCM_STREAM_CAPTURE]) 
    {
      snd_pcm_hw_params_get_buffer_size_max(alsa_hw_params[SND_PCM_STREAM_CAPTURE], &max_rec_buffer_size);
      if (max_buffer_size > max_rec_buffer_size) 
	max_buffer_size = max_rec_buffer_size;
    }
  return(max_buffer_size);
}

static snd_pcm_uframes_t alsa_clamp_buffer_size(snd_pcm_uframes_t buf_size)
{
  snd_pcm_uframes_t minb, maxb;
  minb = alsa_get_min_buffer_size();
  maxb = alsa_get_max_buffer_size();
  if (buf_size > maxb)
    buf_size = maxb;
  if (buf_size < minb)
    buf_size = minb;
  return(buf_size);
}

static bool alsa_set_playback_parameters(void)
{
  /* playback stream parameters */
  if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK]) free(alsa_hw_params[SND_PCM_STREAM_PLAYBACK]);
  alsa_hw_params[SND_PCM_STREAM_PLAYBACK] = alsa_get_hardware_params(alsa_playback_device_name, SND_PCM_STREAM_PLAYBACK, alsa_open_mode);
  if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK]) 
    {
      snd_pcm_uframes_t size;
      int old_buffers;
      old_buffers = alsa_buffers;
      if (alsa_sw_params[SND_PCM_STREAM_PLAYBACK]) free(alsa_sw_params[SND_PCM_STREAM_PLAYBACK]);
      alsa_sw_params[SND_PCM_STREAM_PLAYBACK] = alsa_get_software_params();
      sound_cards = 1;
      alsa_buffers = alsa_clamp_buffers(alsa_buffers);
      if (alsa_buffers <= 0)
	{
	  alsa_buffers = old_buffers;
	  return(false);
	}
      size = alsa_clamp_buffer_size((snd_pcm_uframes_t)(alsa_samples_per_channel * alsa_buffers));
      if (size <= 0) return(false);
      alsa_samples_per_channel = size / alsa_buffers;
    }
  return(alsa_hw_params[SND_PCM_STREAM_PLAYBACK] && alsa_sw_params[SND_PCM_STREAM_PLAYBACK]);
}

static bool alsa_set_capture_parameters(void)
{  
  /* capture stream parameters */
  if (alsa_hw_params[SND_PCM_STREAM_CAPTURE]) free(alsa_hw_params[SND_PCM_STREAM_CAPTURE]);
  alsa_hw_params[SND_PCM_STREAM_CAPTURE] = alsa_get_hardware_params(alsa_capture_device_name, SND_PCM_STREAM_CAPTURE, alsa_open_mode);
  if (alsa_hw_params[SND_PCM_STREAM_CAPTURE]) 
    {
      snd_pcm_uframes_t size;
      int old_buffers;
      old_buffers = alsa_buffers;
      if (alsa_sw_params[SND_PCM_STREAM_CAPTURE]) free(alsa_sw_params[SND_PCM_STREAM_CAPTURE]);
      alsa_sw_params[SND_PCM_STREAM_CAPTURE] = alsa_get_software_params();
      sound_cards = 1;
      alsa_buffers = alsa_clamp_buffers(alsa_buffers);
      if (alsa_buffers <= 0)
	{
	  alsa_buffers = old_buffers;
	  return(false);
	}
      size = alsa_clamp_buffer_size((snd_pcm_uframes_t)(alsa_samples_per_channel * alsa_buffers));
      if (size <= 0) return(false);
      alsa_samples_per_channel = size / alsa_buffers;
    }
  return(alsa_hw_params[SND_PCM_STREAM_CAPTURE] && alsa_sw_params[SND_PCM_STREAM_CAPTURE]);
}


char *mus_alsa_playback_device(void) {return(alsa_playback_device_name);}
char *mus_alsa_set_playback_device(const char *name) 
{
  if (alsa_check_device_name(name) == MUS_NO_ERROR)
    {
      char *old_name = alsa_playback_device_name;
      alsa_playback_device_name = mus_strdup(name); 
      if (!alsa_set_playback_parameters())
	{
	  alsa_playback_device_name = old_name; /* try to back out of the mistake */
	  alsa_set_playback_parameters();
	}
    }
  return(alsa_playback_device_name);
}

char *mus_alsa_capture_device(void) {return(alsa_capture_device_name);}
char *mus_alsa_set_capture_device(const char *name) 
{
  if (alsa_check_device_name(name) == MUS_NO_ERROR)
    {
      char *old_name = alsa_capture_device_name;
      alsa_capture_device_name = mus_strdup(name); 
      if (!alsa_set_capture_parameters())
	{
	  alsa_capture_device_name = old_name;
	  alsa_set_capture_parameters();
	}
    }
  return(alsa_capture_device_name);
}

char *mus_alsa_device(void) {return(alsa_sndlib_device_name);}
char *mus_alsa_set_device(const char *name) 
{
  if (alsa_check_device_name(name) == MUS_NO_ERROR)
    {
      alsa_sndlib_device_name = mus_strdup(name);
      mus_alsa_set_playback_device(name);
      mus_alsa_set_capture_device(name);
    }
  return(alsa_sndlib_device_name);
}

int mus_alsa_buffer_size(void) {return(alsa_samples_per_channel);}
int mus_alsa_set_buffer_size(int size) 
{
  snd_pcm_uframes_t bsize;
  if (alsa_buffers == 0) alsa_buffers = 1;
  if (size > 0)
    {
      bsize = alsa_clamp_buffer_size((snd_pcm_uframes_t)(size * alsa_buffers));
      alsa_samples_per_channel = bsize / alsa_buffers;
    }
  return(alsa_samples_per_channel);
}

int mus_alsa_buffers(void) {return(alsa_buffers);}
int mus_alsa_set_buffers(int num) 
{
  snd_pcm_uframes_t size;
  if (num > 0)
    {
      alsa_buffers = alsa_clamp_buffers(num);
      if (alsa_buffers > 0)
	{
	  size = alsa_clamp_buffer_size((snd_pcm_uframes_t)(alsa_samples_per_channel * alsa_buffers));
	  alsa_samples_per_channel = size / alsa_buffers;
	}
    }
  return(alsa_buffers);
}

static bool alsa_squelch_warning = false;
bool mus_alsa_squelch_warning(void) {return(alsa_squelch_warning);}
bool mus_alsa_set_squelch_warning(bool val) 
{
  alsa_squelch_warning = val; 
  return(val);
}




1661
/* get a device name from the environment */
1662

1663
static char *alsa_get_device_from_env(const char *name)
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
{
  char *string = getenv(name);
  if (string) 
    if (alsa_check_device_name(string) == MUS_NO_ERROR) 
      return(string);
  return(NULL);
}

/* get an integer from the environment */

static int alsa_get_int_from_env(const char *name, int *value, int min, int max)
{
  char *string = getenv(name);
  if (string) 
    {
      char *end;
      long int result = strtol(string, &end, 10);
      if (((min != -1) && (max != -1)) &&
	  (result < min || result > max)) 
	{
	  return(alsa_mus_error(MUS_AUDIO_CANT_READ, 
				mus_format("%s ignored: out of range, value=%d, min=%d, max=%d",
					   name, (int)result, min, max)));
	} 
      else 
	{
	  if (errno == ERANGE) 
	    {
	      return(alsa_mus_error(MUS_AUDIO_CANT_READ, 
				    mus_format("%s ignored: strlol conversion out of range",
					       name)));
	    } 
	  else 
	    {
	      if ((*string != '\0') && (*end == '\0'))
		{
		  *value = (int)result;
		  return(MUS_NO_ERROR);
		} 
	      else 
		{
		  return(alsa_mus_error(MUS_AUDIO_CANT_READ, 
					mus_format("%s ignored: value is \"%s\", not an integer",
						   name, string)));
		}
	    }
	}
    }
  return(MUS_ERROR);
}

/* initialize the audio subsystem */

/* define environment variable names */
#define MUS_ALSA_PLAYBACK_DEVICE_ENV_NAME "MUS_ALSA_PLAYBACK_DEVICE"
#define MUS_ALSA_CAPTURE_DEVICE_ENV_NAME  "MUS_ALSA_CAPTURE_DEVICE"
#define MUS_ALSA_DEVICE_ENV_NAME          "MUS_ALSA_DEVICE"
#define MUS_ALSA_BUFFERS_ENV_NAME         "MUS_ALSA_BUFFERS"
#define MUS_ALSA_BUFFER_SIZE_ENV_NAME     "MUS_ALSA_BUFFER_SIZE"
#define MUS_ALSA_TRACE_ENV_NAME           "MUS_ALSA_TRACE"

static int alsa_mus_audio_initialize(void) 
{
  char *name = NULL;
  char *pname;
  char *cname;
  int value = 0, alsa_buffer_size = 0;

  if (audio_initialized) 
    return(0);

  sound_cards = 0;

  /* get trace flag from environment */
  if (alsa_get_int_from_env(MUS_ALSA_TRACE_ENV_NAME, &value, 0, 1) == MUS_NO_ERROR) 
    alsa_trace = value;

  /* try to get device names from environment */
  pname = alsa_get_device_from_env(MUS_ALSA_PLAYBACK_DEVICE_ENV_NAME);
  if ((pname) && (alsa_probe_device_name(pname)))
    alsa_playback_device_name = pname;

  cname = alsa_get_device_from_env(MUS_ALSA_CAPTURE_DEVICE_ENV_NAME);
  if ((cname) && (alsa_probe_device_name(cname)))
    alsa_capture_device_name = cname;
    
  name = alsa_get_device_from_env(MUS_ALSA_DEVICE_ENV_NAME);
  if ((name) && (alsa_probe_device_name(name)))
    {
      if (!alsa_playback_device_name) 
	alsa_playback_device_name = name;

      if (!alsa_capture_device_name) 
	alsa_capture_device_name = name;

      alsa_sndlib_device_name = name;
    }

  /* now check that we have a plausible name */
  if (!alsa_probe_device_name(alsa_sndlib_device_name))
    {
      alsa_sndlib_device_name = (char *)"default";
      if (!alsa_probe_device_name(alsa_sndlib_device_name))
	{
	  alsa_sndlib_device_name = (char *)"plughw:0";
	  if (!alsa_probe_device_name(alsa_sndlib_device_name))
	    alsa_sndlib_device_name = (char *)"hw:0";
	}
    }
    
  /* if no device name set yet, try for special sndlib name first */
  if (!alsa_playback_device_name) 
    {
      if (alsa_probe_device_name(alsa_sndlib_device_name)) 
	alsa_playback_device_name = alsa_sndlib_device_name;
      else alsa_playback_device_name = (char *)"hw:0";
    }

  if (!alsa_capture_device_name) 
    {
      if (alsa_probe_device_name(alsa_sndlib_device_name)) 
	alsa_capture_device_name = alsa_sndlib_device_name;
      else alsa_capture_device_name = (char *)"hw:0";
    }

  alsa_get_int_from_env(MUS_ALSA_BUFFERS_ENV_NAME, &alsa_buffers, -1, -1);
  alsa_get_int_from_env(MUS_ALSA_BUFFER_SIZE_ENV_NAME, &alsa_buffer_size, -1, -1);

  if ((alsa_buffer_size > 0) && (alsa_buffers > 0))
    alsa_samples_per_channel = alsa_buffer_size / alsa_buffers;

  if (!alsa_set_playback_parameters())
    {
      /* somehow we got a device that passed muster with alsa_probe_device_name, but doesn't return hw params! */
      alsa_playback_device_name = (char *)"plughw:0";
      if (!alsa_set_playback_parameters())
	{
	  alsa_playback_device_name = (char *)"hw:0";
	  if (!alsa_set_playback_parameters())
	    return(MUS_ERROR);
	}
    }

  if (!alsa_set_capture_parameters())
    {
      alsa_capture_device_name = (char *)"plughw:0";
      if (!alsa_set_capture_parameters())
	{
	  alsa_capture_device_name = (char *)"hw:0";
	  if (!alsa_set_capture_parameters())
	    return(MUS_ERROR);
	}
    }

  if ((!alsa_hw_params[SND_PCM_STREAM_CAPTURE]) ||
      (!alsa_hw_params[SND_PCM_STREAM_PLAYBACK]))
    return(MUS_ERROR);

  audio_initialized = true;
  return(0);
}

/* open an input or output stream */

1828
static int alsa_audio_open(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
1829
{
1830
  int device, alsa_device;
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
  snd_pcm_format_t alsa_format;
  snd_pcm_stream_t alsa_stream;
  char *alsa_name;
  int frames, periods;
  int err;
  snd_pcm_t *handle;
  snd_pcm_hw_params_t *hw_params = NULL;
  snd_pcm_sw_params_t *sw_params = NULL;
  
  if ((!audio_initialized) && 
      (mus_audio_initialize() != MUS_NO_ERROR))
    return(MUS_ERROR);
  if (chans <= 0) return(MUS_ERROR);
  
  if (alsa_trace) 
    mus_print("%s: %x rate=%d, chans=%d, format=%d:%s, size=%d", 
1847 1848
	      __func__, ur_dev, srate, chans, samp_type, 
	      mus_sample_type_to_string(samp_type), size);
1849

1850
  /* card = MUS_AUDIO_SYSTEM(ur_dev); */
1851 1852 1853 1854 1855
  device = MUS_AUDIO_DEVICE(ur_dev);

  if ((err = to_alsa_device(device, &alsa_device, &alsa_stream)) < 0) 
    {
      return(alsa_mus_error(MUS_AUDIO_DEVICE_NOT_AVAILABLE, 
1856 1857
			    mus_format("%s: cannot translate device %d to alsa",
				       snd_strerror(err), device)));
1858
    }
1859
  if ((alsa_format = to_alsa_format(samp_type)) == (snd_pcm_format_t)MUS_ERROR) 
1860
    {
1861
      return(alsa_mus_error(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, 
1862
			    mus_format("could not change %s<%d> to alsa format", 
1863
				       mus_sample_type_to_string(samp_type), samp_type)));
1864 1865 1866 1867 1868
    }

  alsa_name = (alsa_stream == SND_PCM_STREAM_PLAYBACK) ? alsa_playback_device_name : alsa_capture_device_name;
  if ((err = snd_pcm_open(&handle, alsa_name, alsa_stream, alsa_open_mode)) != 0) 
    {
1869 1870
      /* snd_pcm_close(handle); */
      /* this segfaults in some versions of ALSA */
1871
      return(alsa_mus_error(MUS_AUDIO_CANT_OPEN, 
1872 1873
			    mus_format("open pcm %s stream %s: %s",
				       alsa_name, snd_pcm_stream_name(alsa_stream), 
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903
				       snd_strerror(err))));
    }
  handles[alsa_stream] = handle;
  hw_params = alsa_hw_params[alsa_stream];
  sw_params = alsa_sw_params[alsa_stream];
  if ((err = snd_pcm_hw_params_any(handle, hw_params)) < 0) 
    {
      snd_pcm_close(handle);
      handles[alsa_stream] = NULL;
      alsa_dump_configuration(alsa_name, hw_params, sw_params);
      return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			    mus_format("%s: no parameter configurations available for %s", 
				       snd_strerror(err), alsa_name)));
    }

  err = snd_pcm_hw_params_set_access(handle, hw_params, alsa_interleave);
  if (err < 0) 
    {
      snd_pcm_close(handle);
      handles[alsa_stream] = NULL;
      alsa_dump_configuration(alsa_name, hw_params, sw_params);
      return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			    mus_format("%s: %s: access type %s not available", 
				       snd_strerror(err), alsa_name, snd_pcm_access_name(alsa_interleave))));
    }

  periods = alsa_buffers;
  err = snd_pcm_hw_params_set_periods(handle, hw_params, periods, 0);
  if (err < 0) 
    {
1904
      uint32_t minp, maxp;
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
      int dir;
      snd_pcm_hw_params_get_periods_min(hw_params, &minp, &dir);
      snd_pcm_hw_params_get_periods_max(hw_params, &maxp, &dir);
      snd_pcm_close(handle);
      handles[alsa_stream] = NULL;
      alsa_dump_configuration(alsa_name, hw_params, sw_params);
      return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			    mus_format("%s: %s: cannot set number of periods to %d, min is %d, max is %d", 
				       snd_strerror(err), alsa_name, periods, (int)minp, (int)maxp)));
    }

1916
  frames = size / chans / mus_bytes_per_sample(samp_type);
1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953

  err = snd_pcm_hw_params_set_buffer_size(handle, hw_params, frames * periods);
  if (err < 0) 
    {
      snd_pcm_uframes_t minp, maxp;
      snd_pcm_hw_params_get_buffer_size_min(hw_params, &minp);
      snd_pcm_hw_params_get_buffer_size_max(hw_params, &maxp);
      snd_pcm_close(handle);
      handles[alsa_stream] = NULL;
      alsa_dump_configuration(alsa_name, hw_params, sw_params);
      return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			    mus_format("%s: %s: cannot set buffer size to %d periods of %d frames; \
total requested buffer size is %d frames, minimum allowed is %d, maximum is %d", 
				       snd_strerror(err), alsa_name, periods, frames, periods * frames, (int)minp, (int)maxp)));
    }

  err = snd_pcm_hw_params_set_format(handle, hw_params, alsa_format);
  if (err < 0) 
    {
      snd_pcm_close(handle);
      handles[alsa_stream] = NULL;
      alsa_dump_configuration(alsa_name, hw_params, sw_params);
      return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			    mus_format("%s: %s: cannot set format to %s", 
				       snd_strerror(err), alsa_name, snd_pcm_format_name(alsa_format))));
    }

  err = snd_pcm_hw_params_set_channels(handle, hw_params, chans);
  if (err < 0) 
    {
      snd_pcm_close(handle);
      handles[alsa_stream] = NULL;
      alsa_dump_configuration(alsa_name, hw_params, sw_params);
      return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			    mus_format("%s: %s: cannot set channels to %d", 
				       snd_strerror(err), alsa_name, chans)));
    }
1954

1955
  {
1956
    uint32_t new_rate;
1957
    new_rate = srate;
1958
    /* r is uint32_t so it can't be negative */
1959
    err = snd_pcm_hw_params_set_rate_near(handle, hw_params, &new_rate, 0);
1960
    if ((new_rate != (uint32_t)srate) && (!alsa_squelch_warning))
1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
      {
	mus_print("%s: could not set rate to exactly %d, set to %d instead",
		  alsa_name, srate, new_rate);
      }
  }

  err = snd_pcm_hw_params(handle, hw_params);
  if (err < 0) 
    {
      snd_pcm_close(handle);
      handles[alsa_stream] = NULL;
      alsa_dump_configuration(alsa_name, hw_params, sw_params);
      return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			    mus_format("%s: cannot set hardware parameters for %s", 
				       snd_strerror(err), alsa_name)));
    }

  snd_pcm_sw_params_current(handle, sw_params);
  err = snd_pcm_sw_params(handle, sw_params);
  if (err < 0) 
    {
      snd_pcm_close(handle);
      handles[alsa_stream] = NULL;
      alsa_dump_configuration(alsa_name, hw_params, sw_params);
      return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			    mus_format("%s: cannot set software parameters for %s", 
				       snd_strerror(err), alsa_name)));
    }

  /* for now the id for the stream is the direction identifier, that is
     not a problem because we only advertise one card with two devices */
  return(alsa_stream);
}

/* sndlib support for opening output devices */

1997
static int alsa_mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
1998
{
1999
  return(alsa_audio_open(ur_dev, srate, chans, samp_type, size));
2000 2001 2002 2003
}

/* sndlib support for opening input devices */

2004
static int alsa_mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
2005
{
2006
  return(alsa_audio_open(ur_dev, srate, chans, samp_type, size));
2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
}

/* sndlib support for closing a device */

/* to force it to stop, snd_pcm_drop */

static bool xrun_warned = false;

static int alsa_mus_audio_close(int id)
{
  xrun_warned = false;
  if (id == MUS_ERROR) return(MUS_ERROR);
2019
  if (alsa_trace) mus_print( "%s: %d", __func__, id); 
2020 2021
  if (handles[id]) 
    {
2022
      int err;
2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
      err = snd_pcm_drain(handles[id]);
      if (err != 0) 
	mus_print("snd_pcm_drain: %s", snd_strerror(err)); 

      err = snd_pcm_close(handles[id]);
      if (err != 0) 
	return(alsa_mus_error(MUS_AUDIO_CANT_CLOSE, 
			      mus_format("snd_pcm_close: %s", 
					 snd_strerror(err)))); 
      handles[id] = NULL;
    }
  return(MUS_NO_ERROR);
}

/* recover from underruns or overruns */

static int recover_from_xrun(int id)
{
  int err;
  snd_pcm_status_t *status;
  snd_pcm_state_t state;
  snd_pcm_status_alloca(&status);
  err = snd_pcm_status(handles[id], status);
  if (err < 0) 
    {
2048
      mus_print("%s: snd_pcm_status: %s", __func__, snd_strerror(err));
2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063
      return(MUS_ERROR);
    }
  state = snd_pcm_status_get_state(status);
  if (state == SND_PCM_STATE_XRUN) 
    {
      if (!xrun_warned)
	{
	  xrun_warned = true;
	  mus_print("[under|over]run detected");
	}
      err = snd_pcm_prepare(handles[id]);
      if (err < 0) 
	mus_print("snd_pcm_prepare: %s", snd_strerror(err));
      else return(MUS_NO_ERROR);
    }
2064
  else mus_print("%s: error, current state is %s", __func__, snd_pcm_state_name(state));
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
  return(MUS_ERROR);
}

/* sndlib support for writing a buffer to an output device */

static int alsa_mus_audio_write(int id, char *buf, int bytes)
{
  snd_pcm_sframes_t status;
  ssize_t frames;
  if (id == MUS_ERROR) return(MUS_ERROR);
  frames = snd_pcm_bytes_to_frames(handles[id], bytes);
  status = snd_pcm_writei(handles[id], buf, frames);
  if ((status == -EAGAIN) || 
      ((status >= 0) && (status < frames)))
    snd_pcm_wait(handles[id], 1000);
  else
    {
      if (status == -EPIPE) 
	return(recover_from_xrun(id));
      else 
	{
	  if (status < 0) 
	    {
	      mus_print("snd_pcm_writei: %s", snd_strerror(status));
	      return(MUS_ERROR);
	    }
	}
    }
  return(MUS_NO_ERROR);
}

/* sndlib support for reading a buffer from an input device */

static int alsa_mus_audio_read(int id, char *buf, int bytes)
{
  snd_pcm_sframes_t status;
  ssize_t frames;
  if (id == MUS_ERROR) return(MUS_ERROR);
  frames = snd_pcm_bytes_to_frames(handles[id], bytes);
  status = snd_pcm_readi(handles[id], buf, frames);
  if ((status == -EAGAIN) || 
      ((status >= 0) && (status < frames)))
    snd_pcm_wait(handles[id], 1000);
  else 
    {
      if (status == -EPIPE) 
	return(recover_from_xrun(id));
      else 
	{
	  if (status < 0) 
	    {
	      mus_print("snd_pcm_readi: %s", snd_strerror(status));
	      return(MUS_ERROR);
	    }
	}
    }
  return(MUS_NO_ERROR);
}

/* read state of the audio hardware */

2126
static int alsa_chans(int ur_dev, int *info)
2127 2128 2129
{
  int card;
  int device;
2130 2131 2132
  int alsa_device = 0;
  snd_pcm_stream_t alsa_stream = SND_PCM_STREAM_PLAYBACK;

2133 2134 2135 2136 2137 2138
  if ((!audio_initialized) && 
      (mus_audio_initialize() != MUS_NO_ERROR))
    return(MUS_ERROR);
  
  card = MUS_AUDIO_SYSTEM(ur_dev);
  device = MUS_AUDIO_DEVICE(ur_dev);
2139
  to_alsa_device(device, &alsa_device, &alsa_stream);
2140

2141 2142
  if (card > 0 || alsa_device > 0) 
    return(alsa_mus_error(MUS_AUDIO_CANT_READ, NULL));
2143

2144 2145 2146
  if ((alsa_stream == SND_PCM_STREAM_CAPTURE) &&
      (alsa_capture_device_name) &&
      (strcmp(alsa_capture_device_name, "default") == 0))
2147
    {
2148 2149 2150
      if (info)
	info[0] = 2;
      else return(2);
2151