(url-open-stream): Really use asynchronous connections (accidentally
[emacs.git] / src / sound.c
blob6f955a7d69141cfe875b1440959caac0b1fb5aae
1 /* sound.c -- sound support.
2 Copyright (C) 1998, 1999, 2001, 2002, 2003, 2004,
3 2005, 2006 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 2, or (at your option)
10 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; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA. */
22 /* Written by Gerd Moellmann <gerd@gnu.org>. Tested with Luigi's
23 driver on FreeBSD 2.2.7 with a SoundBlaster 16. */
26 Modified by Ben Key <Bkey1@tampabay.rr.com> to add a partial
27 implementation of the play-sound specification for Windows.
29 Notes:
30 In the Windows implementation of play-sound-internal only the
31 :file and :volume keywords are supported. The :device keyword,
32 if present, is ignored. The :data keyword, if present, will
33 cause an error to be generated.
35 The Windows implementation of play-sound is implemented via the
36 Win32 API functions mciSendString, waveOutGetVolume, and
37 waveOutSetVolume which are exported by Winmm.dll.
40 #include <config.h>
42 #if defined HAVE_SOUND
44 /* BEGIN: Common Includes */
45 #include <fcntl.h>
46 #include <unistd.h>
47 #include <sys/types.h>
48 #include <errno.h>
49 #include "lisp.h"
50 #include "dispextern.h"
51 #include "atimer.h"
52 #include <signal.h>
53 #include "syssignal.h"
54 /* END: Common Includes */
57 /* BEGIN: Non Windows Includes */
58 #ifndef WINDOWSNT
60 #ifndef MSDOS
61 #include <sys/ioctl.h>
62 #endif
64 /* FreeBSD has machine/soundcard.h. Voxware sound driver docs mention
65 sys/soundcard.h. So, let's try whatever's there. */
67 #ifdef HAVE_MACHINE_SOUNDCARD_H
68 #include <machine/soundcard.h>
69 #endif
70 #ifdef HAVE_SYS_SOUNDCARD_H
71 #include <sys/soundcard.h>
72 #endif
73 #ifdef HAVE_SOUNDCARD_H
74 #include <soundcard.h>
75 #endif
76 #ifdef HAVE_ALSA
77 #include <asoundlib.h>
78 #endif
80 /* END: Non Windows Includes */
82 #else /* WINDOWSNT */
84 /* BEGIN: Windows Specific Includes */
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <string.h>
88 #include <limits.h>
89 #include <windows.h>
90 #include <mmsystem.h>
91 /* END: Windows Specific Includes */
93 #endif /* WINDOWSNT */
95 /* BEGIN: Common Definitions */
96 #define abs(X) ((X) < 0 ? -(X) : (X))
98 /* Symbols. */
100 extern Lisp_Object QCfile, QCdata;
101 Lisp_Object QCvolume, QCdevice;
102 Lisp_Object Qsound;
103 Lisp_Object Qplay_sound_functions;
105 /* Indices of attributes in a sound attributes vector. */
107 enum sound_attr
109 SOUND_FILE,
110 SOUND_DATA,
111 SOUND_DEVICE,
112 SOUND_VOLUME,
113 SOUND_ATTR_SENTINEL
116 static void alsa_sound_perror P_ ((char *, int)) NO_RETURN;
117 static void sound_perror P_ ((char *)) NO_RETURN;
118 static void sound_warning P_ ((char *));
119 static int parse_sound P_ ((Lisp_Object, Lisp_Object *));
121 /* END: Common Definitions */
123 /* BEGIN: Non Windows Definitions */
124 #ifndef WINDOWSNT
126 #ifndef DEFAULT_SOUND_DEVICE
127 #define DEFAULT_SOUND_DEVICE "/dev/dsp"
128 #endif
129 #ifndef DEFAULT_ALSA_SOUND_DEVICE
130 #define DEFAULT_ALSA_SOUND_DEVICE "default"
131 #endif
134 /* Structure forward declarations. */
136 struct sound;
137 struct sound_device;
139 /* The file header of RIFF-WAVE files (*.wav). Files are always in
140 little-endian byte-order. */
142 struct wav_header
144 u_int32_t magic;
145 u_int32_t length;
146 u_int32_t chunk_type;
147 u_int32_t chunk_format;
148 u_int32_t chunk_length;
149 u_int16_t format;
150 u_int16_t channels;
151 u_int32_t sample_rate;
152 u_int32_t bytes_per_second;
153 u_int16_t sample_size;
154 u_int16_t precision;
155 u_int32_t chunk_data;
156 u_int32_t data_length;
159 /* The file header of Sun adio files (*.au). Files are always in
160 big-endian byte-order. */
162 struct au_header
164 /* ASCII ".snd" */
165 u_int32_t magic_number;
167 /* Offset of data part from start of file. Minimum value is 24. */
168 u_int32_t data_offset;
170 /* Size of data part, 0xffffffff if unknown. */
171 u_int32_t data_size;
173 /* Data encoding format.
174 1 8-bit ISDN u-law
175 2 8-bit linear PCM (REF-PCM)
176 3 16-bit linear PCM
177 4 24-bit linear PCM
178 5 32-bit linear PCM
179 6 32-bit IEEE floating-point
180 7 64-bit IEEE floating-point
181 23 8-bit u-law compressed using CCITT 0.721 ADPCM voice data
182 encoding scheme. */
183 u_int32_t encoding;
185 /* Number of samples per second. */
186 u_int32_t sample_rate;
188 /* Number of interleaved channels. */
189 u_int32_t channels;
192 /* Maximum of all sound file headers sizes. */
194 #define MAX_SOUND_HEADER_BYTES \
195 max (sizeof (struct wav_header), sizeof (struct au_header))
197 /* Interface structure for sound devices. */
199 struct sound_device
201 /* The name of the device or null meaning use a default device name. */
202 char *file;
204 /* File descriptor of the device. */
205 int fd;
207 /* Device-dependent format. */
208 int format;
210 /* Volume (0..100). Zero means unspecified. */
211 int volume;
213 /* Sample size. */
214 int sample_size;
216 /* Sample rate. */
217 int sample_rate;
219 /* Bytes per second. */
220 int bps;
222 /* 1 = mono, 2 = stereo, 0 = don't set. */
223 int channels;
225 /* Open device SD. */
226 void (* open) P_ ((struct sound_device *sd));
228 /* Close device SD. */
229 void (* close) P_ ((struct sound_device *sd));
231 /* Configure SD accoring to device-dependent parameters. */
232 void (* configure) P_ ((struct sound_device *device));
234 /* Choose a device-dependent format for outputting sound S. */
235 void (* choose_format) P_ ((struct sound_device *sd,
236 struct sound *s));
238 /* Return a preferred data size in bytes to be sent to write (below)
239 each time. 2048 is used if this is NULL. */
240 int (* period_size) P_ ((struct sound_device *sd));
242 /* Write NYBTES bytes from BUFFER to device SD. */
243 void (* write) P_ ((struct sound_device *sd, const char *buffer,
244 int nbytes));
246 /* A place for devices to store additional data. */
247 void *data;
250 /* An enumerator for each supported sound file type. */
252 enum sound_type
254 RIFF,
255 SUN_AUDIO
258 /* Interface structure for sound files. */
260 struct sound
262 /* The type of the file. */
263 enum sound_type type;
265 /* File descriptor of a sound file. */
266 int fd;
268 /* Pointer to sound file header. This contains header_size bytes
269 read from the start of a sound file. */
270 char *header;
272 /* Number of bytes raed from sound file. This is always <=
273 MAX_SOUND_HEADER_BYTES. */
274 int header_size;
276 /* Sound data, if a string. */
277 Lisp_Object data;
279 /* Play sound file S on device SD. */
280 void (* play) P_ ((struct sound *s, struct sound_device *sd));
283 /* These are set during `play-sound-internal' so that sound_cleanup has
284 access to them. */
286 struct sound_device *current_sound_device;
287 struct sound *current_sound;
289 /* Function prototypes. */
291 static void vox_open P_ ((struct sound_device *));
292 static void vox_configure P_ ((struct sound_device *));
293 static void vox_close P_ ((struct sound_device *sd));
294 static void vox_choose_format P_ ((struct sound_device *, struct sound *));
295 static int vox_init P_ ((struct sound_device *));
296 static void vox_write P_ ((struct sound_device *, const char *, int));
297 static void find_sound_type P_ ((struct sound *));
298 static u_int32_t le2hl P_ ((u_int32_t));
299 static u_int16_t le2hs P_ ((u_int16_t));
300 static u_int32_t be2hl P_ ((u_int32_t));
301 static int wav_init P_ ((struct sound *));
302 static void wav_play P_ ((struct sound *, struct sound_device *));
303 static int au_init P_ ((struct sound *));
304 static void au_play P_ ((struct sound *, struct sound_device *));
306 #if 0 /* Currently not used. */
307 static u_int16_t be2hs P_ ((u_int16_t));
308 #endif
310 /* END: Non Windows Definitions */
311 #else /* WINDOWSNT */
313 /* BEGIN: Windows Specific Definitions */
314 static int do_play_sound P_ ((const char *, unsigned long));
316 END: Windows Specific Definitions */
317 #endif /* WINDOWSNT */
320 /***********************************************************************
321 General
322 ***********************************************************************/
324 /* BEGIN: Common functions */
326 /* Like perror, but signals an error. */
328 static void
329 sound_perror (msg)
330 char *msg;
332 int saved_errno = errno;
334 turn_on_atimers (1);
335 #ifdef SIGIO
336 sigunblock (sigmask (SIGIO));
337 #endif
338 if (saved_errno != 0)
339 error ("%s: %s", msg, strerror (saved_errno));
340 else
341 error ("%s", msg);
345 /* Display a warning message. */
347 static void
348 sound_warning (msg)
349 char *msg;
351 message (msg);
355 /* Parse sound specification SOUND, and fill ATTRS with what is
356 found. Value is non-zero if SOUND Is a valid sound specification.
357 A valid sound specification is a list starting with the symbol
358 `sound'. The rest of the list is a property list which may
359 contain the following key/value pairs:
361 - `:file FILE'
363 FILE is the sound file to play. If it isn't an absolute name,
364 it's searched under `data-directory'.
366 - `:data DATA'
368 DATA is a string containing sound data. Either :file or :data
369 may be present, but not both.
371 - `:device DEVICE'
373 DEVICE is the name of the device to play on, e.g. "/dev/dsp2".
374 If not specified, a default device is used.
376 - `:volume VOL'
378 VOL must be an integer in the range [0, 100], or a float in the
379 range [0, 1]. */
381 static int
382 parse_sound (sound, attrs)
383 Lisp_Object sound;
384 Lisp_Object *attrs;
386 /* SOUND must be a list starting with the symbol `sound'. */
387 if (!CONSP (sound) || !EQ (XCAR (sound), Qsound))
388 return 0;
390 sound = XCDR (sound);
391 attrs[SOUND_FILE] = Fplist_get (sound, QCfile);
392 attrs[SOUND_DATA] = Fplist_get (sound, QCdata);
393 attrs[SOUND_DEVICE] = Fplist_get (sound, QCdevice);
394 attrs[SOUND_VOLUME] = Fplist_get (sound, QCvolume);
396 #ifndef WINDOWSNT
397 /* File name or data must be specified. */
398 if (!STRINGP (attrs[SOUND_FILE])
399 && !STRINGP (attrs[SOUND_DATA]))
400 return 0;
401 #else /* WINDOWSNT */
403 Data is not supported in Windows. Therefore a
404 File name MUST be supplied.
406 if (!STRINGP (attrs[SOUND_FILE]))
408 return 0;
410 #endif /* WINDOWSNT */
412 /* Volume must be in the range 0..100 or unspecified. */
413 if (!NILP (attrs[SOUND_VOLUME]))
415 if (INTEGERP (attrs[SOUND_VOLUME]))
417 if (XINT (attrs[SOUND_VOLUME]) < 0
418 || XINT (attrs[SOUND_VOLUME]) > 100)
419 return 0;
421 else if (FLOATP (attrs[SOUND_VOLUME]))
423 if (XFLOAT_DATA (attrs[SOUND_VOLUME]) < 0
424 || XFLOAT_DATA (attrs[SOUND_VOLUME]) > 1)
425 return 0;
427 else
428 return 0;
431 #ifndef WINDOWSNT
432 /* Device must be a string or unspecified. */
433 if (!NILP (attrs[SOUND_DEVICE])
434 && !STRINGP (attrs[SOUND_DEVICE]))
435 return 0;
436 #endif /* WINDOWSNT */
438 Since device is ignored in Windows, it does not matter
439 what it is.
441 return 1;
444 /* END: Common functions */
446 /* BEGIN: Non Windows functions */
447 #ifndef WINDOWSNT
449 /* Find out the type of the sound file whose file descriptor is FD.
450 S is the sound file structure to fill in. */
452 static void
453 find_sound_type (s)
454 struct sound *s;
456 if (!wav_init (s) && !au_init (s))
457 error ("Unknown sound format");
461 /* Function installed by play-sound-internal with record_unwind_protect. */
463 static Lisp_Object
464 sound_cleanup (arg)
465 Lisp_Object arg;
467 if (current_sound_device->close)
468 current_sound_device->close (current_sound_device);
469 if (current_sound->fd > 0)
470 emacs_close (current_sound->fd);
471 free (current_sound_device);
472 free (current_sound);
474 return Qnil;
477 /***********************************************************************
478 Byte-order Conversion
479 ***********************************************************************/
481 /* Convert 32-bit value VALUE which is in little-endian byte-order
482 to host byte-order. */
484 static u_int32_t
485 le2hl (value)
486 u_int32_t value;
488 #ifdef WORDS_BIG_ENDIAN
489 unsigned char *p = (unsigned char *) &value;
490 value = p[0] + (p[1] << 8) + (p[2] << 16) + (p[3] << 24);
491 #endif
492 return value;
496 /* Convert 16-bit value VALUE which is in little-endian byte-order
497 to host byte-order. */
499 static u_int16_t
500 le2hs (value)
501 u_int16_t value;
503 #ifdef WORDS_BIG_ENDIAN
504 unsigned char *p = (unsigned char *) &value;
505 value = p[0] + (p[1] << 8);
506 #endif
507 return value;
511 /* Convert 32-bit value VALUE which is in big-endian byte-order
512 to host byte-order. */
514 static u_int32_t
515 be2hl (value)
516 u_int32_t value;
518 #ifndef WORDS_BIG_ENDIAN
519 unsigned char *p = (unsigned char *) &value;
520 value = p[3] + (p[2] << 8) + (p[1] << 16) + (p[0] << 24);
521 #endif
522 return value;
526 #if 0 /* Currently not used. */
528 /* Convert 16-bit value VALUE which is in big-endian byte-order
529 to host byte-order. */
531 static u_int16_t
532 be2hs (value)
533 u_int16_t value;
535 #ifndef WORDS_BIG_ENDIAN
536 unsigned char *p = (unsigned char *) &value;
537 value = p[1] + (p[0] << 8);
538 #endif
539 return value;
542 #endif /* 0 */
544 /***********************************************************************
545 RIFF-WAVE (*.wav)
546 ***********************************************************************/
548 /* Try to initialize sound file S from S->header. S->header
549 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
550 sound file. If the file is a WAV-format file, set up interface
551 functions in S and convert header fields to host byte-order.
552 Value is non-zero if the file is a WAV file. */
554 static int
555 wav_init (s)
556 struct sound *s;
558 struct wav_header *header = (struct wav_header *) s->header;
560 if (s->header_size < sizeof *header
561 || bcmp (s->header, "RIFF", 4) != 0)
562 return 0;
564 /* WAV files are in little-endian order. Convert the header
565 if on a big-endian machine. */
566 header->magic = le2hl (header->magic);
567 header->length = le2hl (header->length);
568 header->chunk_type = le2hl (header->chunk_type);
569 header->chunk_format = le2hl (header->chunk_format);
570 header->chunk_length = le2hl (header->chunk_length);
571 header->format = le2hs (header->format);
572 header->channels = le2hs (header->channels);
573 header->sample_rate = le2hl (header->sample_rate);
574 header->bytes_per_second = le2hl (header->bytes_per_second);
575 header->sample_size = le2hs (header->sample_size);
576 header->precision = le2hs (header->precision);
577 header->chunk_data = le2hl (header->chunk_data);
578 header->data_length = le2hl (header->data_length);
580 /* Set up the interface functions for WAV. */
581 s->type = RIFF;
582 s->play = wav_play;
584 return 1;
588 /* Play RIFF-WAVE audio file S on sound device SD. */
590 static void
591 wav_play (s, sd)
592 struct sound *s;
593 struct sound_device *sd;
595 struct wav_header *header = (struct wav_header *) s->header;
597 /* Let the device choose a suitable device-dependent format
598 for the file. */
599 sd->choose_format (sd, s);
601 /* Configure the device. */
602 sd->sample_size = header->sample_size;
603 sd->sample_rate = header->sample_rate;
604 sd->bps = header->bytes_per_second;
605 sd->channels = header->channels;
606 sd->configure (sd);
608 /* Copy sound data to the device. The WAV file specification is
609 actually more complex. This simple scheme worked with all WAV
610 files I found so far. If someone feels inclined to implement the
611 whole RIFF-WAVE spec, please do. */
612 if (STRINGP (s->data))
613 sd->write (sd, SDATA (s->data) + sizeof *header,
614 SBYTES (s->data) - sizeof *header);
615 else
617 char *buffer;
618 int nbytes;
619 int blksize = sd->period_size ? sd->period_size (sd) : 2048;
621 buffer = (char *) alloca (blksize);
622 lseek (s->fd, sizeof *header, SEEK_SET);
624 while ((nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
625 sd->write (sd, buffer, nbytes);
627 if (nbytes < 0)
628 sound_perror ("Error reading sound file");
633 /***********************************************************************
634 Sun Audio (*.au)
635 ***********************************************************************/
637 /* Sun audio file encodings. */
639 enum au_encoding
641 AU_ENCODING_ULAW_8 = 1,
642 AU_ENCODING_8,
643 AU_ENCODING_16,
644 AU_ENCODING_24,
645 AU_ENCODING_32,
646 AU_ENCODING_IEEE32,
647 AU_ENCODING_IEEE64,
648 AU_COMPRESSED = 23,
649 AU_ENCODING_ALAW_8 = 27
653 /* Try to initialize sound file S from S->header. S->header
654 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
655 sound file. If the file is a AU-format file, set up interface
656 functions in S and convert header fields to host byte-order.
657 Value is non-zero if the file is an AU file. */
659 static int
660 au_init (s)
661 struct sound *s;
663 struct au_header *header = (struct au_header *) s->header;
665 if (s->header_size < sizeof *header
666 || bcmp (s->header, ".snd", 4) != 0)
667 return 0;
669 header->magic_number = be2hl (header->magic_number);
670 header->data_offset = be2hl (header->data_offset);
671 header->data_size = be2hl (header->data_size);
672 header->encoding = be2hl (header->encoding);
673 header->sample_rate = be2hl (header->sample_rate);
674 header->channels = be2hl (header->channels);
676 /* Set up the interface functions for AU. */
677 s->type = SUN_AUDIO;
678 s->play = au_play;
680 return 1;
684 /* Play Sun audio file S on sound device SD. */
686 static void
687 au_play (s, sd)
688 struct sound *s;
689 struct sound_device *sd;
691 struct au_header *header = (struct au_header *) s->header;
693 sd->sample_size = 0;
694 sd->sample_rate = header->sample_rate;
695 sd->bps = 0;
696 sd->channels = header->channels;
697 sd->choose_format (sd, s);
698 sd->configure (sd);
700 if (STRINGP (s->data))
701 sd->write (sd, SDATA (s->data) + header->data_offset,
702 SBYTES (s->data) - header->data_offset);
703 else
705 int blksize = sd->period_size ? sd->period_size (sd) : 2048;
706 char *buffer;
707 int nbytes;
709 /* Seek */
710 lseek (s->fd, header->data_offset, SEEK_SET);
712 /* Copy sound data to the device. */
713 buffer = (char *) alloca (blksize);
714 while ((nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
715 sd->write (sd, buffer, nbytes);
717 if (nbytes < 0)
718 sound_perror ("Error reading sound file");
723 /***********************************************************************
724 Voxware Driver Interface
725 ***********************************************************************/
727 /* This driver is available on GNU/Linux, and the free BSDs. FreeBSD
728 has a compatible own driver aka Luigi's driver. */
731 /* Open device SD. If SD->file is non-null, open that device,
732 otherwise use a default device name. */
734 static void
735 vox_open (sd)
736 struct sound_device *sd;
738 char *file;
740 /* Open the sound device. Default is /dev/dsp. */
741 if (sd->file)
742 file = sd->file;
743 else
744 file = DEFAULT_SOUND_DEVICE;
746 sd->fd = emacs_open (file, O_WRONLY, 0);
747 if (sd->fd < 0)
748 sound_perror (file);
752 /* Configure device SD from parameters in it. */
754 static void
755 vox_configure (sd)
756 struct sound_device *sd;
758 int val;
760 xassert (sd->fd >= 0);
762 /* On GNU/Linux, it seems that the device driver doesn't like to be
763 interrupted by a signal. Block the ones we know to cause
764 troubles. */
765 turn_on_atimers (0);
766 #ifdef SIGIO
767 sigblock (sigmask (SIGIO));
768 #endif
770 val = sd->format;
771 if (ioctl (sd->fd, SNDCTL_DSP_SETFMT, &sd->format) < 0
772 || val != sd->format)
773 sound_perror ("Could not set sound format");
775 val = sd->channels != 1;
776 if (ioctl (sd->fd, SNDCTL_DSP_STEREO, &val) < 0
777 || val != (sd->channels != 1))
778 sound_perror ("Could not set stereo/mono");
780 /* I think bps and sampling_rate are the same, but who knows.
781 Check this. and use SND_DSP_SPEED for both. */
782 if (sd->sample_rate > 0)
784 val = sd->sample_rate;
785 if (ioctl (sd->fd, SNDCTL_DSP_SPEED, &sd->sample_rate) < 0)
786 sound_perror ("Could not set sound speed");
787 else if (val != sd->sample_rate)
788 sound_warning ("Could not set sample rate");
791 if (sd->volume > 0)
793 int volume = sd->volume & 0xff;
794 volume |= volume << 8;
795 /* This may fail if there is no mixer. Ignore the failure. */
796 ioctl (sd->fd, SOUND_MIXER_WRITE_PCM, &volume);
799 turn_on_atimers (1);
800 #ifdef SIGIO
801 sigunblock (sigmask (SIGIO));
802 #endif
806 /* Close device SD if it is open. */
808 static void
809 vox_close (sd)
810 struct sound_device *sd;
812 if (sd->fd >= 0)
814 /* On GNU/Linux, it seems that the device driver doesn't like to
815 be interrupted by a signal. Block the ones we know to cause
816 troubles. */
817 #ifdef SIGIO
818 sigblock (sigmask (SIGIO));
819 #endif
820 turn_on_atimers (0);
822 /* Flush sound data, and reset the device. */
823 ioctl (sd->fd, SNDCTL_DSP_SYNC, NULL);
825 turn_on_atimers (1);
826 #ifdef SIGIO
827 sigunblock (sigmask (SIGIO));
828 #endif
830 /* Close the device. */
831 emacs_close (sd->fd);
832 sd->fd = -1;
837 /* Choose device-dependent format for device SD from sound file S. */
839 static void
840 vox_choose_format (sd, s)
841 struct sound_device *sd;
842 struct sound *s;
844 if (s->type == RIFF)
846 struct wav_header *h = (struct wav_header *) s->header;
847 if (h->precision == 8)
848 sd->format = AFMT_U8;
849 else if (h->precision == 16)
850 sd->format = AFMT_S16_LE;
851 else
852 error ("Unsupported WAV file format");
854 else if (s->type == SUN_AUDIO)
856 struct au_header *header = (struct au_header *) s->header;
857 switch (header->encoding)
859 case AU_ENCODING_ULAW_8:
860 case AU_ENCODING_IEEE32:
861 case AU_ENCODING_IEEE64:
862 sd->format = AFMT_MU_LAW;
863 break;
865 case AU_ENCODING_8:
866 case AU_ENCODING_16:
867 case AU_ENCODING_24:
868 case AU_ENCODING_32:
869 sd->format = AFMT_S16_LE;
870 break;
872 default:
873 error ("Unsupported AU file format");
876 else
877 abort ();
881 /* Initialize device SD. Set up the interface functions in the device
882 structure. */
884 static int
885 vox_init (sd)
886 struct sound_device *sd;
888 char *file;
889 int fd;
891 /* Open the sound device. Default is /dev/dsp. */
892 if (sd->file)
893 file = sd->file;
894 else
895 file = DEFAULT_SOUND_DEVICE;
896 fd = emacs_open (file, O_WRONLY, 0);
897 if (fd >= 0)
898 emacs_close (fd);
899 else
900 return 0;
902 sd->fd = -1;
903 sd->open = vox_open;
904 sd->close = vox_close;
905 sd->configure = vox_configure;
906 sd->choose_format = vox_choose_format;
907 sd->write = vox_write;
908 sd->period_size = NULL;
910 return 1;
913 /* Write NBYTES bytes from BUFFER to device SD. */
915 static void
916 vox_write (sd, buffer, nbytes)
917 struct sound_device *sd;
918 const char *buffer;
919 int nbytes;
921 int nwritten = emacs_write (sd->fd, buffer, nbytes);
922 if (nwritten < 0)
923 sound_perror ("Error writing to sound device");
926 #ifdef HAVE_ALSA
927 /***********************************************************************
928 ALSA Driver Interface
929 ***********************************************************************/
931 /* This driver is available on GNU/Linux. */
933 static void
934 alsa_sound_perror (msg, err)
935 char *msg;
936 int err;
938 error ("%s: %s", msg, snd_strerror (err));
941 struct alsa_params
943 snd_pcm_t *handle;
944 snd_pcm_hw_params_t *hwparams;
945 snd_pcm_sw_params_t *swparams;
946 snd_pcm_uframes_t period_size;
949 /* Open device SD. If SD->file is non-null, open that device,
950 otherwise use a default device name. */
952 static void
953 alsa_open (sd)
954 struct sound_device *sd;
956 char *file;
957 struct alsa_params *p;
958 int err;
960 /* Open the sound device. Default is "default". */
961 if (sd->file)
962 file = sd->file;
963 else
964 file = DEFAULT_ALSA_SOUND_DEVICE;
966 p = xmalloc (sizeof (*p));
967 p->handle = NULL;
968 p->hwparams = NULL;
969 p->swparams = NULL;
971 sd->fd = -1;
972 sd->data = p;
975 err = snd_pcm_open (&p->handle, file, SND_PCM_STREAM_PLAYBACK, 0);
976 if (err < 0)
977 alsa_sound_perror (file, err);
980 static int
981 alsa_period_size (sd)
982 struct sound_device *sd;
984 struct alsa_params *p = (struct alsa_params *) sd->data;
985 return p->period_size;
988 static void
989 alsa_configure (sd)
990 struct sound_device *sd;
992 int val, err, dir;
993 unsigned uval;
994 struct alsa_params *p = (struct alsa_params *) sd->data;
995 snd_pcm_uframes_t buffer_size;
997 xassert (p->handle != 0);
999 err = snd_pcm_hw_params_malloc (&p->hwparams);
1000 if (err < 0)
1001 alsa_sound_perror ("Could not allocate hardware parameter structure", err);
1003 err = snd_pcm_sw_params_malloc (&p->swparams);
1004 if (err < 0)
1005 alsa_sound_perror ("Could not allocate software parameter structure", err);
1007 err = snd_pcm_hw_params_any (p->handle, p->hwparams);
1008 if (err < 0)
1009 alsa_sound_perror ("Could not initialize hardware parameter structure", err);
1011 err = snd_pcm_hw_params_set_access (p->handle, p->hwparams,
1012 SND_PCM_ACCESS_RW_INTERLEAVED);
1013 if (err < 0)
1014 alsa_sound_perror ("Could not set access type", err);
1016 val = sd->format;
1017 err = snd_pcm_hw_params_set_format (p->handle, p->hwparams, val);
1018 if (err < 0)
1019 alsa_sound_perror ("Could not set sound format", err);
1021 uval = sd->sample_rate;
1022 err = snd_pcm_hw_params_set_rate_near (p->handle, p->hwparams, &uval, 0);
1023 if (err < 0)
1024 alsa_sound_perror ("Could not set sample rate", err);
1026 val = sd->channels;
1027 err = snd_pcm_hw_params_set_channels (p->handle, p->hwparams, val);
1028 if (err < 0)
1029 alsa_sound_perror ("Could not set channel count", err);
1031 err = snd_pcm_hw_params (p->handle, p->hwparams);
1032 if (err < 0)
1033 alsa_sound_perror ("Could not set parameters", err);
1036 err = snd_pcm_hw_params_get_period_size (p->hwparams, &p->period_size, &dir);
1037 if (err < 0)
1038 alsa_sound_perror ("Unable to get period size for playback", err);
1040 err = snd_pcm_hw_params_get_buffer_size (p->hwparams, &buffer_size);
1041 if (err < 0)
1042 alsa_sound_perror("Unable to get buffer size for playback", err);
1044 err = snd_pcm_sw_params_current (p->handle, p->swparams);
1045 if (err < 0)
1046 alsa_sound_perror ("Unable to determine current swparams for playback",
1047 err);
1049 /* Start the transfer when the buffer is almost full */
1050 err = snd_pcm_sw_params_set_start_threshold (p->handle, p->swparams,
1051 (buffer_size / p->period_size)
1052 * p->period_size);
1053 if (err < 0)
1054 alsa_sound_perror ("Unable to set start threshold mode for playback", err);
1056 /* Allow the transfer when at least period_size samples can be processed */
1057 err = snd_pcm_sw_params_set_avail_min (p->handle, p->swparams, p->period_size);
1058 if (err < 0)
1059 alsa_sound_perror ("Unable to set avail min for playback", err);
1061 /* Align all transfers to 1 period */
1062 err = snd_pcm_sw_params_set_xfer_align (p->handle, p->swparams,
1063 p->period_size);
1064 if (err < 0)
1065 alsa_sound_perror ("Unable to set transfer align for playback", err);
1067 err = snd_pcm_sw_params (p->handle, p->swparams);
1068 if (err < 0)
1069 alsa_sound_perror ("Unable to set sw params for playback\n", err);
1071 snd_pcm_hw_params_free (p->hwparams);
1072 p->hwparams = NULL;
1073 snd_pcm_sw_params_free (p->swparams);
1074 p->swparams = NULL;
1076 err = snd_pcm_prepare (p->handle);
1077 if (err < 0)
1078 alsa_sound_perror ("Could not prepare audio interface for use", err);
1080 if (sd->volume > 0)
1082 int chn;
1083 snd_mixer_t *handle;
1084 snd_mixer_elem_t *e;
1085 char *file = sd->file ? sd->file : DEFAULT_ALSA_SOUND_DEVICE;
1087 if (snd_mixer_open (&handle, 0) >= 0)
1089 if (snd_mixer_attach (handle, file) >= 0
1090 && snd_mixer_load (handle) >= 0
1091 && snd_mixer_selem_register (handle, NULL, NULL) >= 0)
1092 for (e = snd_mixer_first_elem (handle);
1094 e = snd_mixer_elem_next (e))
1096 if (snd_mixer_selem_has_playback_volume (e))
1098 long pmin, pmax;
1099 snd_mixer_selem_get_playback_volume_range (e, &pmin, &pmax);
1100 long vol = pmin + (sd->volume * (pmax - pmin)) / 100;
1102 for (chn = 0; chn <= SND_MIXER_SCHN_LAST; chn++)
1103 snd_mixer_selem_set_playback_volume (e, chn, vol);
1106 snd_mixer_close(handle);
1112 /* Close device SD if it is open. */
1114 static void
1115 alsa_close (sd)
1116 struct sound_device *sd;
1118 struct alsa_params *p = (struct alsa_params *) sd->data;
1119 if (p)
1121 if (p->hwparams)
1122 snd_pcm_hw_params_free (p->hwparams);
1123 if (p->swparams)
1124 snd_pcm_sw_params_free (p->swparams);
1125 if (p->handle)
1127 snd_pcm_drain (p->handle);
1128 snd_pcm_close (p->handle);
1130 free (p);
1134 /* Choose device-dependent format for device SD from sound file S. */
1136 static void
1137 alsa_choose_format (sd, s)
1138 struct sound_device *sd;
1139 struct sound *s;
1141 struct alsa_params *p = (struct alsa_params *) sd->data;
1142 if (s->type == RIFF)
1144 struct wav_header *h = (struct wav_header *) s->header;
1145 if (h->precision == 8)
1146 sd->format = SND_PCM_FORMAT_U8;
1147 else if (h->precision == 16)
1148 sd->format = SND_PCM_FORMAT_S16_LE;
1149 else
1150 error ("Unsupported WAV file format");
1152 else if (s->type == SUN_AUDIO)
1154 struct au_header *header = (struct au_header *) s->header;
1155 switch (header->encoding)
1157 case AU_ENCODING_ULAW_8:
1158 sd->format = SND_PCM_FORMAT_MU_LAW;
1159 break;
1160 case AU_ENCODING_ALAW_8:
1161 sd->format = SND_PCM_FORMAT_A_LAW;
1162 break;
1163 case AU_ENCODING_IEEE32:
1164 sd->format = SND_PCM_FORMAT_FLOAT_BE;
1165 break;
1166 case AU_ENCODING_IEEE64:
1167 sd->format = SND_PCM_FORMAT_FLOAT64_BE;
1168 break;
1169 case AU_ENCODING_8:
1170 sd->format = SND_PCM_FORMAT_S8;
1171 break;
1172 case AU_ENCODING_16:
1173 sd->format = SND_PCM_FORMAT_S16_BE;
1174 break;
1175 case AU_ENCODING_24:
1176 sd->format = SND_PCM_FORMAT_S24_BE;
1177 break;
1178 case AU_ENCODING_32:
1179 sd->format = SND_PCM_FORMAT_S32_BE;
1180 break;
1182 default:
1183 error ("Unsupported AU file format");
1186 else
1187 abort ();
1191 /* Write NBYTES bytes from BUFFER to device SD. */
1193 static void
1194 alsa_write (sd, buffer, nbytes)
1195 struct sound_device *sd;
1196 const char *buffer;
1197 int nbytes;
1199 struct alsa_params *p = (struct alsa_params *) sd->data;
1201 /* The the third parameter to snd_pcm_writei is frames, not bytes. */
1202 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
1203 int nwritten = 0;
1204 int err;
1206 while (nwritten < nbytes)
1208 err = snd_pcm_writei (p->handle,
1209 buffer + nwritten,
1210 (nbytes - nwritten)/fact);
1211 if (err < 0)
1213 if (err == -EPIPE)
1214 { /* under-run */
1215 err = snd_pcm_prepare (p->handle);
1216 if (err < 0)
1217 alsa_sound_perror ("Can't recover from underrun, prepare failed",
1218 err);
1220 else if (err == -ESTRPIPE)
1222 while ((err = snd_pcm_resume (p->handle)) == -EAGAIN)
1223 sleep(1); /* wait until the suspend flag is released */
1224 if (err < 0)
1226 err = snd_pcm_prepare (p->handle);
1227 if (err < 0)
1228 alsa_sound_perror ("Can't recover from suspend, "
1229 "prepare failed",
1230 err);
1233 else
1234 alsa_sound_perror ("Error writing to sound device", err);
1237 else
1238 nwritten += err * fact;
1242 static void
1243 snd_error_quiet (file, line, function, err, fmt)
1244 const char *file;
1245 int line;
1246 const char *function;
1247 int err;
1248 const char *fmt;
1252 /* Initialize device SD. Set up the interface functions in the device
1253 structure. */
1255 static int
1256 alsa_init (sd)
1257 struct sound_device *sd;
1259 char *file;
1260 snd_pcm_t *handle;
1261 int err;
1263 /* Open the sound device. Default is "default". */
1264 if (sd->file)
1265 file = sd->file;
1266 else
1267 file = DEFAULT_ALSA_SOUND_DEVICE;
1269 snd_lib_error_set_handler ((snd_lib_error_handler_t) snd_error_quiet);
1270 err = snd_pcm_open (&handle, file, SND_PCM_STREAM_PLAYBACK, 0);
1271 snd_lib_error_set_handler (NULL);
1272 if (err < 0)
1273 return 0;
1274 snd_pcm_close (handle);
1276 sd->fd = -1;
1277 sd->open = alsa_open;
1278 sd->close = alsa_close;
1279 sd->configure = alsa_configure;
1280 sd->choose_format = alsa_choose_format;
1281 sd->write = alsa_write;
1282 sd->period_size = alsa_period_size;
1284 return 1;
1287 #endif /* HAVE_ALSA */
1290 /* END: Non Windows functions */
1291 #else /* WINDOWSNT */
1293 /* BEGIN: Windows specific functions */
1295 static int
1296 do_play_sound (psz_file, ui_volume)
1297 const char *psz_file;
1298 unsigned long ui_volume;
1300 int i_result = 0;
1301 MCIERROR mci_error = 0;
1302 char sz_cmd_buf[520] = {0};
1303 char sz_ret_buf[520] = {0};
1304 MMRESULT mm_result = MMSYSERR_NOERROR;
1305 unsigned long ui_volume_org = 0;
1306 BOOL b_reset_volume = FALSE;
1308 memset (sz_cmd_buf, 0, sizeof(sz_cmd_buf));
1309 memset (sz_ret_buf, 0, sizeof(sz_ret_buf));
1310 sprintf (sz_cmd_buf,
1311 "open \"%s\" alias GNUEmacs_PlaySound_Device wait",
1312 psz_file);
1313 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, 520, NULL);
1314 if (mci_error != 0)
1316 sound_warning ("The open mciSendString command failed to open\n"
1317 "the specified sound file");
1318 i_result = (int) mci_error;
1319 return i_result;
1321 if ((ui_volume > 0) && (ui_volume != UINT_MAX))
1323 mm_result = waveOutGetVolume ((HWAVEOUT) WAVE_MAPPER, &ui_volume_org);
1324 if (mm_result == MMSYSERR_NOERROR)
1326 b_reset_volume = TRUE;
1327 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume);
1328 if ( mm_result != MMSYSERR_NOERROR)
1330 sound_warning ("waveOutSetVolume failed to set the volume level\n"
1331 "of the WAVE_MAPPER device.\n"
1332 "As a result, the user selected volume level will\n"
1333 "not be used.");
1336 else
1338 sound_warning ("waveOutGetVolume failed to obtain the original\n"
1339 "volume level of the WAVE_MAPPER device.\n"
1340 "As a result, the user selected volume level will\n"
1341 "not be used.");
1344 memset (sz_cmd_buf, 0, sizeof(sz_cmd_buf));
1345 memset (sz_ret_buf, 0, sizeof(sz_ret_buf));
1346 strcpy (sz_cmd_buf, "play GNUEmacs_PlaySound_Device wait");
1347 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, 520, NULL);
1348 if (mci_error != 0)
1350 sound_warning ("The play mciSendString command failed to play the\n"
1351 "opened sound file.");
1352 i_result = (int) mci_error;
1354 memset (sz_cmd_buf, 0, sizeof(sz_cmd_buf));
1355 memset (sz_ret_buf, 0, sizeof(sz_ret_buf));
1356 strcpy (sz_cmd_buf, "close GNUEmacs_PlaySound_Device wait");
1357 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, 520, NULL);
1358 if (b_reset_volume == TRUE)
1360 mm_result=waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume_org);
1361 if (mm_result != MMSYSERR_NOERROR)
1363 sound_warning ("waveOutSetVolume failed to reset the original volume\n"
1364 "level of the WAVE_MAPPER device.");
1367 return i_result;
1370 /* END: Windows specific functions */
1372 #endif /* WINDOWSNT */
1374 DEFUN ("play-sound-internal", Fplay_sound_internal, Splay_sound_internal, 1, 1, 0,
1375 doc: /* Play sound SOUND.
1377 Internal use only, use `play-sound' instead.\n */)
1378 (sound)
1379 Lisp_Object sound;
1381 Lisp_Object attrs[SOUND_ATTR_SENTINEL];
1382 int count = SPECPDL_INDEX ();
1384 #ifndef WINDOWSNT
1385 Lisp_Object file;
1386 struct gcpro gcpro1, gcpro2;
1387 Lisp_Object args[2];
1388 #else /* WINDOWSNT */
1389 int len = 0;
1390 Lisp_Object lo_file = {0};
1391 char * psz_file = NULL;
1392 unsigned long ui_volume_tmp = UINT_MAX;
1393 unsigned long ui_volume = UINT_MAX;
1394 int i_result = 0;
1395 #endif /* WINDOWSNT */
1397 /* Parse the sound specification. Give up if it is invalid. */
1398 if (!parse_sound (sound, attrs))
1399 error ("Invalid sound specification");
1401 #ifndef WINDOWSNT
1402 file = Qnil;
1403 GCPRO2 (sound, file);
1404 current_sound_device = (struct sound_device *) xmalloc (sizeof (struct sound_device));
1405 bzero (current_sound_device, sizeof (struct sound_device));
1406 current_sound = (struct sound *) xmalloc (sizeof (struct sound));
1407 bzero (current_sound, sizeof (struct sound));
1408 record_unwind_protect (sound_cleanup, Qnil);
1409 current_sound->header = (char *) alloca (MAX_SOUND_HEADER_BYTES);
1411 if (STRINGP (attrs[SOUND_FILE]))
1413 /* Open the sound file. */
1414 current_sound->fd = openp (Fcons (Vdata_directory, Qnil),
1415 attrs[SOUND_FILE], Qnil, &file, Qnil);
1416 if (current_sound->fd < 0)
1417 sound_perror ("Could not open sound file");
1419 /* Read the first bytes from the file. */
1420 current_sound->header_size
1421 = emacs_read (current_sound->fd, current_sound->header,
1422 MAX_SOUND_HEADER_BYTES);
1423 if (current_sound->header_size < 0)
1424 sound_perror ("Invalid sound file header");
1426 else
1428 current_sound->data = attrs[SOUND_DATA];
1429 current_sound->header_size = min (MAX_SOUND_HEADER_BYTES, SBYTES (current_sound->data));
1430 bcopy (SDATA (current_sound->data), current_sound->header, current_sound->header_size);
1433 /* Find out the type of sound. Give up if we can't tell. */
1434 find_sound_type (current_sound);
1436 /* Set up a device. */
1437 if (STRINGP (attrs[SOUND_DEVICE]))
1439 int len = SCHARS (attrs[SOUND_DEVICE]);
1440 current_sound_device->file = (char *) alloca (len + 1);
1441 strcpy (current_sound_device->file, SDATA (attrs[SOUND_DEVICE]));
1444 if (INTEGERP (attrs[SOUND_VOLUME]))
1445 current_sound_device->volume = XFASTINT (attrs[SOUND_VOLUME]);
1446 else if (FLOATP (attrs[SOUND_VOLUME]))
1447 current_sound_device->volume = XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1449 args[0] = Qplay_sound_functions;
1450 args[1] = sound;
1451 Frun_hook_with_args (2, args);
1453 #ifdef HAVE_ALSA
1454 if (!alsa_init (current_sound_device))
1455 #endif
1456 if (!vox_init (current_sound_device))
1457 error ("No usable sound device driver found");
1459 /* Open the device. */
1460 current_sound_device->open (current_sound_device);
1462 /* Play the sound. */
1463 current_sound->play (current_sound, current_sound_device);
1465 /* Clean up. */
1466 UNGCPRO;
1468 #else /* WINDOWSNT */
1470 lo_file = Fexpand_file_name (attrs[SOUND_FILE], Qnil);
1471 len = XSTRING (lo_file)->size;
1472 psz_file = (char *) alloca (len + 1);
1473 strcpy (psz_file, XSTRING (lo_file)->data);
1474 if (INTEGERP (attrs[SOUND_VOLUME]))
1476 ui_volume_tmp = XFASTINT (attrs[SOUND_VOLUME]);
1478 else if (FLOATP (attrs[SOUND_VOLUME]))
1480 ui_volume_tmp = (unsigned long) XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1483 Based on some experiments I have conducted, a value of 100 or less
1484 for the sound volume is much too low. You cannot even hear it.
1485 A value of UINT_MAX indicates that you wish for the sound to played
1486 at the maximum possible volume. A value of UINT_MAX/2 plays the
1487 sound at 50% maximum volume. Therefore the value passed to do_play_sound
1488 (and thus to waveOutSetVolume) must be some fraction of UINT_MAX.
1489 The following code adjusts the user specified volume level appropriately.
1491 if ((ui_volume_tmp > 0) && (ui_volume_tmp <= 100))
1493 ui_volume = ui_volume_tmp * (UINT_MAX / 100);
1495 i_result = do_play_sound (psz_file, ui_volume);
1497 #endif /* WINDOWSNT */
1499 unbind_to (count, Qnil);
1500 return Qnil;
1503 /***********************************************************************
1504 Initialization
1505 ***********************************************************************/
1507 void
1508 syms_of_sound ()
1510 QCdevice = intern (":device");
1511 staticpro (&QCdevice);
1512 QCvolume = intern (":volume");
1513 staticpro (&QCvolume);
1514 Qsound = intern ("sound");
1515 staticpro (&Qsound);
1516 Qplay_sound_functions = intern ("play-sound-functions");
1517 staticpro (&Qplay_sound_functions);
1519 defsubr (&Splay_sound_internal);
1523 void
1524 init_sound ()
1528 #endif /* HAVE_SOUND */
1530 /* arch-tag: dd850ad8-0433-4e2c-9cba-b7aeeccc0dbd
1531 (do not change this comment) */