* Makefile.in (${srcdir}/info/dir): Make sure info directory exists (backport)
[emacs.git] / src / sound.c
blob552f75b68e836428aa76ece0a76a502c96135131
1 /* sound.c -- sound support.
3 Copyright (C) 1998-1999, 2001-2014 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 "dispextern.h"
50 #include "atimer.h"
51 #include "syssignal.h"
52 /* END: Common Includes */
55 /* BEGIN: Non Windows Includes */
56 #ifndef WINDOWSNT
58 #include <byteswap.h>
60 #include <sys/ioctl.h>
62 /* FreeBSD has machine/soundcard.h. Voxware sound driver docs mention
63 sys/soundcard.h. So, let's try whatever's there. */
65 #ifdef HAVE_MACHINE_SOUNDCARD_H
66 #include <machine/soundcard.h>
67 #endif
68 #ifdef HAVE_SYS_SOUNDCARD_H
69 #include <sys/soundcard.h>
70 #endif
71 #ifdef HAVE_SOUNDCARD_H
72 #include <soundcard.h>
73 #endif
74 #ifdef HAVE_ALSA
75 #ifdef ALSA_SUBDIR_INCLUDE
76 #include <alsa/asoundlib.h>
77 #else
78 #include <asoundlib.h>
79 #endif /* ALSA_SUBDIR_INCLUDE */
80 #endif /* HAVE_ALSA */
82 /* END: Non Windows Includes */
84 #else /* WINDOWSNT */
86 /* BEGIN: Windows Specific Includes */
87 #include <stdio.h>
88 #include <limits.h>
89 #include <windows.h>
90 #include <mmsystem.h>
92 #include "coding.h"
93 #include "w32.h"
94 /* END: Windows Specific Includes */
96 #endif /* WINDOWSNT */
98 /* BEGIN: Common Definitions */
100 /* Symbols. */
102 static Lisp_Object QCvolume, QCdevice;
103 static Lisp_Object Qsound;
104 static Lisp_Object Qplay_sound_functions;
106 /* Indices of attributes in a sound attributes vector. */
108 enum sound_attr
110 SOUND_FILE,
111 SOUND_DATA,
112 SOUND_DEVICE,
113 SOUND_VOLUME,
114 SOUND_ATTR_SENTINEL
117 /* END: Common Definitions */
119 /* BEGIN: Non Windows Definitions */
120 #ifndef WINDOWSNT
122 /* Structure forward declarations. */
124 struct sound;
125 struct sound_device;
127 /* The file header of RIFF-WAVE files (*.wav). Files are always in
128 little-endian byte-order. */
130 struct wav_header
132 u_int32_t magic;
133 u_int32_t length;
134 u_int32_t chunk_type;
135 u_int32_t chunk_format;
136 u_int32_t chunk_length;
137 u_int16_t format;
138 u_int16_t channels;
139 u_int32_t sample_rate;
140 u_int32_t bytes_per_second;
141 u_int16_t sample_size;
142 u_int16_t precision;
143 u_int32_t chunk_data;
144 u_int32_t data_length;
147 /* The file header of Sun adio files (*.au). Files are always in
148 big-endian byte-order. */
150 struct au_header
152 /* ASCII ".snd" */
153 u_int32_t magic_number;
155 /* Offset of data part from start of file. Minimum value is 24. */
156 u_int32_t data_offset;
158 /* Size of data part, 0xffffffff if unknown. */
159 u_int32_t data_size;
161 /* Data encoding format.
162 1 8-bit ISDN u-law
163 2 8-bit linear PCM (REF-PCM)
164 3 16-bit linear PCM
165 4 24-bit linear PCM
166 5 32-bit linear PCM
167 6 32-bit IEEE floating-point
168 7 64-bit IEEE floating-point
169 23 8-bit u-law compressed using CCITT 0.721 ADPCM voice data
170 encoding scheme. */
171 u_int32_t encoding;
173 /* Number of samples per second. */
174 u_int32_t sample_rate;
176 /* Number of interleaved channels. */
177 u_int32_t channels;
180 /* Maximum of all sound file headers sizes. */
182 #define MAX_SOUND_HEADER_BYTES \
183 max (sizeof (struct wav_header), sizeof (struct au_header))
185 /* Interface structure for sound devices. */
187 struct sound_device
189 /* If a string, the name of the device; otherwise use a default. */
190 Lisp_Object file;
192 /* File descriptor of the device. */
193 int fd;
195 /* Device-dependent format. */
196 int format;
198 /* Volume (0..100). Zero means unspecified. */
199 int volume;
201 /* Sample size. */
202 int sample_size;
204 /* Sample rate. */
205 int sample_rate;
207 /* Bytes per second. */
208 int bps;
210 /* 1 = mono, 2 = stereo, 0 = don't set. */
211 int channels;
213 /* Open device SD. */
214 void (* open) (struct sound_device *sd);
216 /* Close device SD. */
217 void (* close) (struct sound_device *sd);
219 /* Configure SD according to device-dependent parameters. */
220 void (* configure) (struct sound_device *device);
222 /* Choose a device-dependent format for outputting sound S. */
223 void (* choose_format) (struct sound_device *sd,
224 struct sound *s);
226 /* Return a preferred data size in bytes to be sent to write (below)
227 each time. 2048 is used if this is NULL. */
228 ptrdiff_t (* period_size) (struct sound_device *sd);
230 /* Write NYBTES bytes from BUFFER to device SD. */
231 void (* write) (struct sound_device *sd, const char *buffer,
232 ptrdiff_t nbytes);
234 /* A place for devices to store additional data. */
235 void *data;
238 /* An enumerator for each supported sound file type. */
240 enum sound_type
242 RIFF,
243 SUN_AUDIO
246 /* Interface structure for sound files. */
248 struct sound
250 /* The type of the file. */
251 enum sound_type type;
253 /* File descriptor of a sound file. */
254 int fd;
256 /* Pointer to sound file header. This contains header_size bytes
257 read from the start of a sound file. */
258 char *header;
260 /* Number of bytes read from sound file. This is always <=
261 MAX_SOUND_HEADER_BYTES. */
262 int header_size;
264 /* Sound data, if a string. */
265 Lisp_Object data;
267 /* Play sound file S on device SD. */
268 void (* play) (struct sound *s, struct sound_device *sd);
271 /* These are set during `play-sound-internal' so that sound_cleanup has
272 access to them. */
274 static struct sound_device *current_sound_device;
275 static struct sound *current_sound;
277 /* Function prototypes. */
279 static void vox_write (struct sound_device *, const char *, ptrdiff_t);
280 static bool wav_init (struct sound *);
281 static void wav_play (struct sound *, struct sound_device *);
282 static bool au_init (struct sound *);
283 static void au_play (struct sound *, struct sound_device *);
285 /* END: Non Windows Definitions */
286 #else /* WINDOWSNT */
288 /* BEGIN: Windows Specific Definitions */
289 static int do_play_sound (const char *, unsigned long);
291 END: Windows Specific Definitions */
292 #endif /* WINDOWSNT */
295 /***********************************************************************
296 General
297 ***********************************************************************/
299 /* BEGIN: Common functions */
301 /* Like perror, but signals an error. */
303 static _Noreturn void
304 sound_perror (const char *msg)
306 int saved_errno = errno;
308 turn_on_atimers (1);
309 #ifdef USABLE_SIGIO
311 sigset_t unblocked;
312 sigemptyset (&unblocked);
313 sigaddset (&unblocked, SIGIO);
314 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
316 #endif
317 if (saved_errno != 0)
318 error ("%s: %s", msg, strerror (saved_errno));
319 else
320 error ("%s", msg);
324 /* Display a warning message. */
326 static void
327 sound_warning (const char *msg)
329 message1 (msg);
333 /* Parse sound specification SOUND, and fill ATTRS with what is
334 found. Value is non-zero if SOUND Is a valid sound specification.
335 A valid sound specification is a list starting with the symbol
336 `sound'. The rest of the list is a property list which may
337 contain the following key/value pairs:
339 - `:file FILE'
341 FILE is the sound file to play. If it isn't an absolute name,
342 it's searched under `data-directory'.
344 - `:data DATA'
346 DATA is a string containing sound data. Either :file or :data
347 may be present, but not both.
349 - `:device DEVICE'
351 DEVICE is the name of the device to play on, e.g. "/dev/dsp2".
352 If not specified, a default device is used.
354 - `:volume VOL'
356 VOL must be an integer in the range [0, 100], or a float in the
357 range [0, 1]. */
359 static bool
360 parse_sound (Lisp_Object sound, Lisp_Object *attrs)
362 /* SOUND must be a list starting with the symbol `sound'. */
363 if (!CONSP (sound) || !EQ (XCAR (sound), Qsound))
364 return 0;
366 sound = XCDR (sound);
367 attrs[SOUND_FILE] = Fplist_get (sound, QCfile);
368 attrs[SOUND_DATA] = Fplist_get (sound, QCdata);
369 attrs[SOUND_DEVICE] = Fplist_get (sound, QCdevice);
370 attrs[SOUND_VOLUME] = Fplist_get (sound, QCvolume);
372 #ifndef WINDOWSNT
373 /* File name or data must be specified. */
374 if (!STRINGP (attrs[SOUND_FILE])
375 && !STRINGP (attrs[SOUND_DATA]))
376 return 0;
377 #else /* WINDOWSNT */
379 Data is not supported in Windows. Therefore a
380 File name MUST be supplied.
382 if (!STRINGP (attrs[SOUND_FILE]))
384 return 0;
386 #endif /* WINDOWSNT */
388 /* Volume must be in the range 0..100 or unspecified. */
389 if (!NILP (attrs[SOUND_VOLUME]))
391 if (INTEGERP (attrs[SOUND_VOLUME]))
393 if (XINT (attrs[SOUND_VOLUME]) < 0
394 || XINT (attrs[SOUND_VOLUME]) > 100)
395 return 0;
397 else if (FLOATP (attrs[SOUND_VOLUME]))
399 if (XFLOAT_DATA (attrs[SOUND_VOLUME]) < 0
400 || XFLOAT_DATA (attrs[SOUND_VOLUME]) > 1)
401 return 0;
403 else
404 return 0;
407 #ifndef WINDOWSNT
408 /* Device must be a string or unspecified. */
409 if (!NILP (attrs[SOUND_DEVICE])
410 && !STRINGP (attrs[SOUND_DEVICE]))
411 return 0;
412 #endif /* WINDOWSNT */
414 Since device is ignored in Windows, it does not matter
415 what it is.
417 return 1;
420 /* END: Common functions */
422 /* BEGIN: Non Windows functions */
423 #ifndef WINDOWSNT
425 /* Return S's value as a string if S is a string, otherwise DEFAULT_VALUE. */
427 static char const *
428 string_default (Lisp_Object s, char const *default_value)
430 return STRINGP (s) ? SSDATA (s) : default_value;
434 /* Find out the type of the sound file whose file descriptor is FD.
435 S is the sound file structure to fill in. */
437 static void
438 find_sound_type (struct sound *s)
440 if (!wav_init (s) && !au_init (s))
441 error ("Unknown sound format");
445 /* Function installed by play-sound-internal with record_unwind_protect_void. */
447 static void
448 sound_cleanup (void)
450 if (current_sound_device->close)
451 current_sound_device->close (current_sound_device);
452 if (current_sound->fd > 0)
453 emacs_close (current_sound->fd);
454 xfree (current_sound_device);
455 xfree (current_sound);
458 /***********************************************************************
459 Byte-order Conversion
460 ***********************************************************************/
462 /* Convert 32-bit value VALUE which is in little-endian byte-order
463 to host byte-order. */
465 static u_int32_t
466 le2hl (u_int32_t value)
468 #ifdef WORDS_BIGENDIAN
469 value = bswap_32 (value);
470 #endif
471 return value;
475 /* Convert 16-bit value VALUE which is in little-endian byte-order
476 to host byte-order. */
478 static u_int16_t
479 le2hs (u_int16_t value)
481 #ifdef WORDS_BIGENDIAN
482 value = bswap_16 (value);
483 #endif
484 return value;
488 /* Convert 32-bit value VALUE which is in big-endian byte-order
489 to host byte-order. */
491 static u_int32_t
492 be2hl (u_int32_t value)
494 #ifndef WORDS_BIGENDIAN
495 value = bswap_32 (value);
496 #endif
497 return value;
500 /***********************************************************************
501 RIFF-WAVE (*.wav)
502 ***********************************************************************/
504 /* Try to initialize sound file S from S->header. S->header
505 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
506 sound file. If the file is a WAV-format file, set up interface
507 functions in S and convert header fields to host byte-order.
508 Value is true if the file is a WAV file. */
510 static bool
511 wav_init (struct sound *s)
513 struct wav_header *header = (struct wav_header *) s->header;
515 if (s->header_size < sizeof *header
516 || memcmp (s->header, "RIFF", 4) != 0)
517 return 0;
519 /* WAV files are in little-endian order. Convert the header
520 if on a big-endian machine. */
521 header->magic = le2hl (header->magic);
522 header->length = le2hl (header->length);
523 header->chunk_type = le2hl (header->chunk_type);
524 header->chunk_format = le2hl (header->chunk_format);
525 header->chunk_length = le2hl (header->chunk_length);
526 header->format = le2hs (header->format);
527 header->channels = le2hs (header->channels);
528 header->sample_rate = le2hl (header->sample_rate);
529 header->bytes_per_second = le2hl (header->bytes_per_second);
530 header->sample_size = le2hs (header->sample_size);
531 header->precision = le2hs (header->precision);
532 header->chunk_data = le2hl (header->chunk_data);
533 header->data_length = le2hl (header->data_length);
535 /* Set up the interface functions for WAV. */
536 s->type = RIFF;
537 s->play = wav_play;
539 return 1;
543 /* Play RIFF-WAVE audio file S on sound device SD. */
545 static void
546 wav_play (struct sound *s, struct sound_device *sd)
548 struct wav_header *header = (struct wav_header *) s->header;
550 /* Let the device choose a suitable device-dependent format
551 for the file. */
552 sd->choose_format (sd, s);
554 /* Configure the device. */
555 sd->sample_size = header->sample_size;
556 sd->sample_rate = header->sample_rate;
557 sd->bps = header->bytes_per_second;
558 sd->channels = header->channels;
559 sd->configure (sd);
561 /* Copy sound data to the device. The WAV file specification is
562 actually more complex. This simple scheme worked with all WAV
563 files I found so far. If someone feels inclined to implement the
564 whole RIFF-WAVE spec, please do. */
565 if (STRINGP (s->data))
566 sd->write (sd, SSDATA (s->data) + sizeof *header,
567 SBYTES (s->data) - sizeof *header);
568 else
570 char *buffer;
571 ptrdiff_t nbytes = 0;
572 ptrdiff_t blksize = sd->period_size ? sd->period_size (sd) : 2048;
573 ptrdiff_t data_left = header->data_length;
575 buffer = alloca (blksize);
576 lseek (s->fd, sizeof *header, SEEK_SET);
577 while (data_left > 0
578 && (nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
580 /* Don't play possible garbage at the end of file */
581 if (data_left < nbytes) nbytes = data_left;
582 data_left -= nbytes;
583 sd->write (sd, buffer, nbytes);
586 if (nbytes < 0)
587 sound_perror ("Error reading sound file");
592 /***********************************************************************
593 Sun Audio (*.au)
594 ***********************************************************************/
596 /* Sun audio file encodings. */
598 enum au_encoding
600 AU_ENCODING_ULAW_8 = 1,
601 AU_ENCODING_8,
602 AU_ENCODING_16,
603 AU_ENCODING_24,
604 AU_ENCODING_32,
605 AU_ENCODING_IEEE32,
606 AU_ENCODING_IEEE64,
607 AU_COMPRESSED = 23,
608 AU_ENCODING_ALAW_8 = 27
612 /* Try to initialize sound file S from S->header. S->header
613 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
614 sound file. If the file is a AU-format file, set up interface
615 functions in S and convert header fields to host byte-order.
616 Value is true if the file is an AU file. */
618 static bool
619 au_init (struct sound *s)
621 struct au_header *header = (struct au_header *) s->header;
623 if (s->header_size < sizeof *header
624 || memcmp (s->header, ".snd", 4) != 0)
625 return 0;
627 header->magic_number = be2hl (header->magic_number);
628 header->data_offset = be2hl (header->data_offset);
629 header->data_size = be2hl (header->data_size);
630 header->encoding = be2hl (header->encoding);
631 header->sample_rate = be2hl (header->sample_rate);
632 header->channels = be2hl (header->channels);
634 /* Set up the interface functions for AU. */
635 s->type = SUN_AUDIO;
636 s->play = au_play;
638 return 1;
642 /* Play Sun audio file S on sound device SD. */
644 static void
645 au_play (struct sound *s, struct sound_device *sd)
647 struct au_header *header = (struct au_header *) s->header;
649 sd->sample_size = 0;
650 sd->sample_rate = header->sample_rate;
651 sd->bps = 0;
652 sd->channels = header->channels;
653 sd->choose_format (sd, s);
654 sd->configure (sd);
656 if (STRINGP (s->data))
657 sd->write (sd, SSDATA (s->data) + header->data_offset,
658 SBYTES (s->data) - header->data_offset);
659 else
661 ptrdiff_t blksize = sd->period_size ? sd->period_size (sd) : 2048;
662 char *buffer;
663 ptrdiff_t nbytes;
665 /* Seek */
666 lseek (s->fd, header->data_offset, SEEK_SET);
668 /* Copy sound data to the device. */
669 buffer = alloca (blksize);
670 while ((nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
671 sd->write (sd, buffer, nbytes);
673 if (nbytes < 0)
674 sound_perror ("Error reading sound file");
679 /***********************************************************************
680 Voxware Driver Interface
681 ***********************************************************************/
683 /* This driver is available on GNU/Linux, and the free BSDs. FreeBSD
684 has a compatible own driver aka Luigi's driver. */
687 /* Open device SD. If SD->file is a string, open that device,
688 otherwise use a default device name. */
690 static void
691 vox_open (struct sound_device *sd)
693 /* Open the sound device (eg /dev/dsp). */
694 char const *file = string_default (sd->file, DEFAULT_SOUND_DEVICE);
695 sd->fd = emacs_open (file, O_WRONLY, 0);
696 if (sd->fd < 0)
697 sound_perror (file);
701 /* Configure device SD from parameters in it. */
703 static void
704 vox_configure (struct sound_device *sd)
706 int val;
707 #ifdef USABLE_SIGIO
708 sigset_t blocked;
709 #endif
711 eassert (sd->fd >= 0);
713 /* On GNU/Linux, it seems that the device driver doesn't like to be
714 interrupted by a signal. Block the ones we know to cause
715 troubles. */
716 turn_on_atimers (0);
717 #ifdef USABLE_SIGIO
718 sigemptyset (&blocked);
719 sigaddset (&blocked, SIGIO);
720 pthread_sigmask (SIG_BLOCK, &blocked, 0);
721 #endif
723 val = sd->format;
724 if (ioctl (sd->fd, SNDCTL_DSP_SETFMT, &sd->format) < 0
725 || val != sd->format)
726 sound_perror ("Could not set sound format");
728 val = sd->channels != 1;
729 if (ioctl (sd->fd, SNDCTL_DSP_STEREO, &val) < 0
730 || val != (sd->channels != 1))
731 sound_perror ("Could not set stereo/mono");
733 /* I think bps and sampling_rate are the same, but who knows.
734 Check this. and use SND_DSP_SPEED for both. */
735 if (sd->sample_rate > 0)
737 val = sd->sample_rate;
738 if (ioctl (sd->fd, SNDCTL_DSP_SPEED, &sd->sample_rate) < 0)
739 sound_perror ("Could not set sound speed");
740 else if (val != sd->sample_rate)
741 sound_warning ("Could not set sample rate");
744 if (sd->volume > 0)
746 int volume = sd->volume & 0xff;
747 volume |= volume << 8;
748 /* This may fail if there is no mixer. Ignore the failure. */
749 ioctl (sd->fd, SOUND_MIXER_WRITE_PCM, &volume);
752 turn_on_atimers (1);
753 #ifdef USABLE_SIGIO
754 pthread_sigmask (SIG_UNBLOCK, &blocked, 0);
755 #endif
759 /* Close device SD if it is open. */
761 static void
762 vox_close (struct sound_device *sd)
764 if (sd->fd >= 0)
766 /* On GNU/Linux, it seems that the device driver doesn't like to
767 be interrupted by a signal. Block the ones we know to cause
768 troubles. */
769 #ifdef USABLE_SIGIO
770 sigset_t blocked;
771 sigemptyset (&blocked);
772 sigaddset (&blocked, SIGIO);
773 pthread_sigmask (SIG_BLOCK, &blocked, 0);
774 #endif
775 turn_on_atimers (0);
777 /* Flush sound data, and reset the device. */
778 ioctl (sd->fd, SNDCTL_DSP_SYNC, NULL);
780 turn_on_atimers (1);
781 #ifdef USABLE_SIGIO
782 pthread_sigmask (SIG_UNBLOCK, &blocked, 0);
783 #endif
785 /* Close the device. */
786 emacs_close (sd->fd);
787 sd->fd = -1;
792 /* Choose device-dependent format for device SD from sound file S. */
794 static void
795 vox_choose_format (struct sound_device *sd, struct sound *s)
797 if (s->type == RIFF)
799 struct wav_header *h = (struct wav_header *) s->header;
800 if (h->precision == 8)
801 sd->format = AFMT_U8;
802 else if (h->precision == 16)
803 sd->format = AFMT_S16_LE;
804 else
805 error ("Unsupported WAV file format");
807 else if (s->type == SUN_AUDIO)
809 struct au_header *header = (struct au_header *) s->header;
810 switch (header->encoding)
812 case AU_ENCODING_ULAW_8:
813 case AU_ENCODING_IEEE32:
814 case AU_ENCODING_IEEE64:
815 sd->format = AFMT_MU_LAW;
816 break;
818 case AU_ENCODING_8:
819 case AU_ENCODING_16:
820 case AU_ENCODING_24:
821 case AU_ENCODING_32:
822 sd->format = AFMT_S16_LE;
823 break;
825 default:
826 error ("Unsupported AU file format");
829 else
830 emacs_abort ();
834 /* Initialize device SD. Set up the interface functions in the device
835 structure. */
837 static bool
838 vox_init (struct sound_device *sd)
840 /* Open the sound device (eg /dev/dsp). */
841 char const *file = string_default (sd->file, DEFAULT_SOUND_DEVICE);
842 int fd = emacs_open (file, O_WRONLY, 0);
843 if (fd >= 0)
844 emacs_close (fd);
845 else
846 return 0;
848 sd->fd = -1;
849 sd->open = vox_open;
850 sd->close = vox_close;
851 sd->configure = vox_configure;
852 sd->choose_format = vox_choose_format;
853 sd->write = vox_write;
854 sd->period_size = NULL;
856 return 1;
859 /* Write NBYTES bytes from BUFFER to device SD. */
861 static void
862 vox_write (struct sound_device *sd, const char *buffer, ptrdiff_t nbytes)
864 if (emacs_write_sig (sd->fd, buffer, nbytes) != nbytes)
865 sound_perror ("Error writing to sound device");
868 #ifdef HAVE_ALSA
869 /***********************************************************************
870 ALSA Driver Interface
871 ***********************************************************************/
873 /* This driver is available on GNU/Linux. */
875 #ifndef DEFAULT_ALSA_SOUND_DEVICE
876 #define DEFAULT_ALSA_SOUND_DEVICE "default"
877 #endif
879 static _Noreturn void
880 alsa_sound_perror (const char *msg, int err)
882 error ("%s: %s", msg, snd_strerror (err));
885 struct alsa_params
887 snd_pcm_t *handle;
888 snd_pcm_hw_params_t *hwparams;
889 snd_pcm_sw_params_t *swparams;
890 snd_pcm_uframes_t period_size;
893 /* Open device SD. If SD->file is a string, open that device,
894 otherwise use a default device name. */
896 static void
897 alsa_open (struct sound_device *sd)
899 /* Open the sound device. Default is "default". */
900 struct alsa_params *p = xmalloc (sizeof *p);
901 char const *file = string_default (sd->file, DEFAULT_ALSA_SOUND_DEVICE);
902 int err;
904 p->handle = NULL;
905 p->hwparams = NULL;
906 p->swparams = NULL;
908 sd->fd = -1;
909 sd->data = p;
912 err = snd_pcm_open (&p->handle, file, SND_PCM_STREAM_PLAYBACK, 0);
913 if (err < 0)
914 alsa_sound_perror (file, err);
917 static ptrdiff_t
918 alsa_period_size (struct sound_device *sd)
920 struct alsa_params *p = (struct alsa_params *) sd->data;
921 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
922 return p->period_size * (fact > 0 ? fact : 1);
925 static void
926 alsa_configure (struct sound_device *sd)
928 int val, err, dir;
929 unsigned uval;
930 struct alsa_params *p = (struct alsa_params *) sd->data;
931 snd_pcm_uframes_t buffer_size;
933 eassert (p->handle != 0);
935 err = snd_pcm_hw_params_malloc (&p->hwparams);
936 if (err < 0)
937 alsa_sound_perror ("Could not allocate hardware parameter structure", err);
939 err = snd_pcm_sw_params_malloc (&p->swparams);
940 if (err < 0)
941 alsa_sound_perror ("Could not allocate software parameter structure", err);
943 err = snd_pcm_hw_params_any (p->handle, p->hwparams);
944 if (err < 0)
945 alsa_sound_perror ("Could not initialize hardware parameter structure", err);
947 err = snd_pcm_hw_params_set_access (p->handle, p->hwparams,
948 SND_PCM_ACCESS_RW_INTERLEAVED);
949 if (err < 0)
950 alsa_sound_perror ("Could not set access type", err);
952 val = sd->format;
953 err = snd_pcm_hw_params_set_format (p->handle, p->hwparams, val);
954 if (err < 0)
955 alsa_sound_perror ("Could not set sound format", err);
957 uval = sd->sample_rate;
958 err = snd_pcm_hw_params_set_rate_near (p->handle, p->hwparams, &uval, 0);
959 if (err < 0)
960 alsa_sound_perror ("Could not set sample rate", err);
962 val = sd->channels;
963 err = snd_pcm_hw_params_set_channels (p->handle, p->hwparams, val);
964 if (err < 0)
965 alsa_sound_perror ("Could not set channel count", err);
967 err = snd_pcm_hw_params (p->handle, p->hwparams);
968 if (err < 0)
969 alsa_sound_perror ("Could not set parameters", err);
972 err = snd_pcm_hw_params_get_period_size (p->hwparams, &p->period_size, &dir);
973 if (err < 0)
974 alsa_sound_perror ("Unable to get period size for playback", err);
976 err = snd_pcm_hw_params_get_buffer_size (p->hwparams, &buffer_size);
977 if (err < 0)
978 alsa_sound_perror ("Unable to get buffer size for playback", err);
980 err = snd_pcm_sw_params_current (p->handle, p->swparams);
981 if (err < 0)
982 alsa_sound_perror ("Unable to determine current swparams for playback",
983 err);
985 /* Start the transfer when the buffer is almost full */
986 err = snd_pcm_sw_params_set_start_threshold (p->handle, p->swparams,
987 (buffer_size / p->period_size)
988 * p->period_size);
989 if (err < 0)
990 alsa_sound_perror ("Unable to set start threshold mode for playback", err);
992 /* Allow the transfer when at least period_size samples can be processed */
993 err = snd_pcm_sw_params_set_avail_min (p->handle, p->swparams, p->period_size);
994 if (err < 0)
995 alsa_sound_perror ("Unable to set avail min for playback", err);
997 err = snd_pcm_sw_params (p->handle, p->swparams);
998 if (err < 0)
999 alsa_sound_perror ("Unable to set sw params for playback\n", err);
1001 snd_pcm_hw_params_free (p->hwparams);
1002 p->hwparams = NULL;
1003 snd_pcm_sw_params_free (p->swparams);
1004 p->swparams = NULL;
1006 err = snd_pcm_prepare (p->handle);
1007 if (err < 0)
1008 alsa_sound_perror ("Could not prepare audio interface for use", err);
1010 if (sd->volume > 0)
1012 int chn;
1013 snd_mixer_t *handle;
1014 snd_mixer_elem_t *e;
1015 if (snd_mixer_open (&handle, 0) >= 0)
1017 char const *file = string_default (sd->file,
1018 DEFAULT_ALSA_SOUND_DEVICE);
1019 if (snd_mixer_attach (handle, file) >= 0
1020 && snd_mixer_load (handle) >= 0
1021 && snd_mixer_selem_register (handle, NULL, NULL) >= 0)
1022 for (e = snd_mixer_first_elem (handle);
1024 e = snd_mixer_elem_next (e))
1026 if (snd_mixer_selem_has_playback_volume (e))
1028 long pmin, pmax, vol;
1029 snd_mixer_selem_get_playback_volume_range (e, &pmin, &pmax);
1030 vol = pmin + (sd->volume * (pmax - pmin)) / 100;
1032 for (chn = 0; chn <= SND_MIXER_SCHN_LAST; chn++)
1033 snd_mixer_selem_set_playback_volume (e, chn, vol);
1036 snd_mixer_close (handle);
1042 /* Close device SD if it is open. */
1044 static void
1045 alsa_close (struct sound_device *sd)
1047 struct alsa_params *p = (struct alsa_params *) sd->data;
1048 if (p)
1050 if (p->hwparams)
1051 snd_pcm_hw_params_free (p->hwparams);
1052 if (p->swparams)
1053 snd_pcm_sw_params_free (p->swparams);
1054 if (p->handle)
1056 snd_pcm_drain (p->handle);
1057 snd_pcm_close (p->handle);
1059 xfree (p);
1063 /* Choose device-dependent format for device SD from sound file S. */
1065 static void
1066 alsa_choose_format (struct sound_device *sd, struct sound *s)
1068 if (s->type == RIFF)
1070 struct wav_header *h = (struct wav_header *) s->header;
1071 if (h->precision == 8)
1072 sd->format = SND_PCM_FORMAT_U8;
1073 else if (h->precision == 16)
1074 sd->format = SND_PCM_FORMAT_S16_LE;
1075 else
1076 error ("Unsupported WAV file format");
1078 else if (s->type == SUN_AUDIO)
1080 struct au_header *header = (struct au_header *) s->header;
1081 switch (header->encoding)
1083 case AU_ENCODING_ULAW_8:
1084 sd->format = SND_PCM_FORMAT_MU_LAW;
1085 break;
1086 case AU_ENCODING_ALAW_8:
1087 sd->format = SND_PCM_FORMAT_A_LAW;
1088 break;
1089 case AU_ENCODING_IEEE32:
1090 sd->format = SND_PCM_FORMAT_FLOAT_BE;
1091 break;
1092 case AU_ENCODING_IEEE64:
1093 sd->format = SND_PCM_FORMAT_FLOAT64_BE;
1094 break;
1095 case AU_ENCODING_8:
1096 sd->format = SND_PCM_FORMAT_S8;
1097 break;
1098 case AU_ENCODING_16:
1099 sd->format = SND_PCM_FORMAT_S16_BE;
1100 break;
1101 case AU_ENCODING_24:
1102 sd->format = SND_PCM_FORMAT_S24_BE;
1103 break;
1104 case AU_ENCODING_32:
1105 sd->format = SND_PCM_FORMAT_S32_BE;
1106 break;
1108 default:
1109 error ("Unsupported AU file format");
1112 else
1113 emacs_abort ();
1117 /* Write NBYTES bytes from BUFFER to device SD. */
1119 static void
1120 alsa_write (struct sound_device *sd, const char *buffer, ptrdiff_t nbytes)
1122 struct alsa_params *p = (struct alsa_params *) sd->data;
1124 /* The the third parameter to snd_pcm_writei is frames, not bytes. */
1125 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
1126 ptrdiff_t nwritten = 0;
1127 int err;
1129 while (nwritten < nbytes)
1131 snd_pcm_uframes_t frames = (nbytes - nwritten)/fact;
1132 if (frames == 0) break;
1134 err = snd_pcm_writei (p->handle, buffer + nwritten, frames);
1135 if (err < 0)
1137 if (err == -EPIPE)
1138 { /* under-run */
1139 err = snd_pcm_prepare (p->handle);
1140 if (err < 0)
1141 alsa_sound_perror ("Can't recover from underrun, prepare failed",
1142 err);
1144 else if (err == -ESTRPIPE)
1146 while ((err = snd_pcm_resume (p->handle)) == -EAGAIN)
1147 sleep (1); /* wait until the suspend flag is released */
1148 if (err < 0)
1150 err = snd_pcm_prepare (p->handle);
1151 if (err < 0)
1152 alsa_sound_perror ("Can't recover from suspend, "
1153 "prepare failed",
1154 err);
1157 else
1158 alsa_sound_perror ("Error writing to sound device", err);
1161 else
1162 nwritten += err * fact;
1166 static void
1167 snd_error_quiet (const char *file, int line, const char *function, int err,
1168 const char *fmt)
1172 /* Initialize device SD. Set up the interface functions in the device
1173 structure. */
1175 static bool
1176 alsa_init (struct sound_device *sd)
1178 /* Open the sound device. Default is "default". */
1179 char const *file = string_default (sd->file, DEFAULT_ALSA_SOUND_DEVICE);
1180 snd_pcm_t *handle;
1181 int err;
1183 snd_lib_error_set_handler ((snd_lib_error_handler_t) snd_error_quiet);
1184 err = snd_pcm_open (&handle, file, SND_PCM_STREAM_PLAYBACK, 0);
1185 snd_lib_error_set_handler (NULL);
1186 if (err < 0)
1187 return 0;
1188 snd_pcm_close (handle);
1190 sd->fd = -1;
1191 sd->open = alsa_open;
1192 sd->close = alsa_close;
1193 sd->configure = alsa_configure;
1194 sd->choose_format = alsa_choose_format;
1195 sd->write = alsa_write;
1196 sd->period_size = alsa_period_size;
1198 return 1;
1201 #endif /* HAVE_ALSA */
1204 /* END: Non Windows functions */
1205 #else /* WINDOWSNT */
1207 /* BEGIN: Windows specific functions */
1209 #define SOUND_WARNING(fun, error, text) \
1211 char buf[1024]; \
1212 char err_string[MAXERRORLENGTH]; \
1213 fun (error, err_string, sizeof (err_string)); \
1214 _snprintf (buf, sizeof (buf), "%s\nError: %s", \
1215 text, err_string); \
1216 sound_warning (buf); \
1219 static int
1220 do_play_sound (const char *psz_file, unsigned long ui_volume)
1222 int i_result = 0;
1223 MCIERROR mci_error = 0;
1224 char sz_cmd_buf[520] = {0};
1225 char sz_ret_buf[520] = {0};
1226 MMRESULT mm_result = MMSYSERR_NOERROR;
1227 unsigned long ui_volume_org = 0;
1228 BOOL b_reset_volume = FALSE;
1230 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1231 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1232 sprintf (sz_cmd_buf,
1233 "open \"%s\" alias GNUEmacs_PlaySound_Device wait",
1234 psz_file);
1235 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1236 if (mci_error != 0)
1238 SOUND_WARNING (mciGetErrorString, mci_error,
1239 "The open mciSendString command failed to open "
1240 "the specified sound file.");
1241 i_result = (int) mci_error;
1242 return i_result;
1244 if ((ui_volume > 0) && (ui_volume != UINT_MAX))
1246 mm_result = waveOutGetVolume ((HWAVEOUT) WAVE_MAPPER, &ui_volume_org);
1247 if (mm_result == MMSYSERR_NOERROR)
1249 b_reset_volume = TRUE;
1250 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume);
1251 if (mm_result != MMSYSERR_NOERROR)
1253 SOUND_WARNING (waveOutGetErrorText, mm_result,
1254 "waveOutSetVolume failed to set the volume level "
1255 "of the WAVE_MAPPER device.\n"
1256 "As a result, the user selected volume level will "
1257 "not be used.");
1260 else
1262 SOUND_WARNING (waveOutGetErrorText, mm_result,
1263 "waveOutGetVolume failed to obtain the original "
1264 "volume level of the WAVE_MAPPER device.\n"
1265 "As a result, the user selected volume level will "
1266 "not be used.");
1269 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1270 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1271 strcpy (sz_cmd_buf, "play GNUEmacs_PlaySound_Device wait");
1272 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1273 if (mci_error != 0)
1275 SOUND_WARNING (mciGetErrorString, mci_error,
1276 "The play mciSendString command failed to play the "
1277 "opened sound file.");
1278 i_result = (int) mci_error;
1280 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1281 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1282 strcpy (sz_cmd_buf, "close GNUEmacs_PlaySound_Device wait");
1283 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1284 if (b_reset_volume == TRUE)
1286 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume_org);
1287 if (mm_result != MMSYSERR_NOERROR)
1289 SOUND_WARNING (waveOutGetErrorText, mm_result,
1290 "waveOutSetVolume failed to reset the original volume "
1291 "level of the WAVE_MAPPER device.");
1294 return i_result;
1297 /* END: Windows specific functions */
1299 #endif /* WINDOWSNT */
1301 DEFUN ("play-sound-internal", Fplay_sound_internal, Splay_sound_internal, 1, 1, 0,
1302 doc: /* Play sound SOUND.
1304 Internal use only, use `play-sound' instead. */)
1305 (Lisp_Object sound)
1307 Lisp_Object attrs[SOUND_ATTR_SENTINEL];
1308 ptrdiff_t count = SPECPDL_INDEX ();
1310 #ifndef WINDOWSNT
1311 Lisp_Object file;
1312 struct gcpro gcpro1, gcpro2;
1313 Lisp_Object args[2];
1314 #else /* WINDOWSNT */
1315 Lisp_Object lo_file;
1316 unsigned long ui_volume_tmp = UINT_MAX;
1317 unsigned long ui_volume = UINT_MAX;
1318 #endif /* WINDOWSNT */
1320 /* Parse the sound specification. Give up if it is invalid. */
1321 if (!parse_sound (sound, attrs))
1322 error ("Invalid sound specification");
1324 #ifndef WINDOWSNT
1325 file = Qnil;
1326 GCPRO2 (sound, file);
1327 current_sound_device = xzalloc (sizeof *current_sound_device);
1328 current_sound = xzalloc (sizeof *current_sound);
1329 record_unwind_protect_void (sound_cleanup);
1330 current_sound->header = alloca (MAX_SOUND_HEADER_BYTES);
1332 if (STRINGP (attrs[SOUND_FILE]))
1334 /* Open the sound file. */
1335 current_sound->fd = openp (list1 (Vdata_directory),
1336 attrs[SOUND_FILE], Qnil, &file, Qnil, false);
1337 if (current_sound->fd < 0)
1338 sound_perror ("Could not open sound file");
1340 /* Read the first bytes from the file. */
1341 current_sound->header_size
1342 = emacs_read (current_sound->fd, current_sound->header,
1343 MAX_SOUND_HEADER_BYTES);
1344 if (current_sound->header_size < 0)
1345 sound_perror ("Invalid sound file header");
1347 else
1349 current_sound->data = attrs[SOUND_DATA];
1350 current_sound->header_size = min (MAX_SOUND_HEADER_BYTES, SBYTES (current_sound->data));
1351 memcpy (current_sound->header, SDATA (current_sound->data),
1352 current_sound->header_size);
1355 /* Find out the type of sound. Give up if we can't tell. */
1356 find_sound_type (current_sound);
1358 /* Set up a device. */
1359 current_sound_device->file = attrs[SOUND_DEVICE];
1361 if (INTEGERP (attrs[SOUND_VOLUME]))
1362 current_sound_device->volume = XFASTINT (attrs[SOUND_VOLUME]);
1363 else if (FLOATP (attrs[SOUND_VOLUME]))
1364 current_sound_device->volume = XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1366 args[0] = Qplay_sound_functions;
1367 args[1] = sound;
1368 Frun_hook_with_args (2, args);
1370 #ifdef HAVE_ALSA
1371 if (!alsa_init (current_sound_device))
1372 #endif
1373 if (!vox_init (current_sound_device))
1374 error ("No usable sound device driver found");
1376 /* Open the device. */
1377 current_sound_device->open (current_sound_device);
1379 /* Play the sound. */
1380 current_sound->play (current_sound, current_sound_device);
1382 /* Clean up. */
1383 UNGCPRO;
1385 #else /* WINDOWSNT */
1387 lo_file = Fexpand_file_name (attrs[SOUND_FILE], Vdata_directory);
1388 lo_file = ENCODE_FILE (lo_file);
1389 /* Since UNICOWS.DLL includes only a stub for mciSendStringW, we
1390 need to encode the file in the ANSI codepage. */
1391 lo_file = ansi_encode_filename (lo_file);
1392 if (INTEGERP (attrs[SOUND_VOLUME]))
1394 ui_volume_tmp = XFASTINT (attrs[SOUND_VOLUME]);
1396 else if (FLOATP (attrs[SOUND_VOLUME]))
1398 ui_volume_tmp = XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1401 Based on some experiments I have conducted, a value of 100 or less
1402 for the sound volume is much too low. You cannot even hear it.
1403 A value of UINT_MAX indicates that you wish for the sound to played
1404 at the maximum possible volume. A value of UINT_MAX/2 plays the
1405 sound at 50% maximum volume. Therefore the value passed to do_play_sound
1406 (and thus to waveOutSetVolume) must be some fraction of UINT_MAX.
1407 The following code adjusts the user specified volume level appropriately.
1409 if ((ui_volume_tmp > 0) && (ui_volume_tmp <= 100))
1411 ui_volume = ui_volume_tmp * (UINT_MAX / 100);
1413 do_play_sound (SDATA (lo_file), ui_volume);
1415 #endif /* WINDOWSNT */
1417 unbind_to (count, Qnil);
1418 return Qnil;
1421 /***********************************************************************
1422 Initialization
1423 ***********************************************************************/
1425 void
1426 syms_of_sound (void)
1428 DEFSYM (QCdevice, ":device");
1429 DEFSYM (QCvolume, ":volume");
1430 DEFSYM (Qsound, "sound");
1431 DEFSYM (Qplay_sound_functions, "play-sound-functions");
1433 defsubr (&Splay_sound_internal);
1436 #endif /* HAVE_SOUND */