Merge from emacs-24; up to r117499
[emacs/old-mirror.git] / src / sound.c
blob7ba14b36f3353b2af1674d0722d44a4cd57d9442
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 ptrdiff_t nbytes = 0;
571 ptrdiff_t blksize = sd->period_size ? sd->period_size (sd) : 2048;
572 ptrdiff_t data_left = header->data_length;
573 USE_SAFE_ALLOCA;
574 char *buffer = SAFE_ALLOCA (blksize);
575 lseek (s->fd, sizeof *header, SEEK_SET);
576 while (data_left > 0
577 && (nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
579 /* Don't play possible garbage at the end of file */
580 if (data_left < nbytes) nbytes = data_left;
581 data_left -= nbytes;
582 sd->write (sd, buffer, nbytes);
585 if (nbytes < 0)
586 sound_perror ("Error reading sound file");
587 SAFE_FREE ();
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 ptrdiff_t nbytes;
664 /* Seek */
665 lseek (s->fd, header->data_offset, SEEK_SET);
667 /* Copy sound data to the device. */
668 USE_SAFE_ALLOCA;
669 char *buffer = SAFE_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");
675 SAFE_FREE ();
680 /***********************************************************************
681 Voxware Driver Interface
682 ***********************************************************************/
684 /* This driver is available on GNU/Linux, and the free BSDs. FreeBSD
685 has a compatible own driver aka Luigi's driver. */
688 /* Open device SD. If SD->file is a string, open that device,
689 otherwise use a default device name. */
691 static void
692 vox_open (struct sound_device *sd)
694 /* Open the sound device (eg /dev/dsp). */
695 char const *file = string_default (sd->file, DEFAULT_SOUND_DEVICE);
696 sd->fd = emacs_open (file, O_WRONLY, 0);
697 if (sd->fd < 0)
698 sound_perror (file);
702 /* Configure device SD from parameters in it. */
704 static void
705 vox_configure (struct sound_device *sd)
707 int val;
708 #ifdef USABLE_SIGIO
709 sigset_t oldset, blocked;
710 #endif
712 eassert (sd->fd >= 0);
714 /* On GNU/Linux, it seems that the device driver doesn't like to be
715 interrupted by a signal. Block the ones we know to cause
716 troubles. */
717 turn_on_atimers (0);
718 #ifdef USABLE_SIGIO
719 sigemptyset (&blocked);
720 sigaddset (&blocked, SIGIO);
721 pthread_sigmask (SIG_BLOCK, &blocked, &oldset);
722 #endif
724 val = sd->format;
725 if (ioctl (sd->fd, SNDCTL_DSP_SETFMT, &sd->format) < 0
726 || val != sd->format)
727 sound_perror ("Could not set sound format");
729 val = sd->channels != 1;
730 if (ioctl (sd->fd, SNDCTL_DSP_STEREO, &val) < 0
731 || val != (sd->channels != 1))
732 sound_perror ("Could not set stereo/mono");
734 /* I think bps and sampling_rate are the same, but who knows.
735 Check this. and use SND_DSP_SPEED for both. */
736 if (sd->sample_rate > 0)
738 val = sd->sample_rate;
739 if (ioctl (sd->fd, SNDCTL_DSP_SPEED, &sd->sample_rate) < 0)
740 sound_perror ("Could not set sound speed");
741 else if (val != sd->sample_rate)
742 sound_warning ("Could not set sample rate");
745 if (sd->volume > 0)
747 int volume = sd->volume & 0xff;
748 volume |= volume << 8;
749 /* This may fail if there is no mixer. Ignore the failure. */
750 ioctl (sd->fd, SOUND_MIXER_WRITE_PCM, &volume);
753 turn_on_atimers (1);
754 #ifdef USABLE_SIGIO
755 pthread_sigmask (SIG_SETMASK, &oldset, 0);
756 #endif
760 /* Close device SD if it is open. */
762 static void
763 vox_close (struct sound_device *sd)
765 if (sd->fd >= 0)
767 /* On GNU/Linux, it seems that the device driver doesn't like to
768 be interrupted by a signal. Block the ones we know to cause
769 troubles. */
770 #ifdef USABLE_SIGIO
771 sigset_t blocked, oldset;
772 sigemptyset (&blocked);
773 sigaddset (&blocked, SIGIO);
774 pthread_sigmask (SIG_BLOCK, &blocked, &oldset);
775 #endif
776 turn_on_atimers (0);
778 /* Flush sound data, and reset the device. */
779 ioctl (sd->fd, SNDCTL_DSP_SYNC, NULL);
781 turn_on_atimers (1);
782 #ifdef USABLE_SIGIO
783 pthread_sigmask (SIG_SETMASK, &oldset, 0);
784 #endif
786 /* Close the device. */
787 emacs_close (sd->fd);
788 sd->fd = -1;
793 /* Choose device-dependent format for device SD from sound file S. */
795 static void
796 vox_choose_format (struct sound_device *sd, struct sound *s)
798 if (s->type == RIFF)
800 struct wav_header *h = (struct wav_header *) s->header;
801 if (h->precision == 8)
802 sd->format = AFMT_U8;
803 else if (h->precision == 16)
804 sd->format = AFMT_S16_LE;
805 else
806 error ("Unsupported WAV file format");
808 else if (s->type == SUN_AUDIO)
810 struct au_header *header = (struct au_header *) s->header;
811 switch (header->encoding)
813 case AU_ENCODING_ULAW_8:
814 case AU_ENCODING_IEEE32:
815 case AU_ENCODING_IEEE64:
816 sd->format = AFMT_MU_LAW;
817 break;
819 case AU_ENCODING_8:
820 case AU_ENCODING_16:
821 case AU_ENCODING_24:
822 case AU_ENCODING_32:
823 sd->format = AFMT_S16_LE;
824 break;
826 default:
827 error ("Unsupported AU file format");
830 else
831 emacs_abort ();
835 /* Initialize device SD. Set up the interface functions in the device
836 structure. */
838 static bool
839 vox_init (struct sound_device *sd)
841 /* Open the sound device (eg /dev/dsp). */
842 char const *file = string_default (sd->file, DEFAULT_SOUND_DEVICE);
843 int fd = emacs_open (file, O_WRONLY, 0);
844 if (fd >= 0)
845 emacs_close (fd);
846 else
847 return 0;
849 sd->fd = -1;
850 sd->open = vox_open;
851 sd->close = vox_close;
852 sd->configure = vox_configure;
853 sd->choose_format = vox_choose_format;
854 sd->write = vox_write;
855 sd->period_size = NULL;
857 return 1;
860 /* Write NBYTES bytes from BUFFER to device SD. */
862 static void
863 vox_write (struct sound_device *sd, const char *buffer, ptrdiff_t nbytes)
865 if (emacs_write_sig (sd->fd, buffer, nbytes) != nbytes)
866 sound_perror ("Error writing to sound device");
869 #ifdef HAVE_ALSA
870 /***********************************************************************
871 ALSA Driver Interface
872 ***********************************************************************/
874 /* This driver is available on GNU/Linux. */
876 #ifndef DEFAULT_ALSA_SOUND_DEVICE
877 #define DEFAULT_ALSA_SOUND_DEVICE "default"
878 #endif
880 static _Noreturn void
881 alsa_sound_perror (const char *msg, int err)
883 error ("%s: %s", msg, snd_strerror (err));
886 struct alsa_params
888 snd_pcm_t *handle;
889 snd_pcm_hw_params_t *hwparams;
890 snd_pcm_sw_params_t *swparams;
891 snd_pcm_uframes_t period_size;
894 /* Open device SD. If SD->file is a string, open that device,
895 otherwise use a default device name. */
897 static void
898 alsa_open (struct sound_device *sd)
900 /* Open the sound device. Default is "default". */
901 struct alsa_params *p = xmalloc (sizeof *p);
902 char const *file = string_default (sd->file, DEFAULT_ALSA_SOUND_DEVICE);
903 int err;
905 p->handle = NULL;
906 p->hwparams = NULL;
907 p->swparams = NULL;
909 sd->fd = -1;
910 sd->data = p;
913 err = snd_pcm_open (&p->handle, file, SND_PCM_STREAM_PLAYBACK, 0);
914 if (err < 0)
915 alsa_sound_perror (file, err);
918 static ptrdiff_t
919 alsa_period_size (struct sound_device *sd)
921 struct alsa_params *p = (struct alsa_params *) sd->data;
922 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
923 return p->period_size * (fact > 0 ? fact : 1);
926 static void
927 alsa_configure (struct sound_device *sd)
929 int val, err, dir;
930 unsigned uval;
931 struct alsa_params *p = (struct alsa_params *) sd->data;
932 snd_pcm_uframes_t buffer_size;
934 eassert (p->handle != 0);
936 err = snd_pcm_hw_params_malloc (&p->hwparams);
937 if (err < 0)
938 alsa_sound_perror ("Could not allocate hardware parameter structure", err);
940 err = snd_pcm_sw_params_malloc (&p->swparams);
941 if (err < 0)
942 alsa_sound_perror ("Could not allocate software parameter structure", err);
944 err = snd_pcm_hw_params_any (p->handle, p->hwparams);
945 if (err < 0)
946 alsa_sound_perror ("Could not initialize hardware parameter structure", err);
948 err = snd_pcm_hw_params_set_access (p->handle, p->hwparams,
949 SND_PCM_ACCESS_RW_INTERLEAVED);
950 if (err < 0)
951 alsa_sound_perror ("Could not set access type", err);
953 val = sd->format;
954 err = snd_pcm_hw_params_set_format (p->handle, p->hwparams, val);
955 if (err < 0)
956 alsa_sound_perror ("Could not set sound format", err);
958 uval = sd->sample_rate;
959 err = snd_pcm_hw_params_set_rate_near (p->handle, p->hwparams, &uval, 0);
960 if (err < 0)
961 alsa_sound_perror ("Could not set sample rate", err);
963 val = sd->channels;
964 err = snd_pcm_hw_params_set_channels (p->handle, p->hwparams, val);
965 if (err < 0)
966 alsa_sound_perror ("Could not set channel count", err);
968 err = snd_pcm_hw_params (p->handle, p->hwparams);
969 if (err < 0)
970 alsa_sound_perror ("Could not set parameters", err);
973 err = snd_pcm_hw_params_get_period_size (p->hwparams, &p->period_size, &dir);
974 if (err < 0)
975 alsa_sound_perror ("Unable to get period size for playback", err);
977 err = snd_pcm_hw_params_get_buffer_size (p->hwparams, &buffer_size);
978 if (err < 0)
979 alsa_sound_perror ("Unable to get buffer size for playback", err);
981 err = snd_pcm_sw_params_current (p->handle, p->swparams);
982 if (err < 0)
983 alsa_sound_perror ("Unable to determine current swparams for playback",
984 err);
986 /* Start the transfer when the buffer is almost full */
987 err = snd_pcm_sw_params_set_start_threshold (p->handle, p->swparams,
988 (buffer_size / p->period_size)
989 * p->period_size);
990 if (err < 0)
991 alsa_sound_perror ("Unable to set start threshold mode for playback", err);
993 /* Allow the transfer when at least period_size samples can be processed */
994 err = snd_pcm_sw_params_set_avail_min (p->handle, p->swparams, p->period_size);
995 if (err < 0)
996 alsa_sound_perror ("Unable to set avail min for playback", err);
998 err = snd_pcm_sw_params (p->handle, p->swparams);
999 if (err < 0)
1000 alsa_sound_perror ("Unable to set sw params for playback\n", err);
1002 snd_pcm_hw_params_free (p->hwparams);
1003 p->hwparams = NULL;
1004 snd_pcm_sw_params_free (p->swparams);
1005 p->swparams = NULL;
1007 err = snd_pcm_prepare (p->handle);
1008 if (err < 0)
1009 alsa_sound_perror ("Could not prepare audio interface for use", err);
1011 if (sd->volume > 0)
1013 int chn;
1014 snd_mixer_t *handle;
1015 snd_mixer_elem_t *e;
1016 if (snd_mixer_open (&handle, 0) >= 0)
1018 char const *file = string_default (sd->file,
1019 DEFAULT_ALSA_SOUND_DEVICE);
1020 if (snd_mixer_attach (handle, file) >= 0
1021 && snd_mixer_load (handle) >= 0
1022 && snd_mixer_selem_register (handle, NULL, NULL) >= 0)
1023 for (e = snd_mixer_first_elem (handle);
1025 e = snd_mixer_elem_next (e))
1027 if (snd_mixer_selem_has_playback_volume (e))
1029 long pmin, pmax, vol;
1030 snd_mixer_selem_get_playback_volume_range (e, &pmin, &pmax);
1031 vol = pmin + (sd->volume * (pmax - pmin)) / 100;
1033 for (chn = 0; chn <= SND_MIXER_SCHN_LAST; chn++)
1034 snd_mixer_selem_set_playback_volume (e, chn, vol);
1037 snd_mixer_close (handle);
1043 /* Close device SD if it is open. */
1045 static void
1046 alsa_close (struct sound_device *sd)
1048 struct alsa_params *p = (struct alsa_params *) sd->data;
1049 if (p)
1051 if (p->hwparams)
1052 snd_pcm_hw_params_free (p->hwparams);
1053 if (p->swparams)
1054 snd_pcm_sw_params_free (p->swparams);
1055 if (p->handle)
1057 snd_pcm_drain (p->handle);
1058 snd_pcm_close (p->handle);
1060 xfree (p);
1064 /* Choose device-dependent format for device SD from sound file S. */
1066 static void
1067 alsa_choose_format (struct sound_device *sd, struct sound *s)
1069 if (s->type == RIFF)
1071 struct wav_header *h = (struct wav_header *) s->header;
1072 if (h->precision == 8)
1073 sd->format = SND_PCM_FORMAT_U8;
1074 else if (h->precision == 16)
1075 sd->format = SND_PCM_FORMAT_S16_LE;
1076 else
1077 error ("Unsupported WAV file format");
1079 else if (s->type == SUN_AUDIO)
1081 struct au_header *header = (struct au_header *) s->header;
1082 switch (header->encoding)
1084 case AU_ENCODING_ULAW_8:
1085 sd->format = SND_PCM_FORMAT_MU_LAW;
1086 break;
1087 case AU_ENCODING_ALAW_8:
1088 sd->format = SND_PCM_FORMAT_A_LAW;
1089 break;
1090 case AU_ENCODING_IEEE32:
1091 sd->format = SND_PCM_FORMAT_FLOAT_BE;
1092 break;
1093 case AU_ENCODING_IEEE64:
1094 sd->format = SND_PCM_FORMAT_FLOAT64_BE;
1095 break;
1096 case AU_ENCODING_8:
1097 sd->format = SND_PCM_FORMAT_S8;
1098 break;
1099 case AU_ENCODING_16:
1100 sd->format = SND_PCM_FORMAT_S16_BE;
1101 break;
1102 case AU_ENCODING_24:
1103 sd->format = SND_PCM_FORMAT_S24_BE;
1104 break;
1105 case AU_ENCODING_32:
1106 sd->format = SND_PCM_FORMAT_S32_BE;
1107 break;
1109 default:
1110 error ("Unsupported AU file format");
1113 else
1114 emacs_abort ();
1118 /* Write NBYTES bytes from BUFFER to device SD. */
1120 static void
1121 alsa_write (struct sound_device *sd, const char *buffer, ptrdiff_t nbytes)
1123 struct alsa_params *p = (struct alsa_params *) sd->data;
1125 /* The the third parameter to snd_pcm_writei is frames, not bytes. */
1126 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
1127 ptrdiff_t nwritten = 0;
1128 int err;
1130 while (nwritten < nbytes)
1132 snd_pcm_uframes_t frames = (nbytes - nwritten)/fact;
1133 if (frames == 0) break;
1135 err = snd_pcm_writei (p->handle, buffer + nwritten, frames);
1136 if (err < 0)
1138 if (err == -EPIPE)
1139 { /* under-run */
1140 err = snd_pcm_prepare (p->handle);
1141 if (err < 0)
1142 alsa_sound_perror ("Can't recover from underrun, prepare failed",
1143 err);
1145 else if (err == -ESTRPIPE)
1147 while ((err = snd_pcm_resume (p->handle)) == -EAGAIN)
1148 sleep (1); /* wait until the suspend flag is released */
1149 if (err < 0)
1151 err = snd_pcm_prepare (p->handle);
1152 if (err < 0)
1153 alsa_sound_perror ("Can't recover from suspend, "
1154 "prepare failed",
1155 err);
1158 else
1159 alsa_sound_perror ("Error writing to sound device", err);
1162 else
1163 nwritten += err * fact;
1167 static void
1168 snd_error_quiet (const char *file, int line, const char *function, int err,
1169 const char *fmt)
1173 /* Initialize device SD. Set up the interface functions in the device
1174 structure. */
1176 static bool
1177 alsa_init (struct sound_device *sd)
1179 /* Open the sound device. Default is "default". */
1180 char const *file = string_default (sd->file, DEFAULT_ALSA_SOUND_DEVICE);
1181 snd_pcm_t *handle;
1182 int err;
1184 snd_lib_error_set_handler ((snd_lib_error_handler_t) snd_error_quiet);
1185 err = snd_pcm_open (&handle, file, SND_PCM_STREAM_PLAYBACK, 0);
1186 snd_lib_error_set_handler (NULL);
1187 if (err < 0)
1188 return 0;
1189 snd_pcm_close (handle);
1191 sd->fd = -1;
1192 sd->open = alsa_open;
1193 sd->close = alsa_close;
1194 sd->configure = alsa_configure;
1195 sd->choose_format = alsa_choose_format;
1196 sd->write = alsa_write;
1197 sd->period_size = alsa_period_size;
1199 return 1;
1202 #endif /* HAVE_ALSA */
1205 /* END: Non Windows functions */
1206 #else /* WINDOWSNT */
1208 /* BEGIN: Windows specific functions */
1210 #define SOUND_WARNING(fun, error, text) \
1212 char buf[1024]; \
1213 char err_string[MAXERRORLENGTH]; \
1214 fun (error, err_string, sizeof (err_string)); \
1215 _snprintf (buf, sizeof (buf), "%s\nError: %s", \
1216 text, err_string); \
1217 sound_warning (buf); \
1220 static int
1221 do_play_sound (const char *psz_file, unsigned long ui_volume)
1223 int i_result = 0;
1224 MCIERROR mci_error = 0;
1225 char sz_cmd_buf[520] = {0};
1226 char sz_ret_buf[520] = {0};
1227 MMRESULT mm_result = MMSYSERR_NOERROR;
1228 unsigned long ui_volume_org = 0;
1229 BOOL b_reset_volume = FALSE;
1231 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1232 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1233 sprintf (sz_cmd_buf,
1234 "open \"%s\" alias GNUEmacs_PlaySound_Device wait",
1235 psz_file);
1236 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1237 if (mci_error != 0)
1239 SOUND_WARNING (mciGetErrorString, mci_error,
1240 "The open mciSendString command failed to open "
1241 "the specified sound file.");
1242 i_result = (int) mci_error;
1243 return i_result;
1245 if ((ui_volume > 0) && (ui_volume != UINT_MAX))
1247 mm_result = waveOutGetVolume ((HWAVEOUT) WAVE_MAPPER, &ui_volume_org);
1248 if (mm_result == MMSYSERR_NOERROR)
1250 b_reset_volume = TRUE;
1251 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume);
1252 if (mm_result != MMSYSERR_NOERROR)
1254 SOUND_WARNING (waveOutGetErrorText, mm_result,
1255 "waveOutSetVolume failed to set the volume level "
1256 "of the WAVE_MAPPER device.\n"
1257 "As a result, the user selected volume level will "
1258 "not be used.");
1261 else
1263 SOUND_WARNING (waveOutGetErrorText, mm_result,
1264 "waveOutGetVolume failed to obtain the original "
1265 "volume level of the WAVE_MAPPER device.\n"
1266 "As a result, the user selected volume level will "
1267 "not be used.");
1270 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1271 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1272 strcpy (sz_cmd_buf, "play GNUEmacs_PlaySound_Device wait");
1273 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1274 if (mci_error != 0)
1276 SOUND_WARNING (mciGetErrorString, mci_error,
1277 "The play mciSendString command failed to play the "
1278 "opened sound file.");
1279 i_result = (int) mci_error;
1281 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1282 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1283 strcpy (sz_cmd_buf, "close GNUEmacs_PlaySound_Device wait");
1284 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1285 if (b_reset_volume == TRUE)
1287 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume_org);
1288 if (mm_result != MMSYSERR_NOERROR)
1290 SOUND_WARNING (waveOutGetErrorText, mm_result,
1291 "waveOutSetVolume failed to reset the original volume "
1292 "level of the WAVE_MAPPER device.");
1295 return i_result;
1298 /* END: Windows specific functions */
1300 #endif /* WINDOWSNT */
1302 DEFUN ("play-sound-internal", Fplay_sound_internal, Splay_sound_internal, 1, 1, 0,
1303 doc: /* Play sound SOUND.
1305 Internal use only, use `play-sound' instead. */)
1306 (Lisp_Object sound)
1308 Lisp_Object attrs[SOUND_ATTR_SENTINEL];
1309 ptrdiff_t count = SPECPDL_INDEX ();
1311 #ifndef WINDOWSNT
1312 Lisp_Object file;
1313 struct gcpro gcpro1, gcpro2;
1314 Lisp_Object args[2];
1315 #else /* WINDOWSNT */
1316 Lisp_Object lo_file;
1317 unsigned long ui_volume_tmp = UINT_MAX;
1318 unsigned long ui_volume = UINT_MAX;
1319 #endif /* WINDOWSNT */
1321 /* Parse the sound specification. Give up if it is invalid. */
1322 if (!parse_sound (sound, attrs))
1323 error ("Invalid sound specification");
1325 #ifndef WINDOWSNT
1326 file = Qnil;
1327 GCPRO2 (sound, file);
1328 current_sound_device = xzalloc (sizeof *current_sound_device);
1329 current_sound = xzalloc (sizeof *current_sound);
1330 record_unwind_protect_void (sound_cleanup);
1331 char headerbuf[MAX_SOUND_HEADER_BYTES];
1332 current_sound->header = headerbuf;
1334 if (STRINGP (attrs[SOUND_FILE]))
1336 /* Open the sound file. */
1337 current_sound->fd = openp (list1 (Vdata_directory),
1338 attrs[SOUND_FILE], Qnil, &file, Qnil, false);
1339 if (current_sound->fd < 0)
1340 sound_perror ("Could not open sound file");
1342 /* Read the first bytes from the file. */
1343 current_sound->header_size
1344 = emacs_read (current_sound->fd, current_sound->header,
1345 MAX_SOUND_HEADER_BYTES);
1346 if (current_sound->header_size < 0)
1347 sound_perror ("Invalid sound file header");
1349 else
1351 current_sound->data = attrs[SOUND_DATA];
1352 current_sound->header_size = min (MAX_SOUND_HEADER_BYTES, SBYTES (current_sound->data));
1353 memcpy (current_sound->header, SDATA (current_sound->data),
1354 current_sound->header_size);
1357 /* Find out the type of sound. Give up if we can't tell. */
1358 find_sound_type (current_sound);
1360 /* Set up a device. */
1361 current_sound_device->file = attrs[SOUND_DEVICE];
1363 if (INTEGERP (attrs[SOUND_VOLUME]))
1364 current_sound_device->volume = XFASTINT (attrs[SOUND_VOLUME]);
1365 else if (FLOATP (attrs[SOUND_VOLUME]))
1366 current_sound_device->volume = XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1368 args[0] = Qplay_sound_functions;
1369 args[1] = sound;
1370 Frun_hook_with_args (2, args);
1372 #ifdef HAVE_ALSA
1373 if (!alsa_init (current_sound_device))
1374 #endif
1375 if (!vox_init (current_sound_device))
1376 error ("No usable sound device driver found");
1378 /* Open the device. */
1379 current_sound_device->open (current_sound_device);
1381 /* Play the sound. */
1382 current_sound->play (current_sound, current_sound_device);
1384 /* Clean up. */
1385 UNGCPRO;
1387 #else /* WINDOWSNT */
1389 lo_file = Fexpand_file_name (attrs[SOUND_FILE], Vdata_directory);
1390 lo_file = ENCODE_FILE (lo_file);
1391 /* Since UNICOWS.DLL includes only a stub for mciSendStringW, we
1392 need to encode the file in the ANSI codepage. */
1393 lo_file = ansi_encode_filename (lo_file);
1394 if (INTEGERP (attrs[SOUND_VOLUME]))
1396 ui_volume_tmp = XFASTINT (attrs[SOUND_VOLUME]);
1398 else if (FLOATP (attrs[SOUND_VOLUME]))
1400 ui_volume_tmp = XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1403 Based on some experiments I have conducted, a value of 100 or less
1404 for the sound volume is much too low. You cannot even hear it.
1405 A value of UINT_MAX indicates that you wish for the sound to played
1406 at the maximum possible volume. A value of UINT_MAX/2 plays the
1407 sound at 50% maximum volume. Therefore the value passed to do_play_sound
1408 (and thus to waveOutSetVolume) must be some fraction of UINT_MAX.
1409 The following code adjusts the user specified volume level appropriately.
1411 if ((ui_volume_tmp > 0) && (ui_volume_tmp <= 100))
1413 ui_volume = ui_volume_tmp * (UINT_MAX / 100);
1415 do_play_sound (SDATA (lo_file), ui_volume);
1417 #endif /* WINDOWSNT */
1419 unbind_to (count, Qnil);
1420 return Qnil;
1423 /***********************************************************************
1424 Initialization
1425 ***********************************************************************/
1427 void
1428 syms_of_sound (void)
1430 DEFSYM (QCdevice, ":device");
1431 DEFSYM (QCvolume, ":volume");
1432 DEFSYM (Qsound, "sound");
1433 DEFSYM (Qplay_sound_functions, "play-sound-functions");
1435 defsubr (&Splay_sound_internal);
1438 #endif /* HAVE_SOUND */