Small url-cache fix.
[emacs.git] / src / sound.c
blobb93099283daea6f244a170d4f1d1fd51f5be14b1
1 /* sound.c -- sound support.
2 Copyright (C) 1998, 1999, 2001, 2002, 2003, 2004,
3 2005, 2006, 2007, 2008, 2009, 2010 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 Win32 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>
47 #include <setjmp.h>
48 #include "lisp.h"
49 #include "dispextern.h"
50 #include "atimer.h"
51 #include <signal.h>
52 #include "syssignal.h"
53 /* END: Common Includes */
56 /* BEGIN: Non Windows Includes */
57 #ifndef WINDOWSNT
59 #ifndef MSDOS
60 #include <sys/ioctl.h>
61 #endif
63 /* FreeBSD has machine/soundcard.h. Voxware sound driver docs mention
64 sys/soundcard.h. So, let's try whatever's there. */
66 #ifdef HAVE_MACHINE_SOUNDCARD_H
67 #include <machine/soundcard.h>
68 #endif
69 #ifdef HAVE_SYS_SOUNDCARD_H
70 #include <sys/soundcard.h>
71 #endif
72 #ifdef HAVE_SOUNDCARD_H
73 #include <soundcard.h>
74 #endif
75 #ifdef HAVE_ALSA
76 #ifdef ALSA_SUBDIR_INCLUDE
77 #include <alsa/asoundlib.h>
78 #else
79 #include <asoundlib.h>
80 #endif /* ALSA_SUBDIR_INCLUDE */
81 #endif /* HAVE_ALSA */
83 /* END: Non Windows Includes */
85 #else /* WINDOWSNT */
87 /* BEGIN: Windows Specific Includes */
88 #include <stdio.h>
89 #include <stdlib.h>
90 #include <string.h>
91 #include <limits.h>
92 #include <windows.h>
93 #include <mmsystem.h>
94 /* END: Windows Specific Includes */
96 #endif /* WINDOWSNT */
98 /* BEGIN: Common Definitions */
100 /* Symbols. */
102 Lisp_Object QCvolume, QCdevice;
103 Lisp_Object Qsound;
104 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 #ifdef HAVE_ALSA
118 static void alsa_sound_perror (const char *, int) NO_RETURN;
119 #endif
120 static void sound_perror (const char *) NO_RETURN;
121 static void sound_warning (const char *);
122 static int parse_sound (Lisp_Object, Lisp_Object *);
124 /* END: Common Definitions */
126 /* BEGIN: Non Windows Definitions */
127 #ifndef WINDOWSNT
129 #ifndef DEFAULT_SOUND_DEVICE
130 #define DEFAULT_SOUND_DEVICE "/dev/dsp"
131 #endif
132 #ifndef DEFAULT_ALSA_SOUND_DEVICE
133 #define DEFAULT_ALSA_SOUND_DEVICE "default"
134 #endif
137 /* Structure forward declarations. */
139 struct sound;
140 struct sound_device;
142 /* The file header of RIFF-WAVE files (*.wav). Files are always in
143 little-endian byte-order. */
145 struct wav_header
147 u_int32_t magic;
148 u_int32_t length;
149 u_int32_t chunk_type;
150 u_int32_t chunk_format;
151 u_int32_t chunk_length;
152 u_int16_t format;
153 u_int16_t channels;
154 u_int32_t sample_rate;
155 u_int32_t bytes_per_second;
156 u_int16_t sample_size;
157 u_int16_t precision;
158 u_int32_t chunk_data;
159 u_int32_t data_length;
162 /* The file header of Sun adio files (*.au). Files are always in
163 big-endian byte-order. */
165 struct au_header
167 /* ASCII ".snd" */
168 u_int32_t magic_number;
170 /* Offset of data part from start of file. Minimum value is 24. */
171 u_int32_t data_offset;
173 /* Size of data part, 0xffffffff if unknown. */
174 u_int32_t data_size;
176 /* Data encoding format.
177 1 8-bit ISDN u-law
178 2 8-bit linear PCM (REF-PCM)
179 3 16-bit linear PCM
180 4 24-bit linear PCM
181 5 32-bit linear PCM
182 6 32-bit IEEE floating-point
183 7 64-bit IEEE floating-point
184 23 8-bit u-law compressed using CCITT 0.721 ADPCM voice data
185 encoding scheme. */
186 u_int32_t encoding;
188 /* Number of samples per second. */
189 u_int32_t sample_rate;
191 /* Number of interleaved channels. */
192 u_int32_t channels;
195 /* Maximum of all sound file headers sizes. */
197 #define MAX_SOUND_HEADER_BYTES \
198 max (sizeof (struct wav_header), sizeof (struct au_header))
200 /* Interface structure for sound devices. */
202 struct sound_device
204 /* The name of the device or null meaning use a default device name. */
205 char *file;
207 /* File descriptor of the device. */
208 int fd;
210 /* Device-dependent format. */
211 int format;
213 /* Volume (0..100). Zero means unspecified. */
214 int volume;
216 /* Sample size. */
217 int sample_size;
219 /* Sample rate. */
220 int sample_rate;
222 /* Bytes per second. */
223 int bps;
225 /* 1 = mono, 2 = stereo, 0 = don't set. */
226 int channels;
228 /* Open device SD. */
229 void (* open) (struct sound_device *sd);
231 /* Close device SD. */
232 void (* close) (struct sound_device *sd);
234 /* Configure SD accoring to device-dependent parameters. */
235 void (* configure) (struct sound_device *device);
237 /* Choose a device-dependent format for outputting sound S. */
238 void (* choose_format) (struct sound_device *sd,
239 struct sound *s);
241 /* Return a preferred data size in bytes to be sent to write (below)
242 each time. 2048 is used if this is NULL. */
243 int (* period_size) (struct sound_device *sd);
245 /* Write NYBTES bytes from BUFFER to device SD. */
246 void (* write) (struct sound_device *sd, const char *buffer,
247 int nbytes);
249 /* A place for devices to store additional data. */
250 void *data;
253 /* An enumerator for each supported sound file type. */
255 enum sound_type
257 RIFF,
258 SUN_AUDIO
261 /* Interface structure for sound files. */
263 struct sound
265 /* The type of the file. */
266 enum sound_type type;
268 /* File descriptor of a sound file. */
269 int fd;
271 /* Pointer to sound file header. This contains header_size bytes
272 read from the start of a sound file. */
273 char *header;
275 /* Number of bytes raed from sound file. This is always <=
276 MAX_SOUND_HEADER_BYTES. */
277 int header_size;
279 /* Sound data, if a string. */
280 Lisp_Object data;
282 /* Play sound file S on device SD. */
283 void (* play) (struct sound *s, struct sound_device *sd);
286 /* These are set during `play-sound-internal' so that sound_cleanup has
287 access to them. */
289 struct sound_device *current_sound_device;
290 struct sound *current_sound;
292 /* Function prototypes. */
294 static void vox_open (struct sound_device *);
295 static void vox_configure (struct sound_device *);
296 static void vox_close (struct sound_device *sd);
297 static void vox_choose_format (struct sound_device *, struct sound *);
298 static int vox_init (struct sound_device *);
299 static void vox_write (struct sound_device *, const char *, int);
300 static void find_sound_type (struct sound *);
301 static u_int32_t le2hl (u_int32_t);
302 static u_int16_t le2hs (u_int16_t);
303 static u_int32_t be2hl (u_int32_t);
304 static int wav_init (struct sound *);
305 static void wav_play (struct sound *, struct sound_device *);
306 static int au_init (struct sound *);
307 static void au_play (struct sound *, struct sound_device *);
309 #if 0 /* Currently not used. */
310 static u_int16_t be2hs (u_int16_t);
311 #endif
313 /* END: Non Windows Definitions */
314 #else /* WINDOWSNT */
316 /* BEGIN: Windows Specific Definitions */
317 static int do_play_sound (const char *, unsigned long);
319 END: Windows Specific Definitions */
320 #endif /* WINDOWSNT */
323 /***********************************************************************
324 General
325 ***********************************************************************/
327 /* BEGIN: Common functions */
329 /* Like perror, but signals an error. */
331 static void
332 sound_perror (const char *msg)
334 int saved_errno = errno;
336 turn_on_atimers (1);
337 #ifdef SIGIO
338 sigunblock (sigmask (SIGIO));
339 #endif
340 if (saved_errno != 0)
341 error ("%s: %s", msg, strerror (saved_errno));
342 else
343 error ("%s", msg);
347 /* Display a warning message. */
349 static void
350 sound_warning (const char *msg)
352 message (msg);
356 /* Parse sound specification SOUND, and fill ATTRS with what is
357 found. Value is non-zero if SOUND Is a valid sound specification.
358 A valid sound specification is a list starting with the symbol
359 `sound'. The rest of the list is a property list which may
360 contain the following key/value pairs:
362 - `:file FILE'
364 FILE is the sound file to play. If it isn't an absolute name,
365 it's searched under `data-directory'.
367 - `:data DATA'
369 DATA is a string containing sound data. Either :file or :data
370 may be present, but not both.
372 - `:device DEVICE'
374 DEVICE is the name of the device to play on, e.g. "/dev/dsp2".
375 If not specified, a default device is used.
377 - `:volume VOL'
379 VOL must be an integer in the range [0, 100], or a float in the
380 range [0, 1]. */
382 static int
383 parse_sound (Lisp_Object sound, Lisp_Object *attrs)
385 /* SOUND must be a list starting with the symbol `sound'. */
386 if (!CONSP (sound) || !EQ (XCAR (sound), Qsound))
387 return 0;
389 sound = XCDR (sound);
390 attrs[SOUND_FILE] = Fplist_get (sound, QCfile);
391 attrs[SOUND_DATA] = Fplist_get (sound, QCdata);
392 attrs[SOUND_DEVICE] = Fplist_get (sound, QCdevice);
393 attrs[SOUND_VOLUME] = Fplist_get (sound, QCvolume);
395 #ifndef WINDOWSNT
396 /* File name or data must be specified. */
397 if (!STRINGP (attrs[SOUND_FILE])
398 && !STRINGP (attrs[SOUND_DATA]))
399 return 0;
400 #else /* WINDOWSNT */
402 Data is not supported in Windows. Therefore a
403 File name MUST be supplied.
405 if (!STRINGP (attrs[SOUND_FILE]))
407 return 0;
409 #endif /* WINDOWSNT */
411 /* Volume must be in the range 0..100 or unspecified. */
412 if (!NILP (attrs[SOUND_VOLUME]))
414 if (INTEGERP (attrs[SOUND_VOLUME]))
416 if (XINT (attrs[SOUND_VOLUME]) < 0
417 || XINT (attrs[SOUND_VOLUME]) > 100)
418 return 0;
420 else if (FLOATP (attrs[SOUND_VOLUME]))
422 if (XFLOAT_DATA (attrs[SOUND_VOLUME]) < 0
423 || XFLOAT_DATA (attrs[SOUND_VOLUME]) > 1)
424 return 0;
426 else
427 return 0;
430 #ifndef WINDOWSNT
431 /* Device must be a string or unspecified. */
432 if (!NILP (attrs[SOUND_DEVICE])
433 && !STRINGP (attrs[SOUND_DEVICE]))
434 return 0;
435 #endif /* WINDOWSNT */
437 Since device is ignored in Windows, it does not matter
438 what it is.
440 return 1;
443 /* END: Common functions */
445 /* BEGIN: Non Windows functions */
446 #ifndef WINDOWSNT
448 /* Find out the type of the sound file whose file descriptor is FD.
449 S is the sound file structure to fill in. */
451 static void
452 find_sound_type (struct sound *s)
454 if (!wav_init (s) && !au_init (s))
455 error ("Unknown sound format");
459 /* Function installed by play-sound-internal with record_unwind_protect. */
461 static Lisp_Object
462 sound_cleanup (Lisp_Object arg)
464 if (current_sound_device->close)
465 current_sound_device->close (current_sound_device);
466 if (current_sound->fd > 0)
467 emacs_close (current_sound->fd);
468 free (current_sound_device);
469 free (current_sound);
471 return Qnil;
474 /***********************************************************************
475 Byte-order Conversion
476 ***********************************************************************/
478 /* Convert 32-bit value VALUE which is in little-endian byte-order
479 to host byte-order. */
481 static u_int32_t
482 le2hl (u_int32_t value)
484 #ifdef WORDS_BIGENDIAN
485 unsigned char *p = (unsigned char *) &value;
486 value = p[0] + (p[1] << 8) + (p[2] << 16) + (p[3] << 24);
487 #endif
488 return value;
492 /* Convert 16-bit value VALUE which is in little-endian byte-order
493 to host byte-order. */
495 static u_int16_t
496 le2hs (u_int16_t value)
498 #ifdef WORDS_BIGENDIAN
499 unsigned char *p = (unsigned char *) &value;
500 value = p[0] + (p[1] << 8);
501 #endif
502 return value;
506 /* Convert 32-bit value VALUE which is in big-endian byte-order
507 to host byte-order. */
509 static u_int32_t
510 be2hl (u_int32_t value)
512 #ifndef WORDS_BIGENDIAN
513 unsigned char *p = (unsigned char *) &value;
514 value = p[3] + (p[2] << 8) + (p[1] << 16) + (p[0] << 24);
515 #endif
516 return value;
520 #if 0 /* Currently not used. */
522 /* Convert 16-bit value VALUE which is in big-endian byte-order
523 to host byte-order. */
525 static u_int16_t
526 be2hs (u_int16_t value)
528 #ifndef WORDS_BIGENDIAN
529 unsigned char *p = (unsigned char *) &value;
530 value = p[1] + (p[0] << 8);
531 #endif
532 return value;
535 #endif /* 0 */
537 /***********************************************************************
538 RIFF-WAVE (*.wav)
539 ***********************************************************************/
541 /* Try to initialize sound file S from S->header. S->header
542 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
543 sound file. If the file is a WAV-format file, set up interface
544 functions in S and convert header fields to host byte-order.
545 Value is non-zero if the file is a WAV file. */
547 static int
548 wav_init (struct sound *s)
550 struct wav_header *header = (struct wav_header *) s->header;
552 if (s->header_size < sizeof *header
553 || memcmp (s->header, "RIFF", 4) != 0)
554 return 0;
556 /* WAV files are in little-endian order. Convert the header
557 if on a big-endian machine. */
558 header->magic = le2hl (header->magic);
559 header->length = le2hl (header->length);
560 header->chunk_type = le2hl (header->chunk_type);
561 header->chunk_format = le2hl (header->chunk_format);
562 header->chunk_length = le2hl (header->chunk_length);
563 header->format = le2hs (header->format);
564 header->channels = le2hs (header->channels);
565 header->sample_rate = le2hl (header->sample_rate);
566 header->bytes_per_second = le2hl (header->bytes_per_second);
567 header->sample_size = le2hs (header->sample_size);
568 header->precision = le2hs (header->precision);
569 header->chunk_data = le2hl (header->chunk_data);
570 header->data_length = le2hl (header->data_length);
572 /* Set up the interface functions for WAV. */
573 s->type = RIFF;
574 s->play = wav_play;
576 return 1;
580 /* Play RIFF-WAVE audio file S on sound device SD. */
582 static void
583 wav_play (struct sound *s, struct sound_device *sd)
585 struct wav_header *header = (struct wav_header *) s->header;
587 /* Let the device choose a suitable device-dependent format
588 for the file. */
589 sd->choose_format (sd, s);
591 /* Configure the device. */
592 sd->sample_size = header->sample_size;
593 sd->sample_rate = header->sample_rate;
594 sd->bps = header->bytes_per_second;
595 sd->channels = header->channels;
596 sd->configure (sd);
598 /* Copy sound data to the device. The WAV file specification is
599 actually more complex. This simple scheme worked with all WAV
600 files I found so far. If someone feels inclined to implement the
601 whole RIFF-WAVE spec, please do. */
602 if (STRINGP (s->data))
603 sd->write (sd, SDATA (s->data) + sizeof *header,
604 SBYTES (s->data) - sizeof *header);
605 else
607 char *buffer;
608 int nbytes;
609 int blksize = sd->period_size ? sd->period_size (sd) : 2048;
610 int data_left = header->data_length;
612 buffer = (char *) alloca (blksize);
613 lseek (s->fd, sizeof *header, SEEK_SET);
614 while (data_left > 0
615 && (nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
617 /* Don't play possible garbage at the end of file */
618 if (data_left < nbytes) nbytes = data_left;
619 data_left -= nbytes;
620 sd->write (sd, buffer, nbytes);
623 if (nbytes < 0)
624 sound_perror ("Error reading sound file");
629 /***********************************************************************
630 Sun Audio (*.au)
631 ***********************************************************************/
633 /* Sun audio file encodings. */
635 enum au_encoding
637 AU_ENCODING_ULAW_8 = 1,
638 AU_ENCODING_8,
639 AU_ENCODING_16,
640 AU_ENCODING_24,
641 AU_ENCODING_32,
642 AU_ENCODING_IEEE32,
643 AU_ENCODING_IEEE64,
644 AU_COMPRESSED = 23,
645 AU_ENCODING_ALAW_8 = 27
649 /* Try to initialize sound file S from S->header. S->header
650 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
651 sound file. If the file is a AU-format file, set up interface
652 functions in S and convert header fields to host byte-order.
653 Value is non-zero if the file is an AU file. */
655 static int
656 au_init (struct sound *s)
658 struct au_header *header = (struct au_header *) s->header;
660 if (s->header_size < sizeof *header
661 || memcmp (s->header, ".snd", 4) != 0)
662 return 0;
664 header->magic_number = be2hl (header->magic_number);
665 header->data_offset = be2hl (header->data_offset);
666 header->data_size = be2hl (header->data_size);
667 header->encoding = be2hl (header->encoding);
668 header->sample_rate = be2hl (header->sample_rate);
669 header->channels = be2hl (header->channels);
671 /* Set up the interface functions for AU. */
672 s->type = SUN_AUDIO;
673 s->play = au_play;
675 return 1;
679 /* Play Sun audio file S on sound device SD. */
681 static void
682 au_play (struct sound *s, struct sound_device *sd)
684 struct au_header *header = (struct au_header *) s->header;
686 sd->sample_size = 0;
687 sd->sample_rate = header->sample_rate;
688 sd->bps = 0;
689 sd->channels = header->channels;
690 sd->choose_format (sd, s);
691 sd->configure (sd);
693 if (STRINGP (s->data))
694 sd->write (sd, SDATA (s->data) + header->data_offset,
695 SBYTES (s->data) - header->data_offset);
696 else
698 int blksize = sd->period_size ? sd->period_size (sd) : 2048;
699 char *buffer;
700 int nbytes;
702 /* Seek */
703 lseek (s->fd, header->data_offset, SEEK_SET);
705 /* Copy sound data to the device. */
706 buffer = (char *) alloca (blksize);
707 while ((nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
708 sd->write (sd, buffer, nbytes);
710 if (nbytes < 0)
711 sound_perror ("Error reading sound file");
716 /***********************************************************************
717 Voxware Driver Interface
718 ***********************************************************************/
720 /* This driver is available on GNU/Linux, and the free BSDs. FreeBSD
721 has a compatible own driver aka Luigi's driver. */
724 /* Open device SD. If SD->file is non-null, open that device,
725 otherwise use a default device name. */
727 static void
728 vox_open (struct sound_device *sd)
730 const char *file;
732 /* Open the sound device. Default is /dev/dsp. */
733 if (sd->file)
734 file = sd->file;
735 else
736 file = DEFAULT_SOUND_DEVICE;
738 sd->fd = emacs_open (file, O_WRONLY, 0);
739 if (sd->fd < 0)
740 sound_perror (file);
744 /* Configure device SD from parameters in it. */
746 static void
747 vox_configure (struct sound_device *sd)
749 int val;
751 xassert (sd->fd >= 0);
753 /* On GNU/Linux, it seems that the device driver doesn't like to be
754 interrupted by a signal. Block the ones we know to cause
755 troubles. */
756 turn_on_atimers (0);
757 #ifdef SIGIO
758 sigblock (sigmask (SIGIO));
759 #endif
761 val = sd->format;
762 if (ioctl (sd->fd, SNDCTL_DSP_SETFMT, &sd->format) < 0
763 || val != sd->format)
764 sound_perror ("Could not set sound format");
766 val = sd->channels != 1;
767 if (ioctl (sd->fd, SNDCTL_DSP_STEREO, &val) < 0
768 || val != (sd->channels != 1))
769 sound_perror ("Could not set stereo/mono");
771 /* I think bps and sampling_rate are the same, but who knows.
772 Check this. and use SND_DSP_SPEED for both. */
773 if (sd->sample_rate > 0)
775 val = sd->sample_rate;
776 if (ioctl (sd->fd, SNDCTL_DSP_SPEED, &sd->sample_rate) < 0)
777 sound_perror ("Could not set sound speed");
778 else if (val != sd->sample_rate)
779 sound_warning ("Could not set sample rate");
782 if (sd->volume > 0)
784 int volume = sd->volume & 0xff;
785 volume |= volume << 8;
786 /* This may fail if there is no mixer. Ignore the failure. */
787 ioctl (sd->fd, SOUND_MIXER_WRITE_PCM, &volume);
790 turn_on_atimers (1);
791 #ifdef SIGIO
792 sigunblock (sigmask (SIGIO));
793 #endif
797 /* Close device SD if it is open. */
799 static void
800 vox_close (struct sound_device *sd)
802 if (sd->fd >= 0)
804 /* On GNU/Linux, it seems that the device driver doesn't like to
805 be interrupted by a signal. Block the ones we know to cause
806 troubles. */
807 #ifdef SIGIO
808 sigblock (sigmask (SIGIO));
809 #endif
810 turn_on_atimers (0);
812 /* Flush sound data, and reset the device. */
813 ioctl (sd->fd, SNDCTL_DSP_SYNC, NULL);
815 turn_on_atimers (1);
816 #ifdef SIGIO
817 sigunblock (sigmask (SIGIO));
818 #endif
820 /* Close the device. */
821 emacs_close (sd->fd);
822 sd->fd = -1;
827 /* Choose device-dependent format for device SD from sound file S. */
829 static void
830 vox_choose_format (struct sound_device *sd, struct sound *s)
832 if (s->type == RIFF)
834 struct wav_header *h = (struct wav_header *) s->header;
835 if (h->precision == 8)
836 sd->format = AFMT_U8;
837 else if (h->precision == 16)
838 sd->format = AFMT_S16_LE;
839 else
840 error ("Unsupported WAV file format");
842 else if (s->type == SUN_AUDIO)
844 struct au_header *header = (struct au_header *) s->header;
845 switch (header->encoding)
847 case AU_ENCODING_ULAW_8:
848 case AU_ENCODING_IEEE32:
849 case AU_ENCODING_IEEE64:
850 sd->format = AFMT_MU_LAW;
851 break;
853 case AU_ENCODING_8:
854 case AU_ENCODING_16:
855 case AU_ENCODING_24:
856 case AU_ENCODING_32:
857 sd->format = AFMT_S16_LE;
858 break;
860 default:
861 error ("Unsupported AU file format");
864 else
865 abort ();
869 /* Initialize device SD. Set up the interface functions in the device
870 structure. */
872 static int
873 vox_init (struct sound_device *sd)
875 const char *file;
876 int fd;
878 /* Open the sound device. Default is /dev/dsp. */
879 if (sd->file)
880 file = sd->file;
881 else
882 file = DEFAULT_SOUND_DEVICE;
883 fd = emacs_open (file, O_WRONLY, 0);
884 if (fd >= 0)
885 emacs_close (fd);
886 else
887 return 0;
889 sd->fd = -1;
890 sd->open = vox_open;
891 sd->close = vox_close;
892 sd->configure = vox_configure;
893 sd->choose_format = vox_choose_format;
894 sd->write = vox_write;
895 sd->period_size = NULL;
897 return 1;
900 /* Write NBYTES bytes from BUFFER to device SD. */
902 static void
903 vox_write (struct sound_device *sd, const char *buffer, int nbytes)
905 int nwritten = emacs_write (sd->fd, buffer, nbytes);
906 if (nwritten < 0)
907 sound_perror ("Error writing to sound device");
910 #ifdef HAVE_ALSA
911 /***********************************************************************
912 ALSA Driver Interface
913 ***********************************************************************/
915 /* This driver is available on GNU/Linux. */
917 static void
918 alsa_sound_perror (const char *msg, int err)
920 error ("%s: %s", msg, snd_strerror (err));
923 struct alsa_params
925 snd_pcm_t *handle;
926 snd_pcm_hw_params_t *hwparams;
927 snd_pcm_sw_params_t *swparams;
928 snd_pcm_uframes_t period_size;
931 /* Open device SD. If SD->file is non-null, open that device,
932 otherwise use a default device name. */
934 static void
935 alsa_open (struct sound_device *sd)
937 const char *file;
938 struct alsa_params *p;
939 int err;
941 /* Open the sound device. Default is "default". */
942 if (sd->file)
943 file = sd->file;
944 else
945 file = DEFAULT_ALSA_SOUND_DEVICE;
947 p = xmalloc (sizeof (*p));
948 p->handle = NULL;
949 p->hwparams = NULL;
950 p->swparams = NULL;
952 sd->fd = -1;
953 sd->data = p;
956 err = snd_pcm_open (&p->handle, file, SND_PCM_STREAM_PLAYBACK, 0);
957 if (err < 0)
958 alsa_sound_perror (file, err);
961 static int
962 alsa_period_size (struct sound_device *sd)
964 struct alsa_params *p = (struct alsa_params *) sd->data;
965 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
966 return p->period_size * (fact > 0 ? fact : 1);
969 static void
970 alsa_configure (struct sound_device *sd)
972 int val, err, dir;
973 unsigned uval;
974 struct alsa_params *p = (struct alsa_params *) sd->data;
975 snd_pcm_uframes_t buffer_size;
977 xassert (p->handle != 0);
979 err = snd_pcm_hw_params_malloc (&p->hwparams);
980 if (err < 0)
981 alsa_sound_perror ("Could not allocate hardware parameter structure", err);
983 err = snd_pcm_sw_params_malloc (&p->swparams);
984 if (err < 0)
985 alsa_sound_perror ("Could not allocate software parameter structure", err);
987 err = snd_pcm_hw_params_any (p->handle, p->hwparams);
988 if (err < 0)
989 alsa_sound_perror ("Could not initialize hardware parameter structure", err);
991 err = snd_pcm_hw_params_set_access (p->handle, p->hwparams,
992 SND_PCM_ACCESS_RW_INTERLEAVED);
993 if (err < 0)
994 alsa_sound_perror ("Could not set access type", err);
996 val = sd->format;
997 err = snd_pcm_hw_params_set_format (p->handle, p->hwparams, val);
998 if (err < 0)
999 alsa_sound_perror ("Could not set sound format", err);
1001 uval = sd->sample_rate;
1002 err = snd_pcm_hw_params_set_rate_near (p->handle, p->hwparams, &uval, 0);
1003 if (err < 0)
1004 alsa_sound_perror ("Could not set sample rate", err);
1006 val = sd->channels;
1007 err = snd_pcm_hw_params_set_channels (p->handle, p->hwparams, val);
1008 if (err < 0)
1009 alsa_sound_perror ("Could not set channel count", err);
1011 err = snd_pcm_hw_params (p->handle, p->hwparams);
1012 if (err < 0)
1013 alsa_sound_perror ("Could not set parameters", err);
1016 err = snd_pcm_hw_params_get_period_size (p->hwparams, &p->period_size, &dir);
1017 if (err < 0)
1018 alsa_sound_perror ("Unable to get period size for playback", err);
1020 err = snd_pcm_hw_params_get_buffer_size (p->hwparams, &buffer_size);
1021 if (err < 0)
1022 alsa_sound_perror("Unable to get buffer size for playback", err);
1024 err = snd_pcm_sw_params_current (p->handle, p->swparams);
1025 if (err < 0)
1026 alsa_sound_perror ("Unable to determine current swparams for playback",
1027 err);
1029 /* Start the transfer when the buffer is almost full */
1030 err = snd_pcm_sw_params_set_start_threshold (p->handle, p->swparams,
1031 (buffer_size / p->period_size)
1032 * p->period_size);
1033 if (err < 0)
1034 alsa_sound_perror ("Unable to set start threshold mode for playback", err);
1036 /* Allow the transfer when at least period_size samples can be processed */
1037 err = snd_pcm_sw_params_set_avail_min (p->handle, p->swparams, p->period_size);
1038 if (err < 0)
1039 alsa_sound_perror ("Unable to set avail min for playback", err);
1041 err = snd_pcm_sw_params (p->handle, p->swparams);
1042 if (err < 0)
1043 alsa_sound_perror ("Unable to set sw params for playback\n", err);
1045 snd_pcm_hw_params_free (p->hwparams);
1046 p->hwparams = NULL;
1047 snd_pcm_sw_params_free (p->swparams);
1048 p->swparams = NULL;
1050 err = snd_pcm_prepare (p->handle);
1051 if (err < 0)
1052 alsa_sound_perror ("Could not prepare audio interface for use", err);
1054 if (sd->volume > 0)
1056 int chn;
1057 snd_mixer_t *handle;
1058 snd_mixer_elem_t *e;
1059 const char *file = sd->file ? sd->file : DEFAULT_ALSA_SOUND_DEVICE;
1061 if (snd_mixer_open (&handle, 0) >= 0)
1063 if (snd_mixer_attach (handle, file) >= 0
1064 && snd_mixer_load (handle) >= 0
1065 && snd_mixer_selem_register (handle, NULL, NULL) >= 0)
1066 for (e = snd_mixer_first_elem (handle);
1068 e = snd_mixer_elem_next (e))
1070 if (snd_mixer_selem_has_playback_volume (e))
1072 long pmin, pmax, vol;
1073 snd_mixer_selem_get_playback_volume_range (e, &pmin, &pmax);
1074 vol = pmin + (sd->volume * (pmax - pmin)) / 100;
1076 for (chn = 0; chn <= SND_MIXER_SCHN_LAST; chn++)
1077 snd_mixer_selem_set_playback_volume (e, chn, vol);
1080 snd_mixer_close(handle);
1086 /* Close device SD if it is open. */
1088 static void
1089 alsa_close (struct sound_device *sd)
1091 struct alsa_params *p = (struct alsa_params *) sd->data;
1092 if (p)
1094 if (p->hwparams)
1095 snd_pcm_hw_params_free (p->hwparams);
1096 if (p->swparams)
1097 snd_pcm_sw_params_free (p->swparams);
1098 if (p->handle)
1100 snd_pcm_drain (p->handle);
1101 snd_pcm_close (p->handle);
1103 free (p);
1107 /* Choose device-dependent format for device SD from sound file S. */
1109 static void
1110 alsa_choose_format (struct sound_device *sd, struct sound *s)
1112 struct alsa_params *p = (struct alsa_params *) sd->data;
1113 if (s->type == RIFF)
1115 struct wav_header *h = (struct wav_header *) s->header;
1116 if (h->precision == 8)
1117 sd->format = SND_PCM_FORMAT_U8;
1118 else if (h->precision == 16)
1119 sd->format = SND_PCM_FORMAT_S16_LE;
1120 else
1121 error ("Unsupported WAV file format");
1123 else if (s->type == SUN_AUDIO)
1125 struct au_header *header = (struct au_header *) s->header;
1126 switch (header->encoding)
1128 case AU_ENCODING_ULAW_8:
1129 sd->format = SND_PCM_FORMAT_MU_LAW;
1130 break;
1131 case AU_ENCODING_ALAW_8:
1132 sd->format = SND_PCM_FORMAT_A_LAW;
1133 break;
1134 case AU_ENCODING_IEEE32:
1135 sd->format = SND_PCM_FORMAT_FLOAT_BE;
1136 break;
1137 case AU_ENCODING_IEEE64:
1138 sd->format = SND_PCM_FORMAT_FLOAT64_BE;
1139 break;
1140 case AU_ENCODING_8:
1141 sd->format = SND_PCM_FORMAT_S8;
1142 break;
1143 case AU_ENCODING_16:
1144 sd->format = SND_PCM_FORMAT_S16_BE;
1145 break;
1146 case AU_ENCODING_24:
1147 sd->format = SND_PCM_FORMAT_S24_BE;
1148 break;
1149 case AU_ENCODING_32:
1150 sd->format = SND_PCM_FORMAT_S32_BE;
1151 break;
1153 default:
1154 error ("Unsupported AU file format");
1157 else
1158 abort ();
1162 /* Write NBYTES bytes from BUFFER to device SD. */
1164 static void
1165 alsa_write (struct sound_device *sd, const char *buffer, int nbytes)
1167 struct alsa_params *p = (struct alsa_params *) sd->data;
1169 /* The the third parameter to snd_pcm_writei is frames, not bytes. */
1170 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
1171 int nwritten = 0;
1172 int err;
1174 while (nwritten < nbytes)
1176 snd_pcm_uframes_t frames = (nbytes - nwritten)/fact;
1177 if (frames == 0) break;
1179 err = snd_pcm_writei (p->handle, buffer + nwritten, frames);
1180 if (err < 0)
1182 if (err == -EPIPE)
1183 { /* under-run */
1184 err = snd_pcm_prepare (p->handle);
1185 if (err < 0)
1186 alsa_sound_perror ("Can't recover from underrun, prepare failed",
1187 err);
1189 else if (err == -ESTRPIPE)
1191 while ((err = snd_pcm_resume (p->handle)) == -EAGAIN)
1192 sleep(1); /* wait until the suspend flag is released */
1193 if (err < 0)
1195 err = snd_pcm_prepare (p->handle);
1196 if (err < 0)
1197 alsa_sound_perror ("Can't recover from suspend, "
1198 "prepare failed",
1199 err);
1202 else
1203 alsa_sound_perror ("Error writing to sound device", err);
1206 else
1207 nwritten += err * fact;
1211 static void
1212 snd_error_quiet (const char *file, int line, const char *function, int err,
1213 const char *fmt)
1217 /* Initialize device SD. Set up the interface functions in the device
1218 structure. */
1220 static int
1221 alsa_init (struct sound_device *sd)
1223 const char *file;
1224 snd_pcm_t *handle;
1225 int err;
1227 /* Open the sound device. Default is "default". */
1228 if (sd->file)
1229 file = sd->file;
1230 else
1231 file = DEFAULT_ALSA_SOUND_DEVICE;
1233 snd_lib_error_set_handler ((snd_lib_error_handler_t) snd_error_quiet);
1234 err = snd_pcm_open (&handle, file, SND_PCM_STREAM_PLAYBACK, 0);
1235 snd_lib_error_set_handler (NULL);
1236 if (err < 0)
1237 return 0;
1238 snd_pcm_close (handle);
1240 sd->fd = -1;
1241 sd->open = alsa_open;
1242 sd->close = alsa_close;
1243 sd->configure = alsa_configure;
1244 sd->choose_format = alsa_choose_format;
1245 sd->write = alsa_write;
1246 sd->period_size = alsa_period_size;
1248 return 1;
1251 #endif /* HAVE_ALSA */
1254 /* END: Non Windows functions */
1255 #else /* WINDOWSNT */
1257 /* BEGIN: Windows specific functions */
1259 #define SOUND_WARNING(fun, error, text) \
1261 char buf[1024]; \
1262 char err_string[MAXERRORLENGTH]; \
1263 fun (error, err_string, sizeof (err_string)); \
1264 _snprintf (buf, sizeof (buf), "%s\nError: %s", \
1265 text, err_string); \
1266 sound_warning (buf); \
1269 static int
1270 do_play_sound (const char *psz_file, unsigned long ui_volume)
1272 int i_result = 0;
1273 MCIERROR mci_error = 0;
1274 char sz_cmd_buf[520] = {0};
1275 char sz_ret_buf[520] = {0};
1276 MMRESULT mm_result = MMSYSERR_NOERROR;
1277 unsigned long ui_volume_org = 0;
1278 BOOL b_reset_volume = FALSE;
1280 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1281 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1282 sprintf (sz_cmd_buf,
1283 "open \"%s\" alias GNUEmacs_PlaySound_Device wait",
1284 psz_file);
1285 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1286 if (mci_error != 0)
1288 SOUND_WARNING (mciGetErrorString, mci_error,
1289 "The open mciSendString command failed to open "
1290 "the specified sound file.");
1291 i_result = (int) mci_error;
1292 return i_result;
1294 if ((ui_volume > 0) && (ui_volume != UINT_MAX))
1296 mm_result = waveOutGetVolume ((HWAVEOUT) WAVE_MAPPER, &ui_volume_org);
1297 if (mm_result == MMSYSERR_NOERROR)
1299 b_reset_volume = TRUE;
1300 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume);
1301 if (mm_result != MMSYSERR_NOERROR)
1303 SOUND_WARNING (waveOutGetErrorText, mm_result,
1304 "waveOutSetVolume failed to set the volume level "
1305 "of the WAVE_MAPPER device.\n"
1306 "As a result, the user selected volume level will "
1307 "not be used.");
1310 else
1312 SOUND_WARNING (waveOutGetErrorText, mm_result,
1313 "waveOutGetVolume failed to obtain the original "
1314 "volume level of the WAVE_MAPPER device.\n"
1315 "As a result, the user selected volume level will "
1316 "not be used.");
1319 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1320 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1321 strcpy (sz_cmd_buf, "play GNUEmacs_PlaySound_Device wait");
1322 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1323 if (mci_error != 0)
1325 SOUND_WARNING (mciGetErrorString, mci_error,
1326 "The play mciSendString command failed to play the "
1327 "opened sound file.");
1328 i_result = (int) mci_error;
1330 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1331 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1332 strcpy (sz_cmd_buf, "close GNUEmacs_PlaySound_Device wait");
1333 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1334 if (b_reset_volume == TRUE)
1336 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume_org);
1337 if (mm_result != MMSYSERR_NOERROR)
1339 SOUND_WARNING (waveOutGetErrorText, mm_result,
1340 "waveOutSetVolume failed to reset the original volume "
1341 "level of the WAVE_MAPPER device.");
1344 return i_result;
1347 /* END: Windows specific functions */
1349 #endif /* WINDOWSNT */
1351 DEFUN ("play-sound-internal", Fplay_sound_internal, Splay_sound_internal, 1, 1, 0,
1352 doc: /* Play sound SOUND.
1354 Internal use only, use `play-sound' instead. */)
1355 (Lisp_Object sound)
1357 Lisp_Object attrs[SOUND_ATTR_SENTINEL];
1358 int count = SPECPDL_INDEX ();
1360 #ifndef WINDOWSNT
1361 Lisp_Object file;
1362 struct gcpro gcpro1, gcpro2;
1363 Lisp_Object args[2];
1364 #else /* WINDOWSNT */
1365 int len = 0;
1366 Lisp_Object lo_file = {0};
1367 char * psz_file = NULL;
1368 unsigned long ui_volume_tmp = UINT_MAX;
1369 unsigned long ui_volume = UINT_MAX;
1370 int i_result = 0;
1371 #endif /* WINDOWSNT */
1373 /* Parse the sound specification. Give up if it is invalid. */
1374 if (!parse_sound (sound, attrs))
1375 error ("Invalid sound specification");
1377 #ifndef WINDOWSNT
1378 file = Qnil;
1379 GCPRO2 (sound, file);
1380 current_sound_device = (struct sound_device *) xmalloc (sizeof (struct sound_device));
1381 memset (current_sound_device, 0, sizeof (struct sound_device));
1382 current_sound = (struct sound *) xmalloc (sizeof (struct sound));
1383 memset (current_sound, 0, sizeof (struct sound));
1384 record_unwind_protect (sound_cleanup, Qnil);
1385 current_sound->header = (char *) alloca (MAX_SOUND_HEADER_BYTES);
1387 if (STRINGP (attrs[SOUND_FILE]))
1389 /* Open the sound file. */
1390 current_sound->fd = openp (Fcons (Vdata_directory, Qnil),
1391 attrs[SOUND_FILE], Qnil, &file, Qnil);
1392 if (current_sound->fd < 0)
1393 sound_perror ("Could not open sound file");
1395 /* Read the first bytes from the file. */
1396 current_sound->header_size
1397 = emacs_read (current_sound->fd, current_sound->header,
1398 MAX_SOUND_HEADER_BYTES);
1399 if (current_sound->header_size < 0)
1400 sound_perror ("Invalid sound file header");
1402 else
1404 current_sound->data = attrs[SOUND_DATA];
1405 current_sound->header_size = min (MAX_SOUND_HEADER_BYTES, SBYTES (current_sound->data));
1406 memcpy (current_sound->header, SDATA (current_sound->data),
1407 current_sound->header_size);
1410 /* Find out the type of sound. Give up if we can't tell. */
1411 find_sound_type (current_sound);
1413 /* Set up a device. */
1414 if (STRINGP (attrs[SOUND_DEVICE]))
1416 int len = SCHARS (attrs[SOUND_DEVICE]);
1417 current_sound_device->file = (char *) alloca (len + 1);
1418 strcpy (current_sound_device->file, SDATA (attrs[SOUND_DEVICE]));
1421 if (INTEGERP (attrs[SOUND_VOLUME]))
1422 current_sound_device->volume = XFASTINT (attrs[SOUND_VOLUME]);
1423 else if (FLOATP (attrs[SOUND_VOLUME]))
1424 current_sound_device->volume = XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1426 args[0] = Qplay_sound_functions;
1427 args[1] = sound;
1428 Frun_hook_with_args (2, args);
1430 #ifdef HAVE_ALSA
1431 if (!alsa_init (current_sound_device))
1432 #endif
1433 if (!vox_init (current_sound_device))
1434 error ("No usable sound device driver found");
1436 /* Open the device. */
1437 current_sound_device->open (current_sound_device);
1439 /* Play the sound. */
1440 current_sound->play (current_sound, current_sound_device);
1442 /* Clean up. */
1443 UNGCPRO;
1445 #else /* WINDOWSNT */
1447 lo_file = Fexpand_file_name (attrs[SOUND_FILE], Qnil);
1448 len = XSTRING (lo_file)->size;
1449 psz_file = (char *) alloca (len + 1);
1450 strcpy (psz_file, XSTRING (lo_file)->data);
1451 if (INTEGERP (attrs[SOUND_VOLUME]))
1453 ui_volume_tmp = XFASTINT (attrs[SOUND_VOLUME]);
1455 else if (FLOATP (attrs[SOUND_VOLUME]))
1457 ui_volume_tmp = (unsigned long) XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1460 Based on some experiments I have conducted, a value of 100 or less
1461 for the sound volume is much too low. You cannot even hear it.
1462 A value of UINT_MAX indicates that you wish for the sound to played
1463 at the maximum possible volume. A value of UINT_MAX/2 plays the
1464 sound at 50% maximum volume. Therefore the value passed to do_play_sound
1465 (and thus to waveOutSetVolume) must be some fraction of UINT_MAX.
1466 The following code adjusts the user specified volume level appropriately.
1468 if ((ui_volume_tmp > 0) && (ui_volume_tmp <= 100))
1470 ui_volume = ui_volume_tmp * (UINT_MAX / 100);
1472 i_result = do_play_sound (psz_file, ui_volume);
1474 #endif /* WINDOWSNT */
1476 unbind_to (count, Qnil);
1477 return Qnil;
1480 /***********************************************************************
1481 Initialization
1482 ***********************************************************************/
1484 void
1485 syms_of_sound (void)
1487 QCdevice = intern_c_string(":device");
1488 staticpro (&QCdevice);
1489 QCvolume = intern_c_string (":volume");
1490 staticpro (&QCvolume);
1491 Qsound = intern_c_string ("sound");
1492 staticpro (&Qsound);
1493 Qplay_sound_functions = intern_c_string ("play-sound-functions");
1494 staticpro (&Qplay_sound_functions);
1496 defsubr (&Splay_sound_internal);
1500 void
1501 init_sound (void)
1505 #endif /* HAVE_SOUND */
1507 /* arch-tag: dd850ad8-0433-4e2c-9cba-b7aeeccc0dbd
1508 (do not change this comment) */