* lisp/gnus/smime.el (smime-mode): Use define-derived-mode.
[emacs.git] / src / sound.c
blob3869f3a57ff9a30823fa62a912b8227179747faa
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 <limits.h>
90 #include <windows.h>
91 #include <mmsystem.h>
92 /* END: Windows Specific Includes */
94 #endif /* WINDOWSNT */
96 /* BEGIN: Common Definitions */
98 /* Symbols. */
100 Lisp_Object QCvolume, QCdevice;
101 Lisp_Object Qsound;
102 Lisp_Object Qplay_sound_functions;
104 /* Indices of attributes in a sound attributes vector. */
106 enum sound_attr
108 SOUND_FILE,
109 SOUND_DATA,
110 SOUND_DEVICE,
111 SOUND_VOLUME,
112 SOUND_ATTR_SENTINEL
115 #ifdef HAVE_ALSA
116 static void alsa_sound_perror (const char *, int) NO_RETURN;
117 #endif
118 static void sound_perror (const char *) NO_RETURN;
119 static void sound_warning (const char *);
120 static int parse_sound (Lisp_Object, Lisp_Object *);
122 /* END: Common Definitions */
124 /* BEGIN: Non Windows Definitions */
125 #ifndef WINDOWSNT
127 #ifndef DEFAULT_SOUND_DEVICE
128 #define DEFAULT_SOUND_DEVICE "/dev/dsp"
129 #endif
130 #ifndef DEFAULT_ALSA_SOUND_DEVICE
131 #define DEFAULT_ALSA_SOUND_DEVICE "default"
132 #endif
135 /* Structure forward declarations. */
137 struct sound;
138 struct sound_device;
140 /* The file header of RIFF-WAVE files (*.wav). Files are always in
141 little-endian byte-order. */
143 struct wav_header
145 u_int32_t magic;
146 u_int32_t length;
147 u_int32_t chunk_type;
148 u_int32_t chunk_format;
149 u_int32_t chunk_length;
150 u_int16_t format;
151 u_int16_t channels;
152 u_int32_t sample_rate;
153 u_int32_t bytes_per_second;
154 u_int16_t sample_size;
155 u_int16_t precision;
156 u_int32_t chunk_data;
157 u_int32_t data_length;
160 /* The file header of Sun adio files (*.au). Files are always in
161 big-endian byte-order. */
163 struct au_header
165 /* ASCII ".snd" */
166 u_int32_t magic_number;
168 /* Offset of data part from start of file. Minimum value is 24. */
169 u_int32_t data_offset;
171 /* Size of data part, 0xffffffff if unknown. */
172 u_int32_t data_size;
174 /* Data encoding format.
175 1 8-bit ISDN u-law
176 2 8-bit linear PCM (REF-PCM)
177 3 16-bit linear PCM
178 4 24-bit linear PCM
179 5 32-bit linear PCM
180 6 32-bit IEEE floating-point
181 7 64-bit IEEE floating-point
182 23 8-bit u-law compressed using CCITT 0.721 ADPCM voice data
183 encoding scheme. */
184 u_int32_t encoding;
186 /* Number of samples per second. */
187 u_int32_t sample_rate;
189 /* Number of interleaved channels. */
190 u_int32_t channels;
193 /* Maximum of all sound file headers sizes. */
195 #define MAX_SOUND_HEADER_BYTES \
196 max (sizeof (struct wav_header), sizeof (struct au_header))
198 /* Interface structure for sound devices. */
200 struct sound_device
202 /* The name of the device or null meaning use a default device name. */
203 char *file;
205 /* File descriptor of the device. */
206 int fd;
208 /* Device-dependent format. */
209 int format;
211 /* Volume (0..100). Zero means unspecified. */
212 int volume;
214 /* Sample size. */
215 int sample_size;
217 /* Sample rate. */
218 int sample_rate;
220 /* Bytes per second. */
221 int bps;
223 /* 1 = mono, 2 = stereo, 0 = don't set. */
224 int channels;
226 /* Open device SD. */
227 void (* open) (struct sound_device *sd);
229 /* Close device SD. */
230 void (* close) (struct sound_device *sd);
232 /* Configure SD accoring to device-dependent parameters. */
233 void (* configure) (struct sound_device *device);
235 /* Choose a device-dependent format for outputting sound S. */
236 void (* choose_format) (struct sound_device *sd,
237 struct sound *s);
239 /* Return a preferred data size in bytes to be sent to write (below)
240 each time. 2048 is used if this is NULL. */
241 int (* period_size) (struct sound_device *sd);
243 /* Write NYBTES bytes from BUFFER to device SD. */
244 void (* write) (struct sound_device *sd, const char *buffer,
245 int nbytes);
247 /* A place for devices to store additional data. */
248 void *data;
251 /* An enumerator for each supported sound file type. */
253 enum sound_type
255 RIFF,
256 SUN_AUDIO
259 /* Interface structure for sound files. */
261 struct sound
263 /* The type of the file. */
264 enum sound_type type;
266 /* File descriptor of a sound file. */
267 int fd;
269 /* Pointer to sound file header. This contains header_size bytes
270 read from the start of a sound file. */
271 char *header;
273 /* Number of bytes raed from sound file. This is always <=
274 MAX_SOUND_HEADER_BYTES. */
275 int header_size;
277 /* Sound data, if a string. */
278 Lisp_Object data;
280 /* Play sound file S on device SD. */
281 void (* play) (struct sound *s, struct sound_device *sd);
284 /* These are set during `play-sound-internal' so that sound_cleanup has
285 access to them. */
287 struct sound_device *current_sound_device;
288 struct sound *current_sound;
290 /* Function prototypes. */
292 static void vox_open (struct sound_device *);
293 static void vox_configure (struct sound_device *);
294 static void vox_close (struct sound_device *sd);
295 static void vox_choose_format (struct sound_device *, struct sound *);
296 static int vox_init (struct sound_device *);
297 static void vox_write (struct sound_device *, const char *, int);
298 static void find_sound_type (struct sound *);
299 static u_int32_t le2hl (u_int32_t);
300 static u_int16_t le2hs (u_int16_t);
301 static u_int32_t be2hl (u_int32_t);
302 static int wav_init (struct sound *);
303 static void wav_play (struct sound *, struct sound_device *);
304 static int au_init (struct sound *);
305 static void au_play (struct sound *, struct sound_device *);
307 #if 0 /* Currently not used. */
308 static u_int16_t be2hs (u_int16_t);
309 #endif
311 /* END: Non Windows Definitions */
312 #else /* WINDOWSNT */
314 /* BEGIN: Windows Specific Definitions */
315 static int do_play_sound (const char *, unsigned long);
317 END: Windows Specific Definitions */
318 #endif /* WINDOWSNT */
321 /***********************************************************************
322 General
323 ***********************************************************************/
325 /* BEGIN: Common functions */
327 /* Like perror, but signals an error. */
329 static void
330 sound_perror (const 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 (const char *msg)
350 message (msg);
354 /* Parse sound specification SOUND, and fill ATTRS with what is
355 found. Value is non-zero if SOUND Is a valid sound specification.
356 A valid sound specification is a list starting with the symbol
357 `sound'. The rest of the list is a property list which may
358 contain the following key/value pairs:
360 - `:file FILE'
362 FILE is the sound file to play. If it isn't an absolute name,
363 it's searched under `data-directory'.
365 - `:data DATA'
367 DATA is a string containing sound data. Either :file or :data
368 may be present, but not both.
370 - `:device DEVICE'
372 DEVICE is the name of the device to play on, e.g. "/dev/dsp2".
373 If not specified, a default device is used.
375 - `:volume VOL'
377 VOL must be an integer in the range [0, 100], or a float in the
378 range [0, 1]. */
380 static int
381 parse_sound (Lisp_Object sound, Lisp_Object *attrs)
383 /* SOUND must be a list starting with the symbol `sound'. */
384 if (!CONSP (sound) || !EQ (XCAR (sound), Qsound))
385 return 0;
387 sound = XCDR (sound);
388 attrs[SOUND_FILE] = Fplist_get (sound, QCfile);
389 attrs[SOUND_DATA] = Fplist_get (sound, QCdata);
390 attrs[SOUND_DEVICE] = Fplist_get (sound, QCdevice);
391 attrs[SOUND_VOLUME] = Fplist_get (sound, QCvolume);
393 #ifndef WINDOWSNT
394 /* File name or data must be specified. */
395 if (!STRINGP (attrs[SOUND_FILE])
396 && !STRINGP (attrs[SOUND_DATA]))
397 return 0;
398 #else /* WINDOWSNT */
400 Data is not supported in Windows. Therefore a
401 File name MUST be supplied.
403 if (!STRINGP (attrs[SOUND_FILE]))
405 return 0;
407 #endif /* WINDOWSNT */
409 /* Volume must be in the range 0..100 or unspecified. */
410 if (!NILP (attrs[SOUND_VOLUME]))
412 if (INTEGERP (attrs[SOUND_VOLUME]))
414 if (XINT (attrs[SOUND_VOLUME]) < 0
415 || XINT (attrs[SOUND_VOLUME]) > 100)
416 return 0;
418 else if (FLOATP (attrs[SOUND_VOLUME]))
420 if (XFLOAT_DATA (attrs[SOUND_VOLUME]) < 0
421 || XFLOAT_DATA (attrs[SOUND_VOLUME]) > 1)
422 return 0;
424 else
425 return 0;
428 #ifndef WINDOWSNT
429 /* Device must be a string or unspecified. */
430 if (!NILP (attrs[SOUND_DEVICE])
431 && !STRINGP (attrs[SOUND_DEVICE]))
432 return 0;
433 #endif /* WINDOWSNT */
435 Since device is ignored in Windows, it does not matter
436 what it is.
438 return 1;
441 /* END: Common functions */
443 /* BEGIN: Non Windows functions */
444 #ifndef WINDOWSNT
446 /* Find out the type of the sound file whose file descriptor is FD.
447 S is the sound file structure to fill in. */
449 static void
450 find_sound_type (struct sound *s)
452 if (!wav_init (s) && !au_init (s))
453 error ("Unknown sound format");
457 /* Function installed by play-sound-internal with record_unwind_protect. */
459 static Lisp_Object
460 sound_cleanup (Lisp_Object arg)
462 if (current_sound_device->close)
463 current_sound_device->close (current_sound_device);
464 if (current_sound->fd > 0)
465 emacs_close (current_sound->fd);
466 free (current_sound_device);
467 free (current_sound);
469 return Qnil;
472 /***********************************************************************
473 Byte-order Conversion
474 ***********************************************************************/
476 /* Convert 32-bit value VALUE which is in little-endian byte-order
477 to host byte-order. */
479 static u_int32_t
480 le2hl (u_int32_t value)
482 #ifdef WORDS_BIGENDIAN
483 unsigned char *p = (unsigned char *) &value;
484 value = p[0] + (p[1] << 8) + (p[2] << 16) + (p[3] << 24);
485 #endif
486 return value;
490 /* Convert 16-bit value VALUE which is in little-endian byte-order
491 to host byte-order. */
493 static u_int16_t
494 le2hs (u_int16_t value)
496 #ifdef WORDS_BIGENDIAN
497 unsigned char *p = (unsigned char *) &value;
498 value = p[0] + (p[1] << 8);
499 #endif
500 return value;
504 /* Convert 32-bit value VALUE which is in big-endian byte-order
505 to host byte-order. */
507 static u_int32_t
508 be2hl (u_int32_t value)
510 #ifndef WORDS_BIGENDIAN
511 unsigned char *p = (unsigned char *) &value;
512 value = p[3] + (p[2] << 8) + (p[1] << 16) + (p[0] << 24);
513 #endif
514 return value;
518 #if 0 /* Currently not used. */
520 /* Convert 16-bit value VALUE which is in big-endian byte-order
521 to host byte-order. */
523 static u_int16_t
524 be2hs (u_int16_t value)
526 #ifndef WORDS_BIGENDIAN
527 unsigned char *p = (unsigned char *) &value;
528 value = p[1] + (p[0] << 8);
529 #endif
530 return value;
533 #endif /* 0 */
535 /***********************************************************************
536 RIFF-WAVE (*.wav)
537 ***********************************************************************/
539 /* Try to initialize sound file S from S->header. S->header
540 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
541 sound file. If the file is a WAV-format file, set up interface
542 functions in S and convert header fields to host byte-order.
543 Value is non-zero if the file is a WAV file. */
545 static int
546 wav_init (struct sound *s)
548 struct wav_header *header = (struct wav_header *) s->header;
550 if (s->header_size < sizeof *header
551 || memcmp (s->header, "RIFF", 4) != 0)
552 return 0;
554 /* WAV files are in little-endian order. Convert the header
555 if on a big-endian machine. */
556 header->magic = le2hl (header->magic);
557 header->length = le2hl (header->length);
558 header->chunk_type = le2hl (header->chunk_type);
559 header->chunk_format = le2hl (header->chunk_format);
560 header->chunk_length = le2hl (header->chunk_length);
561 header->format = le2hs (header->format);
562 header->channels = le2hs (header->channels);
563 header->sample_rate = le2hl (header->sample_rate);
564 header->bytes_per_second = le2hl (header->bytes_per_second);
565 header->sample_size = le2hs (header->sample_size);
566 header->precision = le2hs (header->precision);
567 header->chunk_data = le2hl (header->chunk_data);
568 header->data_length = le2hl (header->data_length);
570 /* Set up the interface functions for WAV. */
571 s->type = RIFF;
572 s->play = wav_play;
574 return 1;
578 /* Play RIFF-WAVE audio file S on sound device SD. */
580 static void
581 wav_play (struct sound *s, struct sound_device *sd)
583 struct wav_header *header = (struct wav_header *) s->header;
585 /* Let the device choose a suitable device-dependent format
586 for the file. */
587 sd->choose_format (sd, s);
589 /* Configure the device. */
590 sd->sample_size = header->sample_size;
591 sd->sample_rate = header->sample_rate;
592 sd->bps = header->bytes_per_second;
593 sd->channels = header->channels;
594 sd->configure (sd);
596 /* Copy sound data to the device. The WAV file specification is
597 actually more complex. This simple scheme worked with all WAV
598 files I found so far. If someone feels inclined to implement the
599 whole RIFF-WAVE spec, please do. */
600 if (STRINGP (s->data))
601 sd->write (sd, SDATA (s->data) + sizeof *header,
602 SBYTES (s->data) - sizeof *header);
603 else
605 char *buffer;
606 int nbytes;
607 int blksize = sd->period_size ? sd->period_size (sd) : 2048;
608 int data_left = header->data_length;
610 buffer = (char *) alloca (blksize);
611 lseek (s->fd, sizeof *header, SEEK_SET);
612 while (data_left > 0
613 && (nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
615 /* Don't play possible garbage at the end of file */
616 if (data_left < nbytes) nbytes = data_left;
617 data_left -= nbytes;
618 sd->write (sd, buffer, nbytes);
621 if (nbytes < 0)
622 sound_perror ("Error reading sound file");
627 /***********************************************************************
628 Sun Audio (*.au)
629 ***********************************************************************/
631 /* Sun audio file encodings. */
633 enum au_encoding
635 AU_ENCODING_ULAW_8 = 1,
636 AU_ENCODING_8,
637 AU_ENCODING_16,
638 AU_ENCODING_24,
639 AU_ENCODING_32,
640 AU_ENCODING_IEEE32,
641 AU_ENCODING_IEEE64,
642 AU_COMPRESSED = 23,
643 AU_ENCODING_ALAW_8 = 27
647 /* Try to initialize sound file S from S->header. S->header
648 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
649 sound file. If the file is a AU-format file, set up interface
650 functions in S and convert header fields to host byte-order.
651 Value is non-zero if the file is an AU file. */
653 static int
654 au_init (struct sound *s)
656 struct au_header *header = (struct au_header *) s->header;
658 if (s->header_size < sizeof *header
659 || memcmp (s->header, ".snd", 4) != 0)
660 return 0;
662 header->magic_number = be2hl (header->magic_number);
663 header->data_offset = be2hl (header->data_offset);
664 header->data_size = be2hl (header->data_size);
665 header->encoding = be2hl (header->encoding);
666 header->sample_rate = be2hl (header->sample_rate);
667 header->channels = be2hl (header->channels);
669 /* Set up the interface functions for AU. */
670 s->type = SUN_AUDIO;
671 s->play = au_play;
673 return 1;
677 /* Play Sun audio file S on sound device SD. */
679 static void
680 au_play (struct sound *s, struct sound_device *sd)
682 struct au_header *header = (struct au_header *) s->header;
684 sd->sample_size = 0;
685 sd->sample_rate = header->sample_rate;
686 sd->bps = 0;
687 sd->channels = header->channels;
688 sd->choose_format (sd, s);
689 sd->configure (sd);
691 if (STRINGP (s->data))
692 sd->write (sd, SDATA (s->data) + header->data_offset,
693 SBYTES (s->data) - header->data_offset);
694 else
696 int blksize = sd->period_size ? sd->period_size (sd) : 2048;
697 char *buffer;
698 int nbytes;
700 /* Seek */
701 lseek (s->fd, header->data_offset, SEEK_SET);
703 /* Copy sound data to the device. */
704 buffer = (char *) alloca (blksize);
705 while ((nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
706 sd->write (sd, buffer, nbytes);
708 if (nbytes < 0)
709 sound_perror ("Error reading sound file");
714 /***********************************************************************
715 Voxware Driver Interface
716 ***********************************************************************/
718 /* This driver is available on GNU/Linux, and the free BSDs. FreeBSD
719 has a compatible own driver aka Luigi's driver. */
722 /* Open device SD. If SD->file is non-null, open that device,
723 otherwise use a default device name. */
725 static void
726 vox_open (struct sound_device *sd)
728 const char *file;
730 /* Open the sound device. Default is /dev/dsp. */
731 if (sd->file)
732 file = sd->file;
733 else
734 file = DEFAULT_SOUND_DEVICE;
736 sd->fd = emacs_open (file, O_WRONLY, 0);
737 if (sd->fd < 0)
738 sound_perror (file);
742 /* Configure device SD from parameters in it. */
744 static void
745 vox_configure (struct sound_device *sd)
747 int val;
749 xassert (sd->fd >= 0);
751 /* On GNU/Linux, it seems that the device driver doesn't like to be
752 interrupted by a signal. Block the ones we know to cause
753 troubles. */
754 turn_on_atimers (0);
755 #ifdef SIGIO
756 sigblock (sigmask (SIGIO));
757 #endif
759 val = sd->format;
760 if (ioctl (sd->fd, SNDCTL_DSP_SETFMT, &sd->format) < 0
761 || val != sd->format)
762 sound_perror ("Could not set sound format");
764 val = sd->channels != 1;
765 if (ioctl (sd->fd, SNDCTL_DSP_STEREO, &val) < 0
766 || val != (sd->channels != 1))
767 sound_perror ("Could not set stereo/mono");
769 /* I think bps and sampling_rate are the same, but who knows.
770 Check this. and use SND_DSP_SPEED for both. */
771 if (sd->sample_rate > 0)
773 val = sd->sample_rate;
774 if (ioctl (sd->fd, SNDCTL_DSP_SPEED, &sd->sample_rate) < 0)
775 sound_perror ("Could not set sound speed");
776 else if (val != sd->sample_rate)
777 sound_warning ("Could not set sample rate");
780 if (sd->volume > 0)
782 int volume = sd->volume & 0xff;
783 volume |= volume << 8;
784 /* This may fail if there is no mixer. Ignore the failure. */
785 ioctl (sd->fd, SOUND_MIXER_WRITE_PCM, &volume);
788 turn_on_atimers (1);
789 #ifdef SIGIO
790 sigunblock (sigmask (SIGIO));
791 #endif
795 /* Close device SD if it is open. */
797 static void
798 vox_close (struct sound_device *sd)
800 if (sd->fd >= 0)
802 /* On GNU/Linux, it seems that the device driver doesn't like to
803 be interrupted by a signal. Block the ones we know to cause
804 troubles. */
805 #ifdef SIGIO
806 sigblock (sigmask (SIGIO));
807 #endif
808 turn_on_atimers (0);
810 /* Flush sound data, and reset the device. */
811 ioctl (sd->fd, SNDCTL_DSP_SYNC, NULL);
813 turn_on_atimers (1);
814 #ifdef SIGIO
815 sigunblock (sigmask (SIGIO));
816 #endif
818 /* Close the device. */
819 emacs_close (sd->fd);
820 sd->fd = -1;
825 /* Choose device-dependent format for device SD from sound file S. */
827 static void
828 vox_choose_format (struct sound_device *sd, struct sound *s)
830 if (s->type == RIFF)
832 struct wav_header *h = (struct wav_header *) s->header;
833 if (h->precision == 8)
834 sd->format = AFMT_U8;
835 else if (h->precision == 16)
836 sd->format = AFMT_S16_LE;
837 else
838 error ("Unsupported WAV file format");
840 else if (s->type == SUN_AUDIO)
842 struct au_header *header = (struct au_header *) s->header;
843 switch (header->encoding)
845 case AU_ENCODING_ULAW_8:
846 case AU_ENCODING_IEEE32:
847 case AU_ENCODING_IEEE64:
848 sd->format = AFMT_MU_LAW;
849 break;
851 case AU_ENCODING_8:
852 case AU_ENCODING_16:
853 case AU_ENCODING_24:
854 case AU_ENCODING_32:
855 sd->format = AFMT_S16_LE;
856 break;
858 default:
859 error ("Unsupported AU file format");
862 else
863 abort ();
867 /* Initialize device SD. Set up the interface functions in the device
868 structure. */
870 static int
871 vox_init (struct sound_device *sd)
873 const char *file;
874 int fd;
876 /* Open the sound device. Default is /dev/dsp. */
877 if (sd->file)
878 file = sd->file;
879 else
880 file = DEFAULT_SOUND_DEVICE;
881 fd = emacs_open (file, O_WRONLY, 0);
882 if (fd >= 0)
883 emacs_close (fd);
884 else
885 return 0;
887 sd->fd = -1;
888 sd->open = vox_open;
889 sd->close = vox_close;
890 sd->configure = vox_configure;
891 sd->choose_format = vox_choose_format;
892 sd->write = vox_write;
893 sd->period_size = NULL;
895 return 1;
898 /* Write NBYTES bytes from BUFFER to device SD. */
900 static void
901 vox_write (struct sound_device *sd, const char *buffer, int nbytes)
903 int nwritten = emacs_write (sd->fd, buffer, nbytes);
904 if (nwritten < 0)
905 sound_perror ("Error writing to sound device");
908 #ifdef HAVE_ALSA
909 /***********************************************************************
910 ALSA Driver Interface
911 ***********************************************************************/
913 /* This driver is available on GNU/Linux. */
915 static void
916 alsa_sound_perror (const char *msg, int err)
918 error ("%s: %s", msg, snd_strerror (err));
921 struct alsa_params
923 snd_pcm_t *handle;
924 snd_pcm_hw_params_t *hwparams;
925 snd_pcm_sw_params_t *swparams;
926 snd_pcm_uframes_t period_size;
929 /* Open device SD. If SD->file is non-null, open that device,
930 otherwise use a default device name. */
932 static void
933 alsa_open (struct sound_device *sd)
935 const char *file;
936 struct alsa_params *p;
937 int err;
939 /* Open the sound device. Default is "default". */
940 if (sd->file)
941 file = sd->file;
942 else
943 file = DEFAULT_ALSA_SOUND_DEVICE;
945 p = xmalloc (sizeof (*p));
946 p->handle = NULL;
947 p->hwparams = NULL;
948 p->swparams = NULL;
950 sd->fd = -1;
951 sd->data = p;
954 err = snd_pcm_open (&p->handle, file, SND_PCM_STREAM_PLAYBACK, 0);
955 if (err < 0)
956 alsa_sound_perror (file, err);
959 static int
960 alsa_period_size (struct sound_device *sd)
962 struct alsa_params *p = (struct alsa_params *) sd->data;
963 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
964 return p->period_size * (fact > 0 ? fact : 1);
967 static void
968 alsa_configure (struct sound_device *sd)
970 int val, err, dir;
971 unsigned uval;
972 struct alsa_params *p = (struct alsa_params *) sd->data;
973 snd_pcm_uframes_t buffer_size;
975 xassert (p->handle != 0);
977 err = snd_pcm_hw_params_malloc (&p->hwparams);
978 if (err < 0)
979 alsa_sound_perror ("Could not allocate hardware parameter structure", err);
981 err = snd_pcm_sw_params_malloc (&p->swparams);
982 if (err < 0)
983 alsa_sound_perror ("Could not allocate software parameter structure", err);
985 err = snd_pcm_hw_params_any (p->handle, p->hwparams);
986 if (err < 0)
987 alsa_sound_perror ("Could not initialize hardware parameter structure", err);
989 err = snd_pcm_hw_params_set_access (p->handle, p->hwparams,
990 SND_PCM_ACCESS_RW_INTERLEAVED);
991 if (err < 0)
992 alsa_sound_perror ("Could not set access type", err);
994 val = sd->format;
995 err = snd_pcm_hw_params_set_format (p->handle, p->hwparams, val);
996 if (err < 0)
997 alsa_sound_perror ("Could not set sound format", err);
999 uval = sd->sample_rate;
1000 err = snd_pcm_hw_params_set_rate_near (p->handle, p->hwparams, &uval, 0);
1001 if (err < 0)
1002 alsa_sound_perror ("Could not set sample rate", err);
1004 val = sd->channels;
1005 err = snd_pcm_hw_params_set_channels (p->handle, p->hwparams, val);
1006 if (err < 0)
1007 alsa_sound_perror ("Could not set channel count", err);
1009 err = snd_pcm_hw_params (p->handle, p->hwparams);
1010 if (err < 0)
1011 alsa_sound_perror ("Could not set parameters", err);
1014 err = snd_pcm_hw_params_get_period_size (p->hwparams, &p->period_size, &dir);
1015 if (err < 0)
1016 alsa_sound_perror ("Unable to get period size for playback", err);
1018 err = snd_pcm_hw_params_get_buffer_size (p->hwparams, &buffer_size);
1019 if (err < 0)
1020 alsa_sound_perror("Unable to get buffer size for playback", err);
1022 err = snd_pcm_sw_params_current (p->handle, p->swparams);
1023 if (err < 0)
1024 alsa_sound_perror ("Unable to determine current swparams for playback",
1025 err);
1027 /* Start the transfer when the buffer is almost full */
1028 err = snd_pcm_sw_params_set_start_threshold (p->handle, p->swparams,
1029 (buffer_size / p->period_size)
1030 * p->period_size);
1031 if (err < 0)
1032 alsa_sound_perror ("Unable to set start threshold mode for playback", err);
1034 /* Allow the transfer when at least period_size samples can be processed */
1035 err = snd_pcm_sw_params_set_avail_min (p->handle, p->swparams, p->period_size);
1036 if (err < 0)
1037 alsa_sound_perror ("Unable to set avail min for playback", err);
1039 err = snd_pcm_sw_params (p->handle, p->swparams);
1040 if (err < 0)
1041 alsa_sound_perror ("Unable to set sw params for playback\n", err);
1043 snd_pcm_hw_params_free (p->hwparams);
1044 p->hwparams = NULL;
1045 snd_pcm_sw_params_free (p->swparams);
1046 p->swparams = NULL;
1048 err = snd_pcm_prepare (p->handle);
1049 if (err < 0)
1050 alsa_sound_perror ("Could not prepare audio interface for use", err);
1052 if (sd->volume > 0)
1054 int chn;
1055 snd_mixer_t *handle;
1056 snd_mixer_elem_t *e;
1057 const char *file = sd->file ? sd->file : DEFAULT_ALSA_SOUND_DEVICE;
1059 if (snd_mixer_open (&handle, 0) >= 0)
1061 if (snd_mixer_attach (handle, file) >= 0
1062 && snd_mixer_load (handle) >= 0
1063 && snd_mixer_selem_register (handle, NULL, NULL) >= 0)
1064 for (e = snd_mixer_first_elem (handle);
1066 e = snd_mixer_elem_next (e))
1068 if (snd_mixer_selem_has_playback_volume (e))
1070 long pmin, pmax, vol;
1071 snd_mixer_selem_get_playback_volume_range (e, &pmin, &pmax);
1072 vol = pmin + (sd->volume * (pmax - pmin)) / 100;
1074 for (chn = 0; chn <= SND_MIXER_SCHN_LAST; chn++)
1075 snd_mixer_selem_set_playback_volume (e, chn, vol);
1078 snd_mixer_close(handle);
1084 /* Close device SD if it is open. */
1086 static void
1087 alsa_close (struct sound_device *sd)
1089 struct alsa_params *p = (struct alsa_params *) sd->data;
1090 if (p)
1092 if (p->hwparams)
1093 snd_pcm_hw_params_free (p->hwparams);
1094 if (p->swparams)
1095 snd_pcm_sw_params_free (p->swparams);
1096 if (p->handle)
1098 snd_pcm_drain (p->handle);
1099 snd_pcm_close (p->handle);
1101 free (p);
1105 /* Choose device-dependent format for device SD from sound file S. */
1107 static void
1108 alsa_choose_format (struct sound_device *sd, struct sound *s)
1110 struct alsa_params *p = (struct alsa_params *) sd->data;
1111 if (s->type == RIFF)
1113 struct wav_header *h = (struct wav_header *) s->header;
1114 if (h->precision == 8)
1115 sd->format = SND_PCM_FORMAT_U8;
1116 else if (h->precision == 16)
1117 sd->format = SND_PCM_FORMAT_S16_LE;
1118 else
1119 error ("Unsupported WAV file format");
1121 else if (s->type == SUN_AUDIO)
1123 struct au_header *header = (struct au_header *) s->header;
1124 switch (header->encoding)
1126 case AU_ENCODING_ULAW_8:
1127 sd->format = SND_PCM_FORMAT_MU_LAW;
1128 break;
1129 case AU_ENCODING_ALAW_8:
1130 sd->format = SND_PCM_FORMAT_A_LAW;
1131 break;
1132 case AU_ENCODING_IEEE32:
1133 sd->format = SND_PCM_FORMAT_FLOAT_BE;
1134 break;
1135 case AU_ENCODING_IEEE64:
1136 sd->format = SND_PCM_FORMAT_FLOAT64_BE;
1137 break;
1138 case AU_ENCODING_8:
1139 sd->format = SND_PCM_FORMAT_S8;
1140 break;
1141 case AU_ENCODING_16:
1142 sd->format = SND_PCM_FORMAT_S16_BE;
1143 break;
1144 case AU_ENCODING_24:
1145 sd->format = SND_PCM_FORMAT_S24_BE;
1146 break;
1147 case AU_ENCODING_32:
1148 sd->format = SND_PCM_FORMAT_S32_BE;
1149 break;
1151 default:
1152 error ("Unsupported AU file format");
1155 else
1156 abort ();
1160 /* Write NBYTES bytes from BUFFER to device SD. */
1162 static void
1163 alsa_write (struct sound_device *sd, const char *buffer, int nbytes)
1165 struct alsa_params *p = (struct alsa_params *) sd->data;
1167 /* The the third parameter to snd_pcm_writei is frames, not bytes. */
1168 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
1169 int nwritten = 0;
1170 int err;
1172 while (nwritten < nbytes)
1174 snd_pcm_uframes_t frames = (nbytes - nwritten)/fact;
1175 if (frames == 0) break;
1177 err = snd_pcm_writei (p->handle, buffer + nwritten, frames);
1178 if (err < 0)
1180 if (err == -EPIPE)
1181 { /* under-run */
1182 err = snd_pcm_prepare (p->handle);
1183 if (err < 0)
1184 alsa_sound_perror ("Can't recover from underrun, prepare failed",
1185 err);
1187 else if (err == -ESTRPIPE)
1189 while ((err = snd_pcm_resume (p->handle)) == -EAGAIN)
1190 sleep(1); /* wait until the suspend flag is released */
1191 if (err < 0)
1193 err = snd_pcm_prepare (p->handle);
1194 if (err < 0)
1195 alsa_sound_perror ("Can't recover from suspend, "
1196 "prepare failed",
1197 err);
1200 else
1201 alsa_sound_perror ("Error writing to sound device", err);
1204 else
1205 nwritten += err * fact;
1209 static void
1210 snd_error_quiet (const char *file, int line, const char *function, int err,
1211 const char *fmt)
1215 /* Initialize device SD. Set up the interface functions in the device
1216 structure. */
1218 static int
1219 alsa_init (struct sound_device *sd)
1221 const char *file;
1222 snd_pcm_t *handle;
1223 int err;
1225 /* Open the sound device. Default is "default". */
1226 if (sd->file)
1227 file = sd->file;
1228 else
1229 file = DEFAULT_ALSA_SOUND_DEVICE;
1231 snd_lib_error_set_handler ((snd_lib_error_handler_t) snd_error_quiet);
1232 err = snd_pcm_open (&handle, file, SND_PCM_STREAM_PLAYBACK, 0);
1233 snd_lib_error_set_handler (NULL);
1234 if (err < 0)
1235 return 0;
1236 snd_pcm_close (handle);
1238 sd->fd = -1;
1239 sd->open = alsa_open;
1240 sd->close = alsa_close;
1241 sd->configure = alsa_configure;
1242 sd->choose_format = alsa_choose_format;
1243 sd->write = alsa_write;
1244 sd->period_size = alsa_period_size;
1246 return 1;
1249 #endif /* HAVE_ALSA */
1252 /* END: Non Windows functions */
1253 #else /* WINDOWSNT */
1255 /* BEGIN: Windows specific functions */
1257 #define SOUND_WARNING(fun, error, text) \
1259 char buf[1024]; \
1260 char err_string[MAXERRORLENGTH]; \
1261 fun (error, err_string, sizeof (err_string)); \
1262 _snprintf (buf, sizeof (buf), "%s\nError: %s", \
1263 text, err_string); \
1264 sound_warning (buf); \
1267 static int
1268 do_play_sound (const char *psz_file, unsigned long ui_volume)
1270 int i_result = 0;
1271 MCIERROR mci_error = 0;
1272 char sz_cmd_buf[520] = {0};
1273 char sz_ret_buf[520] = {0};
1274 MMRESULT mm_result = MMSYSERR_NOERROR;
1275 unsigned long ui_volume_org = 0;
1276 BOOL b_reset_volume = FALSE;
1278 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1279 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1280 sprintf (sz_cmd_buf,
1281 "open \"%s\" alias GNUEmacs_PlaySound_Device wait",
1282 psz_file);
1283 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1284 if (mci_error != 0)
1286 SOUND_WARNING (mciGetErrorString, mci_error,
1287 "The open mciSendString command failed to open "
1288 "the specified sound file.");
1289 i_result = (int) mci_error;
1290 return i_result;
1292 if ((ui_volume > 0) && (ui_volume != UINT_MAX))
1294 mm_result = waveOutGetVolume ((HWAVEOUT) WAVE_MAPPER, &ui_volume_org);
1295 if (mm_result == MMSYSERR_NOERROR)
1297 b_reset_volume = TRUE;
1298 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume);
1299 if (mm_result != MMSYSERR_NOERROR)
1301 SOUND_WARNING (waveOutGetErrorText, mm_result,
1302 "waveOutSetVolume failed to set the volume level "
1303 "of the WAVE_MAPPER device.\n"
1304 "As a result, the user selected volume level will "
1305 "not be used.");
1308 else
1310 SOUND_WARNING (waveOutGetErrorText, mm_result,
1311 "waveOutGetVolume failed to obtain the original "
1312 "volume level of the WAVE_MAPPER device.\n"
1313 "As a result, the user selected volume level will "
1314 "not be used.");
1317 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1318 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1319 strcpy (sz_cmd_buf, "play GNUEmacs_PlaySound_Device wait");
1320 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1321 if (mci_error != 0)
1323 SOUND_WARNING (mciGetErrorString, mci_error,
1324 "The play mciSendString command failed to play the "
1325 "opened sound file.");
1326 i_result = (int) mci_error;
1328 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1329 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1330 strcpy (sz_cmd_buf, "close GNUEmacs_PlaySound_Device wait");
1331 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1332 if (b_reset_volume == TRUE)
1334 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume_org);
1335 if (mm_result != MMSYSERR_NOERROR)
1337 SOUND_WARNING (waveOutGetErrorText, mm_result,
1338 "waveOutSetVolume failed to reset the original volume "
1339 "level of the WAVE_MAPPER device.");
1342 return i_result;
1345 /* END: Windows specific functions */
1347 #endif /* WINDOWSNT */
1349 DEFUN ("play-sound-internal", Fplay_sound_internal, Splay_sound_internal, 1, 1, 0,
1350 doc: /* Play sound SOUND.
1352 Internal use only, use `play-sound' instead. */)
1353 (Lisp_Object sound)
1355 Lisp_Object attrs[SOUND_ATTR_SENTINEL];
1356 int count = SPECPDL_INDEX ();
1358 #ifndef WINDOWSNT
1359 Lisp_Object file;
1360 struct gcpro gcpro1, gcpro2;
1361 Lisp_Object args[2];
1362 #else /* WINDOWSNT */
1363 int len = 0;
1364 Lisp_Object lo_file = {0};
1365 char * psz_file = NULL;
1366 unsigned long ui_volume_tmp = UINT_MAX;
1367 unsigned long ui_volume = UINT_MAX;
1368 int i_result = 0;
1369 #endif /* WINDOWSNT */
1371 /* Parse the sound specification. Give up if it is invalid. */
1372 if (!parse_sound (sound, attrs))
1373 error ("Invalid sound specification");
1375 #ifndef WINDOWSNT
1376 file = Qnil;
1377 GCPRO2 (sound, file);
1378 current_sound_device = (struct sound_device *) xmalloc (sizeof (struct sound_device));
1379 memset (current_sound_device, 0, sizeof (struct sound_device));
1380 current_sound = (struct sound *) xmalloc (sizeof (struct sound));
1381 memset (current_sound, 0, sizeof (struct sound));
1382 record_unwind_protect (sound_cleanup, Qnil);
1383 current_sound->header = (char *) alloca (MAX_SOUND_HEADER_BYTES);
1385 if (STRINGP (attrs[SOUND_FILE]))
1387 /* Open the sound file. */
1388 current_sound->fd = openp (Fcons (Vdata_directory, Qnil),
1389 attrs[SOUND_FILE], Qnil, &file, Qnil);
1390 if (current_sound->fd < 0)
1391 sound_perror ("Could not open sound file");
1393 /* Read the first bytes from the file. */
1394 current_sound->header_size
1395 = emacs_read (current_sound->fd, current_sound->header,
1396 MAX_SOUND_HEADER_BYTES);
1397 if (current_sound->header_size < 0)
1398 sound_perror ("Invalid sound file header");
1400 else
1402 current_sound->data = attrs[SOUND_DATA];
1403 current_sound->header_size = min (MAX_SOUND_HEADER_BYTES, SBYTES (current_sound->data));
1404 memcpy (current_sound->header, SDATA (current_sound->data),
1405 current_sound->header_size);
1408 /* Find out the type of sound. Give up if we can't tell. */
1409 find_sound_type (current_sound);
1411 /* Set up a device. */
1412 if (STRINGP (attrs[SOUND_DEVICE]))
1414 int len = SCHARS (attrs[SOUND_DEVICE]);
1415 current_sound_device->file = (char *) alloca (len + 1);
1416 strcpy (current_sound_device->file, SDATA (attrs[SOUND_DEVICE]));
1419 if (INTEGERP (attrs[SOUND_VOLUME]))
1420 current_sound_device->volume = XFASTINT (attrs[SOUND_VOLUME]);
1421 else if (FLOATP (attrs[SOUND_VOLUME]))
1422 current_sound_device->volume = XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1424 args[0] = Qplay_sound_functions;
1425 args[1] = sound;
1426 Frun_hook_with_args (2, args);
1428 #ifdef HAVE_ALSA
1429 if (!alsa_init (current_sound_device))
1430 #endif
1431 if (!vox_init (current_sound_device))
1432 error ("No usable sound device driver found");
1434 /* Open the device. */
1435 current_sound_device->open (current_sound_device);
1437 /* Play the sound. */
1438 current_sound->play (current_sound, current_sound_device);
1440 /* Clean up. */
1441 UNGCPRO;
1443 #else /* WINDOWSNT */
1445 lo_file = Fexpand_file_name (attrs[SOUND_FILE], Qnil);
1446 len = XSTRING (lo_file)->size;
1447 psz_file = (char *) alloca (len + 1);
1448 strcpy (psz_file, XSTRING (lo_file)->data);
1449 if (INTEGERP (attrs[SOUND_VOLUME]))
1451 ui_volume_tmp = XFASTINT (attrs[SOUND_VOLUME]);
1453 else if (FLOATP (attrs[SOUND_VOLUME]))
1455 ui_volume_tmp = (unsigned long) XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1458 Based on some experiments I have conducted, a value of 100 or less
1459 for the sound volume is much too low. You cannot even hear it.
1460 A value of UINT_MAX indicates that you wish for the sound to played
1461 at the maximum possible volume. A value of UINT_MAX/2 plays the
1462 sound at 50% maximum volume. Therefore the value passed to do_play_sound
1463 (and thus to waveOutSetVolume) must be some fraction of UINT_MAX.
1464 The following code adjusts the user specified volume level appropriately.
1466 if ((ui_volume_tmp > 0) && (ui_volume_tmp <= 100))
1468 ui_volume = ui_volume_tmp * (UINT_MAX / 100);
1470 i_result = do_play_sound (psz_file, ui_volume);
1472 #endif /* WINDOWSNT */
1474 unbind_to (count, Qnil);
1475 return Qnil;
1478 /***********************************************************************
1479 Initialization
1480 ***********************************************************************/
1482 void
1483 syms_of_sound (void)
1485 QCdevice = intern_c_string(":device");
1486 staticpro (&QCdevice);
1487 QCvolume = intern_c_string (":volume");
1488 staticpro (&QCvolume);
1489 Qsound = intern_c_string ("sound");
1490 staticpro (&Qsound);
1491 Qplay_sound_functions = intern_c_string ("play-sound-functions");
1492 staticpro (&Qplay_sound_functions);
1494 defsubr (&Splay_sound_internal);
1498 void
1499 init_sound (void)
1503 #endif /* HAVE_SOUND */
1505 /* arch-tag: dd850ad8-0433-4e2c-9cba-b7aeeccc0dbd
1506 (do not change this comment) */