; * admin/release-process: Remove some obsolete records.
[emacs.git] / src / sound.c
blob42f1fca2e20258822129325da180cc7b2c259c60
1 /* sound.c -- sound support.
3 Copyright (C) 1998-1999, 2001-2016 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 /* Written by Gerd Moellmann <gerd@gnu.org>. Tested with Luigi's
21 driver on FreeBSD 2.2.7 with a SoundBlaster 16. */
24 Modified by Ben Key <Bkey1@tampabay.rr.com> to add a partial
25 implementation of the play-sound specification for Windows.
27 Notes:
28 In the Windows implementation of play-sound-internal only the
29 :file and :volume keywords are supported. The :device keyword,
30 if present, is ignored. The :data keyword, if present, will
31 cause an error to be generated.
33 The Windows implementation of play-sound is implemented via the
34 Windows API functions mciSendString, waveOutGetVolume, and
35 waveOutSetVolume which are exported by Winmm.dll.
38 #include <config.h>
40 #if defined HAVE_SOUND
42 /* BEGIN: Common Includes */
43 #include <fcntl.h>
44 #include <unistd.h>
45 #include <sys/types.h>
46 #include <errno.h>
48 #include "lisp.h"
49 #include "atimer.h"
50 #include "syssignal.h"
51 /* END: Common Includes */
54 /* BEGIN: Non Windows Includes */
55 #ifndef WINDOWSNT
57 #include <byteswap.h>
59 #include <sys/ioctl.h>
61 /* FreeBSD has machine/soundcard.h. Voxware sound driver docs mention
62 sys/soundcard.h. So, let's try whatever's there. */
64 #ifdef HAVE_MACHINE_SOUNDCARD_H
65 #include <machine/soundcard.h>
66 #endif
67 #ifdef HAVE_SYS_SOUNDCARD_H
68 #include <sys/soundcard.h>
69 #endif
70 #ifdef HAVE_SOUNDCARD_H
71 #include <soundcard.h>
72 #endif
73 #ifdef HAVE_ALSA
74 #ifdef ALSA_SUBDIR_INCLUDE
75 #include <alsa/asoundlib.h>
76 #else
77 #include <asoundlib.h>
78 #endif /* ALSA_SUBDIR_INCLUDE */
79 #endif /* HAVE_ALSA */
81 /* END: Non Windows Includes */
83 #else /* WINDOWSNT */
85 /* BEGIN: Windows Specific Includes */
86 #include <stdio.h>
87 #include <limits.h>
88 #include <mbstring.h>
89 #include <windows.h>
90 #include <mmsystem.h>
92 #include "coding.h"
93 #include "w32common.h"
94 #include "w32.h"
95 /* END: Windows Specific Includes */
97 #endif /* WINDOWSNT */
99 /* BEGIN: Common Definitions */
101 /* Indices of attributes in a sound attributes vector. */
103 enum sound_attr
105 SOUND_FILE,
106 SOUND_DATA,
107 SOUND_DEVICE,
108 SOUND_VOLUME,
109 SOUND_ATTR_SENTINEL
112 /* END: Common Definitions */
114 /* BEGIN: Non Windows Definitions */
115 #ifndef WINDOWSNT
117 /* Structure forward declarations. */
119 struct sound;
120 struct sound_device;
122 /* The file header of RIFF-WAVE files (*.wav). Files are always in
123 little-endian byte-order. */
125 struct wav_header
127 u_int32_t magic;
128 u_int32_t length;
129 u_int32_t chunk_type;
130 u_int32_t chunk_format;
131 u_int32_t chunk_length;
132 u_int16_t format;
133 u_int16_t channels;
134 u_int32_t sample_rate;
135 u_int32_t bytes_per_second;
136 u_int16_t sample_size;
137 u_int16_t precision;
138 u_int32_t chunk_data;
139 u_int32_t data_length;
142 /* The file header of Sun adio files (*.au). Files are always in
143 big-endian byte-order. */
145 struct au_header
147 /* ASCII ".snd" */
148 u_int32_t magic_number;
150 /* Offset of data part from start of file. Minimum value is 24. */
151 u_int32_t data_offset;
153 /* Size of data part, 0xffffffff if unknown. */
154 u_int32_t data_size;
156 /* Data encoding format.
157 1 8-bit ISDN u-law
158 2 8-bit linear PCM (REF-PCM)
159 3 16-bit linear PCM
160 4 24-bit linear PCM
161 5 32-bit linear PCM
162 6 32-bit IEEE floating-point
163 7 64-bit IEEE floating-point
164 23 8-bit u-law compressed using CCITT 0.721 ADPCM voice data
165 encoding scheme. */
166 u_int32_t encoding;
168 /* Number of samples per second. */
169 u_int32_t sample_rate;
171 /* Number of interleaved channels. */
172 u_int32_t channels;
175 /* Maximum of all sound file headers sizes. */
177 #define MAX_SOUND_HEADER_BYTES \
178 max (sizeof (struct wav_header), sizeof (struct au_header))
180 /* Interface structure for sound devices. */
182 struct sound_device
184 /* If a string, the name of the device; otherwise use a default. */
185 Lisp_Object file;
187 /* File descriptor of the device. */
188 int fd;
190 /* Device-dependent format. */
191 int format;
193 /* Volume (0..100). Zero means unspecified. */
194 int volume;
196 /* Sample size. */
197 int sample_size;
199 /* Sample rate. */
200 int sample_rate;
202 /* Bytes per second. */
203 int bps;
205 /* 1 = mono, 2 = stereo, 0 = don't set. */
206 int channels;
208 /* Open device SD. */
209 void (* open) (struct sound_device *sd);
211 /* Close device SD. */
212 void (* close) (struct sound_device *sd);
214 /* Configure SD according to device-dependent parameters. */
215 void (* configure) (struct sound_device *device);
217 /* Choose a device-dependent format for outputting sound S. */
218 void (* choose_format) (struct sound_device *sd,
219 struct sound *s);
221 /* Return a preferred data size in bytes to be sent to write (below)
222 each time. 2048 is used if this is NULL. */
223 ptrdiff_t (* period_size) (struct sound_device *sd);
225 /* Write NYBTES bytes from BUFFER to device SD. */
226 void (* write) (struct sound_device *sd, const char *buffer,
227 ptrdiff_t nbytes);
229 /* A place for devices to store additional data. */
230 void *data;
233 /* An enumerator for each supported sound file type. */
235 enum sound_type
237 RIFF,
238 SUN_AUDIO
241 /* Interface structure for sound files. */
243 struct sound
245 /* The type of the file. */
246 enum sound_type type;
248 /* File descriptor of a sound file. */
249 int fd;
251 /* Pointer to sound file header. This contains header_size bytes
252 read from the start of a sound file. */
253 char *header;
255 /* Number of bytes read from sound file. This is always <=
256 MAX_SOUND_HEADER_BYTES. */
257 int header_size;
259 /* Sound data, if a string. */
260 Lisp_Object data;
262 /* Play sound file S on device SD. */
263 void (* play) (struct sound *s, struct sound_device *sd);
266 /* These are set during `play-sound-internal' so that sound_cleanup has
267 access to them. */
269 static struct sound_device *current_sound_device;
270 static struct sound *current_sound;
272 /* Function prototypes. */
274 static void vox_write (struct sound_device *, const char *, ptrdiff_t);
275 static bool wav_init (struct sound *);
276 static void wav_play (struct sound *, struct sound_device *);
277 static bool au_init (struct sound *);
278 static void au_play (struct sound *, struct sound_device *);
280 /* END: Non Windows Definitions */
281 #else /* WINDOWSNT */
283 /* BEGIN: Windows Specific Definitions */
284 static int do_play_sound (const char *, unsigned long);
286 END: Windows Specific Definitions */
287 #endif /* WINDOWSNT */
290 /***********************************************************************
291 General
292 ***********************************************************************/
294 /* BEGIN: Common functions */
296 /* Like perror, but signals an error. */
298 static _Noreturn void
299 sound_perror (const char *msg)
301 int saved_errno = errno;
303 turn_on_atimers (1);
304 #ifdef USABLE_SIGIO
306 sigset_t unblocked;
307 sigemptyset (&unblocked);
308 sigaddset (&unblocked, SIGIO);
309 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
311 #endif
312 if (saved_errno != 0)
313 error ("%s: %s", msg, strerror (saved_errno));
314 else
315 error ("%s", msg);
319 /* Display a warning message. */
321 static void
322 sound_warning (const char *msg)
324 message1 (msg);
328 /* Parse sound specification SOUND, and fill ATTRS with what is
329 found. Value is non-zero if SOUND Is a valid sound specification.
330 A valid sound specification is a list starting with the symbol
331 `sound'. The rest of the list is a property list which may
332 contain the following key/value pairs:
334 - `:file FILE'
336 FILE is the sound file to play. If it isn't an absolute name,
337 it's searched under `data-directory'.
339 - `:data DATA'
341 DATA is a string containing sound data. Either :file or :data
342 may be present, but not both.
344 - `:device DEVICE'
346 DEVICE is the name of the device to play on, e.g. "/dev/dsp2".
347 If not specified, a default device is used.
349 - `:volume VOL'
351 VOL must be an integer in the range [0, 100], or a float in the
352 range [0, 1]. */
354 static bool
355 parse_sound (Lisp_Object sound, Lisp_Object *attrs)
357 /* SOUND must be a list starting with the symbol `sound'. */
358 if (!CONSP (sound) || !EQ (XCAR (sound), Qsound))
359 return 0;
361 sound = XCDR (sound);
362 attrs[SOUND_FILE] = Fplist_get (sound, QCfile);
363 attrs[SOUND_DATA] = Fplist_get (sound, QCdata);
364 attrs[SOUND_DEVICE] = Fplist_get (sound, QCdevice);
365 attrs[SOUND_VOLUME] = Fplist_get (sound, QCvolume);
367 #ifndef WINDOWSNT
368 /* File name or data must be specified. */
369 if (!STRINGP (attrs[SOUND_FILE])
370 && !STRINGP (attrs[SOUND_DATA]))
371 return 0;
372 #else /* WINDOWSNT */
374 Data is not supported in Windows. Therefore a
375 File name MUST be supplied.
377 if (!STRINGP (attrs[SOUND_FILE]))
379 return 0;
381 #endif /* WINDOWSNT */
383 /* Volume must be in the range 0..100 or unspecified. */
384 if (!NILP (attrs[SOUND_VOLUME]))
386 if (INTEGERP (attrs[SOUND_VOLUME]))
388 if (XINT (attrs[SOUND_VOLUME]) < 0
389 || XINT (attrs[SOUND_VOLUME]) > 100)
390 return 0;
392 else if (FLOATP (attrs[SOUND_VOLUME]))
394 if (XFLOAT_DATA (attrs[SOUND_VOLUME]) < 0
395 || XFLOAT_DATA (attrs[SOUND_VOLUME]) > 1)
396 return 0;
398 else
399 return 0;
402 #ifndef WINDOWSNT
403 /* Device must be a string or unspecified. */
404 if (!NILP (attrs[SOUND_DEVICE])
405 && !STRINGP (attrs[SOUND_DEVICE]))
406 return 0;
407 #endif /* WINDOWSNT */
409 Since device is ignored in Windows, it does not matter
410 what it is.
412 return 1;
415 /* END: Common functions */
417 /* BEGIN: Non Windows functions */
418 #ifndef WINDOWSNT
420 /* Return S's value as a string if S is a string, otherwise DEFAULT_VALUE. */
422 static char const *
423 string_default (Lisp_Object s, char const *default_value)
425 return STRINGP (s) ? SSDATA (s) : default_value;
429 /* Find out the type of the sound file whose file descriptor is FD.
430 S is the sound file structure to fill in. */
432 static void
433 find_sound_type (struct sound *s)
435 if (!wav_init (s) && !au_init (s))
436 error ("Unknown sound format");
440 /* Function installed by play-sound-internal with record_unwind_protect_void. */
442 static void
443 sound_cleanup (void)
445 if (current_sound_device->close)
446 current_sound_device->close (current_sound_device);
447 if (current_sound->fd > 0)
448 emacs_close (current_sound->fd);
449 xfree (current_sound_device);
450 xfree (current_sound);
453 /***********************************************************************
454 Byte-order Conversion
455 ***********************************************************************/
457 /* Convert 32-bit value VALUE which is in little-endian byte-order
458 to host byte-order. */
460 static u_int32_t
461 le2hl (u_int32_t value)
463 #ifdef WORDS_BIGENDIAN
464 value = bswap_32 (value);
465 #endif
466 return value;
470 /* Convert 16-bit value VALUE which is in little-endian byte-order
471 to host byte-order. */
473 static u_int16_t
474 le2hs (u_int16_t value)
476 #ifdef WORDS_BIGENDIAN
477 value = bswap_16 (value);
478 #endif
479 return value;
483 /* Convert 32-bit value VALUE which is in big-endian byte-order
484 to host byte-order. */
486 static u_int32_t
487 be2hl (u_int32_t value)
489 #ifndef WORDS_BIGENDIAN
490 value = bswap_32 (value);
491 #endif
492 return value;
495 /***********************************************************************
496 RIFF-WAVE (*.wav)
497 ***********************************************************************/
499 /* Try to initialize sound file S from S->header. S->header
500 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
501 sound file. If the file is a WAV-format file, set up interface
502 functions in S and convert header fields to host byte-order.
503 Value is true if the file is a WAV file. */
505 static bool
506 wav_init (struct sound *s)
508 struct wav_header *header = (struct wav_header *) s->header;
510 if (s->header_size < sizeof *header
511 || memcmp (s->header, "RIFF", 4) != 0)
512 return 0;
514 /* WAV files are in little-endian order. Convert the header
515 if on a big-endian machine. */
516 header->magic = le2hl (header->magic);
517 header->length = le2hl (header->length);
518 header->chunk_type = le2hl (header->chunk_type);
519 header->chunk_format = le2hl (header->chunk_format);
520 header->chunk_length = le2hl (header->chunk_length);
521 header->format = le2hs (header->format);
522 header->channels = le2hs (header->channels);
523 header->sample_rate = le2hl (header->sample_rate);
524 header->bytes_per_second = le2hl (header->bytes_per_second);
525 header->sample_size = le2hs (header->sample_size);
526 header->precision = le2hs (header->precision);
527 header->chunk_data = le2hl (header->chunk_data);
528 header->data_length = le2hl (header->data_length);
530 /* Set up the interface functions for WAV. */
531 s->type = RIFF;
532 s->play = wav_play;
534 return 1;
538 /* Play RIFF-WAVE audio file S on sound device SD. */
540 static void
541 wav_play (struct sound *s, struct sound_device *sd)
543 struct wav_header *header = (struct wav_header *) s->header;
545 /* Let the device choose a suitable device-dependent format
546 for the file. */
547 sd->choose_format (sd, s);
549 /* Configure the device. */
550 sd->sample_size = header->sample_size;
551 sd->sample_rate = header->sample_rate;
552 sd->bps = header->bytes_per_second;
553 sd->channels = header->channels;
554 sd->configure (sd);
556 /* Copy sound data to the device. The WAV file specification is
557 actually more complex. This simple scheme worked with all WAV
558 files I found so far. If someone feels inclined to implement the
559 whole RIFF-WAVE spec, please do. */
560 if (STRINGP (s->data))
561 sd->write (sd, SSDATA (s->data) + sizeof *header,
562 SBYTES (s->data) - sizeof *header);
563 else
565 ptrdiff_t nbytes = 0;
566 ptrdiff_t blksize = sd->period_size ? sd->period_size (sd) : 2048;
567 ptrdiff_t data_left = header->data_length;
568 USE_SAFE_ALLOCA;
569 char *buffer = SAFE_ALLOCA (blksize);
570 lseek (s->fd, sizeof *header, SEEK_SET);
571 while (data_left > 0
572 && (nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
574 /* Don't play possible garbage at the end of file */
575 if (data_left < nbytes) nbytes = data_left;
576 data_left -= nbytes;
577 sd->write (sd, buffer, nbytes);
580 if (nbytes < 0)
581 sound_perror ("Error reading sound file");
582 SAFE_FREE ();
587 /***********************************************************************
588 Sun Audio (*.au)
589 ***********************************************************************/
591 /* Sun audio file encodings. */
593 enum au_encoding
595 AU_ENCODING_ULAW_8 = 1,
596 AU_ENCODING_8,
597 AU_ENCODING_16,
598 AU_ENCODING_24,
599 AU_ENCODING_32,
600 AU_ENCODING_IEEE32,
601 AU_ENCODING_IEEE64,
602 AU_COMPRESSED = 23,
603 AU_ENCODING_ALAW_8 = 27
607 /* Try to initialize sound file S from S->header. S->header
608 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
609 sound file. If the file is a AU-format file, set up interface
610 functions in S and convert header fields to host byte-order.
611 Value is true if the file is an AU file. */
613 static bool
614 au_init (struct sound *s)
616 struct au_header *header = (struct au_header *) s->header;
618 if (s->header_size < sizeof *header
619 || memcmp (s->header, ".snd", 4) != 0)
620 return 0;
622 header->magic_number = be2hl (header->magic_number);
623 header->data_offset = be2hl (header->data_offset);
624 header->data_size = be2hl (header->data_size);
625 header->encoding = be2hl (header->encoding);
626 header->sample_rate = be2hl (header->sample_rate);
627 header->channels = be2hl (header->channels);
629 /* Set up the interface functions for AU. */
630 s->type = SUN_AUDIO;
631 s->play = au_play;
633 return 1;
637 /* Play Sun audio file S on sound device SD. */
639 static void
640 au_play (struct sound *s, struct sound_device *sd)
642 struct au_header *header = (struct au_header *) s->header;
644 sd->sample_size = 0;
645 sd->sample_rate = header->sample_rate;
646 sd->bps = 0;
647 sd->channels = header->channels;
648 sd->choose_format (sd, s);
649 sd->configure (sd);
651 if (STRINGP (s->data))
652 sd->write (sd, SSDATA (s->data) + header->data_offset,
653 SBYTES (s->data) - header->data_offset);
654 else
656 ptrdiff_t blksize = sd->period_size ? sd->period_size (sd) : 2048;
657 ptrdiff_t nbytes;
659 /* Seek */
660 lseek (s->fd, header->data_offset, SEEK_SET);
662 /* Copy sound data to the device. */
663 USE_SAFE_ALLOCA;
664 char *buffer = SAFE_ALLOCA (blksize);
665 while ((nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
666 sd->write (sd, buffer, nbytes);
668 if (nbytes < 0)
669 sound_perror ("Error reading sound file");
670 SAFE_FREE ();
675 /***********************************************************************
676 Voxware Driver Interface
677 ***********************************************************************/
679 /* This driver is available on GNU/Linux, and the free BSDs. FreeBSD
680 has a compatible own driver aka Luigi's driver. */
683 /* Open device SD. If SD->file is a string, open that device,
684 otherwise use a default device name. */
686 static void
687 vox_open (struct sound_device *sd)
689 /* Open the sound device (eg /dev/dsp). */
690 char const *file = string_default (sd->file, DEFAULT_SOUND_DEVICE);
691 sd->fd = emacs_open (file, O_WRONLY, 0);
692 if (sd->fd < 0)
693 sound_perror (file);
697 /* Configure device SD from parameters in it. */
699 static void
700 vox_configure (struct sound_device *sd)
702 int val;
703 #ifdef USABLE_SIGIO
704 sigset_t oldset, blocked;
705 #endif
707 eassert (sd->fd >= 0);
709 /* On GNU/Linux, it seems that the device driver doesn't like to be
710 interrupted by a signal. Block the ones we know to cause
711 troubles. */
712 turn_on_atimers (0);
713 #ifdef USABLE_SIGIO
714 sigemptyset (&blocked);
715 sigaddset (&blocked, SIGIO);
716 pthread_sigmask (SIG_BLOCK, &blocked, &oldset);
717 #endif
719 val = sd->format;
720 if (ioctl (sd->fd, SNDCTL_DSP_SETFMT, &sd->format) < 0
721 || val != sd->format)
722 sound_perror ("Could not set sound format");
724 val = sd->channels != 1;
725 if (ioctl (sd->fd, SNDCTL_DSP_STEREO, &val) < 0
726 || val != (sd->channels != 1))
727 sound_perror ("Could not set stereo/mono");
729 /* I think bps and sampling_rate are the same, but who knows.
730 Check this. and use SND_DSP_SPEED for both. */
731 if (sd->sample_rate > 0)
733 val = sd->sample_rate;
734 if (ioctl (sd->fd, SNDCTL_DSP_SPEED, &sd->sample_rate) < 0)
735 sound_perror ("Could not set sound speed");
736 else if (val != sd->sample_rate)
737 sound_warning ("Could not set sample rate");
740 if (sd->volume > 0)
742 int volume = sd->volume & 0xff;
743 volume |= volume << 8;
744 /* This may fail if there is no mixer. Ignore the failure. */
745 ioctl (sd->fd, SOUND_MIXER_WRITE_PCM, &volume);
748 turn_on_atimers (1);
749 #ifdef USABLE_SIGIO
750 pthread_sigmask (SIG_SETMASK, &oldset, 0);
751 #endif
755 /* Close device SD if it is open. */
757 static void
758 vox_close (struct sound_device *sd)
760 if (sd->fd >= 0)
762 /* On GNU/Linux, it seems that the device driver doesn't like to
763 be interrupted by a signal. Block the ones we know to cause
764 troubles. */
765 #ifdef USABLE_SIGIO
766 sigset_t blocked, oldset;
767 sigemptyset (&blocked);
768 sigaddset (&blocked, SIGIO);
769 pthread_sigmask (SIG_BLOCK, &blocked, &oldset);
770 #endif
771 turn_on_atimers (0);
773 /* Flush sound data, and reset the device. */
774 ioctl (sd->fd, SNDCTL_DSP_SYNC, NULL);
776 turn_on_atimers (1);
777 #ifdef USABLE_SIGIO
778 pthread_sigmask (SIG_SETMASK, &oldset, 0);
779 #endif
781 /* Close the device. */
782 emacs_close (sd->fd);
783 sd->fd = -1;
788 /* Choose device-dependent format for device SD from sound file S. */
790 static void
791 vox_choose_format (struct sound_device *sd, struct sound *s)
793 if (s->type == RIFF)
795 struct wav_header *h = (struct wav_header *) s->header;
796 if (h->precision == 8)
797 sd->format = AFMT_U8;
798 else if (h->precision == 16)
799 sd->format = AFMT_S16_LE;
800 else
801 error ("Unsupported WAV file format");
803 else if (s->type == SUN_AUDIO)
805 struct au_header *header = (struct au_header *) s->header;
806 switch (header->encoding)
808 case AU_ENCODING_ULAW_8:
809 case AU_ENCODING_IEEE32:
810 case AU_ENCODING_IEEE64:
811 sd->format = AFMT_MU_LAW;
812 break;
814 case AU_ENCODING_8:
815 case AU_ENCODING_16:
816 case AU_ENCODING_24:
817 case AU_ENCODING_32:
818 sd->format = AFMT_S16_LE;
819 break;
821 default:
822 error ("Unsupported AU file format");
825 else
826 emacs_abort ();
830 /* Initialize device SD. Set up the interface functions in the device
831 structure. */
833 static bool
834 vox_init (struct sound_device *sd)
836 /* Open the sound device (eg /dev/dsp). */
837 char const *file = string_default (sd->file, DEFAULT_SOUND_DEVICE);
838 int fd = emacs_open (file, O_WRONLY, 0);
839 if (fd >= 0)
840 emacs_close (fd);
841 else
842 return 0;
844 sd->fd = -1;
845 sd->open = vox_open;
846 sd->close = vox_close;
847 sd->configure = vox_configure;
848 sd->choose_format = vox_choose_format;
849 sd->write = vox_write;
850 sd->period_size = NULL;
852 return 1;
855 /* Write NBYTES bytes from BUFFER to device SD. */
857 static void
858 vox_write (struct sound_device *sd, const char *buffer, ptrdiff_t nbytes)
860 if (emacs_write_sig (sd->fd, buffer, nbytes) != nbytes)
861 sound_perror ("Error writing to sound device");
864 #ifdef HAVE_ALSA
865 /***********************************************************************
866 ALSA Driver Interface
867 ***********************************************************************/
869 /* This driver is available on GNU/Linux. */
871 #ifndef DEFAULT_ALSA_SOUND_DEVICE
872 #define DEFAULT_ALSA_SOUND_DEVICE "default"
873 #endif
875 static _Noreturn void
876 alsa_sound_perror (const char *msg, int err)
878 error ("%s: %s", msg, snd_strerror (err));
881 struct alsa_params
883 snd_pcm_t *handle;
884 snd_pcm_hw_params_t *hwparams;
885 snd_pcm_sw_params_t *swparams;
886 snd_pcm_uframes_t period_size;
889 /* Open device SD. If SD->file is a string, open that device,
890 otherwise use a default device name. */
892 static void
893 alsa_open (struct sound_device *sd)
895 /* Open the sound device. Default is "default". */
896 struct alsa_params *p = xmalloc (sizeof *p);
897 char const *file = string_default (sd->file, DEFAULT_ALSA_SOUND_DEVICE);
898 int err;
900 p->handle = NULL;
901 p->hwparams = NULL;
902 p->swparams = NULL;
904 sd->fd = -1;
905 sd->data = p;
908 err = snd_pcm_open (&p->handle, file, SND_PCM_STREAM_PLAYBACK, 0);
909 if (err < 0)
910 alsa_sound_perror (file, err);
913 static ptrdiff_t
914 alsa_period_size (struct sound_device *sd)
916 struct alsa_params *p = (struct alsa_params *) sd->data;
917 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
918 return p->period_size * (fact > 0 ? fact : 1);
921 static void
922 alsa_configure (struct sound_device *sd)
924 int val, err, dir;
925 unsigned uval;
926 struct alsa_params *p = (struct alsa_params *) sd->data;
927 snd_pcm_uframes_t buffer_size;
929 eassert (p->handle != 0);
931 err = snd_pcm_hw_params_malloc (&p->hwparams);
932 if (err < 0)
933 alsa_sound_perror ("Could not allocate hardware parameter structure", err);
935 err = snd_pcm_sw_params_malloc (&p->swparams);
936 if (err < 0)
937 alsa_sound_perror ("Could not allocate software parameter structure", err);
939 err = snd_pcm_hw_params_any (p->handle, p->hwparams);
940 if (err < 0)
941 alsa_sound_perror ("Could not initialize hardware parameter structure", err);
943 err = snd_pcm_hw_params_set_access (p->handle, p->hwparams,
944 SND_PCM_ACCESS_RW_INTERLEAVED);
945 if (err < 0)
946 alsa_sound_perror ("Could not set access type", err);
948 val = sd->format;
949 err = snd_pcm_hw_params_set_format (p->handle, p->hwparams, val);
950 if (err < 0)
951 alsa_sound_perror ("Could not set sound format", err);
953 uval = sd->sample_rate;
954 err = snd_pcm_hw_params_set_rate_near (p->handle, p->hwparams, &uval, 0);
955 if (err < 0)
956 alsa_sound_perror ("Could not set sample rate", err);
958 val = sd->channels;
959 err = snd_pcm_hw_params_set_channels (p->handle, p->hwparams, val);
960 if (err < 0)
961 alsa_sound_perror ("Could not set channel count", err);
963 err = snd_pcm_hw_params (p->handle, p->hwparams);
964 if (err < 0)
965 alsa_sound_perror ("Could not set parameters", err);
968 err = snd_pcm_hw_params_get_period_size (p->hwparams, &p->period_size, &dir);
969 if (err < 0)
970 alsa_sound_perror ("Unable to get period size for playback", err);
972 err = snd_pcm_hw_params_get_buffer_size (p->hwparams, &buffer_size);
973 if (err < 0)
974 alsa_sound_perror ("Unable to get buffer size for playback", err);
976 err = snd_pcm_sw_params_current (p->handle, p->swparams);
977 if (err < 0)
978 alsa_sound_perror ("Unable to determine current swparams for playback",
979 err);
981 /* Start the transfer when the buffer is almost full */
982 err = snd_pcm_sw_params_set_start_threshold (p->handle, p->swparams,
983 (buffer_size / p->period_size)
984 * p->period_size);
985 if (err < 0)
986 alsa_sound_perror ("Unable to set start threshold mode for playback", err);
988 /* Allow the transfer when at least period_size samples can be processed */
989 err = snd_pcm_sw_params_set_avail_min (p->handle, p->swparams, p->period_size);
990 if (err < 0)
991 alsa_sound_perror ("Unable to set avail min for playback", err);
993 err = snd_pcm_sw_params (p->handle, p->swparams);
994 if (err < 0)
995 alsa_sound_perror ("Unable to set sw params for playback\n", err);
997 snd_pcm_hw_params_free (p->hwparams);
998 p->hwparams = NULL;
999 snd_pcm_sw_params_free (p->swparams);
1000 p->swparams = NULL;
1002 err = snd_pcm_prepare (p->handle);
1003 if (err < 0)
1004 alsa_sound_perror ("Could not prepare audio interface for use", err);
1006 if (sd->volume > 0)
1008 int chn;
1009 snd_mixer_t *handle;
1010 snd_mixer_elem_t *e;
1011 if (snd_mixer_open (&handle, 0) >= 0)
1013 char const *file = string_default (sd->file,
1014 DEFAULT_ALSA_SOUND_DEVICE);
1015 if (snd_mixer_attach (handle, file) >= 0
1016 && snd_mixer_load (handle) >= 0
1017 && snd_mixer_selem_register (handle, NULL, NULL) >= 0)
1018 for (e = snd_mixer_first_elem (handle);
1020 e = snd_mixer_elem_next (e))
1022 if (snd_mixer_selem_has_playback_volume (e))
1024 long pmin, pmax, vol;
1025 snd_mixer_selem_get_playback_volume_range (e, &pmin, &pmax);
1026 vol = pmin + (sd->volume * (pmax - pmin)) / 100;
1028 for (chn = 0; chn <= SND_MIXER_SCHN_LAST; chn++)
1029 snd_mixer_selem_set_playback_volume (e, chn, vol);
1032 snd_mixer_close (handle);
1038 /* Close device SD if it is open. */
1040 static void
1041 alsa_close (struct sound_device *sd)
1043 struct alsa_params *p = (struct alsa_params *) sd->data;
1044 if (p)
1046 if (p->hwparams)
1047 snd_pcm_hw_params_free (p->hwparams);
1048 if (p->swparams)
1049 snd_pcm_sw_params_free (p->swparams);
1050 if (p->handle)
1052 snd_pcm_drain (p->handle);
1053 snd_pcm_close (p->handle);
1055 xfree (p);
1059 /* Choose device-dependent format for device SD from sound file S. */
1061 static void
1062 alsa_choose_format (struct sound_device *sd, struct sound *s)
1064 if (s->type == RIFF)
1066 struct wav_header *h = (struct wav_header *) s->header;
1067 if (h->precision == 8)
1068 sd->format = SND_PCM_FORMAT_U8;
1069 else if (h->precision == 16)
1070 sd->format = SND_PCM_FORMAT_S16_LE;
1071 else
1072 error ("Unsupported WAV file format");
1074 else if (s->type == SUN_AUDIO)
1076 struct au_header *header = (struct au_header *) s->header;
1077 switch (header->encoding)
1079 case AU_ENCODING_ULAW_8:
1080 sd->format = SND_PCM_FORMAT_MU_LAW;
1081 break;
1082 case AU_ENCODING_ALAW_8:
1083 sd->format = SND_PCM_FORMAT_A_LAW;
1084 break;
1085 case AU_ENCODING_IEEE32:
1086 sd->format = SND_PCM_FORMAT_FLOAT_BE;
1087 break;
1088 case AU_ENCODING_IEEE64:
1089 sd->format = SND_PCM_FORMAT_FLOAT64_BE;
1090 break;
1091 case AU_ENCODING_8:
1092 sd->format = SND_PCM_FORMAT_S8;
1093 break;
1094 case AU_ENCODING_16:
1095 sd->format = SND_PCM_FORMAT_S16_BE;
1096 break;
1097 case AU_ENCODING_24:
1098 sd->format = SND_PCM_FORMAT_S24_BE;
1099 break;
1100 case AU_ENCODING_32:
1101 sd->format = SND_PCM_FORMAT_S32_BE;
1102 break;
1104 default:
1105 error ("Unsupported AU file format");
1108 else
1109 emacs_abort ();
1113 /* Write NBYTES bytes from BUFFER to device SD. */
1115 static void
1116 alsa_write (struct sound_device *sd, const char *buffer, ptrdiff_t nbytes)
1118 struct alsa_params *p = (struct alsa_params *) sd->data;
1120 /* The the third parameter to snd_pcm_writei is frames, not bytes. */
1121 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
1122 ptrdiff_t nwritten = 0;
1123 int err;
1125 while (nwritten < nbytes)
1127 snd_pcm_uframes_t frames = (nbytes - nwritten)/fact;
1128 if (frames == 0) break;
1130 err = snd_pcm_writei (p->handle, buffer + nwritten, frames);
1131 if (err < 0)
1133 if (err == -EPIPE)
1134 { /* under-run */
1135 err = snd_pcm_prepare (p->handle);
1136 if (err < 0)
1137 alsa_sound_perror ("Can't recover from underrun, prepare failed",
1138 err);
1140 else if (err == -ESTRPIPE)
1142 while ((err = snd_pcm_resume (p->handle)) == -EAGAIN)
1143 sleep (1); /* wait until the suspend flag is released */
1144 if (err < 0)
1146 err = snd_pcm_prepare (p->handle);
1147 if (err < 0)
1148 alsa_sound_perror ("Can't recover from suspend, "
1149 "prepare failed",
1150 err);
1153 else
1154 alsa_sound_perror ("Error writing to sound device", err);
1157 else
1158 nwritten += err * fact;
1162 static void
1163 snd_error_quiet (const char *file, int line, const char *function, int err,
1164 const char *fmt)
1168 /* Initialize device SD. Set up the interface functions in the device
1169 structure. */
1171 static bool
1172 alsa_init (struct sound_device *sd)
1174 /* Open the sound device. Default is "default". */
1175 char const *file = string_default (sd->file, DEFAULT_ALSA_SOUND_DEVICE);
1176 snd_pcm_t *handle;
1177 int err;
1179 snd_lib_error_set_handler ((snd_lib_error_handler_t) snd_error_quiet);
1180 err = snd_pcm_open (&handle, file, SND_PCM_STREAM_PLAYBACK, 0);
1181 snd_lib_error_set_handler (NULL);
1182 if (err < 0)
1183 return 0;
1184 snd_pcm_close (handle);
1186 sd->fd = -1;
1187 sd->open = alsa_open;
1188 sd->close = alsa_close;
1189 sd->configure = alsa_configure;
1190 sd->choose_format = alsa_choose_format;
1191 sd->write = alsa_write;
1192 sd->period_size = alsa_period_size;
1194 return 1;
1197 #endif /* HAVE_ALSA */
1200 /* END: Non Windows functions */
1201 #else /* WINDOWSNT */
1203 /* BEGIN: Windows specific functions */
1205 #define SOUND_WARNING(func, error, text) \
1206 do { \
1207 char buf[1024]; \
1208 char err_string[MAXERRORLENGTH]; \
1209 func (error, err_string, sizeof (err_string)); \
1210 _snprintf (buf, sizeof (buf), "%s\nMCI Error: %s", \
1211 text, err_string); \
1212 message_with_string ("%s", build_string (buf), 1); \
1213 } while (0)
1215 static int
1216 do_play_sound (const char *psz_file, unsigned long ui_volume)
1218 int i_result = 0;
1219 MCIERROR mci_error = 0;
1220 char sz_cmd_buf_a[520];
1221 char sz_ret_buf_a[520];
1222 MMRESULT mm_result = MMSYSERR_NOERROR;
1223 unsigned long ui_volume_org = 0;
1224 BOOL b_reset_volume = FALSE;
1225 char warn_text[560];
1227 /* Since UNICOWS.DLL includes only a stub for mciSendStringW, we
1228 need to encode the file in the ANSI codepage on Windows 9X even
1229 if w32_unicode_filenames is non-zero. */
1230 if (w32_major_version <= 4 || !w32_unicode_filenames)
1232 char fname_a[MAX_PATH], shortname[MAX_PATH], *fname_to_use;
1234 filename_to_ansi (psz_file, fname_a);
1235 fname_to_use = fname_a;
1236 /* If the file name is not encodable in ANSI, try its short 8+3
1237 alias. This will only work if w32_unicode_filenames is
1238 non-zero. */
1239 if (_mbspbrk ((const unsigned char *)fname_a,
1240 (const unsigned char *)"?"))
1242 if (w32_get_short_filename (psz_file, shortname, MAX_PATH))
1243 fname_to_use = shortname;
1244 else
1245 mci_error = MCIERR_FILE_NOT_FOUND;
1248 if (!mci_error)
1250 memset (sz_cmd_buf_a, 0, sizeof (sz_cmd_buf_a));
1251 memset (sz_ret_buf_a, 0, sizeof (sz_ret_buf_a));
1252 sprintf (sz_cmd_buf_a,
1253 "open \"%s\" alias GNUEmacs_PlaySound_Device wait",
1254 fname_to_use);
1255 mci_error = mciSendStringA (sz_cmd_buf_a,
1256 sz_ret_buf_a, sizeof (sz_ret_buf_a), NULL);
1259 else
1261 wchar_t sz_cmd_buf_w[520];
1262 wchar_t sz_ret_buf_w[520];
1263 wchar_t fname_w[MAX_PATH];
1265 filename_to_utf16 (psz_file, fname_w);
1266 memset (sz_cmd_buf_w, 0, sizeof (sz_cmd_buf_w));
1267 memset (sz_ret_buf_w, 0, sizeof (sz_ret_buf_w));
1268 /* _swprintf is not available on Windows 9X, so we construct the
1269 UTF-16 command string by hand. */
1270 wcscpy (sz_cmd_buf_w, L"open \"");
1271 wcscat (sz_cmd_buf_w, fname_w);
1272 wcscat (sz_cmd_buf_w, L"\" alias GNUEmacs_PlaySound_Device wait");
1273 mci_error = mciSendStringW (sz_cmd_buf_w,
1274 sz_ret_buf_w, ARRAYELTS (sz_ret_buf_w) , NULL);
1276 if (mci_error != 0)
1278 strcpy (warn_text,
1279 "mciSendString: 'open' command failed to open sound file ");
1280 strcat (warn_text, psz_file);
1281 SOUND_WARNING (mciGetErrorString, mci_error, warn_text);
1282 i_result = (int) mci_error;
1283 return i_result;
1285 if ((ui_volume > 0) && (ui_volume != UINT_MAX))
1287 mm_result = waveOutGetVolume ((HWAVEOUT) WAVE_MAPPER, &ui_volume_org);
1288 if (mm_result == MMSYSERR_NOERROR)
1290 b_reset_volume = TRUE;
1291 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume);
1292 if (mm_result != MMSYSERR_NOERROR)
1294 SOUND_WARNING (waveOutGetErrorText, mm_result,
1295 "waveOutSetVolume: failed to set the volume level"
1296 " of the WAVE_MAPPER device.\n"
1297 "As a result, the user selected volume level will"
1298 " not be used.");
1301 else
1303 SOUND_WARNING (waveOutGetErrorText, mm_result,
1304 "waveOutGetVolume: failed to obtain the original"
1305 " volume level of the WAVE_MAPPER device.\n"
1306 "As a result, the user selected volume level will"
1307 " not be used.");
1310 memset (sz_cmd_buf_a, 0, sizeof (sz_cmd_buf_a));
1311 memset (sz_ret_buf_a, 0, sizeof (sz_ret_buf_a));
1312 strcpy (sz_cmd_buf_a, "play GNUEmacs_PlaySound_Device wait");
1313 mci_error = mciSendStringA (sz_cmd_buf_a, sz_ret_buf_a, sizeof (sz_ret_buf_a),
1314 NULL);
1315 if (mci_error != 0)
1317 strcpy (warn_text,
1318 "mciSendString: 'play' command failed to play sound file ");
1319 strcat (warn_text, psz_file);
1320 SOUND_WARNING (mciGetErrorString, mci_error, warn_text);
1321 i_result = (int) mci_error;
1323 memset (sz_cmd_buf_a, 0, sizeof (sz_cmd_buf_a));
1324 memset (sz_ret_buf_a, 0, sizeof (sz_ret_buf_a));
1325 strcpy (sz_cmd_buf_a, "close GNUEmacs_PlaySound_Device wait");
1326 mci_error = mciSendStringA (sz_cmd_buf_a, sz_ret_buf_a, sizeof (sz_ret_buf_a),
1327 NULL);
1328 if (b_reset_volume == TRUE)
1330 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume_org);
1331 if (mm_result != MMSYSERR_NOERROR)
1333 SOUND_WARNING (waveOutGetErrorText, mm_result,
1334 "waveOutSetVolume: failed to reset the original"
1335 " volume level of the WAVE_MAPPER device.");
1338 return i_result;
1341 /* END: Windows specific functions */
1343 #endif /* WINDOWSNT */
1345 DEFUN ("play-sound-internal", Fplay_sound_internal, Splay_sound_internal, 1, 1, 0,
1346 doc: /* Play sound SOUND.
1348 Internal use only, use `play-sound' instead. */)
1349 (Lisp_Object sound)
1351 Lisp_Object attrs[SOUND_ATTR_SENTINEL];
1352 ptrdiff_t count = SPECPDL_INDEX ();
1354 #ifdef WINDOWSNT
1355 unsigned long ui_volume_tmp = UINT_MAX;
1356 unsigned long ui_volume = UINT_MAX;
1357 #endif /* WINDOWSNT */
1359 /* Parse the sound specification. Give up if it is invalid. */
1360 if (!parse_sound (sound, attrs))
1361 error ("Invalid sound specification");
1363 Lisp_Object file = Qnil;
1365 #ifndef WINDOWSNT
1366 current_sound_device = xzalloc (sizeof *current_sound_device);
1367 current_sound = xzalloc (sizeof *current_sound);
1368 record_unwind_protect_void (sound_cleanup);
1369 char headerbuf[MAX_SOUND_HEADER_BYTES];
1370 current_sound->header = headerbuf;
1372 if (STRINGP (attrs[SOUND_FILE]))
1374 /* Open the sound file. */
1375 current_sound->fd = openp (list1 (Vdata_directory),
1376 attrs[SOUND_FILE], Qnil, &file, Qnil, false);
1377 if (current_sound->fd < 0)
1378 sound_perror ("Could not open sound file");
1380 /* Read the first bytes from the file. */
1381 current_sound->header_size
1382 = emacs_read (current_sound->fd, current_sound->header,
1383 MAX_SOUND_HEADER_BYTES);
1384 if (current_sound->header_size < 0)
1385 sound_perror ("Invalid sound file header");
1387 else
1389 current_sound->data = attrs[SOUND_DATA];
1390 current_sound->header_size = min (MAX_SOUND_HEADER_BYTES, SBYTES (current_sound->data));
1391 memcpy (current_sound->header, SDATA (current_sound->data),
1392 current_sound->header_size);
1395 /* Find out the type of sound. Give up if we can't tell. */
1396 find_sound_type (current_sound);
1398 /* Set up a device. */
1399 current_sound_device->file = attrs[SOUND_DEVICE];
1401 if (INTEGERP (attrs[SOUND_VOLUME]))
1402 current_sound_device->volume = XFASTINT (attrs[SOUND_VOLUME]);
1403 else if (FLOATP (attrs[SOUND_VOLUME]))
1404 current_sound_device->volume = XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1406 CALLN (Frun_hook_with_args, Qplay_sound_functions, sound);
1408 #ifdef HAVE_ALSA
1409 if (!alsa_init (current_sound_device))
1410 #endif
1411 if (!vox_init (current_sound_device))
1412 error ("No usable sound device driver found");
1414 /* Open the device. */
1415 current_sound_device->open (current_sound_device);
1417 /* Play the sound. */
1418 current_sound->play (current_sound, current_sound_device);
1420 #else /* WINDOWSNT */
1422 file = Fexpand_file_name (attrs[SOUND_FILE], Vdata_directory);
1423 file = ENCODE_FILE (file);
1424 if (INTEGERP (attrs[SOUND_VOLUME]))
1426 ui_volume_tmp = XFASTINT (attrs[SOUND_VOLUME]);
1428 else if (FLOATP (attrs[SOUND_VOLUME]))
1430 ui_volume_tmp = XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1433 CALLN (Frun_hook_with_args, Qplay_sound_functions, sound);
1436 Based on some experiments I have conducted, a value of 100 or less
1437 for the sound volume is much too low. You cannot even hear it.
1438 A value of UINT_MAX indicates that you wish for the sound to played
1439 at the maximum possible volume. A value of UINT_MAX/2 plays the
1440 sound at 50% maximum volume. Therefore the value passed to do_play_sound
1441 (and thus to waveOutSetVolume) must be some fraction of UINT_MAX.
1442 The following code adjusts the user specified volume level appropriately.
1444 if ((ui_volume_tmp > 0) && (ui_volume_tmp <= 100))
1446 ui_volume = ui_volume_tmp * (UINT_MAX / 100);
1448 (void)do_play_sound (SSDATA (file), ui_volume);
1450 #endif /* WINDOWSNT */
1452 return unbind_to (count, Qnil);
1455 /***********************************************************************
1456 Initialization
1457 ***********************************************************************/
1459 void
1460 syms_of_sound (void)
1462 DEFSYM (QCdevice, ":device");
1463 DEFSYM (QCvolume, ":volume");
1464 DEFSYM (Qsound, "sound");
1465 DEFSYM (Qplay_sound_functions, "play-sound-functions");
1467 defsubr (&Splay_sound_internal);
1470 #endif /* HAVE_SOUND */