Merge from emacs-24; up to 2012-04-25T15:23:19Z!sdl.web@gmail.com
[emacs.git] / src / sound.c
blob143653e48e46dca99fbbc13c92b37501318ae19b
1 /* sound.c -- sound support.
2 Copyright (C) 1998-1999, 2001-2012 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 static Lisp_Object QCvolume, QCdevice;
98 static Lisp_Object Qsound;
99 static 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
129 /* Structure forward declarations. */
131 struct sound;
132 struct sound_device;
134 /* The file header of RIFF-WAVE files (*.wav). Files are always in
135 little-endian byte-order. */
137 struct wav_header
139 u_int32_t magic;
140 u_int32_t length;
141 u_int32_t chunk_type;
142 u_int32_t chunk_format;
143 u_int32_t chunk_length;
144 u_int16_t format;
145 u_int16_t channels;
146 u_int32_t sample_rate;
147 u_int32_t bytes_per_second;
148 u_int16_t sample_size;
149 u_int16_t precision;
150 u_int32_t chunk_data;
151 u_int32_t data_length;
154 /* The file header of Sun adio files (*.au). Files are always in
155 big-endian byte-order. */
157 struct au_header
159 /* ASCII ".snd" */
160 u_int32_t magic_number;
162 /* Offset of data part from start of file. Minimum value is 24. */
163 u_int32_t data_offset;
165 /* Size of data part, 0xffffffff if unknown. */
166 u_int32_t data_size;
168 /* Data encoding format.
169 1 8-bit ISDN u-law
170 2 8-bit linear PCM (REF-PCM)
171 3 16-bit linear PCM
172 4 24-bit linear PCM
173 5 32-bit linear PCM
174 6 32-bit IEEE floating-point
175 7 64-bit IEEE floating-point
176 23 8-bit u-law compressed using CCITT 0.721 ADPCM voice data
177 encoding scheme. */
178 u_int32_t encoding;
180 /* Number of samples per second. */
181 u_int32_t sample_rate;
183 /* Number of interleaved channels. */
184 u_int32_t channels;
187 /* Maximum of all sound file headers sizes. */
189 #define MAX_SOUND_HEADER_BYTES \
190 max (sizeof (struct wav_header), sizeof (struct au_header))
192 /* Interface structure for sound devices. */
194 struct sound_device
196 /* The name of the device or null meaning use a default device name. */
197 char *file;
199 /* File descriptor of the device. */
200 int fd;
202 /* Device-dependent format. */
203 int format;
205 /* Volume (0..100). Zero means unspecified. */
206 int volume;
208 /* Sample size. */
209 int sample_size;
211 /* Sample rate. */
212 int sample_rate;
214 /* Bytes per second. */
215 int bps;
217 /* 1 = mono, 2 = stereo, 0 = don't set. */
218 int channels;
220 /* Open device SD. */
221 void (* open) (struct sound_device *sd);
223 /* Close device SD. */
224 void (* close) (struct sound_device *sd);
226 /* Configure SD according to device-dependent parameters. */
227 void (* configure) (struct sound_device *device);
229 /* Choose a device-dependent format for outputting sound S. */
230 void (* choose_format) (struct sound_device *sd,
231 struct sound *s);
233 /* Return a preferred data size in bytes to be sent to write (below)
234 each time. 2048 is used if this is NULL. */
235 ptrdiff_t (* period_size) (struct sound_device *sd);
237 /* Write NYBTES bytes from BUFFER to device SD. */
238 void (* write) (struct sound_device *sd, const char *buffer,
239 ptrdiff_t nbytes);
241 /* A place for devices to store additional data. */
242 void *data;
245 /* An enumerator for each supported sound file type. */
247 enum sound_type
249 RIFF,
250 SUN_AUDIO
253 /* Interface structure for sound files. */
255 struct sound
257 /* The type of the file. */
258 enum sound_type type;
260 /* File descriptor of a sound file. */
261 int fd;
263 /* Pointer to sound file header. This contains header_size bytes
264 read from the start of a sound file. */
265 char *header;
267 /* Number of bytes read from sound file. This is always <=
268 MAX_SOUND_HEADER_BYTES. */
269 int header_size;
271 /* Sound data, if a string. */
272 Lisp_Object data;
274 /* Play sound file S on device SD. */
275 void (* play) (struct sound *s, struct sound_device *sd);
278 /* These are set during `play-sound-internal' so that sound_cleanup has
279 access to them. */
281 static struct sound_device *current_sound_device;
282 static struct sound *current_sound;
284 /* Function prototypes. */
286 static void vox_open (struct sound_device *);
287 static void vox_configure (struct sound_device *);
288 static void vox_close (struct sound_device *sd);
289 static void vox_choose_format (struct sound_device *, struct sound *);
290 static int vox_init (struct sound_device *);
291 static void vox_write (struct sound_device *, const char *, ptrdiff_t);
292 static void find_sound_type (struct sound *);
293 static u_int32_t le2hl (u_int32_t);
294 static u_int16_t le2hs (u_int16_t);
295 static u_int32_t be2hl (u_int32_t);
296 static int wav_init (struct sound *);
297 static void wav_play (struct sound *, struct sound_device *);
298 static int au_init (struct sound *);
299 static void au_play (struct sound *, struct sound_device *);
301 #if 0 /* Currently not used. */
302 static u_int16_t be2hs (u_int16_t);
303 #endif
305 /* END: Non Windows Definitions */
306 #else /* WINDOWSNT */
308 /* BEGIN: Windows Specific Definitions */
309 static int do_play_sound (const char *, unsigned long);
311 END: Windows Specific Definitions */
312 #endif /* WINDOWSNT */
315 /***********************************************************************
316 General
317 ***********************************************************************/
319 /* BEGIN: Common functions */
321 /* Like perror, but signals an error. */
323 static void
324 sound_perror (const char *msg)
326 int saved_errno = errno;
328 turn_on_atimers (1);
329 #ifdef SIGIO
330 sigunblock (sigmask (SIGIO));
331 #endif
332 if (saved_errno != 0)
333 error ("%s: %s", msg, strerror (saved_errno));
334 else
335 error ("%s", msg);
339 /* Display a warning message. */
341 static void
342 sound_warning (const char *msg)
344 message ("%s", msg);
348 /* Parse sound specification SOUND, and fill ATTRS with what is
349 found. Value is non-zero if SOUND Is a valid sound specification.
350 A valid sound specification is a list starting with the symbol
351 `sound'. The rest of the list is a property list which may
352 contain the following key/value pairs:
354 - `:file FILE'
356 FILE is the sound file to play. If it isn't an absolute name,
357 it's searched under `data-directory'.
359 - `:data DATA'
361 DATA is a string containing sound data. Either :file or :data
362 may be present, but not both.
364 - `:device DEVICE'
366 DEVICE is the name of the device to play on, e.g. "/dev/dsp2".
367 If not specified, a default device is used.
369 - `:volume VOL'
371 VOL must be an integer in the range [0, 100], or a float in the
372 range [0, 1]. */
374 static int
375 parse_sound (Lisp_Object sound, Lisp_Object *attrs)
377 /* SOUND must be a list starting with the symbol `sound'. */
378 if (!CONSP (sound) || !EQ (XCAR (sound), Qsound))
379 return 0;
381 sound = XCDR (sound);
382 attrs[SOUND_FILE] = Fplist_get (sound, QCfile);
383 attrs[SOUND_DATA] = Fplist_get (sound, QCdata);
384 attrs[SOUND_DEVICE] = Fplist_get (sound, QCdevice);
385 attrs[SOUND_VOLUME] = Fplist_get (sound, QCvolume);
387 #ifndef WINDOWSNT
388 /* File name or data must be specified. */
389 if (!STRINGP (attrs[SOUND_FILE])
390 && !STRINGP (attrs[SOUND_DATA]))
391 return 0;
392 #else /* WINDOWSNT */
394 Data is not supported in Windows. Therefore a
395 File name MUST be supplied.
397 if (!STRINGP (attrs[SOUND_FILE]))
399 return 0;
401 #endif /* WINDOWSNT */
403 /* Volume must be in the range 0..100 or unspecified. */
404 if (!NILP (attrs[SOUND_VOLUME]))
406 if (INTEGERP (attrs[SOUND_VOLUME]))
408 if (XINT (attrs[SOUND_VOLUME]) < 0
409 || XINT (attrs[SOUND_VOLUME]) > 100)
410 return 0;
412 else if (FLOATP (attrs[SOUND_VOLUME]))
414 if (XFLOAT_DATA (attrs[SOUND_VOLUME]) < 0
415 || XFLOAT_DATA (attrs[SOUND_VOLUME]) > 1)
416 return 0;
418 else
419 return 0;
422 #ifndef WINDOWSNT
423 /* Device must be a string or unspecified. */
424 if (!NILP (attrs[SOUND_DEVICE])
425 && !STRINGP (attrs[SOUND_DEVICE]))
426 return 0;
427 #endif /* WINDOWSNT */
429 Since device is ignored in Windows, it does not matter
430 what it is.
432 return 1;
435 /* END: Common functions */
437 /* BEGIN: Non Windows functions */
438 #ifndef WINDOWSNT
440 /* Find out the type of the sound file whose file descriptor is FD.
441 S is the sound file structure to fill in. */
443 static void
444 find_sound_type (struct sound *s)
446 if (!wav_init (s) && !au_init (s))
447 error ("Unknown sound format");
451 /* Function installed by play-sound-internal with record_unwind_protect. */
453 static Lisp_Object
454 sound_cleanup (Lisp_Object arg)
456 if (current_sound_device->close)
457 current_sound_device->close (current_sound_device);
458 if (current_sound->fd > 0)
459 emacs_close (current_sound->fd);
460 xfree (current_sound_device);
461 xfree (current_sound);
463 return Qnil;
466 /***********************************************************************
467 Byte-order Conversion
468 ***********************************************************************/
470 /* Convert 32-bit value VALUE which is in little-endian byte-order
471 to host byte-order. */
473 static u_int32_t
474 le2hl (u_int32_t value)
476 #ifdef WORDS_BIGENDIAN
477 unsigned char *p = (unsigned char *) &value;
478 value = p[0] + (p[1] << 8) + (p[2] << 16) + (p[3] << 24);
479 #endif
480 return value;
484 /* Convert 16-bit value VALUE which is in little-endian byte-order
485 to host byte-order. */
487 static u_int16_t
488 le2hs (u_int16_t value)
490 #ifdef WORDS_BIGENDIAN
491 unsigned char *p = (unsigned char *) &value;
492 value = p[0] + (p[1] << 8);
493 #endif
494 return value;
498 /* Convert 32-bit value VALUE which is in big-endian byte-order
499 to host byte-order. */
501 static u_int32_t
502 be2hl (u_int32_t value)
504 #ifndef WORDS_BIGENDIAN
505 unsigned char *p = (unsigned char *) &value;
506 value = p[3] + (p[2] << 8) + (p[1] << 16) + (p[0] << 24);
507 #endif
508 return value;
512 #if 0 /* Currently not used. */
514 /* Convert 16-bit value VALUE which is in big-endian byte-order
515 to host byte-order. */
517 static u_int16_t
518 be2hs (u_int16_t value)
520 #ifndef WORDS_BIGENDIAN
521 unsigned char *p = (unsigned char *) &value;
522 value = p[1] + (p[0] << 8);
523 #endif
524 return value;
527 #endif /* 0 */
529 /***********************************************************************
530 RIFF-WAVE (*.wav)
531 ***********************************************************************/
533 /* Try to initialize sound file S from S->header. S->header
534 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
535 sound file. If the file is a WAV-format file, set up interface
536 functions in S and convert header fields to host byte-order.
537 Value is non-zero if the file is a WAV file. */
539 static int
540 wav_init (struct sound *s)
542 struct wav_header *header = (struct wav_header *) s->header;
544 if (s->header_size < sizeof *header
545 || memcmp (s->header, "RIFF", 4) != 0)
546 return 0;
548 /* WAV files are in little-endian order. Convert the header
549 if on a big-endian machine. */
550 header->magic = le2hl (header->magic);
551 header->length = le2hl (header->length);
552 header->chunk_type = le2hl (header->chunk_type);
553 header->chunk_format = le2hl (header->chunk_format);
554 header->chunk_length = le2hl (header->chunk_length);
555 header->format = le2hs (header->format);
556 header->channels = le2hs (header->channels);
557 header->sample_rate = le2hl (header->sample_rate);
558 header->bytes_per_second = le2hl (header->bytes_per_second);
559 header->sample_size = le2hs (header->sample_size);
560 header->precision = le2hs (header->precision);
561 header->chunk_data = le2hl (header->chunk_data);
562 header->data_length = le2hl (header->data_length);
564 /* Set up the interface functions for WAV. */
565 s->type = RIFF;
566 s->play = wav_play;
568 return 1;
572 /* Play RIFF-WAVE audio file S on sound device SD. */
574 static void
575 wav_play (struct sound *s, struct sound_device *sd)
577 struct wav_header *header = (struct wav_header *) s->header;
579 /* Let the device choose a suitable device-dependent format
580 for the file. */
581 sd->choose_format (sd, s);
583 /* Configure the device. */
584 sd->sample_size = header->sample_size;
585 sd->sample_rate = header->sample_rate;
586 sd->bps = header->bytes_per_second;
587 sd->channels = header->channels;
588 sd->configure (sd);
590 /* Copy sound data to the device. The WAV file specification is
591 actually more complex. This simple scheme worked with all WAV
592 files I found so far. If someone feels inclined to implement the
593 whole RIFF-WAVE spec, please do. */
594 if (STRINGP (s->data))
595 sd->write (sd, SSDATA (s->data) + sizeof *header,
596 SBYTES (s->data) - sizeof *header);
597 else
599 char *buffer;
600 ptrdiff_t nbytes = 0;
601 ptrdiff_t blksize = sd->period_size ? sd->period_size (sd) : 2048;
602 ptrdiff_t data_left = header->data_length;
604 buffer = (char *) alloca (blksize);
605 lseek (s->fd, sizeof *header, SEEK_SET);
606 while (data_left > 0
607 && (nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
609 /* Don't play possible garbage at the end of file */
610 if (data_left < nbytes) nbytes = data_left;
611 data_left -= nbytes;
612 sd->write (sd, buffer, nbytes);
615 if (nbytes < 0)
616 sound_perror ("Error reading sound file");
621 /***********************************************************************
622 Sun Audio (*.au)
623 ***********************************************************************/
625 /* Sun audio file encodings. */
627 enum au_encoding
629 AU_ENCODING_ULAW_8 = 1,
630 AU_ENCODING_8,
631 AU_ENCODING_16,
632 AU_ENCODING_24,
633 AU_ENCODING_32,
634 AU_ENCODING_IEEE32,
635 AU_ENCODING_IEEE64,
636 AU_COMPRESSED = 23,
637 AU_ENCODING_ALAW_8 = 27
641 /* Try to initialize sound file S from S->header. S->header
642 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
643 sound file. If the file is a AU-format file, set up interface
644 functions in S and convert header fields to host byte-order.
645 Value is non-zero if the file is an AU file. */
647 static int
648 au_init (struct sound *s)
650 struct au_header *header = (struct au_header *) s->header;
652 if (s->header_size < sizeof *header
653 || memcmp (s->header, ".snd", 4) != 0)
654 return 0;
656 header->magic_number = be2hl (header->magic_number);
657 header->data_offset = be2hl (header->data_offset);
658 header->data_size = be2hl (header->data_size);
659 header->encoding = be2hl (header->encoding);
660 header->sample_rate = be2hl (header->sample_rate);
661 header->channels = be2hl (header->channels);
663 /* Set up the interface functions for AU. */
664 s->type = SUN_AUDIO;
665 s->play = au_play;
667 return 1;
671 /* Play Sun audio file S on sound device SD. */
673 static void
674 au_play (struct sound *s, struct sound_device *sd)
676 struct au_header *header = (struct au_header *) s->header;
678 sd->sample_size = 0;
679 sd->sample_rate = header->sample_rate;
680 sd->bps = 0;
681 sd->channels = header->channels;
682 sd->choose_format (sd, s);
683 sd->configure (sd);
685 if (STRINGP (s->data))
686 sd->write (sd, SSDATA (s->data) + header->data_offset,
687 SBYTES (s->data) - header->data_offset);
688 else
690 ptrdiff_t blksize = sd->period_size ? sd->period_size (sd) : 2048;
691 char *buffer;
692 ptrdiff_t nbytes;
694 /* Seek */
695 lseek (s->fd, header->data_offset, SEEK_SET);
697 /* Copy sound data to the device. */
698 buffer = (char *) alloca (blksize);
699 while ((nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
700 sd->write (sd, buffer, nbytes);
702 if (nbytes < 0)
703 sound_perror ("Error reading sound file");
708 /***********************************************************************
709 Voxware Driver Interface
710 ***********************************************************************/
712 /* This driver is available on GNU/Linux, and the free BSDs. FreeBSD
713 has a compatible own driver aka Luigi's driver. */
716 /* Open device SD. If SD->file is non-null, open that device,
717 otherwise use a default device name. */
719 static void
720 vox_open (struct sound_device *sd)
722 const char *file;
724 /* Open the sound device. Default is /dev/dsp. */
725 if (sd->file)
726 file = sd->file;
727 else
728 file = DEFAULT_SOUND_DEVICE;
730 sd->fd = emacs_open (file, O_WRONLY, 0);
731 if (sd->fd < 0)
732 sound_perror (file);
736 /* Configure device SD from parameters in it. */
738 static void
739 vox_configure (struct sound_device *sd)
741 int val;
743 xassert (sd->fd >= 0);
745 /* On GNU/Linux, it seems that the device driver doesn't like to be
746 interrupted by a signal. Block the ones we know to cause
747 troubles. */
748 turn_on_atimers (0);
749 #ifdef SIGIO
750 sigblock (sigmask (SIGIO));
751 #endif
753 val = sd->format;
754 if (ioctl (sd->fd, SNDCTL_DSP_SETFMT, &sd->format) < 0
755 || val != sd->format)
756 sound_perror ("Could not set sound format");
758 val = sd->channels != 1;
759 if (ioctl (sd->fd, SNDCTL_DSP_STEREO, &val) < 0
760 || val != (sd->channels != 1))
761 sound_perror ("Could not set stereo/mono");
763 /* I think bps and sampling_rate are the same, but who knows.
764 Check this. and use SND_DSP_SPEED for both. */
765 if (sd->sample_rate > 0)
767 val = sd->sample_rate;
768 if (ioctl (sd->fd, SNDCTL_DSP_SPEED, &sd->sample_rate) < 0)
769 sound_perror ("Could not set sound speed");
770 else if (val != sd->sample_rate)
771 sound_warning ("Could not set sample rate");
774 if (sd->volume > 0)
776 int volume = sd->volume & 0xff;
777 volume |= volume << 8;
778 /* This may fail if there is no mixer. Ignore the failure. */
779 ioctl (sd->fd, SOUND_MIXER_WRITE_PCM, &volume);
782 turn_on_atimers (1);
783 #ifdef SIGIO
784 sigunblock (sigmask (SIGIO));
785 #endif
789 /* Close device SD if it is open. */
791 static void
792 vox_close (struct sound_device *sd)
794 if (sd->fd >= 0)
796 /* On GNU/Linux, it seems that the device driver doesn't like to
797 be interrupted by a signal. Block the ones we know to cause
798 troubles. */
799 #ifdef SIGIO
800 sigblock (sigmask (SIGIO));
801 #endif
802 turn_on_atimers (0);
804 /* Flush sound data, and reset the device. */
805 ioctl (sd->fd, SNDCTL_DSP_SYNC, NULL);
807 turn_on_atimers (1);
808 #ifdef SIGIO
809 sigunblock (sigmask (SIGIO));
810 #endif
812 /* Close the device. */
813 emacs_close (sd->fd);
814 sd->fd = -1;
819 /* Choose device-dependent format for device SD from sound file S. */
821 static void
822 vox_choose_format (struct sound_device *sd, struct sound *s)
824 if (s->type == RIFF)
826 struct wav_header *h = (struct wav_header *) s->header;
827 if (h->precision == 8)
828 sd->format = AFMT_U8;
829 else if (h->precision == 16)
830 sd->format = AFMT_S16_LE;
831 else
832 error ("Unsupported WAV file format");
834 else if (s->type == SUN_AUDIO)
836 struct au_header *header = (struct au_header *) s->header;
837 switch (header->encoding)
839 case AU_ENCODING_ULAW_8:
840 case AU_ENCODING_IEEE32:
841 case AU_ENCODING_IEEE64:
842 sd->format = AFMT_MU_LAW;
843 break;
845 case AU_ENCODING_8:
846 case AU_ENCODING_16:
847 case AU_ENCODING_24:
848 case AU_ENCODING_32:
849 sd->format = AFMT_S16_LE;
850 break;
852 default:
853 error ("Unsupported AU file format");
856 else
857 abort ();
861 /* Initialize device SD. Set up the interface functions in the device
862 structure. */
864 static int
865 vox_init (struct sound_device *sd)
867 const char *file;
868 int fd;
870 /* Open the sound device. Default is /dev/dsp. */
871 if (sd->file)
872 file = sd->file;
873 else
874 file = DEFAULT_SOUND_DEVICE;
875 fd = emacs_open (file, O_WRONLY, 0);
876 if (fd >= 0)
877 emacs_close (fd);
878 else
879 return 0;
881 sd->fd = -1;
882 sd->open = vox_open;
883 sd->close = vox_close;
884 sd->configure = vox_configure;
885 sd->choose_format = vox_choose_format;
886 sd->write = vox_write;
887 sd->period_size = NULL;
889 return 1;
892 /* Write NBYTES bytes from BUFFER to device SD. */
894 static void
895 vox_write (struct sound_device *sd, const char *buffer, ptrdiff_t nbytes)
897 if (emacs_write (sd->fd, buffer, nbytes) != nbytes)
898 sound_perror ("Error writing to sound device");
901 #ifdef HAVE_ALSA
902 /***********************************************************************
903 ALSA Driver Interface
904 ***********************************************************************/
906 /* This driver is available on GNU/Linux. */
908 #ifndef DEFAULT_ALSA_SOUND_DEVICE
909 #define DEFAULT_ALSA_SOUND_DEVICE "default"
910 #endif
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 ptrdiff_t
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 xfree (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 if (s->type == RIFF)
1109 struct wav_header *h = (struct wav_header *) s->header;
1110 if (h->precision == 8)
1111 sd->format = SND_PCM_FORMAT_U8;
1112 else if (h->precision == 16)
1113 sd->format = SND_PCM_FORMAT_S16_LE;
1114 else
1115 error ("Unsupported WAV file format");
1117 else if (s->type == SUN_AUDIO)
1119 struct au_header *header = (struct au_header *) s->header;
1120 switch (header->encoding)
1122 case AU_ENCODING_ULAW_8:
1123 sd->format = SND_PCM_FORMAT_MU_LAW;
1124 break;
1125 case AU_ENCODING_ALAW_8:
1126 sd->format = SND_PCM_FORMAT_A_LAW;
1127 break;
1128 case AU_ENCODING_IEEE32:
1129 sd->format = SND_PCM_FORMAT_FLOAT_BE;
1130 break;
1131 case AU_ENCODING_IEEE64:
1132 sd->format = SND_PCM_FORMAT_FLOAT64_BE;
1133 break;
1134 case AU_ENCODING_8:
1135 sd->format = SND_PCM_FORMAT_S8;
1136 break;
1137 case AU_ENCODING_16:
1138 sd->format = SND_PCM_FORMAT_S16_BE;
1139 break;
1140 case AU_ENCODING_24:
1141 sd->format = SND_PCM_FORMAT_S24_BE;
1142 break;
1143 case AU_ENCODING_32:
1144 sd->format = SND_PCM_FORMAT_S32_BE;
1145 break;
1147 default:
1148 error ("Unsupported AU file format");
1151 else
1152 abort ();
1156 /* Write NBYTES bytes from BUFFER to device SD. */
1158 static void
1159 alsa_write (struct sound_device *sd, const char *buffer, ptrdiff_t nbytes)
1161 struct alsa_params *p = (struct alsa_params *) sd->data;
1163 /* The the third parameter to snd_pcm_writei is frames, not bytes. */
1164 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
1165 ptrdiff_t nwritten = 0;
1166 int err;
1168 while (nwritten < nbytes)
1170 snd_pcm_uframes_t frames = (nbytes - nwritten)/fact;
1171 if (frames == 0) break;
1173 err = snd_pcm_writei (p->handle, buffer + nwritten, frames);
1174 if (err < 0)
1176 if (err == -EPIPE)
1177 { /* under-run */
1178 err = snd_pcm_prepare (p->handle);
1179 if (err < 0)
1180 alsa_sound_perror ("Can't recover from underrun, prepare failed",
1181 err);
1183 else if (err == -ESTRPIPE)
1185 while ((err = snd_pcm_resume (p->handle)) == -EAGAIN)
1186 sleep (1); /* wait until the suspend flag is released */
1187 if (err < 0)
1189 err = snd_pcm_prepare (p->handle);
1190 if (err < 0)
1191 alsa_sound_perror ("Can't recover from suspend, "
1192 "prepare failed",
1193 err);
1196 else
1197 alsa_sound_perror ("Error writing to sound device", err);
1200 else
1201 nwritten += err * fact;
1205 static void
1206 snd_error_quiet (const char *file, int line, const char *function, int err,
1207 const char *fmt)
1211 /* Initialize device SD. Set up the interface functions in the device
1212 structure. */
1214 static int
1215 alsa_init (struct sound_device *sd)
1217 const char *file;
1218 snd_pcm_t *handle;
1219 int err;
1221 /* Open the sound device. Default is "default". */
1222 if (sd->file)
1223 file = sd->file;
1224 else
1225 file = DEFAULT_ALSA_SOUND_DEVICE;
1227 snd_lib_error_set_handler ((snd_lib_error_handler_t) snd_error_quiet);
1228 err = snd_pcm_open (&handle, file, SND_PCM_STREAM_PLAYBACK, 0);
1229 snd_lib_error_set_handler (NULL);
1230 if (err < 0)
1231 return 0;
1232 snd_pcm_close (handle);
1234 sd->fd = -1;
1235 sd->open = alsa_open;
1236 sd->close = alsa_close;
1237 sd->configure = alsa_configure;
1238 sd->choose_format = alsa_choose_format;
1239 sd->write = alsa_write;
1240 sd->period_size = alsa_period_size;
1242 return 1;
1245 #endif /* HAVE_ALSA */
1248 /* END: Non Windows functions */
1249 #else /* WINDOWSNT */
1251 /* BEGIN: Windows specific functions */
1253 #define SOUND_WARNING(fun, error, text) \
1255 char buf[1024]; \
1256 char err_string[MAXERRORLENGTH]; \
1257 fun (error, err_string, sizeof (err_string)); \
1258 _snprintf (buf, sizeof (buf), "%s\nError: %s", \
1259 text, err_string); \
1260 sound_warning (buf); \
1263 static int
1264 do_play_sound (const char *psz_file, unsigned long ui_volume)
1266 int i_result = 0;
1267 MCIERROR mci_error = 0;
1268 char sz_cmd_buf[520] = {0};
1269 char sz_ret_buf[520] = {0};
1270 MMRESULT mm_result = MMSYSERR_NOERROR;
1271 unsigned long ui_volume_org = 0;
1272 BOOL b_reset_volume = FALSE;
1274 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1275 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1276 sprintf (sz_cmd_buf,
1277 "open \"%s\" alias GNUEmacs_PlaySound_Device wait",
1278 psz_file);
1279 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1280 if (mci_error != 0)
1282 SOUND_WARNING (mciGetErrorString, mci_error,
1283 "The open mciSendString command failed to open "
1284 "the specified sound file.");
1285 i_result = (int) mci_error;
1286 return i_result;
1288 if ((ui_volume > 0) && (ui_volume != UINT_MAX))
1290 mm_result = waveOutGetVolume ((HWAVEOUT) WAVE_MAPPER, &ui_volume_org);
1291 if (mm_result == MMSYSERR_NOERROR)
1293 b_reset_volume = TRUE;
1294 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume);
1295 if (mm_result != MMSYSERR_NOERROR)
1297 SOUND_WARNING (waveOutGetErrorText, mm_result,
1298 "waveOutSetVolume failed to set the volume level "
1299 "of the WAVE_MAPPER device.\n"
1300 "As a result, the user selected volume level will "
1301 "not be used.");
1304 else
1306 SOUND_WARNING (waveOutGetErrorText, mm_result,
1307 "waveOutGetVolume failed to obtain the original "
1308 "volume level of the WAVE_MAPPER device.\n"
1309 "As a result, the user selected volume level will "
1310 "not be used.");
1313 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1314 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1315 strcpy (sz_cmd_buf, "play GNUEmacs_PlaySound_Device wait");
1316 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1317 if (mci_error != 0)
1319 SOUND_WARNING (mciGetErrorString, mci_error,
1320 "The play mciSendString command failed to play the "
1321 "opened sound file.");
1322 i_result = (int) mci_error;
1324 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1325 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1326 strcpy (sz_cmd_buf, "close GNUEmacs_PlaySound_Device wait");
1327 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1328 if (b_reset_volume == TRUE)
1330 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume_org);
1331 if (mm_result != MMSYSERR_NOERROR)
1333 SOUND_WARNING (waveOutGetErrorText, mm_result,
1334 "waveOutSetVolume failed to reset the original volume "
1335 "level of the WAVE_MAPPER device.");
1338 return i_result;
1341 /* END: Windows specific functions */
1343 #endif /* WINDOWSNT */
1345 DEFUN ("play-sound-internal", Fplay_sound_internal, Splay_sound_internal, 1, 1, 0,
1346 doc: /* Play sound SOUND.
1348 Internal use only, use `play-sound' instead. */)
1349 (Lisp_Object sound)
1351 Lisp_Object attrs[SOUND_ATTR_SENTINEL];
1352 ptrdiff_t count = SPECPDL_INDEX ();
1354 #ifndef WINDOWSNT
1355 Lisp_Object file;
1356 struct gcpro gcpro1, gcpro2;
1357 Lisp_Object args[2];
1358 #else /* WINDOWSNT */
1359 int len = 0;
1360 Lisp_Object lo_file = {0};
1361 char * psz_file = NULL;
1362 unsigned long ui_volume_tmp = UINT_MAX;
1363 unsigned long ui_volume = UINT_MAX;
1364 int i_result = 0;
1365 #endif /* WINDOWSNT */
1367 /* Parse the sound specification. Give up if it is invalid. */
1368 if (!parse_sound (sound, attrs))
1369 error ("Invalid sound specification");
1371 #ifndef WINDOWSNT
1372 file = Qnil;
1373 GCPRO2 (sound, file);
1374 current_sound_device = (struct sound_device *) xmalloc (sizeof (struct sound_device));
1375 memset (current_sound_device, 0, sizeof (struct sound_device));
1376 current_sound = (struct sound *) xmalloc (sizeof (struct sound));
1377 memset (current_sound, 0, sizeof (struct sound));
1378 record_unwind_protect (sound_cleanup, Qnil);
1379 current_sound->header = (char *) alloca (MAX_SOUND_HEADER_BYTES);
1381 if (STRINGP (attrs[SOUND_FILE]))
1383 /* Open the sound file. */
1384 current_sound->fd = openp (Fcons (Vdata_directory, Qnil),
1385 attrs[SOUND_FILE], Qnil, &file, Qnil);
1386 if (current_sound->fd < 0)
1387 sound_perror ("Could not open sound file");
1389 /* Read the first bytes from the file. */
1390 current_sound->header_size
1391 = emacs_read (current_sound->fd, current_sound->header,
1392 MAX_SOUND_HEADER_BYTES);
1393 if (current_sound->header_size < 0)
1394 sound_perror ("Invalid sound file header");
1396 else
1398 current_sound->data = attrs[SOUND_DATA];
1399 current_sound->header_size = min (MAX_SOUND_HEADER_BYTES, SBYTES (current_sound->data));
1400 memcpy (current_sound->header, SDATA (current_sound->data),
1401 current_sound->header_size);
1404 /* Find out the type of sound. Give up if we can't tell. */
1405 find_sound_type (current_sound);
1407 /* Set up a device. */
1408 if (STRINGP (attrs[SOUND_DEVICE]))
1410 int len = SCHARS (attrs[SOUND_DEVICE]);
1411 current_sound_device->file = (char *) alloca (len + 1);
1412 strcpy (current_sound_device->file, SSDATA (attrs[SOUND_DEVICE]));
1415 if (INTEGERP (attrs[SOUND_VOLUME]))
1416 current_sound_device->volume = XFASTINT (attrs[SOUND_VOLUME]);
1417 else if (FLOATP (attrs[SOUND_VOLUME]))
1418 current_sound_device->volume = XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1420 args[0] = Qplay_sound_functions;
1421 args[1] = sound;
1422 Frun_hook_with_args (2, args);
1424 #ifdef HAVE_ALSA
1425 if (!alsa_init (current_sound_device))
1426 #endif
1427 if (!vox_init (current_sound_device))
1428 error ("No usable sound device driver found");
1430 /* Open the device. */
1431 current_sound_device->open (current_sound_device);
1433 /* Play the sound. */
1434 current_sound->play (current_sound, current_sound_device);
1436 /* Clean up. */
1437 UNGCPRO;
1439 #else /* WINDOWSNT */
1441 lo_file = Fexpand_file_name (attrs[SOUND_FILE], Qnil);
1442 len = XSTRING (lo_file)->size;
1443 psz_file = (char *) alloca (len + 1);
1444 strcpy (psz_file, XSTRING (lo_file)->data);
1445 if (INTEGERP (attrs[SOUND_VOLUME]))
1447 ui_volume_tmp = XFASTINT (attrs[SOUND_VOLUME]);
1449 else if (FLOATP (attrs[SOUND_VOLUME]))
1451 ui_volume_tmp = XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1454 Based on some experiments I have conducted, a value of 100 or less
1455 for the sound volume is much too low. You cannot even hear it.
1456 A value of UINT_MAX indicates that you wish for the sound to played
1457 at the maximum possible volume. A value of UINT_MAX/2 plays the
1458 sound at 50% maximum volume. Therefore the value passed to do_play_sound
1459 (and thus to waveOutSetVolume) must be some fraction of UINT_MAX.
1460 The following code adjusts the user specified volume level appropriately.
1462 if ((ui_volume_tmp > 0) && (ui_volume_tmp <= 100))
1464 ui_volume = ui_volume_tmp * (UINT_MAX / 100);
1466 i_result = do_play_sound (psz_file, ui_volume);
1468 #endif /* WINDOWSNT */
1470 unbind_to (count, Qnil);
1471 return Qnil;
1474 /***********************************************************************
1475 Initialization
1476 ***********************************************************************/
1478 void
1479 syms_of_sound (void)
1481 DEFSYM (QCdevice, ":device");
1482 DEFSYM (QCvolume, ":volume");
1483 DEFSYM (Qsound, "sound");
1484 DEFSYM (Qplay_sound_functions, "play-sound-functions");
1486 defsubr (&Splay_sound_internal);
1490 void
1491 init_sound (void)
1495 #endif /* HAVE_SOUND */