Update copyright year to 2015
[emacs.git] / src / sound.c
blob88d86f6f84acd8a0754f22fa044d3439e80263d0
1 /* sound.c -- sound support.
3 Copyright (C) 1998-1999, 2001-2015 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 <mbstring.h>
90 #include <windows.h>
91 #include <mmsystem.h>
93 #include "coding.h"
94 #include "w32common.h"
95 #include "w32.h"
96 /* END: Windows Specific Includes */
98 #endif /* WINDOWSNT */
100 /* BEGIN: Common Definitions */
102 /* Symbols. */
104 static Lisp_Object QCvolume, QCdevice;
105 static Lisp_Object Qsound;
106 static Lisp_Object Qplay_sound_functions;
108 /* Indices of attributes in a sound attributes vector. */
110 enum sound_attr
112 SOUND_FILE,
113 SOUND_DATA,
114 SOUND_DEVICE,
115 SOUND_VOLUME,
116 SOUND_ATTR_SENTINEL
119 /* END: Common Definitions */
121 /* BEGIN: Non Windows Definitions */
122 #ifndef WINDOWSNT
124 /* Structure forward declarations. */
126 struct sound;
127 struct sound_device;
129 /* The file header of RIFF-WAVE files (*.wav). Files are always in
130 little-endian byte-order. */
132 struct wav_header
134 u_int32_t magic;
135 u_int32_t length;
136 u_int32_t chunk_type;
137 u_int32_t chunk_format;
138 u_int32_t chunk_length;
139 u_int16_t format;
140 u_int16_t channels;
141 u_int32_t sample_rate;
142 u_int32_t bytes_per_second;
143 u_int16_t sample_size;
144 u_int16_t precision;
145 u_int32_t chunk_data;
146 u_int32_t data_length;
149 /* The file header of Sun adio files (*.au). Files are always in
150 big-endian byte-order. */
152 struct au_header
154 /* ASCII ".snd" */
155 u_int32_t magic_number;
157 /* Offset of data part from start of file. Minimum value is 24. */
158 u_int32_t data_offset;
160 /* Size of data part, 0xffffffff if unknown. */
161 u_int32_t data_size;
163 /* Data encoding format.
164 1 8-bit ISDN u-law
165 2 8-bit linear PCM (REF-PCM)
166 3 16-bit linear PCM
167 4 24-bit linear PCM
168 5 32-bit linear PCM
169 6 32-bit IEEE floating-point
170 7 64-bit IEEE floating-point
171 23 8-bit u-law compressed using CCITT 0.721 ADPCM voice data
172 encoding scheme. */
173 u_int32_t encoding;
175 /* Number of samples per second. */
176 u_int32_t sample_rate;
178 /* Number of interleaved channels. */
179 u_int32_t channels;
182 /* Maximum of all sound file headers sizes. */
184 #define MAX_SOUND_HEADER_BYTES \
185 max (sizeof (struct wav_header), sizeof (struct au_header))
187 /* Interface structure for sound devices. */
189 struct sound_device
191 /* If a string, the name of the device; otherwise use a default. */
192 Lisp_Object file;
194 /* File descriptor of the device. */
195 int fd;
197 /* Device-dependent format. */
198 int format;
200 /* Volume (0..100). Zero means unspecified. */
201 int volume;
203 /* Sample size. */
204 int sample_size;
206 /* Sample rate. */
207 int sample_rate;
209 /* Bytes per second. */
210 int bps;
212 /* 1 = mono, 2 = stereo, 0 = don't set. */
213 int channels;
215 /* Open device SD. */
216 void (* open) (struct sound_device *sd);
218 /* Close device SD. */
219 void (* close) (struct sound_device *sd);
221 /* Configure SD according to device-dependent parameters. */
222 void (* configure) (struct sound_device *device);
224 /* Choose a device-dependent format for outputting sound S. */
225 void (* choose_format) (struct sound_device *sd,
226 struct sound *s);
228 /* Return a preferred data size in bytes to be sent to write (below)
229 each time. 2048 is used if this is NULL. */
230 ptrdiff_t (* period_size) (struct sound_device *sd);
232 /* Write NYBTES bytes from BUFFER to device SD. */
233 void (* write) (struct sound_device *sd, const char *buffer,
234 ptrdiff_t nbytes);
236 /* A place for devices to store additional data. */
237 void *data;
240 /* An enumerator for each supported sound file type. */
242 enum sound_type
244 RIFF,
245 SUN_AUDIO
248 /* Interface structure for sound files. */
250 struct sound
252 /* The type of the file. */
253 enum sound_type type;
255 /* File descriptor of a sound file. */
256 int fd;
258 /* Pointer to sound file header. This contains header_size bytes
259 read from the start of a sound file. */
260 char *header;
262 /* Number of bytes read from sound file. This is always <=
263 MAX_SOUND_HEADER_BYTES. */
264 int header_size;
266 /* Sound data, if a string. */
267 Lisp_Object data;
269 /* Play sound file S on device SD. */
270 void (* play) (struct sound *s, struct sound_device *sd);
273 /* These are set during `play-sound-internal' so that sound_cleanup has
274 access to them. */
276 static struct sound_device *current_sound_device;
277 static struct sound *current_sound;
279 /* Function prototypes. */
281 static void vox_write (struct sound_device *, const char *, ptrdiff_t);
282 static bool wav_init (struct sound *);
283 static void wav_play (struct sound *, struct sound_device *);
284 static bool au_init (struct sound *);
285 static void au_play (struct sound *, struct sound_device *);
287 /* END: Non Windows Definitions */
288 #else /* WINDOWSNT */
290 /* BEGIN: Windows Specific Definitions */
291 static int do_play_sound (const char *, unsigned long);
293 END: Windows Specific Definitions */
294 #endif /* WINDOWSNT */
297 /***********************************************************************
298 General
299 ***********************************************************************/
301 /* BEGIN: Common functions */
303 /* Like perror, but signals an error. */
305 static _Noreturn void
306 sound_perror (const char *msg)
308 int saved_errno = errno;
310 turn_on_atimers (1);
311 #ifdef USABLE_SIGIO
313 sigset_t unblocked;
314 sigemptyset (&unblocked);
315 sigaddset (&unblocked, SIGIO);
316 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
318 #endif
319 if (saved_errno != 0)
320 error ("%s: %s", msg, strerror (saved_errno));
321 else
322 error ("%s", msg);
326 /* Display a warning message. */
328 static void
329 sound_warning (const char *msg)
331 message1 (msg);
335 /* Parse sound specification SOUND, and fill ATTRS with what is
336 found. Value is non-zero if SOUND Is a valid sound specification.
337 A valid sound specification is a list starting with the symbol
338 `sound'. The rest of the list is a property list which may
339 contain the following key/value pairs:
341 - `:file FILE'
343 FILE is the sound file to play. If it isn't an absolute name,
344 it's searched under `data-directory'.
346 - `:data DATA'
348 DATA is a string containing sound data. Either :file or :data
349 may be present, but not both.
351 - `:device DEVICE'
353 DEVICE is the name of the device to play on, e.g. "/dev/dsp2".
354 If not specified, a default device is used.
356 - `:volume VOL'
358 VOL must be an integer in the range [0, 100], or a float in the
359 range [0, 1]. */
361 static bool
362 parse_sound (Lisp_Object sound, Lisp_Object *attrs)
364 /* SOUND must be a list starting with the symbol `sound'. */
365 if (!CONSP (sound) || !EQ (XCAR (sound), Qsound))
366 return 0;
368 sound = XCDR (sound);
369 attrs[SOUND_FILE] = Fplist_get (sound, QCfile);
370 attrs[SOUND_DATA] = Fplist_get (sound, QCdata);
371 attrs[SOUND_DEVICE] = Fplist_get (sound, QCdevice);
372 attrs[SOUND_VOLUME] = Fplist_get (sound, QCvolume);
374 #ifndef WINDOWSNT
375 /* File name or data must be specified. */
376 if (!STRINGP (attrs[SOUND_FILE])
377 && !STRINGP (attrs[SOUND_DATA]))
378 return 0;
379 #else /* WINDOWSNT */
381 Data is not supported in Windows. Therefore a
382 File name MUST be supplied.
384 if (!STRINGP (attrs[SOUND_FILE]))
386 return 0;
388 #endif /* WINDOWSNT */
390 /* Volume must be in the range 0..100 or unspecified. */
391 if (!NILP (attrs[SOUND_VOLUME]))
393 if (INTEGERP (attrs[SOUND_VOLUME]))
395 if (XINT (attrs[SOUND_VOLUME]) < 0
396 || XINT (attrs[SOUND_VOLUME]) > 100)
397 return 0;
399 else if (FLOATP (attrs[SOUND_VOLUME]))
401 if (XFLOAT_DATA (attrs[SOUND_VOLUME]) < 0
402 || XFLOAT_DATA (attrs[SOUND_VOLUME]) > 1)
403 return 0;
405 else
406 return 0;
409 #ifndef WINDOWSNT
410 /* Device must be a string or unspecified. */
411 if (!NILP (attrs[SOUND_DEVICE])
412 && !STRINGP (attrs[SOUND_DEVICE]))
413 return 0;
414 #endif /* WINDOWSNT */
416 Since device is ignored in Windows, it does not matter
417 what it is.
419 return 1;
422 /* END: Common functions */
424 /* BEGIN: Non Windows functions */
425 #ifndef WINDOWSNT
427 /* Return S's value as a string if S is a string, otherwise DEFAULT_VALUE. */
429 static char const *
430 string_default (Lisp_Object s, char const *default_value)
432 return STRINGP (s) ? SSDATA (s) : default_value;
436 /* Find out the type of the sound file whose file descriptor is FD.
437 S is the sound file structure to fill in. */
439 static void
440 find_sound_type (struct sound *s)
442 if (!wav_init (s) && !au_init (s))
443 error ("Unknown sound format");
447 /* Function installed by play-sound-internal with record_unwind_protect_void. */
449 static void
450 sound_cleanup (void)
452 if (current_sound_device->close)
453 current_sound_device->close (current_sound_device);
454 if (current_sound->fd > 0)
455 emacs_close (current_sound->fd);
456 xfree (current_sound_device);
457 xfree (current_sound);
460 /***********************************************************************
461 Byte-order Conversion
462 ***********************************************************************/
464 /* Convert 32-bit value VALUE which is in little-endian byte-order
465 to host byte-order. */
467 static u_int32_t
468 le2hl (u_int32_t value)
470 #ifdef WORDS_BIGENDIAN
471 value = bswap_32 (value);
472 #endif
473 return value;
477 /* Convert 16-bit value VALUE which is in little-endian byte-order
478 to host byte-order. */
480 static u_int16_t
481 le2hs (u_int16_t value)
483 #ifdef WORDS_BIGENDIAN
484 value = bswap_16 (value);
485 #endif
486 return value;
490 /* Convert 32-bit value VALUE which is in big-endian byte-order
491 to host byte-order. */
493 static u_int32_t
494 be2hl (u_int32_t value)
496 #ifndef WORDS_BIGENDIAN
497 value = bswap_32 (value);
498 #endif
499 return value;
502 /***********************************************************************
503 RIFF-WAVE (*.wav)
504 ***********************************************************************/
506 /* Try to initialize sound file S from S->header. S->header
507 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
508 sound file. If the file is a WAV-format file, set up interface
509 functions in S and convert header fields to host byte-order.
510 Value is true if the file is a WAV file. */
512 static bool
513 wav_init (struct sound *s)
515 struct wav_header *header = (struct wav_header *) s->header;
517 if (s->header_size < sizeof *header
518 || memcmp (s->header, "RIFF", 4) != 0)
519 return 0;
521 /* WAV files are in little-endian order. Convert the header
522 if on a big-endian machine. */
523 header->magic = le2hl (header->magic);
524 header->length = le2hl (header->length);
525 header->chunk_type = le2hl (header->chunk_type);
526 header->chunk_format = le2hl (header->chunk_format);
527 header->chunk_length = le2hl (header->chunk_length);
528 header->format = le2hs (header->format);
529 header->channels = le2hs (header->channels);
530 header->sample_rate = le2hl (header->sample_rate);
531 header->bytes_per_second = le2hl (header->bytes_per_second);
532 header->sample_size = le2hs (header->sample_size);
533 header->precision = le2hs (header->precision);
534 header->chunk_data = le2hl (header->chunk_data);
535 header->data_length = le2hl (header->data_length);
537 /* Set up the interface functions for WAV. */
538 s->type = RIFF;
539 s->play = wav_play;
541 return 1;
545 /* Play RIFF-WAVE audio file S on sound device SD. */
547 static void
548 wav_play (struct sound *s, struct sound_device *sd)
550 struct wav_header *header = (struct wav_header *) s->header;
552 /* Let the device choose a suitable device-dependent format
553 for the file. */
554 sd->choose_format (sd, s);
556 /* Configure the device. */
557 sd->sample_size = header->sample_size;
558 sd->sample_rate = header->sample_rate;
559 sd->bps = header->bytes_per_second;
560 sd->channels = header->channels;
561 sd->configure (sd);
563 /* Copy sound data to the device. The WAV file specification is
564 actually more complex. This simple scheme worked with all WAV
565 files I found so far. If someone feels inclined to implement the
566 whole RIFF-WAVE spec, please do. */
567 if (STRINGP (s->data))
568 sd->write (sd, SSDATA (s->data) + sizeof *header,
569 SBYTES (s->data) - sizeof *header);
570 else
572 ptrdiff_t nbytes = 0;
573 ptrdiff_t blksize = sd->period_size ? sd->period_size (sd) : 2048;
574 ptrdiff_t data_left = header->data_length;
575 USE_SAFE_ALLOCA;
576 char *buffer = SAFE_ALLOCA (blksize);
577 lseek (s->fd, sizeof *header, SEEK_SET);
578 while (data_left > 0
579 && (nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
581 /* Don't play possible garbage at the end of file */
582 if (data_left < nbytes) nbytes = data_left;
583 data_left -= nbytes;
584 sd->write (sd, buffer, nbytes);
587 if (nbytes < 0)
588 sound_perror ("Error reading sound file");
589 SAFE_FREE ();
594 /***********************************************************************
595 Sun Audio (*.au)
596 ***********************************************************************/
598 /* Sun audio file encodings. */
600 enum au_encoding
602 AU_ENCODING_ULAW_8 = 1,
603 AU_ENCODING_8,
604 AU_ENCODING_16,
605 AU_ENCODING_24,
606 AU_ENCODING_32,
607 AU_ENCODING_IEEE32,
608 AU_ENCODING_IEEE64,
609 AU_COMPRESSED = 23,
610 AU_ENCODING_ALAW_8 = 27
614 /* Try to initialize sound file S from S->header. S->header
615 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
616 sound file. If the file is a AU-format file, set up interface
617 functions in S and convert header fields to host byte-order.
618 Value is true if the file is an AU file. */
620 static bool
621 au_init (struct sound *s)
623 struct au_header *header = (struct au_header *) s->header;
625 if (s->header_size < sizeof *header
626 || memcmp (s->header, ".snd", 4) != 0)
627 return 0;
629 header->magic_number = be2hl (header->magic_number);
630 header->data_offset = be2hl (header->data_offset);
631 header->data_size = be2hl (header->data_size);
632 header->encoding = be2hl (header->encoding);
633 header->sample_rate = be2hl (header->sample_rate);
634 header->channels = be2hl (header->channels);
636 /* Set up the interface functions for AU. */
637 s->type = SUN_AUDIO;
638 s->play = au_play;
640 return 1;
644 /* Play Sun audio file S on sound device SD. */
646 static void
647 au_play (struct sound *s, struct sound_device *sd)
649 struct au_header *header = (struct au_header *) s->header;
651 sd->sample_size = 0;
652 sd->sample_rate = header->sample_rate;
653 sd->bps = 0;
654 sd->channels = header->channels;
655 sd->choose_format (sd, s);
656 sd->configure (sd);
658 if (STRINGP (s->data))
659 sd->write (sd, SSDATA (s->data) + header->data_offset,
660 SBYTES (s->data) - header->data_offset);
661 else
663 ptrdiff_t blksize = sd->period_size ? sd->period_size (sd) : 2048;
664 ptrdiff_t nbytes;
666 /* Seek */
667 lseek (s->fd, header->data_offset, SEEK_SET);
669 /* Copy sound data to the device. */
670 USE_SAFE_ALLOCA;
671 char *buffer = SAFE_ALLOCA (blksize);
672 while ((nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
673 sd->write (sd, buffer, nbytes);
675 if (nbytes < 0)
676 sound_perror ("Error reading sound file");
677 SAFE_FREE ();
682 /***********************************************************************
683 Voxware Driver Interface
684 ***********************************************************************/
686 /* This driver is available on GNU/Linux, and the free BSDs. FreeBSD
687 has a compatible own driver aka Luigi's driver. */
690 /* Open device SD. If SD->file is a string, open that device,
691 otherwise use a default device name. */
693 static void
694 vox_open (struct sound_device *sd)
696 /* Open the sound device (eg /dev/dsp). */
697 char const *file = string_default (sd->file, DEFAULT_SOUND_DEVICE);
698 sd->fd = emacs_open (file, O_WRONLY, 0);
699 if (sd->fd < 0)
700 sound_perror (file);
704 /* Configure device SD from parameters in it. */
706 static void
707 vox_configure (struct sound_device *sd)
709 int val;
710 #ifdef USABLE_SIGIO
711 sigset_t oldset, blocked;
712 #endif
714 eassert (sd->fd >= 0);
716 /* On GNU/Linux, it seems that the device driver doesn't like to be
717 interrupted by a signal. Block the ones we know to cause
718 troubles. */
719 turn_on_atimers (0);
720 #ifdef USABLE_SIGIO
721 sigemptyset (&blocked);
722 sigaddset (&blocked, SIGIO);
723 pthread_sigmask (SIG_BLOCK, &blocked, &oldset);
724 #endif
726 val = sd->format;
727 if (ioctl (sd->fd, SNDCTL_DSP_SETFMT, &sd->format) < 0
728 || val != sd->format)
729 sound_perror ("Could not set sound format");
731 val = sd->channels != 1;
732 if (ioctl (sd->fd, SNDCTL_DSP_STEREO, &val) < 0
733 || val != (sd->channels != 1))
734 sound_perror ("Could not set stereo/mono");
736 /* I think bps and sampling_rate are the same, but who knows.
737 Check this. and use SND_DSP_SPEED for both. */
738 if (sd->sample_rate > 0)
740 val = sd->sample_rate;
741 if (ioctl (sd->fd, SNDCTL_DSP_SPEED, &sd->sample_rate) < 0)
742 sound_perror ("Could not set sound speed");
743 else if (val != sd->sample_rate)
744 sound_warning ("Could not set sample rate");
747 if (sd->volume > 0)
749 int volume = sd->volume & 0xff;
750 volume |= volume << 8;
751 /* This may fail if there is no mixer. Ignore the failure. */
752 ioctl (sd->fd, SOUND_MIXER_WRITE_PCM, &volume);
755 turn_on_atimers (1);
756 #ifdef USABLE_SIGIO
757 pthread_sigmask (SIG_SETMASK, &oldset, 0);
758 #endif
762 /* Close device SD if it is open. */
764 static void
765 vox_close (struct sound_device *sd)
767 if (sd->fd >= 0)
769 /* On GNU/Linux, it seems that the device driver doesn't like to
770 be interrupted by a signal. Block the ones we know to cause
771 troubles. */
772 #ifdef USABLE_SIGIO
773 sigset_t blocked, oldset;
774 sigemptyset (&blocked);
775 sigaddset (&blocked, SIGIO);
776 pthread_sigmask (SIG_BLOCK, &blocked, &oldset);
777 #endif
778 turn_on_atimers (0);
780 /* Flush sound data, and reset the device. */
781 ioctl (sd->fd, SNDCTL_DSP_SYNC, NULL);
783 turn_on_atimers (1);
784 #ifdef USABLE_SIGIO
785 pthread_sigmask (SIG_SETMASK, &oldset, 0);
786 #endif
788 /* Close the device. */
789 emacs_close (sd->fd);
790 sd->fd = -1;
795 /* Choose device-dependent format for device SD from sound file S. */
797 static void
798 vox_choose_format (struct sound_device *sd, struct sound *s)
800 if (s->type == RIFF)
802 struct wav_header *h = (struct wav_header *) s->header;
803 if (h->precision == 8)
804 sd->format = AFMT_U8;
805 else if (h->precision == 16)
806 sd->format = AFMT_S16_LE;
807 else
808 error ("Unsupported WAV file format");
810 else if (s->type == SUN_AUDIO)
812 struct au_header *header = (struct au_header *) s->header;
813 switch (header->encoding)
815 case AU_ENCODING_ULAW_8:
816 case AU_ENCODING_IEEE32:
817 case AU_ENCODING_IEEE64:
818 sd->format = AFMT_MU_LAW;
819 break;
821 case AU_ENCODING_8:
822 case AU_ENCODING_16:
823 case AU_ENCODING_24:
824 case AU_ENCODING_32:
825 sd->format = AFMT_S16_LE;
826 break;
828 default:
829 error ("Unsupported AU file format");
832 else
833 emacs_abort ();
837 /* Initialize device SD. Set up the interface functions in the device
838 structure. */
840 static bool
841 vox_init (struct sound_device *sd)
843 /* Open the sound device (eg /dev/dsp). */
844 char const *file = string_default (sd->file, DEFAULT_SOUND_DEVICE);
845 int fd = emacs_open (file, O_WRONLY, 0);
846 if (fd >= 0)
847 emacs_close (fd);
848 else
849 return 0;
851 sd->fd = -1;
852 sd->open = vox_open;
853 sd->close = vox_close;
854 sd->configure = vox_configure;
855 sd->choose_format = vox_choose_format;
856 sd->write = vox_write;
857 sd->period_size = NULL;
859 return 1;
862 /* Write NBYTES bytes from BUFFER to device SD. */
864 static void
865 vox_write (struct sound_device *sd, const char *buffer, ptrdiff_t nbytes)
867 if (emacs_write_sig (sd->fd, buffer, nbytes) != nbytes)
868 sound_perror ("Error writing to sound device");
871 #ifdef HAVE_ALSA
872 /***********************************************************************
873 ALSA Driver Interface
874 ***********************************************************************/
876 /* This driver is available on GNU/Linux. */
878 #ifndef DEFAULT_ALSA_SOUND_DEVICE
879 #define DEFAULT_ALSA_SOUND_DEVICE "default"
880 #endif
882 static _Noreturn void
883 alsa_sound_perror (const char *msg, int err)
885 error ("%s: %s", msg, snd_strerror (err));
888 struct alsa_params
890 snd_pcm_t *handle;
891 snd_pcm_hw_params_t *hwparams;
892 snd_pcm_sw_params_t *swparams;
893 snd_pcm_uframes_t period_size;
896 /* Open device SD. If SD->file is a string, open that device,
897 otherwise use a default device name. */
899 static void
900 alsa_open (struct sound_device *sd)
902 /* Open the sound device. Default is "default". */
903 struct alsa_params *p = xmalloc (sizeof *p);
904 char const *file = string_default (sd->file, DEFAULT_ALSA_SOUND_DEVICE);
905 int err;
907 p->handle = NULL;
908 p->hwparams = NULL;
909 p->swparams = NULL;
911 sd->fd = -1;
912 sd->data = p;
915 err = snd_pcm_open (&p->handle, file, SND_PCM_STREAM_PLAYBACK, 0);
916 if (err < 0)
917 alsa_sound_perror (file, err);
920 static ptrdiff_t
921 alsa_period_size (struct sound_device *sd)
923 struct alsa_params *p = (struct alsa_params *) sd->data;
924 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
925 return p->period_size * (fact > 0 ? fact : 1);
928 static void
929 alsa_configure (struct sound_device *sd)
931 int val, err, dir;
932 unsigned uval;
933 struct alsa_params *p = (struct alsa_params *) sd->data;
934 snd_pcm_uframes_t buffer_size;
936 eassert (p->handle != 0);
938 err = snd_pcm_hw_params_malloc (&p->hwparams);
939 if (err < 0)
940 alsa_sound_perror ("Could not allocate hardware parameter structure", err);
942 err = snd_pcm_sw_params_malloc (&p->swparams);
943 if (err < 0)
944 alsa_sound_perror ("Could not allocate software parameter structure", err);
946 err = snd_pcm_hw_params_any (p->handle, p->hwparams);
947 if (err < 0)
948 alsa_sound_perror ("Could not initialize hardware parameter structure", err);
950 err = snd_pcm_hw_params_set_access (p->handle, p->hwparams,
951 SND_PCM_ACCESS_RW_INTERLEAVED);
952 if (err < 0)
953 alsa_sound_perror ("Could not set access type", err);
955 val = sd->format;
956 err = snd_pcm_hw_params_set_format (p->handle, p->hwparams, val);
957 if (err < 0)
958 alsa_sound_perror ("Could not set sound format", err);
960 uval = sd->sample_rate;
961 err = snd_pcm_hw_params_set_rate_near (p->handle, p->hwparams, &uval, 0);
962 if (err < 0)
963 alsa_sound_perror ("Could not set sample rate", err);
965 val = sd->channels;
966 err = snd_pcm_hw_params_set_channels (p->handle, p->hwparams, val);
967 if (err < 0)
968 alsa_sound_perror ("Could not set channel count", err);
970 err = snd_pcm_hw_params (p->handle, p->hwparams);
971 if (err < 0)
972 alsa_sound_perror ("Could not set parameters", err);
975 err = snd_pcm_hw_params_get_period_size (p->hwparams, &p->period_size, &dir);
976 if (err < 0)
977 alsa_sound_perror ("Unable to get period size for playback", err);
979 err = snd_pcm_hw_params_get_buffer_size (p->hwparams, &buffer_size);
980 if (err < 0)
981 alsa_sound_perror ("Unable to get buffer size for playback", err);
983 err = snd_pcm_sw_params_current (p->handle, p->swparams);
984 if (err < 0)
985 alsa_sound_perror ("Unable to determine current swparams for playback",
986 err);
988 /* Start the transfer when the buffer is almost full */
989 err = snd_pcm_sw_params_set_start_threshold (p->handle, p->swparams,
990 (buffer_size / p->period_size)
991 * p->period_size);
992 if (err < 0)
993 alsa_sound_perror ("Unable to set start threshold mode for playback", err);
995 /* Allow the transfer when at least period_size samples can be processed */
996 err = snd_pcm_sw_params_set_avail_min (p->handle, p->swparams, p->period_size);
997 if (err < 0)
998 alsa_sound_perror ("Unable to set avail min for playback", err);
1000 err = snd_pcm_sw_params (p->handle, p->swparams);
1001 if (err < 0)
1002 alsa_sound_perror ("Unable to set sw params for playback\n", err);
1004 snd_pcm_hw_params_free (p->hwparams);
1005 p->hwparams = NULL;
1006 snd_pcm_sw_params_free (p->swparams);
1007 p->swparams = NULL;
1009 err = snd_pcm_prepare (p->handle);
1010 if (err < 0)
1011 alsa_sound_perror ("Could not prepare audio interface for use", err);
1013 if (sd->volume > 0)
1015 int chn;
1016 snd_mixer_t *handle;
1017 snd_mixer_elem_t *e;
1018 if (snd_mixer_open (&handle, 0) >= 0)
1020 char const *file = string_default (sd->file,
1021 DEFAULT_ALSA_SOUND_DEVICE);
1022 if (snd_mixer_attach (handle, file) >= 0
1023 && snd_mixer_load (handle) >= 0
1024 && snd_mixer_selem_register (handle, NULL, NULL) >= 0)
1025 for (e = snd_mixer_first_elem (handle);
1027 e = snd_mixer_elem_next (e))
1029 if (snd_mixer_selem_has_playback_volume (e))
1031 long pmin, pmax, vol;
1032 snd_mixer_selem_get_playback_volume_range (e, &pmin, &pmax);
1033 vol = pmin + (sd->volume * (pmax - pmin)) / 100;
1035 for (chn = 0; chn <= SND_MIXER_SCHN_LAST; chn++)
1036 snd_mixer_selem_set_playback_volume (e, chn, vol);
1039 snd_mixer_close (handle);
1045 /* Close device SD if it is open. */
1047 static void
1048 alsa_close (struct sound_device *sd)
1050 struct alsa_params *p = (struct alsa_params *) sd->data;
1051 if (p)
1053 if (p->hwparams)
1054 snd_pcm_hw_params_free (p->hwparams);
1055 if (p->swparams)
1056 snd_pcm_sw_params_free (p->swparams);
1057 if (p->handle)
1059 snd_pcm_drain (p->handle);
1060 snd_pcm_close (p->handle);
1062 xfree (p);
1066 /* Choose device-dependent format for device SD from sound file S. */
1068 static void
1069 alsa_choose_format (struct sound_device *sd, struct sound *s)
1071 if (s->type == RIFF)
1073 struct wav_header *h = (struct wav_header *) s->header;
1074 if (h->precision == 8)
1075 sd->format = SND_PCM_FORMAT_U8;
1076 else if (h->precision == 16)
1077 sd->format = SND_PCM_FORMAT_S16_LE;
1078 else
1079 error ("Unsupported WAV file format");
1081 else if (s->type == SUN_AUDIO)
1083 struct au_header *header = (struct au_header *) s->header;
1084 switch (header->encoding)
1086 case AU_ENCODING_ULAW_8:
1087 sd->format = SND_PCM_FORMAT_MU_LAW;
1088 break;
1089 case AU_ENCODING_ALAW_8:
1090 sd->format = SND_PCM_FORMAT_A_LAW;
1091 break;
1092 case AU_ENCODING_IEEE32:
1093 sd->format = SND_PCM_FORMAT_FLOAT_BE;
1094 break;
1095 case AU_ENCODING_IEEE64:
1096 sd->format = SND_PCM_FORMAT_FLOAT64_BE;
1097 break;
1098 case AU_ENCODING_8:
1099 sd->format = SND_PCM_FORMAT_S8;
1100 break;
1101 case AU_ENCODING_16:
1102 sd->format = SND_PCM_FORMAT_S16_BE;
1103 break;
1104 case AU_ENCODING_24:
1105 sd->format = SND_PCM_FORMAT_S24_BE;
1106 break;
1107 case AU_ENCODING_32:
1108 sd->format = SND_PCM_FORMAT_S32_BE;
1109 break;
1111 default:
1112 error ("Unsupported AU file format");
1115 else
1116 emacs_abort ();
1120 /* Write NBYTES bytes from BUFFER to device SD. */
1122 static void
1123 alsa_write (struct sound_device *sd, const char *buffer, ptrdiff_t nbytes)
1125 struct alsa_params *p = (struct alsa_params *) sd->data;
1127 /* The the third parameter to snd_pcm_writei is frames, not bytes. */
1128 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
1129 ptrdiff_t nwritten = 0;
1130 int err;
1132 while (nwritten < nbytes)
1134 snd_pcm_uframes_t frames = (nbytes - nwritten)/fact;
1135 if (frames == 0) break;
1137 err = snd_pcm_writei (p->handle, buffer + nwritten, frames);
1138 if (err < 0)
1140 if (err == -EPIPE)
1141 { /* under-run */
1142 err = snd_pcm_prepare (p->handle);
1143 if (err < 0)
1144 alsa_sound_perror ("Can't recover from underrun, prepare failed",
1145 err);
1147 else if (err == -ESTRPIPE)
1149 while ((err = snd_pcm_resume (p->handle)) == -EAGAIN)
1150 sleep (1); /* wait until the suspend flag is released */
1151 if (err < 0)
1153 err = snd_pcm_prepare (p->handle);
1154 if (err < 0)
1155 alsa_sound_perror ("Can't recover from suspend, "
1156 "prepare failed",
1157 err);
1160 else
1161 alsa_sound_perror ("Error writing to sound device", err);
1164 else
1165 nwritten += err * fact;
1169 static void
1170 snd_error_quiet (const char *file, int line, const char *function, int err,
1171 const char *fmt)
1175 /* Initialize device SD. Set up the interface functions in the device
1176 structure. */
1178 static bool
1179 alsa_init (struct sound_device *sd)
1181 /* Open the sound device. Default is "default". */
1182 char const *file = string_default (sd->file, DEFAULT_ALSA_SOUND_DEVICE);
1183 snd_pcm_t *handle;
1184 int err;
1186 snd_lib_error_set_handler ((snd_lib_error_handler_t) snd_error_quiet);
1187 err = snd_pcm_open (&handle, file, SND_PCM_STREAM_PLAYBACK, 0);
1188 snd_lib_error_set_handler (NULL);
1189 if (err < 0)
1190 return 0;
1191 snd_pcm_close (handle);
1193 sd->fd = -1;
1194 sd->open = alsa_open;
1195 sd->close = alsa_close;
1196 sd->configure = alsa_configure;
1197 sd->choose_format = alsa_choose_format;
1198 sd->write = alsa_write;
1199 sd->period_size = alsa_period_size;
1201 return 1;
1204 #endif /* HAVE_ALSA */
1207 /* END: Non Windows functions */
1208 #else /* WINDOWSNT */
1210 /* BEGIN: Windows specific functions */
1212 #define SOUND_WARNING(func, error, text) \
1213 do { \
1214 char buf[1024]; \
1215 char err_string[MAXERRORLENGTH]; \
1216 func (error, err_string, sizeof (err_string)); \
1217 _snprintf (buf, sizeof (buf), "%s\nMCI Error: %s", \
1218 text, err_string); \
1219 message_with_string ("%s", build_string (buf), 1); \
1220 } while (0)
1222 static int
1223 do_play_sound (const char *psz_file, unsigned long ui_volume)
1225 int i_result = 0;
1226 MCIERROR mci_error = 0;
1227 char sz_cmd_buf_a[520];
1228 char sz_ret_buf_a[520];
1229 MMRESULT mm_result = MMSYSERR_NOERROR;
1230 unsigned long ui_volume_org = 0;
1231 BOOL b_reset_volume = FALSE;
1232 char warn_text[560];
1234 /* Since UNICOWS.DLL includes only a stub for mciSendStringW, we
1235 need to encode the file in the ANSI codepage on Windows 9X even
1236 if w32_unicode_filenames is non-zero. */
1237 if (w32_major_version <= 4 || !w32_unicode_filenames)
1239 char fname_a[MAX_PATH], shortname[MAX_PATH], *fname_to_use;
1241 filename_to_ansi (psz_file, fname_a);
1242 fname_to_use = fname_a;
1243 /* If the file name is not encodable in ANSI, try its short 8+3
1244 alias. This will only work if w32_unicode_filenames is
1245 non-zero. */
1246 if (_mbspbrk ((const unsigned char *)fname_a,
1247 (const unsigned char *)"?"))
1249 if (w32_get_short_filename (psz_file, shortname, MAX_PATH))
1250 fname_to_use = shortname;
1251 else
1252 mci_error = MCIERR_FILE_NOT_FOUND;
1255 if (!mci_error)
1257 memset (sz_cmd_buf_a, 0, sizeof (sz_cmd_buf_a));
1258 memset (sz_ret_buf_a, 0, sizeof (sz_ret_buf_a));
1259 sprintf (sz_cmd_buf_a,
1260 "open \"%s\" alias GNUEmacs_PlaySound_Device wait",
1261 fname_to_use);
1262 mci_error = mciSendStringA (sz_cmd_buf_a,
1263 sz_ret_buf_a, sizeof (sz_ret_buf_a), NULL);
1266 else
1268 wchar_t sz_cmd_buf_w[520];
1269 wchar_t sz_ret_buf_w[520];
1270 wchar_t fname_w[MAX_PATH];
1272 filename_to_utf16 (psz_file, fname_w);
1273 memset (sz_cmd_buf_w, 0, sizeof (sz_cmd_buf_w));
1274 memset (sz_ret_buf_w, 0, sizeof (sz_ret_buf_w));
1275 /* _swprintf is not available on Windows 9X, so we construct the
1276 UTF-16 command string by hand. */
1277 wcscpy (sz_cmd_buf_w, L"open \"");
1278 wcscat (sz_cmd_buf_w, fname_w);
1279 wcscat (sz_cmd_buf_w, L"\" alias GNUEmacs_PlaySound_Device wait");
1280 mci_error = mciSendStringW (sz_cmd_buf_w,
1281 sz_ret_buf_w, ARRAYELTS (sz_ret_buf_w) , NULL);
1283 if (mci_error != 0)
1285 strcpy (warn_text,
1286 "mciSendString: 'open' command failed to open sound file ");
1287 strcat (warn_text, psz_file);
1288 SOUND_WARNING (mciGetErrorString, mci_error, warn_text);
1289 i_result = (int) mci_error;
1290 return i_result;
1292 if ((ui_volume > 0) && (ui_volume != UINT_MAX))
1294 mm_result = waveOutGetVolume ((HWAVEOUT) WAVE_MAPPER, &ui_volume_org);
1295 if (mm_result == MMSYSERR_NOERROR)
1297 b_reset_volume = TRUE;
1298 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume);
1299 if (mm_result != MMSYSERR_NOERROR)
1301 SOUND_WARNING (waveOutGetErrorText, mm_result,
1302 "waveOutSetVolume: failed to set the volume level"
1303 " of the WAVE_MAPPER device.\n"
1304 "As a result, the user selected volume level will"
1305 " not be used.");
1308 else
1310 SOUND_WARNING (waveOutGetErrorText, mm_result,
1311 "waveOutGetVolume: failed to obtain the original"
1312 " volume level of the WAVE_MAPPER device.\n"
1313 "As a result, the user selected volume level will"
1314 " not be used.");
1317 memset (sz_cmd_buf_a, 0, sizeof (sz_cmd_buf_a));
1318 memset (sz_ret_buf_a, 0, sizeof (sz_ret_buf_a));
1319 strcpy (sz_cmd_buf_a, "play GNUEmacs_PlaySound_Device wait");
1320 mci_error = mciSendStringA (sz_cmd_buf_a, sz_ret_buf_a, sizeof (sz_ret_buf_a),
1321 NULL);
1322 if (mci_error != 0)
1324 strcpy (warn_text,
1325 "mciSendString: 'play' command failed to play sound file ");
1326 strcat (warn_text, psz_file);
1327 SOUND_WARNING (mciGetErrorString, mci_error, warn_text);
1328 i_result = (int) mci_error;
1330 memset (sz_cmd_buf_a, 0, sizeof (sz_cmd_buf_a));
1331 memset (sz_ret_buf_a, 0, sizeof (sz_ret_buf_a));
1332 strcpy (sz_cmd_buf_a, "close GNUEmacs_PlaySound_Device wait");
1333 mci_error = mciSendStringA (sz_cmd_buf_a, sz_ret_buf_a, sizeof (sz_ret_buf_a),
1334 NULL);
1335 if (b_reset_volume == TRUE)
1337 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume_org);
1338 if (mm_result != MMSYSERR_NOERROR)
1340 SOUND_WARNING (waveOutGetErrorText, mm_result,
1341 "waveOutSetVolume: failed to reset the original"
1342 " volume level of the WAVE_MAPPER device.");
1345 return i_result;
1348 /* END: Windows specific functions */
1350 #endif /* WINDOWSNT */
1352 DEFUN ("play-sound-internal", Fplay_sound_internal, Splay_sound_internal, 1, 1, 0,
1353 doc: /* Play sound SOUND.
1355 Internal use only, use `play-sound' instead. */)
1356 (Lisp_Object sound)
1358 Lisp_Object attrs[SOUND_ATTR_SENTINEL];
1359 ptrdiff_t count = SPECPDL_INDEX ();
1360 Lisp_Object file;
1361 Lisp_Object args[2];
1362 struct gcpro gcpro1, gcpro2;
1364 #ifdef WINDOWSNT
1365 unsigned long ui_volume_tmp = UINT_MAX;
1366 unsigned long ui_volume = UINT_MAX;
1367 #endif /* WINDOWSNT */
1369 /* Parse the sound specification. Give up if it is invalid. */
1370 if (!parse_sound (sound, attrs))
1371 error ("Invalid sound specification");
1373 #ifndef WINDOWSNT
1374 file = Qnil;
1375 GCPRO2 (sound, file);
1376 current_sound_device = xzalloc (sizeof *current_sound_device);
1377 current_sound = xzalloc (sizeof *current_sound);
1378 record_unwind_protect_void (sound_cleanup);
1379 char headerbuf[MAX_SOUND_HEADER_BYTES];
1380 current_sound->header = headerbuf;
1382 if (STRINGP (attrs[SOUND_FILE]))
1384 /* Open the sound file. */
1385 current_sound->fd = openp (list1 (Vdata_directory),
1386 attrs[SOUND_FILE], Qnil, &file, Qnil, false);
1387 if (current_sound->fd < 0)
1388 sound_perror ("Could not open sound file");
1390 /* Read the first bytes from the file. */
1391 current_sound->header_size
1392 = emacs_read (current_sound->fd, current_sound->header,
1393 MAX_SOUND_HEADER_BYTES);
1394 if (current_sound->header_size < 0)
1395 sound_perror ("Invalid sound file header");
1397 else
1399 current_sound->data = attrs[SOUND_DATA];
1400 current_sound->header_size = min (MAX_SOUND_HEADER_BYTES, SBYTES (current_sound->data));
1401 memcpy (current_sound->header, SDATA (current_sound->data),
1402 current_sound->header_size);
1405 /* Find out the type of sound. Give up if we can't tell. */
1406 find_sound_type (current_sound);
1408 /* Set up a device. */
1409 current_sound_device->file = attrs[SOUND_DEVICE];
1411 if (INTEGERP (attrs[SOUND_VOLUME]))
1412 current_sound_device->volume = XFASTINT (attrs[SOUND_VOLUME]);
1413 else if (FLOATP (attrs[SOUND_VOLUME]))
1414 current_sound_device->volume = XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1416 args[0] = Qplay_sound_functions;
1417 args[1] = sound;
1418 Frun_hook_with_args (2, args);
1420 #ifdef HAVE_ALSA
1421 if (!alsa_init (current_sound_device))
1422 #endif
1423 if (!vox_init (current_sound_device))
1424 error ("No usable sound device driver found");
1426 /* Open the device. */
1427 current_sound_device->open (current_sound_device);
1429 /* Play the sound. */
1430 current_sound->play (current_sound, current_sound_device);
1432 /* Clean up. */
1433 UNGCPRO;
1435 #else /* WINDOWSNT */
1437 file = Fexpand_file_name (attrs[SOUND_FILE], Vdata_directory);
1438 file = ENCODE_FILE (file);
1439 if (INTEGERP (attrs[SOUND_VOLUME]))
1441 ui_volume_tmp = XFASTINT (attrs[SOUND_VOLUME]);
1443 else if (FLOATP (attrs[SOUND_VOLUME]))
1445 ui_volume_tmp = XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1448 GCPRO2 (sound, file);
1450 args[0] = Qplay_sound_functions;
1451 args[1] = sound;
1452 Frun_hook_with_args (2, args);
1455 Based on some experiments I have conducted, a value of 100 or less
1456 for the sound volume is much too low. You cannot even hear it.
1457 A value of UINT_MAX indicates that you wish for the sound to played
1458 at the maximum possible volume. A value of UINT_MAX/2 plays the
1459 sound at 50% maximum volume. Therefore the value passed to do_play_sound
1460 (and thus to waveOutSetVolume) must be some fraction of UINT_MAX.
1461 The following code adjusts the user specified volume level appropriately.
1463 if ((ui_volume_tmp > 0) && (ui_volume_tmp <= 100))
1465 ui_volume = ui_volume_tmp * (UINT_MAX / 100);
1467 (void)do_play_sound (SSDATA (file), ui_volume);
1469 UNGCPRO;
1471 #endif /* WINDOWSNT */
1473 unbind_to (count, Qnil);
1474 return Qnil;
1477 /***********************************************************************
1478 Initialization
1479 ***********************************************************************/
1481 void
1482 syms_of_sound (void)
1484 DEFSYM (QCdevice, ":device");
1485 DEFSYM (QCvolume, ":volume");
1486 DEFSYM (Qsound, "sound");
1487 DEFSYM (Qplay_sound_functions, "play-sound-functions");
1489 defsubr (&Splay_sound_internal);
1492 #endif /* HAVE_SOUND */