Merge branch 'master' into comment-cache
[emacs.git] / src / sound.c
blob84754165db5759f4373fc8da9c9ef2bcbb319a73
1 /* sound.c -- sound support.
3 Copyright (C) 1998-1999, 2001-2017 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 (at
10 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, emacs_strerror (saved_errno));
314 else
315 error ("%s", msg);
319 #ifndef WINDOWSNT
320 /* Display a warning message. */
322 static void
323 sound_warning (const char *msg)
325 message1 (msg);
327 #endif /* !WINDOWSNT */
330 /* Parse sound specification SOUND, and fill ATTRS with what is
331 found. Value is non-zero if SOUND Is a valid sound specification.
332 A valid sound specification is a list starting with the symbol
333 `sound'. The rest of the list is a property list which may
334 contain the following key/value pairs:
336 - `:file FILE'
338 FILE is the sound file to play. If it isn't an absolute name,
339 it's searched under `data-directory'.
341 - `:data DATA'
343 DATA is a string containing sound data. Either :file or :data
344 may be present, but not both.
346 - `:device DEVICE'
348 DEVICE is the name of the device to play on, e.g. "/dev/dsp2".
349 If not specified, a default device is used.
351 - `:volume VOL'
353 VOL must be an integer in the range [0, 100], or a float in the
354 range [0, 1]. */
356 static bool
357 parse_sound (Lisp_Object sound, Lisp_Object *attrs)
359 /* SOUND must be a list starting with the symbol `sound'. */
360 if (!CONSP (sound) || !EQ (XCAR (sound), Qsound))
361 return 0;
363 sound = XCDR (sound);
364 attrs[SOUND_FILE] = Fplist_get (sound, QCfile);
365 attrs[SOUND_DATA] = Fplist_get (sound, QCdata);
366 attrs[SOUND_DEVICE] = Fplist_get (sound, QCdevice);
367 attrs[SOUND_VOLUME] = Fplist_get (sound, QCvolume);
369 #ifndef WINDOWSNT
370 /* File name or data must be specified. */
371 if (!STRINGP (attrs[SOUND_FILE])
372 && !STRINGP (attrs[SOUND_DATA]))
373 return 0;
374 #else /* WINDOWSNT */
376 Data is not supported in Windows. Therefore a
377 File name MUST be supplied.
379 if (!STRINGP (attrs[SOUND_FILE]))
381 return 0;
383 #endif /* WINDOWSNT */
385 /* Volume must be in the range 0..100 or unspecified. */
386 if (!NILP (attrs[SOUND_VOLUME]))
388 if (INTEGERP (attrs[SOUND_VOLUME]))
390 if (XINT (attrs[SOUND_VOLUME]) < 0
391 || XINT (attrs[SOUND_VOLUME]) > 100)
392 return 0;
394 else if (FLOATP (attrs[SOUND_VOLUME]))
396 if (XFLOAT_DATA (attrs[SOUND_VOLUME]) < 0
397 || XFLOAT_DATA (attrs[SOUND_VOLUME]) > 1)
398 return 0;
400 else
401 return 0;
404 #ifndef WINDOWSNT
405 /* Device must be a string or unspecified. */
406 if (!NILP (attrs[SOUND_DEVICE])
407 && !STRINGP (attrs[SOUND_DEVICE]))
408 return 0;
409 #endif /* WINDOWSNT */
411 Since device is ignored in Windows, it does not matter
412 what it is.
414 return 1;
417 /* END: Common functions */
419 /* BEGIN: Non Windows functions */
420 #ifndef WINDOWSNT
422 /* Return S's value as a string if S is a string, otherwise DEFAULT_VALUE. */
424 static char const *
425 string_default (Lisp_Object s, char const *default_value)
427 return STRINGP (s) ? SSDATA (s) : default_value;
431 /* Find out the type of the sound file whose file descriptor is FD.
432 S is the sound file structure to fill in. */
434 static void
435 find_sound_type (struct sound *s)
437 if (!wav_init (s) && !au_init (s))
438 error ("Unknown sound format");
442 /* Function installed by play-sound-internal with record_unwind_protect_void. */
444 static void
445 sound_cleanup (void)
447 if (current_sound_device->close)
448 current_sound_device->close (current_sound_device);
449 if (current_sound->fd > 0)
450 emacs_close (current_sound->fd);
451 xfree (current_sound_device);
452 xfree (current_sound);
455 /***********************************************************************
456 Byte-order Conversion
457 ***********************************************************************/
459 /* Convert 32-bit value VALUE which is in little-endian byte-order
460 to host byte-order. */
462 static u_int32_t
463 le2hl (u_int32_t value)
465 #ifdef WORDS_BIGENDIAN
466 value = bswap_32 (value);
467 #endif
468 return value;
472 /* Convert 16-bit value VALUE which is in little-endian byte-order
473 to host byte-order. */
475 static u_int16_t
476 le2hs (u_int16_t value)
478 #ifdef WORDS_BIGENDIAN
479 value = bswap_16 (value);
480 #endif
481 return value;
485 /* Convert 32-bit value VALUE which is in big-endian byte-order
486 to host byte-order. */
488 static u_int32_t
489 be2hl (u_int32_t value)
491 #ifndef WORDS_BIGENDIAN
492 value = bswap_32 (value);
493 #endif
494 return value;
497 /***********************************************************************
498 RIFF-WAVE (*.wav)
499 ***********************************************************************/
501 /* Try to initialize sound file S from S->header. S->header
502 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
503 sound file. If the file is a WAV-format file, set up interface
504 functions in S and convert header fields to host byte-order.
505 Value is true if the file is a WAV file. */
507 static bool
508 wav_init (struct sound *s)
510 struct wav_header *header = (struct wav_header *) s->header;
512 if (s->header_size < sizeof *header
513 || memcmp (s->header, "RIFF", 4) != 0)
514 return 0;
516 /* WAV files are in little-endian order. Convert the header
517 if on a big-endian machine. */
518 header->magic = le2hl (header->magic);
519 header->length = le2hl (header->length);
520 header->chunk_type = le2hl (header->chunk_type);
521 header->chunk_format = le2hl (header->chunk_format);
522 header->chunk_length = le2hl (header->chunk_length);
523 header->format = le2hs (header->format);
524 header->channels = le2hs (header->channels);
525 header->sample_rate = le2hl (header->sample_rate);
526 header->bytes_per_second = le2hl (header->bytes_per_second);
527 header->sample_size = le2hs (header->sample_size);
528 header->precision = le2hs (header->precision);
529 header->chunk_data = le2hl (header->chunk_data);
530 header->data_length = le2hl (header->data_length);
532 /* Set up the interface functions for WAV. */
533 s->type = RIFF;
534 s->play = wav_play;
536 return 1;
540 /* Play RIFF-WAVE audio file S on sound device SD. */
542 static void
543 wav_play (struct sound *s, struct sound_device *sd)
545 struct wav_header *header = (struct wav_header *) s->header;
547 /* Let the device choose a suitable device-dependent format
548 for the file. */
549 sd->choose_format (sd, s);
551 /* Configure the device. */
552 sd->sample_size = header->sample_size;
553 sd->sample_rate = header->sample_rate;
554 sd->bps = header->bytes_per_second;
555 sd->channels = header->channels;
556 sd->configure (sd);
558 /* Copy sound data to the device. The WAV file specification is
559 actually more complex. This simple scheme worked with all WAV
560 files I found so far. If someone feels inclined to implement the
561 whole RIFF-WAVE spec, please do. */
562 if (STRINGP (s->data))
563 sd->write (sd, SSDATA (s->data) + sizeof *header,
564 SBYTES (s->data) - sizeof *header);
565 else
567 ptrdiff_t nbytes = 0;
568 ptrdiff_t blksize = sd->period_size ? sd->period_size (sd) : 2048;
569 ptrdiff_t data_left = header->data_length;
570 USE_SAFE_ALLOCA;
571 char *buffer = SAFE_ALLOCA (blksize);
572 lseek (s->fd, sizeof *header, SEEK_SET);
573 while (data_left > 0
574 && (nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
576 /* Don't play possible garbage at the end of file */
577 if (data_left < nbytes) nbytes = data_left;
578 data_left -= nbytes;
579 sd->write (sd, buffer, nbytes);
582 if (nbytes < 0)
583 sound_perror ("Error reading sound file");
584 SAFE_FREE ();
589 /***********************************************************************
590 Sun Audio (*.au)
591 ***********************************************************************/
593 /* Sun audio file encodings. */
595 enum au_encoding
597 AU_ENCODING_ULAW_8 = 1,
598 AU_ENCODING_8,
599 AU_ENCODING_16,
600 AU_ENCODING_24,
601 AU_ENCODING_32,
602 AU_ENCODING_IEEE32,
603 AU_ENCODING_IEEE64,
604 AU_COMPRESSED = 23,
605 AU_ENCODING_ALAW_8 = 27
609 /* Try to initialize sound file S from S->header. S->header
610 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
611 sound file. If the file is a AU-format file, set up interface
612 functions in S and convert header fields to host byte-order.
613 Value is true if the file is an AU file. */
615 static bool
616 au_init (struct sound *s)
618 struct au_header *header = (struct au_header *) s->header;
620 if (s->header_size < sizeof *header
621 || memcmp (s->header, ".snd", 4) != 0)
622 return 0;
624 header->magic_number = be2hl (header->magic_number);
625 header->data_offset = be2hl (header->data_offset);
626 header->data_size = be2hl (header->data_size);
627 header->encoding = be2hl (header->encoding);
628 header->sample_rate = be2hl (header->sample_rate);
629 header->channels = be2hl (header->channels);
631 /* Set up the interface functions for AU. */
632 s->type = SUN_AUDIO;
633 s->play = au_play;
635 return 1;
639 /* Play Sun audio file S on sound device SD. */
641 static void
642 au_play (struct sound *s, struct sound_device *sd)
644 struct au_header *header = (struct au_header *) s->header;
646 sd->sample_size = 0;
647 sd->sample_rate = header->sample_rate;
648 sd->bps = 0;
649 sd->channels = header->channels;
650 sd->choose_format (sd, s);
651 sd->configure (sd);
653 if (STRINGP (s->data))
654 sd->write (sd, SSDATA (s->data) + header->data_offset,
655 SBYTES (s->data) - header->data_offset);
656 else
658 ptrdiff_t blksize = sd->period_size ? sd->period_size (sd) : 2048;
659 ptrdiff_t nbytes;
661 /* Seek */
662 lseek (s->fd, header->data_offset, SEEK_SET);
664 /* Copy sound data to the device. */
665 USE_SAFE_ALLOCA;
666 char *buffer = SAFE_ALLOCA (blksize);
667 while ((nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
668 sd->write (sd, buffer, nbytes);
670 if (nbytes < 0)
671 sound_perror ("Error reading sound file");
672 SAFE_FREE ();
677 /***********************************************************************
678 Voxware Driver Interface
679 ***********************************************************************/
681 /* This driver is available on GNU/Linux, and the free BSDs. FreeBSD
682 has a compatible own driver aka Luigi's driver. */
685 /* Open device SD. If SD->file is a string, open that device,
686 otherwise use a default device name. */
688 static void
689 vox_open (struct sound_device *sd)
691 /* Open the sound device (eg /dev/dsp). */
692 char const *file = string_default (sd->file, DEFAULT_SOUND_DEVICE);
693 sd->fd = emacs_open (file, O_WRONLY, 0);
694 if (sd->fd < 0)
695 sound_perror (file);
699 /* Configure device SD from parameters in it. */
701 static void
702 vox_configure (struct sound_device *sd)
704 int val;
705 #ifdef USABLE_SIGIO
706 sigset_t oldset, blocked;
707 #endif
709 eassert (sd->fd >= 0);
711 /* On GNU/Linux, it seems that the device driver doesn't like to be
712 interrupted by a signal. Block the ones we know to cause
713 troubles. */
714 turn_on_atimers (0);
715 #ifdef USABLE_SIGIO
716 sigemptyset (&blocked);
717 sigaddset (&blocked, SIGIO);
718 pthread_sigmask (SIG_BLOCK, &blocked, &oldset);
719 #endif
721 val = sd->format;
722 if (ioctl (sd->fd, SNDCTL_DSP_SETFMT, &sd->format) < 0
723 || val != sd->format)
724 sound_perror ("Could not set sound format");
726 val = sd->channels != 1;
727 if (ioctl (sd->fd, SNDCTL_DSP_STEREO, &val) < 0
728 || val != (sd->channels != 1))
729 sound_perror ("Could not set stereo/mono");
731 /* I think bps and sampling_rate are the same, but who knows.
732 Check this. and use SND_DSP_SPEED for both. */
733 if (sd->sample_rate > 0)
735 val = sd->sample_rate;
736 if (ioctl (sd->fd, SNDCTL_DSP_SPEED, &sd->sample_rate) < 0)
737 sound_perror ("Could not set sound speed");
738 else if (val != sd->sample_rate)
739 sound_warning ("Could not set sample rate");
742 if (sd->volume > 0)
744 int volume = sd->volume & 0xff;
745 volume |= volume << 8;
746 /* This may fail if there is no mixer. Ignore the failure. */
747 ioctl (sd->fd, SOUND_MIXER_WRITE_PCM, &volume);
750 turn_on_atimers (1);
751 #ifdef USABLE_SIGIO
752 pthread_sigmask (SIG_SETMASK, &oldset, 0);
753 #endif
757 /* Close device SD if it is open. */
759 static void
760 vox_close (struct sound_device *sd)
762 if (sd->fd >= 0)
764 /* On GNU/Linux, it seems that the device driver doesn't like to
765 be interrupted by a signal. Block the ones we know to cause
766 troubles. */
767 #ifdef USABLE_SIGIO
768 sigset_t blocked, oldset;
769 sigemptyset (&blocked);
770 sigaddset (&blocked, SIGIO);
771 pthread_sigmask (SIG_BLOCK, &blocked, &oldset);
772 #endif
773 turn_on_atimers (0);
775 /* Flush sound data, and reset the device. */
776 ioctl (sd->fd, SNDCTL_DSP_SYNC, NULL);
778 turn_on_atimers (1);
779 #ifdef USABLE_SIGIO
780 pthread_sigmask (SIG_SETMASK, &oldset, 0);
781 #endif
783 /* Close the device. */
784 emacs_close (sd->fd);
785 sd->fd = -1;
790 /* Choose device-dependent format for device SD from sound file S. */
792 static void
793 vox_choose_format (struct sound_device *sd, struct sound *s)
795 if (s->type == RIFF)
797 struct wav_header *h = (struct wav_header *) s->header;
798 if (h->precision == 8)
799 sd->format = AFMT_U8;
800 else if (h->precision == 16)
801 sd->format = AFMT_S16_LE;
802 else
803 error ("Unsupported WAV file format");
805 else if (s->type == SUN_AUDIO)
807 struct au_header *header = (struct au_header *) s->header;
808 switch (header->encoding)
810 case AU_ENCODING_ULAW_8:
811 case AU_ENCODING_IEEE32:
812 case AU_ENCODING_IEEE64:
813 sd->format = AFMT_MU_LAW;
814 break;
816 case AU_ENCODING_8:
817 case AU_ENCODING_16:
818 case AU_ENCODING_24:
819 case AU_ENCODING_32:
820 sd->format = AFMT_S16_LE;
821 break;
823 default:
824 error ("Unsupported AU file format");
827 else
828 emacs_abort ();
832 /* Initialize device SD. Set up the interface functions in the device
833 structure. */
835 static bool
836 vox_init (struct sound_device *sd)
838 /* Open the sound device (eg /dev/dsp). */
839 char const *file = string_default (sd->file, DEFAULT_SOUND_DEVICE);
840 int fd = emacs_open (file, O_WRONLY, 0);
841 if (fd >= 0)
842 emacs_close (fd);
843 else
844 return 0;
846 sd->fd = -1;
847 sd->open = vox_open;
848 sd->close = vox_close;
849 sd->configure = vox_configure;
850 sd->choose_format = vox_choose_format;
851 sd->write = vox_write;
852 sd->period_size = NULL;
854 return 1;
857 /* Write NBYTES bytes from BUFFER to device SD. */
859 static void
860 vox_write (struct sound_device *sd, const char *buffer, ptrdiff_t nbytes)
862 if (emacs_write_sig (sd->fd, buffer, nbytes) != nbytes)
863 sound_perror ("Error writing to sound device");
866 #ifdef HAVE_ALSA
867 /***********************************************************************
868 ALSA Driver Interface
869 ***********************************************************************/
871 /* This driver is available on GNU/Linux. */
873 #ifndef DEFAULT_ALSA_SOUND_DEVICE
874 #define DEFAULT_ALSA_SOUND_DEVICE "default"
875 #endif
877 static _Noreturn void
878 alsa_sound_perror (const char *msg, int err)
880 error ("%s: %s", msg, snd_strerror (err));
883 struct alsa_params
885 snd_pcm_t *handle;
886 snd_pcm_hw_params_t *hwparams;
887 snd_pcm_sw_params_t *swparams;
888 snd_pcm_uframes_t period_size;
891 /* Open device SD. If SD->file is a string, open that device,
892 otherwise use a default device name. */
894 static void
895 alsa_open (struct sound_device *sd)
897 /* Open the sound device. Default is "default". */
898 struct alsa_params *p = xmalloc (sizeof *p);
899 char const *file = string_default (sd->file, DEFAULT_ALSA_SOUND_DEVICE);
900 int err;
902 p->handle = NULL;
903 p->hwparams = NULL;
904 p->swparams = NULL;
906 sd->fd = -1;
907 sd->data = p;
910 err = snd_pcm_open (&p->handle, file, SND_PCM_STREAM_PLAYBACK, 0);
911 if (err < 0)
912 alsa_sound_perror (file, err);
915 static ptrdiff_t
916 alsa_period_size (struct sound_device *sd)
918 struct alsa_params *p = (struct alsa_params *) sd->data;
919 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
920 return p->period_size * (fact > 0 ? fact : 1);
923 static void
924 alsa_configure (struct sound_device *sd)
926 int val, err, dir;
927 unsigned uval;
928 struct alsa_params *p = (struct alsa_params *) sd->data;
929 snd_pcm_uframes_t buffer_size;
931 eassert (p->handle != 0);
933 err = snd_pcm_hw_params_malloc (&p->hwparams);
934 if (err < 0)
935 alsa_sound_perror ("Could not allocate hardware parameter structure", err);
937 err = snd_pcm_sw_params_malloc (&p->swparams);
938 if (err < 0)
939 alsa_sound_perror ("Could not allocate software parameter structure", err);
941 err = snd_pcm_hw_params_any (p->handle, p->hwparams);
942 if (err < 0)
943 alsa_sound_perror ("Could not initialize hardware parameter structure", err);
945 err = snd_pcm_hw_params_set_access (p->handle, p->hwparams,
946 SND_PCM_ACCESS_RW_INTERLEAVED);
947 if (err < 0)
948 alsa_sound_perror ("Could not set access type", err);
950 val = sd->format;
951 err = snd_pcm_hw_params_set_format (p->handle, p->hwparams, val);
952 if (err < 0)
953 alsa_sound_perror ("Could not set sound format", err);
955 uval = sd->sample_rate;
956 err = snd_pcm_hw_params_set_rate_near (p->handle, p->hwparams, &uval, 0);
957 if (err < 0)
958 alsa_sound_perror ("Could not set sample rate", err);
960 val = sd->channels;
961 err = snd_pcm_hw_params_set_channels (p->handle, p->hwparams, val);
962 if (err < 0)
963 alsa_sound_perror ("Could not set channel count", err);
965 err = snd_pcm_hw_params (p->handle, p->hwparams);
966 if (err < 0)
967 alsa_sound_perror ("Could not set parameters", err);
970 err = snd_pcm_hw_params_get_period_size (p->hwparams, &p->period_size, &dir);
971 if (err < 0)
972 alsa_sound_perror ("Unable to get period size for playback", err);
974 err = snd_pcm_hw_params_get_buffer_size (p->hwparams, &buffer_size);
975 if (err < 0)
976 alsa_sound_perror ("Unable to get buffer size for playback", err);
978 err = snd_pcm_sw_params_current (p->handle, p->swparams);
979 if (err < 0)
980 alsa_sound_perror ("Unable to determine current swparams for playback",
981 err);
983 /* Start the transfer when the buffer is almost full */
984 err = snd_pcm_sw_params_set_start_threshold (p->handle, p->swparams,
985 (buffer_size / p->period_size)
986 * p->period_size);
987 if (err < 0)
988 alsa_sound_perror ("Unable to set start threshold mode for playback", err);
990 /* Allow the transfer when at least period_size samples can be processed */
991 err = snd_pcm_sw_params_set_avail_min (p->handle, p->swparams, p->period_size);
992 if (err < 0)
993 alsa_sound_perror ("Unable to set avail min for playback", err);
995 err = snd_pcm_sw_params (p->handle, p->swparams);
996 if (err < 0)
997 alsa_sound_perror ("Unable to set sw params for playback\n", err);
999 snd_pcm_hw_params_free (p->hwparams);
1000 p->hwparams = NULL;
1001 snd_pcm_sw_params_free (p->swparams);
1002 p->swparams = NULL;
1004 err = snd_pcm_prepare (p->handle);
1005 if (err < 0)
1006 alsa_sound_perror ("Could not prepare audio interface for use", err);
1008 if (sd->volume > 0)
1010 int chn;
1011 snd_mixer_t *handle;
1012 snd_mixer_elem_t *e;
1013 if (snd_mixer_open (&handle, 0) >= 0)
1015 char const *file = string_default (sd->file,
1016 DEFAULT_ALSA_SOUND_DEVICE);
1017 if (snd_mixer_attach (handle, file) >= 0
1018 && snd_mixer_load (handle) >= 0
1019 && snd_mixer_selem_register (handle, NULL, NULL) >= 0)
1020 for (e = snd_mixer_first_elem (handle);
1022 e = snd_mixer_elem_next (e))
1024 if (snd_mixer_selem_has_playback_volume (e))
1026 long pmin, pmax, vol;
1027 snd_mixer_selem_get_playback_volume_range (e, &pmin, &pmax);
1028 vol = pmin + (sd->volume * (pmax - pmin)) / 100;
1030 for (chn = 0; chn <= SND_MIXER_SCHN_LAST; chn++)
1031 snd_mixer_selem_set_playback_volume (e, chn, vol);
1034 snd_mixer_close (handle);
1040 /* Close device SD if it is open. */
1042 static void
1043 alsa_close (struct sound_device *sd)
1045 struct alsa_params *p = (struct alsa_params *) sd->data;
1046 if (p)
1048 if (p->hwparams)
1049 snd_pcm_hw_params_free (p->hwparams);
1050 if (p->swparams)
1051 snd_pcm_sw_params_free (p->swparams);
1052 if (p->handle)
1054 snd_pcm_drain (p->handle);
1055 snd_pcm_close (p->handle);
1057 xfree (p);
1061 /* Choose device-dependent format for device SD from sound file S. */
1063 static void
1064 alsa_choose_format (struct sound_device *sd, struct sound *s)
1066 if (s->type == RIFF)
1068 struct wav_header *h = (struct wav_header *) s->header;
1069 if (h->precision == 8)
1070 sd->format = SND_PCM_FORMAT_U8;
1071 else if (h->precision == 16)
1072 sd->format = SND_PCM_FORMAT_S16_LE;
1073 else
1074 error ("Unsupported WAV file format");
1076 else if (s->type == SUN_AUDIO)
1078 struct au_header *header = (struct au_header *) s->header;
1079 switch (header->encoding)
1081 case AU_ENCODING_ULAW_8:
1082 sd->format = SND_PCM_FORMAT_MU_LAW;
1083 break;
1084 case AU_ENCODING_ALAW_8:
1085 sd->format = SND_PCM_FORMAT_A_LAW;
1086 break;
1087 case AU_ENCODING_IEEE32:
1088 sd->format = SND_PCM_FORMAT_FLOAT_BE;
1089 break;
1090 case AU_ENCODING_IEEE64:
1091 sd->format = SND_PCM_FORMAT_FLOAT64_BE;
1092 break;
1093 case AU_ENCODING_8:
1094 sd->format = SND_PCM_FORMAT_S8;
1095 break;
1096 case AU_ENCODING_16:
1097 sd->format = SND_PCM_FORMAT_S16_BE;
1098 break;
1099 case AU_ENCODING_24:
1100 sd->format = SND_PCM_FORMAT_S24_BE;
1101 break;
1102 case AU_ENCODING_32:
1103 sd->format = SND_PCM_FORMAT_S32_BE;
1104 break;
1106 default:
1107 error ("Unsupported AU file format");
1110 else
1111 emacs_abort ();
1115 /* Write NBYTES bytes from BUFFER to device SD. */
1117 static void
1118 alsa_write (struct sound_device *sd, const char *buffer, ptrdiff_t nbytes)
1120 struct alsa_params *p = (struct alsa_params *) sd->data;
1122 /* The the third parameter to snd_pcm_writei is frames, not bytes. */
1123 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
1124 ptrdiff_t nwritten = 0;
1125 int err;
1127 while (nwritten < nbytes)
1129 snd_pcm_uframes_t frames = (nbytes - nwritten)/fact;
1130 if (frames == 0) break;
1132 err = snd_pcm_writei (p->handle, buffer + nwritten, frames);
1133 if (err < 0)
1135 if (err == -EPIPE)
1136 { /* under-run */
1137 err = snd_pcm_prepare (p->handle);
1138 if (err < 0)
1139 alsa_sound_perror ("Can't recover from underrun, prepare failed",
1140 err);
1142 else if (err == -ESTRPIPE)
1144 while ((err = snd_pcm_resume (p->handle)) == -EAGAIN)
1145 sleep (1); /* wait until the suspend flag is released */
1146 if (err < 0)
1148 err = snd_pcm_prepare (p->handle);
1149 if (err < 0)
1150 alsa_sound_perror ("Can't recover from suspend, "
1151 "prepare failed",
1152 err);
1155 else
1156 alsa_sound_perror ("Error writing to sound device", err);
1159 else
1160 nwritten += err * fact;
1164 static void
1165 snd_error_quiet (const char *file, int line, const char *function, int err,
1166 const char *fmt)
1170 /* Initialize device SD. Set up the interface functions in the device
1171 structure. */
1173 static bool
1174 alsa_init (struct sound_device *sd)
1176 /* Open the sound device. Default is "default". */
1177 char const *file = string_default (sd->file, DEFAULT_ALSA_SOUND_DEVICE);
1178 snd_pcm_t *handle;
1179 int err;
1181 snd_lib_error_set_handler ((snd_lib_error_handler_t) snd_error_quiet);
1182 err = snd_pcm_open (&handle, file, SND_PCM_STREAM_PLAYBACK, 0);
1183 snd_lib_error_set_handler (NULL);
1184 if (err < 0)
1185 return 0;
1186 snd_pcm_close (handle);
1188 sd->fd = -1;
1189 sd->open = alsa_open;
1190 sd->close = alsa_close;
1191 sd->configure = alsa_configure;
1192 sd->choose_format = alsa_choose_format;
1193 sd->write = alsa_write;
1194 sd->period_size = alsa_period_size;
1196 return 1;
1199 #endif /* HAVE_ALSA */
1202 /* END: Non Windows functions */
1203 #else /* WINDOWSNT */
1205 /* BEGIN: Windows specific functions */
1207 #define SOUND_WARNING(func, error, text) \
1208 do { \
1209 char buf[1024]; \
1210 char err_string[MAXERRORLENGTH]; \
1211 func (error, err_string, sizeof (err_string)); \
1212 _snprintf (buf, sizeof (buf), "%s\nMCI Error: %s", \
1213 text, err_string); \
1214 message_with_string ("%s", build_string (buf), 1); \
1215 } while (0)
1217 static int
1218 do_play_sound (const char *psz_file, unsigned long ui_volume)
1220 int i_result = 0;
1221 MCIERROR mci_error = 0;
1222 char sz_cmd_buf_a[520];
1223 char sz_ret_buf_a[520];
1224 MMRESULT mm_result = MMSYSERR_NOERROR;
1225 unsigned long ui_volume_org = 0;
1226 BOOL b_reset_volume = FALSE;
1227 char warn_text[560];
1229 /* Since UNICOWS.DLL includes only a stub for mciSendStringW, we
1230 need to encode the file in the ANSI codepage on Windows 9X even
1231 if w32_unicode_filenames is non-zero. */
1232 if (w32_major_version <= 4 || !w32_unicode_filenames)
1234 char fname_a[MAX_PATH], shortname[MAX_PATH], *fname_to_use;
1236 filename_to_ansi (psz_file, fname_a);
1237 fname_to_use = fname_a;
1238 /* If the file name is not encodable in ANSI, try its short 8+3
1239 alias. This will only work if w32_unicode_filenames is
1240 non-zero. */
1241 if (_mbspbrk ((const unsigned char *)fname_a,
1242 (const unsigned char *)"?"))
1244 if (w32_get_short_filename (psz_file, shortname, MAX_PATH))
1245 fname_to_use = shortname;
1246 else
1247 mci_error = MCIERR_FILE_NOT_FOUND;
1250 if (!mci_error)
1252 memset (sz_cmd_buf_a, 0, sizeof (sz_cmd_buf_a));
1253 memset (sz_ret_buf_a, 0, sizeof (sz_ret_buf_a));
1254 sprintf (sz_cmd_buf_a,
1255 "open \"%s\" alias GNUEmacs_PlaySound_Device wait",
1256 fname_to_use);
1257 mci_error = mciSendStringA (sz_cmd_buf_a,
1258 sz_ret_buf_a, sizeof (sz_ret_buf_a), NULL);
1261 else
1263 wchar_t sz_cmd_buf_w[520];
1264 wchar_t sz_ret_buf_w[520];
1265 wchar_t fname_w[MAX_PATH];
1267 filename_to_utf16 (psz_file, fname_w);
1268 memset (sz_cmd_buf_w, 0, sizeof (sz_cmd_buf_w));
1269 memset (sz_ret_buf_w, 0, sizeof (sz_ret_buf_w));
1270 /* _swprintf is not available on Windows 9X, so we construct the
1271 UTF-16 command string by hand. */
1272 wcscpy (sz_cmd_buf_w, L"open \"");
1273 wcscat (sz_cmd_buf_w, fname_w);
1274 wcscat (sz_cmd_buf_w, L"\" alias GNUEmacs_PlaySound_Device wait");
1275 mci_error = mciSendStringW (sz_cmd_buf_w,
1276 sz_ret_buf_w, ARRAYELTS (sz_ret_buf_w) , NULL);
1278 if (mci_error != 0)
1280 strcpy (warn_text,
1281 "mciSendString: 'open' command failed to open sound file ");
1282 strcat (warn_text, psz_file);
1283 SOUND_WARNING (mciGetErrorString, mci_error, warn_text);
1284 i_result = (int) mci_error;
1285 return i_result;
1287 if ((ui_volume > 0) && (ui_volume != UINT_MAX))
1289 mm_result = waveOutGetVolume ((HWAVEOUT) WAVE_MAPPER, &ui_volume_org);
1290 if (mm_result == MMSYSERR_NOERROR)
1292 b_reset_volume = TRUE;
1293 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume);
1294 if (mm_result != MMSYSERR_NOERROR)
1296 SOUND_WARNING (waveOutGetErrorText, mm_result,
1297 "waveOutSetVolume: failed to set the volume level"
1298 " of the WAVE_MAPPER device.\n"
1299 "As a result, the user selected volume level will"
1300 " not be used.");
1303 else
1305 SOUND_WARNING (waveOutGetErrorText, mm_result,
1306 "waveOutGetVolume: failed to obtain the original"
1307 " volume level of the WAVE_MAPPER device.\n"
1308 "As a result, the user selected volume level will"
1309 " not be used.");
1312 memset (sz_cmd_buf_a, 0, sizeof (sz_cmd_buf_a));
1313 memset (sz_ret_buf_a, 0, sizeof (sz_ret_buf_a));
1314 strcpy (sz_cmd_buf_a, "play GNUEmacs_PlaySound_Device wait");
1315 mci_error = mciSendStringA (sz_cmd_buf_a, sz_ret_buf_a, sizeof (sz_ret_buf_a),
1316 NULL);
1317 if (mci_error != 0)
1319 strcpy (warn_text,
1320 "mciSendString: 'play' command failed to play sound file ");
1321 strcat (warn_text, psz_file);
1322 SOUND_WARNING (mciGetErrorString, mci_error, warn_text);
1323 i_result = (int) mci_error;
1325 memset (sz_cmd_buf_a, 0, sizeof (sz_cmd_buf_a));
1326 memset (sz_ret_buf_a, 0, sizeof (sz_ret_buf_a));
1327 strcpy (sz_cmd_buf_a, "close GNUEmacs_PlaySound_Device wait");
1328 mci_error = mciSendStringA (sz_cmd_buf_a, sz_ret_buf_a, sizeof (sz_ret_buf_a),
1329 NULL);
1330 if (b_reset_volume == TRUE)
1332 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume_org);
1333 if (mm_result != MMSYSERR_NOERROR)
1335 SOUND_WARNING (waveOutGetErrorText, mm_result,
1336 "waveOutSetVolume: failed to reset the original"
1337 " volume level of the WAVE_MAPPER device.");
1340 return i_result;
1343 /* END: Windows specific functions */
1345 #endif /* WINDOWSNT */
1347 DEFUN ("play-sound-internal", Fplay_sound_internal, Splay_sound_internal, 1, 1, 0,
1348 doc: /* Play sound SOUND.
1350 Internal use only, use `play-sound' instead. */)
1351 (Lisp_Object sound)
1353 Lisp_Object attrs[SOUND_ATTR_SENTINEL];
1354 ptrdiff_t count = SPECPDL_INDEX ();
1356 #ifdef WINDOWSNT
1357 unsigned long ui_volume_tmp = UINT_MAX;
1358 unsigned long ui_volume = UINT_MAX;
1359 #endif /* WINDOWSNT */
1361 /* Parse the sound specification. Give up if it is invalid. */
1362 if (!parse_sound (sound, attrs))
1363 error ("Invalid sound specification");
1365 Lisp_Object file = Qnil;
1367 #ifndef WINDOWSNT
1368 current_sound_device = xzalloc (sizeof *current_sound_device);
1369 current_sound = xzalloc (sizeof *current_sound);
1370 record_unwind_protect_void (sound_cleanup);
1371 char headerbuf[MAX_SOUND_HEADER_BYTES];
1372 current_sound->header = headerbuf;
1374 if (STRINGP (attrs[SOUND_FILE]))
1376 /* Open the sound file. */
1377 current_sound->fd = openp (list1 (Vdata_directory),
1378 attrs[SOUND_FILE], Qnil, &file, Qnil, false);
1379 if (current_sound->fd < 0)
1380 sound_perror ("Could not open sound file");
1382 /* Read the first bytes from the file. */
1383 current_sound->header_size
1384 = emacs_read (current_sound->fd, current_sound->header,
1385 MAX_SOUND_HEADER_BYTES);
1386 if (current_sound->header_size < 0)
1387 sound_perror ("Invalid sound file header");
1389 else
1391 current_sound->data = attrs[SOUND_DATA];
1392 current_sound->header_size = min (MAX_SOUND_HEADER_BYTES, SBYTES (current_sound->data));
1393 memcpy (current_sound->header, SDATA (current_sound->data),
1394 current_sound->header_size);
1397 /* Find out the type of sound. Give up if we can't tell. */
1398 find_sound_type (current_sound);
1400 /* Set up a device. */
1401 current_sound_device->file = attrs[SOUND_DEVICE];
1403 if (INTEGERP (attrs[SOUND_VOLUME]))
1404 current_sound_device->volume = XFASTINT (attrs[SOUND_VOLUME]);
1405 else if (FLOATP (attrs[SOUND_VOLUME]))
1406 current_sound_device->volume = XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1408 CALLN (Frun_hook_with_args, Qplay_sound_functions, sound);
1410 #ifdef HAVE_ALSA
1411 if (!alsa_init (current_sound_device))
1412 #endif
1413 if (!vox_init (current_sound_device))
1414 error ("No usable sound device driver found");
1416 /* Open the device. */
1417 current_sound_device->open (current_sound_device);
1419 /* Play the sound. */
1420 current_sound->play (current_sound, current_sound_device);
1422 #else /* WINDOWSNT */
1424 file = Fexpand_file_name (attrs[SOUND_FILE], Vdata_directory);
1425 file = ENCODE_FILE (file);
1426 if (INTEGERP (attrs[SOUND_VOLUME]))
1428 ui_volume_tmp = XFASTINT (attrs[SOUND_VOLUME]);
1430 else if (FLOATP (attrs[SOUND_VOLUME]))
1432 ui_volume_tmp = XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1435 CALLN (Frun_hook_with_args, Qplay_sound_functions, sound);
1438 Based on some experiments I have conducted, a value of 100 or less
1439 for the sound volume is much too low. You cannot even hear it.
1440 A value of UINT_MAX indicates that you wish for the sound to played
1441 at the maximum possible volume. A value of UINT_MAX/2 plays the
1442 sound at 50% maximum volume. Therefore the value passed to do_play_sound
1443 (and thus to waveOutSetVolume) must be some fraction of UINT_MAX.
1444 The following code adjusts the user specified volume level appropriately.
1446 if ((ui_volume_tmp > 0) && (ui_volume_tmp <= 100))
1448 ui_volume = ui_volume_tmp * (UINT_MAX / 100);
1450 (void)do_play_sound (SSDATA (file), ui_volume);
1452 #endif /* WINDOWSNT */
1454 return unbind_to (count, Qnil);
1457 /***********************************************************************
1458 Initialization
1459 ***********************************************************************/
1461 void
1462 syms_of_sound (void)
1464 DEFSYM (QCdevice, ":device");
1465 DEFSYM (QCvolume, ":volume");
1466 DEFSYM (Qsound, "sound");
1467 DEFSYM (Qplay_sound_functions, "play-sound-functions");
1469 defsubr (&Splay_sound_internal);
1472 #endif /* HAVE_SOUND */