* net/soap-client.el: Add "comm" and "hypermedia" to the
[emacs.git] / src / sound.c
blob3a1668e4903cf95a39cc709f985c6d0397effa07
1 /* sound.c -- sound support.
2 Copyright (C) 1998-1999, 2001-2011 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
19 /* Written by Gerd Moellmann <gerd@gnu.org>. Tested with Luigi's
20 driver on FreeBSD 2.2.7 with a SoundBlaster 16. */
23 Modified by Ben Key <Bkey1@tampabay.rr.com> to add a partial
24 implementation of the play-sound specification for Windows.
26 Notes:
27 In the Windows implementation of play-sound-internal only the
28 :file and :volume keywords are supported. The :device keyword,
29 if present, is ignored. The :data keyword, if present, will
30 cause an error to be generated.
32 The Windows implementation of play-sound is implemented via the
33 Win32 API functions mciSendString, waveOutGetVolume, and
34 waveOutSetVolume which are exported by Winmm.dll.
37 #include <config.h>
39 #if defined HAVE_SOUND
41 /* BEGIN: Common Includes */
42 #include <fcntl.h>
43 #include <unistd.h>
44 #include <sys/types.h>
45 #include <errno.h>
46 #include <setjmp.h>
47 #include "lisp.h"
48 #include "dispextern.h"
49 #include "atimer.h"
50 #include <signal.h>
51 #include "syssignal.h"
52 /* END: Common Includes */
55 /* BEGIN: Non Windows Includes */
56 #ifndef WINDOWSNT
58 #include <sys/ioctl.h>
60 /* FreeBSD has machine/soundcard.h. Voxware sound driver docs mention
61 sys/soundcard.h. So, let's try whatever's there. */
63 #ifdef HAVE_MACHINE_SOUNDCARD_H
64 #include <machine/soundcard.h>
65 #endif
66 #ifdef HAVE_SYS_SOUNDCARD_H
67 #include <sys/soundcard.h>
68 #endif
69 #ifdef HAVE_SOUNDCARD_H
70 #include <soundcard.h>
71 #endif
72 #ifdef HAVE_ALSA
73 #ifdef ALSA_SUBDIR_INCLUDE
74 #include <alsa/asoundlib.h>
75 #else
76 #include <asoundlib.h>
77 #endif /* ALSA_SUBDIR_INCLUDE */
78 #endif /* HAVE_ALSA */
80 /* END: Non Windows Includes */
82 #else /* WINDOWSNT */
84 /* BEGIN: Windows Specific Includes */
85 #include <stdio.h>
86 #include <limits.h>
87 #include <windows.h>
88 #include <mmsystem.h>
89 /* END: Windows Specific Includes */
91 #endif /* WINDOWSNT */
93 /* BEGIN: Common Definitions */
95 /* Symbols. */
97 Lisp_Object QCvolume, QCdevice;
98 Lisp_Object Qsound;
99 Lisp_Object Qplay_sound_functions;
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 #ifdef HAVE_ALSA
113 static void alsa_sound_perror (const char *, int) NO_RETURN;
114 #endif
115 static void sound_perror (const char *) NO_RETURN;
116 static void sound_warning (const char *);
117 static int parse_sound (Lisp_Object, Lisp_Object *);
119 /* END: Common Definitions */
121 /* BEGIN: Non Windows Definitions */
122 #ifndef WINDOWSNT
124 #ifndef DEFAULT_SOUND_DEVICE
125 #define DEFAULT_SOUND_DEVICE "/dev/dsp"
126 #endif
127 #ifndef DEFAULT_ALSA_SOUND_DEVICE
128 #define DEFAULT_ALSA_SOUND_DEVICE "default"
129 #endif
132 /* Structure forward declarations. */
134 struct sound;
135 struct sound_device;
137 /* The file header of RIFF-WAVE files (*.wav). Files are always in
138 little-endian byte-order. */
140 struct wav_header
142 u_int32_t magic;
143 u_int32_t length;
144 u_int32_t chunk_type;
145 u_int32_t chunk_format;
146 u_int32_t chunk_length;
147 u_int16_t format;
148 u_int16_t channels;
149 u_int32_t sample_rate;
150 u_int32_t bytes_per_second;
151 u_int16_t sample_size;
152 u_int16_t precision;
153 u_int32_t chunk_data;
154 u_int32_t data_length;
157 /* The file header of Sun adio files (*.au). Files are always in
158 big-endian byte-order. */
160 struct au_header
162 /* ASCII ".snd" */
163 u_int32_t magic_number;
165 /* Offset of data part from start of file. Minimum value is 24. */
166 u_int32_t data_offset;
168 /* Size of data part, 0xffffffff if unknown. */
169 u_int32_t data_size;
171 /* Data encoding format.
172 1 8-bit ISDN u-law
173 2 8-bit linear PCM (REF-PCM)
174 3 16-bit linear PCM
175 4 24-bit linear PCM
176 5 32-bit linear PCM
177 6 32-bit IEEE floating-point
178 7 64-bit IEEE floating-point
179 23 8-bit u-law compressed using CCITT 0.721 ADPCM voice data
180 encoding scheme. */
181 u_int32_t encoding;
183 /* Number of samples per second. */
184 u_int32_t sample_rate;
186 /* Number of interleaved channels. */
187 u_int32_t channels;
190 /* Maximum of all sound file headers sizes. */
192 #define MAX_SOUND_HEADER_BYTES \
193 max (sizeof (struct wav_header), sizeof (struct au_header))
195 /* Interface structure for sound devices. */
197 struct sound_device
199 /* The name of the device or null meaning use a default device name. */
200 char *file;
202 /* File descriptor of the device. */
203 int fd;
205 /* Device-dependent format. */
206 int format;
208 /* Volume (0..100). Zero means unspecified. */
209 int volume;
211 /* Sample size. */
212 int sample_size;
214 /* Sample rate. */
215 int sample_rate;
217 /* Bytes per second. */
218 int bps;
220 /* 1 = mono, 2 = stereo, 0 = don't set. */
221 int channels;
223 /* Open device SD. */
224 void (* open) (struct sound_device *sd);
226 /* Close device SD. */
227 void (* close) (struct sound_device *sd);
229 /* Configure SD accoring to device-dependent parameters. */
230 void (* configure) (struct sound_device *device);
232 /* Choose a device-dependent format for outputting sound S. */
233 void (* choose_format) (struct sound_device *sd,
234 struct sound *s);
236 /* Return a preferred data size in bytes to be sent to write (below)
237 each time. 2048 is used if this is NULL. */
238 int (* period_size) (struct sound_device *sd);
240 /* Write NYBTES bytes from BUFFER to device SD. */
241 void (* write) (struct sound_device *sd, const char *buffer,
242 int nbytes);
244 /* A place for devices to store additional data. */
245 void *data;
248 /* An enumerator for each supported sound file type. */
250 enum sound_type
252 RIFF,
253 SUN_AUDIO
256 /* Interface structure for sound files. */
258 struct sound
260 /* The type of the file. */
261 enum sound_type type;
263 /* File descriptor of a sound file. */
264 int fd;
266 /* Pointer to sound file header. This contains header_size bytes
267 read from the start of a sound file. */
268 char *header;
270 /* Number of bytes raed from sound file. This is always <=
271 MAX_SOUND_HEADER_BYTES. */
272 int header_size;
274 /* Sound data, if a string. */
275 Lisp_Object data;
277 /* Play sound file S on device SD. */
278 void (* play) (struct sound *s, struct sound_device *sd);
281 /* These are set during `play-sound-internal' so that sound_cleanup has
282 access to them. */
284 struct sound_device *current_sound_device;
285 struct sound *current_sound;
287 /* Function prototypes. */
289 static void vox_open (struct sound_device *);
290 static void vox_configure (struct sound_device *);
291 static void vox_close (struct sound_device *sd);
292 static void vox_choose_format (struct sound_device *, struct sound *);
293 static int vox_init (struct sound_device *);
294 static void vox_write (struct sound_device *, const char *, int);
295 static void find_sound_type (struct sound *);
296 static u_int32_t le2hl (u_int32_t);
297 static u_int16_t le2hs (u_int16_t);
298 static u_int32_t be2hl (u_int32_t);
299 static int wav_init (struct sound *);
300 static void wav_play (struct sound *, struct sound_device *);
301 static int au_init (struct sound *);
302 static void au_play (struct sound *, struct sound_device *);
304 #if 0 /* Currently not used. */
305 static u_int16_t be2hs (u_int16_t);
306 #endif
308 /* END: Non Windows Definitions */
309 #else /* WINDOWSNT */
311 /* BEGIN: Windows Specific Definitions */
312 static int do_play_sound (const char *, unsigned long);
314 END: Windows Specific Definitions */
315 #endif /* WINDOWSNT */
318 /***********************************************************************
319 General
320 ***********************************************************************/
322 /* BEGIN: Common functions */
324 /* Like perror, but signals an error. */
326 static void
327 sound_perror (const char *msg)
329 int saved_errno = errno;
331 turn_on_atimers (1);
332 #ifdef SIGIO
333 sigunblock (sigmask (SIGIO));
334 #endif
335 if (saved_errno != 0)
336 error ("%s: %s", msg, strerror (saved_errno));
337 else
338 error ("%s", msg);
342 /* Display a warning message. */
344 static void
345 sound_warning (const char *msg)
347 message (msg);
351 /* Parse sound specification SOUND, and fill ATTRS with what is
352 found. Value is non-zero if SOUND Is a valid sound specification.
353 A valid sound specification is a list starting with the symbol
354 `sound'. The rest of the list is a property list which may
355 contain the following key/value pairs:
357 - `:file FILE'
359 FILE is the sound file to play. If it isn't an absolute name,
360 it's searched under `data-directory'.
362 - `:data DATA'
364 DATA is a string containing sound data. Either :file or :data
365 may be present, but not both.
367 - `:device DEVICE'
369 DEVICE is the name of the device to play on, e.g. "/dev/dsp2".
370 If not specified, a default device is used.
372 - `:volume VOL'
374 VOL must be an integer in the range [0, 100], or a float in the
375 range [0, 1]. */
377 static int
378 parse_sound (Lisp_Object sound, Lisp_Object *attrs)
380 /* SOUND must be a list starting with the symbol `sound'. */
381 if (!CONSP (sound) || !EQ (XCAR (sound), Qsound))
382 return 0;
384 sound = XCDR (sound);
385 attrs[SOUND_FILE] = Fplist_get (sound, QCfile);
386 attrs[SOUND_DATA] = Fplist_get (sound, QCdata);
387 attrs[SOUND_DEVICE] = Fplist_get (sound, QCdevice);
388 attrs[SOUND_VOLUME] = Fplist_get (sound, QCvolume);
390 #ifndef WINDOWSNT
391 /* File name or data must be specified. */
392 if (!STRINGP (attrs[SOUND_FILE])
393 && !STRINGP (attrs[SOUND_DATA]))
394 return 0;
395 #else /* WINDOWSNT */
397 Data is not supported in Windows. Therefore a
398 File name MUST be supplied.
400 if (!STRINGP (attrs[SOUND_FILE]))
402 return 0;
404 #endif /* WINDOWSNT */
406 /* Volume must be in the range 0..100 or unspecified. */
407 if (!NILP (attrs[SOUND_VOLUME]))
409 if (INTEGERP (attrs[SOUND_VOLUME]))
411 if (XINT (attrs[SOUND_VOLUME]) < 0
412 || XINT (attrs[SOUND_VOLUME]) > 100)
413 return 0;
415 else if (FLOATP (attrs[SOUND_VOLUME]))
417 if (XFLOAT_DATA (attrs[SOUND_VOLUME]) < 0
418 || XFLOAT_DATA (attrs[SOUND_VOLUME]) > 1)
419 return 0;
421 else
422 return 0;
425 #ifndef WINDOWSNT
426 /* Device must be a string or unspecified. */
427 if (!NILP (attrs[SOUND_DEVICE])
428 && !STRINGP (attrs[SOUND_DEVICE]))
429 return 0;
430 #endif /* WINDOWSNT */
432 Since device is ignored in Windows, it does not matter
433 what it is.
435 return 1;
438 /* END: Common functions */
440 /* BEGIN: Non Windows functions */
441 #ifndef WINDOWSNT
443 /* Find out the type of the sound file whose file descriptor is FD.
444 S is the sound file structure to fill in. */
446 static void
447 find_sound_type (struct sound *s)
449 if (!wav_init (s) && !au_init (s))
450 error ("Unknown sound format");
454 /* Function installed by play-sound-internal with record_unwind_protect. */
456 static Lisp_Object
457 sound_cleanup (Lisp_Object arg)
459 if (current_sound_device->close)
460 current_sound_device->close (current_sound_device);
461 if (current_sound->fd > 0)
462 emacs_close (current_sound->fd);
463 free (current_sound_device);
464 free (current_sound);
466 return Qnil;
469 /***********************************************************************
470 Byte-order Conversion
471 ***********************************************************************/
473 /* Convert 32-bit value VALUE which is in little-endian byte-order
474 to host byte-order. */
476 static u_int32_t
477 le2hl (u_int32_t value)
479 #ifdef WORDS_BIGENDIAN
480 unsigned char *p = (unsigned char *) &value;
481 value = p[0] + (p[1] << 8) + (p[2] << 16) + (p[3] << 24);
482 #endif
483 return value;
487 /* Convert 16-bit value VALUE which is in little-endian byte-order
488 to host byte-order. */
490 static u_int16_t
491 le2hs (u_int16_t value)
493 #ifdef WORDS_BIGENDIAN
494 unsigned char *p = (unsigned char *) &value;
495 value = p[0] + (p[1] << 8);
496 #endif
497 return value;
501 /* Convert 32-bit value VALUE which is in big-endian byte-order
502 to host byte-order. */
504 static u_int32_t
505 be2hl (u_int32_t value)
507 #ifndef WORDS_BIGENDIAN
508 unsigned char *p = (unsigned char *) &value;
509 value = p[3] + (p[2] << 8) + (p[1] << 16) + (p[0] << 24);
510 #endif
511 return value;
515 #if 0 /* Currently not used. */
517 /* Convert 16-bit value VALUE which is in big-endian byte-order
518 to host byte-order. */
520 static u_int16_t
521 be2hs (u_int16_t value)
523 #ifndef WORDS_BIGENDIAN
524 unsigned char *p = (unsigned char *) &value;
525 value = p[1] + (p[0] << 8);
526 #endif
527 return value;
530 #endif /* 0 */
532 /***********************************************************************
533 RIFF-WAVE (*.wav)
534 ***********************************************************************/
536 /* Try to initialize sound file S from S->header. S->header
537 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
538 sound file. If the file is a WAV-format file, set up interface
539 functions in S and convert header fields to host byte-order.
540 Value is non-zero if the file is a WAV file. */
542 static int
543 wav_init (struct sound *s)
545 struct wav_header *header = (struct wav_header *) s->header;
547 if (s->header_size < sizeof *header
548 || memcmp (s->header, "RIFF", 4) != 0)
549 return 0;
551 /* WAV files are in little-endian order. Convert the header
552 if on a big-endian machine. */
553 header->magic = le2hl (header->magic);
554 header->length = le2hl (header->length);
555 header->chunk_type = le2hl (header->chunk_type);
556 header->chunk_format = le2hl (header->chunk_format);
557 header->chunk_length = le2hl (header->chunk_length);
558 header->format = le2hs (header->format);
559 header->channels = le2hs (header->channels);
560 header->sample_rate = le2hl (header->sample_rate);
561 header->bytes_per_second = le2hl (header->bytes_per_second);
562 header->sample_size = le2hs (header->sample_size);
563 header->precision = le2hs (header->precision);
564 header->chunk_data = le2hl (header->chunk_data);
565 header->data_length = le2hl (header->data_length);
567 /* Set up the interface functions for WAV. */
568 s->type = RIFF;
569 s->play = wav_play;
571 return 1;
575 /* Play RIFF-WAVE audio file S on sound device SD. */
577 static void
578 wav_play (struct sound *s, struct sound_device *sd)
580 struct wav_header *header = (struct wav_header *) s->header;
582 /* Let the device choose a suitable device-dependent format
583 for the file. */
584 sd->choose_format (sd, s);
586 /* Configure the device. */
587 sd->sample_size = header->sample_size;
588 sd->sample_rate = header->sample_rate;
589 sd->bps = header->bytes_per_second;
590 sd->channels = header->channels;
591 sd->configure (sd);
593 /* Copy sound data to the device. The WAV file specification is
594 actually more complex. This simple scheme worked with all WAV
595 files I found so far. If someone feels inclined to implement the
596 whole RIFF-WAVE spec, please do. */
597 if (STRINGP (s->data))
598 sd->write (sd, SDATA (s->data) + sizeof *header,
599 SBYTES (s->data) - sizeof *header);
600 else
602 char *buffer;
603 int nbytes;
604 int blksize = sd->period_size ? sd->period_size (sd) : 2048;
605 int data_left = header->data_length;
607 buffer = (char *) alloca (blksize);
608 lseek (s->fd, sizeof *header, SEEK_SET);
609 while (data_left > 0
610 && (nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
612 /* Don't play possible garbage at the end of file */
613 if (data_left < nbytes) nbytes = data_left;
614 data_left -= nbytes;
615 sd->write (sd, buffer, nbytes);
618 if (nbytes < 0)
619 sound_perror ("Error reading sound file");
624 /***********************************************************************
625 Sun Audio (*.au)
626 ***********************************************************************/
628 /* Sun audio file encodings. */
630 enum au_encoding
632 AU_ENCODING_ULAW_8 = 1,
633 AU_ENCODING_8,
634 AU_ENCODING_16,
635 AU_ENCODING_24,
636 AU_ENCODING_32,
637 AU_ENCODING_IEEE32,
638 AU_ENCODING_IEEE64,
639 AU_COMPRESSED = 23,
640 AU_ENCODING_ALAW_8 = 27
644 /* Try to initialize sound file S from S->header. S->header
645 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
646 sound file. If the file is a AU-format file, set up interface
647 functions in S and convert header fields to host byte-order.
648 Value is non-zero if the file is an AU file. */
650 static int
651 au_init (struct sound *s)
653 struct au_header *header = (struct au_header *) s->header;
655 if (s->header_size < sizeof *header
656 || memcmp (s->header, ".snd", 4) != 0)
657 return 0;
659 header->magic_number = be2hl (header->magic_number);
660 header->data_offset = be2hl (header->data_offset);
661 header->data_size = be2hl (header->data_size);
662 header->encoding = be2hl (header->encoding);
663 header->sample_rate = be2hl (header->sample_rate);
664 header->channels = be2hl (header->channels);
666 /* Set up the interface functions for AU. */
667 s->type = SUN_AUDIO;
668 s->play = au_play;
670 return 1;
674 /* Play Sun audio file S on sound device SD. */
676 static void
677 au_play (struct sound *s, struct sound_device *sd)
679 struct au_header *header = (struct au_header *) s->header;
681 sd->sample_size = 0;
682 sd->sample_rate = header->sample_rate;
683 sd->bps = 0;
684 sd->channels = header->channels;
685 sd->choose_format (sd, s);
686 sd->configure (sd);
688 if (STRINGP (s->data))
689 sd->write (sd, SDATA (s->data) + header->data_offset,
690 SBYTES (s->data) - header->data_offset);
691 else
693 int blksize = sd->period_size ? sd->period_size (sd) : 2048;
694 char *buffer;
695 int nbytes;
697 /* Seek */
698 lseek (s->fd, header->data_offset, SEEK_SET);
700 /* Copy sound data to the device. */
701 buffer = (char *) alloca (blksize);
702 while ((nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
703 sd->write (sd, buffer, nbytes);
705 if (nbytes < 0)
706 sound_perror ("Error reading sound file");
711 /***********************************************************************
712 Voxware Driver Interface
713 ***********************************************************************/
715 /* This driver is available on GNU/Linux, and the free BSDs. FreeBSD
716 has a compatible own driver aka Luigi's driver. */
719 /* Open device SD. If SD->file is non-null, open that device,
720 otherwise use a default device name. */
722 static void
723 vox_open (struct sound_device *sd)
725 const char *file;
727 /* Open the sound device. Default is /dev/dsp. */
728 if (sd->file)
729 file = sd->file;
730 else
731 file = DEFAULT_SOUND_DEVICE;
733 sd->fd = emacs_open (file, O_WRONLY, 0);
734 if (sd->fd < 0)
735 sound_perror (file);
739 /* Configure device SD from parameters in it. */
741 static void
742 vox_configure (struct sound_device *sd)
744 int val;
746 xassert (sd->fd >= 0);
748 /* On GNU/Linux, it seems that the device driver doesn't like to be
749 interrupted by a signal. Block the ones we know to cause
750 troubles. */
751 turn_on_atimers (0);
752 #ifdef SIGIO
753 sigblock (sigmask (SIGIO));
754 #endif
756 val = sd->format;
757 if (ioctl (sd->fd, SNDCTL_DSP_SETFMT, &sd->format) < 0
758 || val != sd->format)
759 sound_perror ("Could not set sound format");
761 val = sd->channels != 1;
762 if (ioctl (sd->fd, SNDCTL_DSP_STEREO, &val) < 0
763 || val != (sd->channels != 1))
764 sound_perror ("Could not set stereo/mono");
766 /* I think bps and sampling_rate are the same, but who knows.
767 Check this. and use SND_DSP_SPEED for both. */
768 if (sd->sample_rate > 0)
770 val = sd->sample_rate;
771 if (ioctl (sd->fd, SNDCTL_DSP_SPEED, &sd->sample_rate) < 0)
772 sound_perror ("Could not set sound speed");
773 else if (val != sd->sample_rate)
774 sound_warning ("Could not set sample rate");
777 if (sd->volume > 0)
779 int volume = sd->volume & 0xff;
780 volume |= volume << 8;
781 /* This may fail if there is no mixer. Ignore the failure. */
782 ioctl (sd->fd, SOUND_MIXER_WRITE_PCM, &volume);
785 turn_on_atimers (1);
786 #ifdef SIGIO
787 sigunblock (sigmask (SIGIO));
788 #endif
792 /* Close device SD if it is open. */
794 static void
795 vox_close (struct sound_device *sd)
797 if (sd->fd >= 0)
799 /* On GNU/Linux, it seems that the device driver doesn't like to
800 be interrupted by a signal. Block the ones we know to cause
801 troubles. */
802 #ifdef SIGIO
803 sigblock (sigmask (SIGIO));
804 #endif
805 turn_on_atimers (0);
807 /* Flush sound data, and reset the device. */
808 ioctl (sd->fd, SNDCTL_DSP_SYNC, NULL);
810 turn_on_atimers (1);
811 #ifdef SIGIO
812 sigunblock (sigmask (SIGIO));
813 #endif
815 /* Close the device. */
816 emacs_close (sd->fd);
817 sd->fd = -1;
822 /* Choose device-dependent format for device SD from sound file S. */
824 static void
825 vox_choose_format (struct sound_device *sd, struct sound *s)
827 if (s->type == RIFF)
829 struct wav_header *h = (struct wav_header *) s->header;
830 if (h->precision == 8)
831 sd->format = AFMT_U8;
832 else if (h->precision == 16)
833 sd->format = AFMT_S16_LE;
834 else
835 error ("Unsupported WAV file format");
837 else if (s->type == SUN_AUDIO)
839 struct au_header *header = (struct au_header *) s->header;
840 switch (header->encoding)
842 case AU_ENCODING_ULAW_8:
843 case AU_ENCODING_IEEE32:
844 case AU_ENCODING_IEEE64:
845 sd->format = AFMT_MU_LAW;
846 break;
848 case AU_ENCODING_8:
849 case AU_ENCODING_16:
850 case AU_ENCODING_24:
851 case AU_ENCODING_32:
852 sd->format = AFMT_S16_LE;
853 break;
855 default:
856 error ("Unsupported AU file format");
859 else
860 abort ();
864 /* Initialize device SD. Set up the interface functions in the device
865 structure. */
867 static int
868 vox_init (struct sound_device *sd)
870 const char *file;
871 int fd;
873 /* Open the sound device. Default is /dev/dsp. */
874 if (sd->file)
875 file = sd->file;
876 else
877 file = DEFAULT_SOUND_DEVICE;
878 fd = emacs_open (file, O_WRONLY, 0);
879 if (fd >= 0)
880 emacs_close (fd);
881 else
882 return 0;
884 sd->fd = -1;
885 sd->open = vox_open;
886 sd->close = vox_close;
887 sd->configure = vox_configure;
888 sd->choose_format = vox_choose_format;
889 sd->write = vox_write;
890 sd->period_size = NULL;
892 return 1;
895 /* Write NBYTES bytes from BUFFER to device SD. */
897 static void
898 vox_write (struct sound_device *sd, const char *buffer, int nbytes)
900 int nwritten = emacs_write (sd->fd, buffer, nbytes);
901 if (nwritten < 0)
902 sound_perror ("Error writing to sound device");
905 #ifdef HAVE_ALSA
906 /***********************************************************************
907 ALSA Driver Interface
908 ***********************************************************************/
910 /* This driver is available on GNU/Linux. */
912 static void
913 alsa_sound_perror (const char *msg, int err)
915 error ("%s: %s", msg, snd_strerror (err));
918 struct alsa_params
920 snd_pcm_t *handle;
921 snd_pcm_hw_params_t *hwparams;
922 snd_pcm_sw_params_t *swparams;
923 snd_pcm_uframes_t period_size;
926 /* Open device SD. If SD->file is non-null, open that device,
927 otherwise use a default device name. */
929 static void
930 alsa_open (struct sound_device *sd)
932 const char *file;
933 struct alsa_params *p;
934 int err;
936 /* Open the sound device. Default is "default". */
937 if (sd->file)
938 file = sd->file;
939 else
940 file = DEFAULT_ALSA_SOUND_DEVICE;
942 p = xmalloc (sizeof (*p));
943 p->handle = NULL;
944 p->hwparams = NULL;
945 p->swparams = NULL;
947 sd->fd = -1;
948 sd->data = p;
951 err = snd_pcm_open (&p->handle, file, SND_PCM_STREAM_PLAYBACK, 0);
952 if (err < 0)
953 alsa_sound_perror (file, err);
956 static int
957 alsa_period_size (struct sound_device *sd)
959 struct alsa_params *p = (struct alsa_params *) sd->data;
960 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
961 return p->period_size * (fact > 0 ? fact : 1);
964 static void
965 alsa_configure (struct sound_device *sd)
967 int val, err, dir;
968 unsigned uval;
969 struct alsa_params *p = (struct alsa_params *) sd->data;
970 snd_pcm_uframes_t buffer_size;
972 xassert (p->handle != 0);
974 err = snd_pcm_hw_params_malloc (&p->hwparams);
975 if (err < 0)
976 alsa_sound_perror ("Could not allocate hardware parameter structure", err);
978 err = snd_pcm_sw_params_malloc (&p->swparams);
979 if (err < 0)
980 alsa_sound_perror ("Could not allocate software parameter structure", err);
982 err = snd_pcm_hw_params_any (p->handle, p->hwparams);
983 if (err < 0)
984 alsa_sound_perror ("Could not initialize hardware parameter structure", err);
986 err = snd_pcm_hw_params_set_access (p->handle, p->hwparams,
987 SND_PCM_ACCESS_RW_INTERLEAVED);
988 if (err < 0)
989 alsa_sound_perror ("Could not set access type", err);
991 val = sd->format;
992 err = snd_pcm_hw_params_set_format (p->handle, p->hwparams, val);
993 if (err < 0)
994 alsa_sound_perror ("Could not set sound format", err);
996 uval = sd->sample_rate;
997 err = snd_pcm_hw_params_set_rate_near (p->handle, p->hwparams, &uval, 0);
998 if (err < 0)
999 alsa_sound_perror ("Could not set sample rate", err);
1001 val = sd->channels;
1002 err = snd_pcm_hw_params_set_channels (p->handle, p->hwparams, val);
1003 if (err < 0)
1004 alsa_sound_perror ("Could not set channel count", err);
1006 err = snd_pcm_hw_params (p->handle, p->hwparams);
1007 if (err < 0)
1008 alsa_sound_perror ("Could not set parameters", err);
1011 err = snd_pcm_hw_params_get_period_size (p->hwparams, &p->period_size, &dir);
1012 if (err < 0)
1013 alsa_sound_perror ("Unable to get period size for playback", err);
1015 err = snd_pcm_hw_params_get_buffer_size (p->hwparams, &buffer_size);
1016 if (err < 0)
1017 alsa_sound_perror("Unable to get buffer size for playback", err);
1019 err = snd_pcm_sw_params_current (p->handle, p->swparams);
1020 if (err < 0)
1021 alsa_sound_perror ("Unable to determine current swparams for playback",
1022 err);
1024 /* Start the transfer when the buffer is almost full */
1025 err = snd_pcm_sw_params_set_start_threshold (p->handle, p->swparams,
1026 (buffer_size / p->period_size)
1027 * p->period_size);
1028 if (err < 0)
1029 alsa_sound_perror ("Unable to set start threshold mode for playback", err);
1031 /* Allow the transfer when at least period_size samples can be processed */
1032 err = snd_pcm_sw_params_set_avail_min (p->handle, p->swparams, p->period_size);
1033 if (err < 0)
1034 alsa_sound_perror ("Unable to set avail min for playback", err);
1036 err = snd_pcm_sw_params (p->handle, p->swparams);
1037 if (err < 0)
1038 alsa_sound_perror ("Unable to set sw params for playback\n", err);
1040 snd_pcm_hw_params_free (p->hwparams);
1041 p->hwparams = NULL;
1042 snd_pcm_sw_params_free (p->swparams);
1043 p->swparams = NULL;
1045 err = snd_pcm_prepare (p->handle);
1046 if (err < 0)
1047 alsa_sound_perror ("Could not prepare audio interface for use", err);
1049 if (sd->volume > 0)
1051 int chn;
1052 snd_mixer_t *handle;
1053 snd_mixer_elem_t *e;
1054 const char *file = sd->file ? sd->file : DEFAULT_ALSA_SOUND_DEVICE;
1056 if (snd_mixer_open (&handle, 0) >= 0)
1058 if (snd_mixer_attach (handle, file) >= 0
1059 && snd_mixer_load (handle) >= 0
1060 && snd_mixer_selem_register (handle, NULL, NULL) >= 0)
1061 for (e = snd_mixer_first_elem (handle);
1063 e = snd_mixer_elem_next (e))
1065 if (snd_mixer_selem_has_playback_volume (e))
1067 long pmin, pmax, vol;
1068 snd_mixer_selem_get_playback_volume_range (e, &pmin, &pmax);
1069 vol = pmin + (sd->volume * (pmax - pmin)) / 100;
1071 for (chn = 0; chn <= SND_MIXER_SCHN_LAST; chn++)
1072 snd_mixer_selem_set_playback_volume (e, chn, vol);
1075 snd_mixer_close(handle);
1081 /* Close device SD if it is open. */
1083 static void
1084 alsa_close (struct sound_device *sd)
1086 struct alsa_params *p = (struct alsa_params *) sd->data;
1087 if (p)
1089 if (p->hwparams)
1090 snd_pcm_hw_params_free (p->hwparams);
1091 if (p->swparams)
1092 snd_pcm_sw_params_free (p->swparams);
1093 if (p->handle)
1095 snd_pcm_drain (p->handle);
1096 snd_pcm_close (p->handle);
1098 free (p);
1102 /* Choose device-dependent format for device SD from sound file S. */
1104 static void
1105 alsa_choose_format (struct sound_device *sd, struct sound *s)
1107 struct alsa_params *p = (struct alsa_params *) sd->data;
1108 if (s->type == RIFF)
1110 struct wav_header *h = (struct wav_header *) s->header;
1111 if (h->precision == 8)
1112 sd->format = SND_PCM_FORMAT_U8;
1113 else if (h->precision == 16)
1114 sd->format = SND_PCM_FORMAT_S16_LE;
1115 else
1116 error ("Unsupported WAV file format");
1118 else if (s->type == SUN_AUDIO)
1120 struct au_header *header = (struct au_header *) s->header;
1121 switch (header->encoding)
1123 case AU_ENCODING_ULAW_8:
1124 sd->format = SND_PCM_FORMAT_MU_LAW;
1125 break;
1126 case AU_ENCODING_ALAW_8:
1127 sd->format = SND_PCM_FORMAT_A_LAW;
1128 break;
1129 case AU_ENCODING_IEEE32:
1130 sd->format = SND_PCM_FORMAT_FLOAT_BE;
1131 break;
1132 case AU_ENCODING_IEEE64:
1133 sd->format = SND_PCM_FORMAT_FLOAT64_BE;
1134 break;
1135 case AU_ENCODING_8:
1136 sd->format = SND_PCM_FORMAT_S8;
1137 break;
1138 case AU_ENCODING_16:
1139 sd->format = SND_PCM_FORMAT_S16_BE;
1140 break;
1141 case AU_ENCODING_24:
1142 sd->format = SND_PCM_FORMAT_S24_BE;
1143 break;
1144 case AU_ENCODING_32:
1145 sd->format = SND_PCM_FORMAT_S32_BE;
1146 break;
1148 default:
1149 error ("Unsupported AU file format");
1152 else
1153 abort ();
1157 /* Write NBYTES bytes from BUFFER to device SD. */
1159 static void
1160 alsa_write (struct sound_device *sd, const char *buffer, int nbytes)
1162 struct alsa_params *p = (struct alsa_params *) sd->data;
1164 /* The the third parameter to snd_pcm_writei is frames, not bytes. */
1165 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
1166 int nwritten = 0;
1167 int err;
1169 while (nwritten < nbytes)
1171 snd_pcm_uframes_t frames = (nbytes - nwritten)/fact;
1172 if (frames == 0) break;
1174 err = snd_pcm_writei (p->handle, buffer + nwritten, frames);
1175 if (err < 0)
1177 if (err == -EPIPE)
1178 { /* under-run */
1179 err = snd_pcm_prepare (p->handle);
1180 if (err < 0)
1181 alsa_sound_perror ("Can't recover from underrun, prepare failed",
1182 err);
1184 else if (err == -ESTRPIPE)
1186 while ((err = snd_pcm_resume (p->handle)) == -EAGAIN)
1187 sleep(1); /* wait until the suspend flag is released */
1188 if (err < 0)
1190 err = snd_pcm_prepare (p->handle);
1191 if (err < 0)
1192 alsa_sound_perror ("Can't recover from suspend, "
1193 "prepare failed",
1194 err);
1197 else
1198 alsa_sound_perror ("Error writing to sound device", err);
1201 else
1202 nwritten += err * fact;
1206 static void
1207 snd_error_quiet (const char *file, int line, const char *function, int err,
1208 const char *fmt)
1212 /* Initialize device SD. Set up the interface functions in the device
1213 structure. */
1215 static int
1216 alsa_init (struct sound_device *sd)
1218 const char *file;
1219 snd_pcm_t *handle;
1220 int err;
1222 /* Open the sound device. Default is "default". */
1223 if (sd->file)
1224 file = sd->file;
1225 else
1226 file = DEFAULT_ALSA_SOUND_DEVICE;
1228 snd_lib_error_set_handler ((snd_lib_error_handler_t) snd_error_quiet);
1229 err = snd_pcm_open (&handle, file, SND_PCM_STREAM_PLAYBACK, 0);
1230 snd_lib_error_set_handler (NULL);
1231 if (err < 0)
1232 return 0;
1233 snd_pcm_close (handle);
1235 sd->fd = -1;
1236 sd->open = alsa_open;
1237 sd->close = alsa_close;
1238 sd->configure = alsa_configure;
1239 sd->choose_format = alsa_choose_format;
1240 sd->write = alsa_write;
1241 sd->period_size = alsa_period_size;
1243 return 1;
1246 #endif /* HAVE_ALSA */
1249 /* END: Non Windows functions */
1250 #else /* WINDOWSNT */
1252 /* BEGIN: Windows specific functions */
1254 #define SOUND_WARNING(fun, error, text) \
1256 char buf[1024]; \
1257 char err_string[MAXERRORLENGTH]; \
1258 fun (error, err_string, sizeof (err_string)); \
1259 _snprintf (buf, sizeof (buf), "%s\nError: %s", \
1260 text, err_string); \
1261 sound_warning (buf); \
1264 static int
1265 do_play_sound (const char *psz_file, unsigned long ui_volume)
1267 int i_result = 0;
1268 MCIERROR mci_error = 0;
1269 char sz_cmd_buf[520] = {0};
1270 char sz_ret_buf[520] = {0};
1271 MMRESULT mm_result = MMSYSERR_NOERROR;
1272 unsigned long ui_volume_org = 0;
1273 BOOL b_reset_volume = FALSE;
1275 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1276 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1277 sprintf (sz_cmd_buf,
1278 "open \"%s\" alias GNUEmacs_PlaySound_Device wait",
1279 psz_file);
1280 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1281 if (mci_error != 0)
1283 SOUND_WARNING (mciGetErrorString, mci_error,
1284 "The open mciSendString command failed to open "
1285 "the specified sound file.");
1286 i_result = (int) mci_error;
1287 return i_result;
1289 if ((ui_volume > 0) && (ui_volume != UINT_MAX))
1291 mm_result = waveOutGetVolume ((HWAVEOUT) WAVE_MAPPER, &ui_volume_org);
1292 if (mm_result == MMSYSERR_NOERROR)
1294 b_reset_volume = TRUE;
1295 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume);
1296 if (mm_result != MMSYSERR_NOERROR)
1298 SOUND_WARNING (waveOutGetErrorText, mm_result,
1299 "waveOutSetVolume failed to set the volume level "
1300 "of the WAVE_MAPPER device.\n"
1301 "As a result, the user selected volume level will "
1302 "not be used.");
1305 else
1307 SOUND_WARNING (waveOutGetErrorText, mm_result,
1308 "waveOutGetVolume failed to obtain the original "
1309 "volume level of the WAVE_MAPPER device.\n"
1310 "As a result, the user selected volume level will "
1311 "not be used.");
1314 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1315 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1316 strcpy (sz_cmd_buf, "play GNUEmacs_PlaySound_Device wait");
1317 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1318 if (mci_error != 0)
1320 SOUND_WARNING (mciGetErrorString, mci_error,
1321 "The play mciSendString command failed to play the "
1322 "opened sound file.");
1323 i_result = (int) mci_error;
1325 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1326 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1327 strcpy (sz_cmd_buf, "close GNUEmacs_PlaySound_Device wait");
1328 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1329 if (b_reset_volume == TRUE)
1331 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume_org);
1332 if (mm_result != MMSYSERR_NOERROR)
1334 SOUND_WARNING (waveOutGetErrorText, mm_result,
1335 "waveOutSetVolume failed to reset the original volume "
1336 "level of the WAVE_MAPPER device.");
1339 return i_result;
1342 /* END: Windows specific functions */
1344 #endif /* WINDOWSNT */
1346 DEFUN ("play-sound-internal", Fplay_sound_internal, Splay_sound_internal, 1, 1, 0,
1347 doc: /* Play sound SOUND.
1349 Internal use only, use `play-sound' instead. */)
1350 (Lisp_Object sound)
1352 Lisp_Object attrs[SOUND_ATTR_SENTINEL];
1353 int count = SPECPDL_INDEX ();
1355 #ifndef WINDOWSNT
1356 Lisp_Object file;
1357 struct gcpro gcpro1, gcpro2;
1358 Lisp_Object args[2];
1359 #else /* WINDOWSNT */
1360 int len = 0;
1361 Lisp_Object lo_file = {0};
1362 char * psz_file = NULL;
1363 unsigned long ui_volume_tmp = UINT_MAX;
1364 unsigned long ui_volume = UINT_MAX;
1365 int i_result = 0;
1366 #endif /* WINDOWSNT */
1368 /* Parse the sound specification. Give up if it is invalid. */
1369 if (!parse_sound (sound, attrs))
1370 error ("Invalid sound specification");
1372 #ifndef WINDOWSNT
1373 file = Qnil;
1374 GCPRO2 (sound, file);
1375 current_sound_device = (struct sound_device *) xmalloc (sizeof (struct sound_device));
1376 memset (current_sound_device, 0, sizeof (struct sound_device));
1377 current_sound = (struct sound *) xmalloc (sizeof (struct sound));
1378 memset (current_sound, 0, sizeof (struct sound));
1379 record_unwind_protect (sound_cleanup, Qnil);
1380 current_sound->header = (char *) alloca (MAX_SOUND_HEADER_BYTES);
1382 if (STRINGP (attrs[SOUND_FILE]))
1384 /* Open the sound file. */
1385 current_sound->fd = openp (Fcons (Vdata_directory, Qnil),
1386 attrs[SOUND_FILE], Qnil, &file, Qnil);
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 if (STRINGP (attrs[SOUND_DEVICE]))
1411 int len = SCHARS (attrs[SOUND_DEVICE]);
1412 current_sound_device->file = (char *) alloca (len + 1);
1413 strcpy (current_sound_device->file, SDATA (attrs[SOUND_DEVICE]));
1416 if (INTEGERP (attrs[SOUND_VOLUME]))
1417 current_sound_device->volume = XFASTINT (attrs[SOUND_VOLUME]);
1418 else if (FLOATP (attrs[SOUND_VOLUME]))
1419 current_sound_device->volume = XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1421 args[0] = Qplay_sound_functions;
1422 args[1] = sound;
1423 Frun_hook_with_args (2, args);
1425 #ifdef HAVE_ALSA
1426 if (!alsa_init (current_sound_device))
1427 #endif
1428 if (!vox_init (current_sound_device))
1429 error ("No usable sound device driver found");
1431 /* Open the device. */
1432 current_sound_device->open (current_sound_device);
1434 /* Play the sound. */
1435 current_sound->play (current_sound, current_sound_device);
1437 /* Clean up. */
1438 UNGCPRO;
1440 #else /* WINDOWSNT */
1442 lo_file = Fexpand_file_name (attrs[SOUND_FILE], Qnil);
1443 len = XSTRING (lo_file)->size;
1444 psz_file = (char *) alloca (len + 1);
1445 strcpy (psz_file, XSTRING (lo_file)->data);
1446 if (INTEGERP (attrs[SOUND_VOLUME]))
1448 ui_volume_tmp = XFASTINT (attrs[SOUND_VOLUME]);
1450 else if (FLOATP (attrs[SOUND_VOLUME]))
1452 ui_volume_tmp = (unsigned long) XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
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 i_result = do_play_sound (psz_file, ui_volume);
1469 #endif /* WINDOWSNT */
1471 unbind_to (count, Qnil);
1472 return Qnil;
1475 /***********************************************************************
1476 Initialization
1477 ***********************************************************************/
1479 void
1480 syms_of_sound (void)
1482 QCdevice = intern_c_string(":device");
1483 staticpro (&QCdevice);
1484 QCvolume = intern_c_string (":volume");
1485 staticpro (&QCvolume);
1486 Qsound = intern_c_string ("sound");
1487 staticpro (&Qsound);
1488 Qplay_sound_functions = intern_c_string ("play-sound-functions");
1489 staticpro (&Qplay_sound_functions);
1491 defsubr (&Splay_sound_internal);
1495 void
1496 init_sound (void)
1500 #endif /* HAVE_SOUND */