]> code.delx.au - gnu-emacs/blob - src/sound.c
Update copyright year to 2015
[gnu-emacs] / src / sound.c
1 /* sound.c -- sound support.
2
3 Copyright (C) 1998-1999, 2001-2015 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
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.
11
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.
16
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/>. */
19
20 /* Written by Gerd Moellmann <gerd@gnu.org>. Tested with Luigi's
21 driver on FreeBSD 2.2.7 with a SoundBlaster 16. */
22
23 /*
24 Modified by Ben Key <Bkey1@tampabay.rr.com> to add a partial
25 implementation of the play-sound specification for Windows.
26
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.
32
33 The Windows implementation of play-sound is implemented via the
34 Windows API functions mciSendString, waveOutGetVolume, and
35 waveOutSetVolume which are exported by Winmm.dll.
36 */
37
38 #include <config.h>
39
40 #if defined HAVE_SOUND
41
42 /* BEGIN: Common Includes */
43 #include <fcntl.h>
44 #include <unistd.h>
45 #include <sys/types.h>
46 #include <errno.h>
47
48 #include "lisp.h"
49 #include "dispextern.h"
50 #include "atimer.h"
51 #include "syssignal.h"
52 /* END: Common Includes */
53
54
55 /* BEGIN: Non Windows Includes */
56 #ifndef WINDOWSNT
57
58 #include <byteswap.h>
59
60 #include <sys/ioctl.h>
61
62 /* FreeBSD has machine/soundcard.h. Voxware sound driver docs mention
63 sys/soundcard.h. So, let's try whatever's there. */
64
65 #ifdef HAVE_MACHINE_SOUNDCARD_H
66 #include <machine/soundcard.h>
67 #endif
68 #ifdef HAVE_SYS_SOUNDCARD_H
69 #include <sys/soundcard.h>
70 #endif
71 #ifdef HAVE_SOUNDCARD_H
72 #include <soundcard.h>
73 #endif
74 #ifdef HAVE_ALSA
75 #ifdef ALSA_SUBDIR_INCLUDE
76 #include <alsa/asoundlib.h>
77 #else
78 #include <asoundlib.h>
79 #endif /* ALSA_SUBDIR_INCLUDE */
80 #endif /* HAVE_ALSA */
81
82 /* END: Non Windows Includes */
83
84 #else /* WINDOWSNT */
85
86 /* BEGIN: Windows Specific Includes */
87 #include <stdio.h>
88 #include <limits.h>
89 #include <windows.h>
90 #include <mmsystem.h>
91
92 #include "coding.h"
93 #include "w32.h"
94 /* END: Windows Specific Includes */
95
96 #endif /* WINDOWSNT */
97
98 /* BEGIN: Common Definitions */
99
100 /* Symbols. */
101
102 static Lisp_Object QCvolume, QCdevice;
103 static Lisp_Object Qsound;
104 static Lisp_Object Qplay_sound_functions;
105
106 /* Indices of attributes in a sound attributes vector. */
107
108 enum sound_attr
109 {
110 SOUND_FILE,
111 SOUND_DATA,
112 SOUND_DEVICE,
113 SOUND_VOLUME,
114 SOUND_ATTR_SENTINEL
115 };
116
117 /* END: Common Definitions */
118
119 /* BEGIN: Non Windows Definitions */
120 #ifndef WINDOWSNT
121
122 /* Structure forward declarations. */
123
124 struct sound;
125 struct sound_device;
126
127 /* The file header of RIFF-WAVE files (*.wav). Files are always in
128 little-endian byte-order. */
129
130 struct wav_header
131 {
132 u_int32_t magic;
133 u_int32_t length;
134 u_int32_t chunk_type;
135 u_int32_t chunk_format;
136 u_int32_t chunk_length;
137 u_int16_t format;
138 u_int16_t channels;
139 u_int32_t sample_rate;
140 u_int32_t bytes_per_second;
141 u_int16_t sample_size;
142 u_int16_t precision;
143 u_int32_t chunk_data;
144 u_int32_t data_length;
145 };
146
147 /* The file header of Sun adio files (*.au). Files are always in
148 big-endian byte-order. */
149
150 struct au_header
151 {
152 /* ASCII ".snd" */
153 u_int32_t magic_number;
154
155 /* Offset of data part from start of file. Minimum value is 24. */
156 u_int32_t data_offset;
157
158 /* Size of data part, 0xffffffff if unknown. */
159 u_int32_t data_size;
160
161 /* Data encoding format.
162 1 8-bit ISDN u-law
163 2 8-bit linear PCM (REF-PCM)
164 3 16-bit linear PCM
165 4 24-bit linear PCM
166 5 32-bit linear PCM
167 6 32-bit IEEE floating-point
168 7 64-bit IEEE floating-point
169 23 8-bit u-law compressed using CCITT 0.721 ADPCM voice data
170 encoding scheme. */
171 u_int32_t encoding;
172
173 /* Number of samples per second. */
174 u_int32_t sample_rate;
175
176 /* Number of interleaved channels. */
177 u_int32_t channels;
178 };
179
180 /* Maximum of all sound file headers sizes. */
181
182 #define MAX_SOUND_HEADER_BYTES \
183 max (sizeof (struct wav_header), sizeof (struct au_header))
184
185 /* Interface structure for sound devices. */
186
187 struct sound_device
188 {
189 /* If a string, the name of the device; otherwise use a default. */
190 Lisp_Object file;
191
192 /* File descriptor of the device. */
193 int fd;
194
195 /* Device-dependent format. */
196 int format;
197
198 /* Volume (0..100). Zero means unspecified. */
199 int volume;
200
201 /* Sample size. */
202 int sample_size;
203
204 /* Sample rate. */
205 int sample_rate;
206
207 /* Bytes per second. */
208 int bps;
209
210 /* 1 = mono, 2 = stereo, 0 = don't set. */
211 int channels;
212
213 /* Open device SD. */
214 void (* open) (struct sound_device *sd);
215
216 /* Close device SD. */
217 void (* close) (struct sound_device *sd);
218
219 /* Configure SD according to device-dependent parameters. */
220 void (* configure) (struct sound_device *device);
221
222 /* Choose a device-dependent format for outputting sound S. */
223 void (* choose_format) (struct sound_device *sd,
224 struct sound *s);
225
226 /* Return a preferred data size in bytes to be sent to write (below)
227 each time. 2048 is used if this is NULL. */
228 ptrdiff_t (* period_size) (struct sound_device *sd);
229
230 /* Write NYBTES bytes from BUFFER to device SD. */
231 void (* write) (struct sound_device *sd, const char *buffer,
232 ptrdiff_t nbytes);
233
234 /* A place for devices to store additional data. */
235 void *data;
236 };
237
238 /* An enumerator for each supported sound file type. */
239
240 enum sound_type
241 {
242 RIFF,
243 SUN_AUDIO
244 };
245
246 /* Interface structure for sound files. */
247
248 struct sound
249 {
250 /* The type of the file. */
251 enum sound_type type;
252
253 /* File descriptor of a sound file. */
254 int fd;
255
256 /* Pointer to sound file header. This contains header_size bytes
257 read from the start of a sound file. */
258 char *header;
259
260 /* Number of bytes read from sound file. This is always <=
261 MAX_SOUND_HEADER_BYTES. */
262 int header_size;
263
264 /* Sound data, if a string. */
265 Lisp_Object data;
266
267 /* Play sound file S on device SD. */
268 void (* play) (struct sound *s, struct sound_device *sd);
269 };
270
271 /* These are set during `play-sound-internal' so that sound_cleanup has
272 access to them. */
273
274 static struct sound_device *current_sound_device;
275 static struct sound *current_sound;
276
277 /* Function prototypes. */
278
279 static void vox_write (struct sound_device *, const char *, ptrdiff_t);
280 static bool wav_init (struct sound *);
281 static void wav_play (struct sound *, struct sound_device *);
282 static bool au_init (struct sound *);
283 static void au_play (struct sound *, struct sound_device *);
284
285 /* END: Non Windows Definitions */
286 #else /* WINDOWSNT */
287
288 /* BEGIN: Windows Specific Definitions */
289 static int do_play_sound (const char *, unsigned long);
290 /*
291 END: Windows Specific Definitions */
292 #endif /* WINDOWSNT */
293
294 \f
295 /***********************************************************************
296 General
297 ***********************************************************************/
298
299 /* BEGIN: Common functions */
300
301 /* Like perror, but signals an error. */
302
303 static _Noreturn void
304 sound_perror (const char *msg)
305 {
306 int saved_errno = errno;
307
308 turn_on_atimers (1);
309 #ifdef USABLE_SIGIO
310 {
311 sigset_t unblocked;
312 sigemptyset (&unblocked);
313 sigaddset (&unblocked, SIGIO);
314 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
315 }
316 #endif
317 if (saved_errno != 0)
318 error ("%s: %s", msg, strerror (saved_errno));
319 else
320 error ("%s", msg);
321 }
322
323
324 /* Display a warning message. */
325
326 static void
327 sound_warning (const char *msg)
328 {
329 message1 (msg);
330 }
331
332
333 /* Parse sound specification SOUND, and fill ATTRS with what is
334 found. Value is non-zero if SOUND Is a valid sound specification.
335 A valid sound specification is a list starting with the symbol
336 `sound'. The rest of the list is a property list which may
337 contain the following key/value pairs:
338
339 - `:file FILE'
340
341 FILE is the sound file to play. If it isn't an absolute name,
342 it's searched under `data-directory'.
343
344 - `:data DATA'
345
346 DATA is a string containing sound data. Either :file or :data
347 may be present, but not both.
348
349 - `:device DEVICE'
350
351 DEVICE is the name of the device to play on, e.g. "/dev/dsp2".
352 If not specified, a default device is used.
353
354 - `:volume VOL'
355
356 VOL must be an integer in the range [0, 100], or a float in the
357 range [0, 1]. */
358
359 static bool
360 parse_sound (Lisp_Object sound, Lisp_Object *attrs)
361 {
362 /* SOUND must be a list starting with the symbol `sound'. */
363 if (!CONSP (sound) || !EQ (XCAR (sound), Qsound))
364 return 0;
365
366 sound = XCDR (sound);
367 attrs[SOUND_FILE] = Fplist_get (sound, QCfile);
368 attrs[SOUND_DATA] = Fplist_get (sound, QCdata);
369 attrs[SOUND_DEVICE] = Fplist_get (sound, QCdevice);
370 attrs[SOUND_VOLUME] = Fplist_get (sound, QCvolume);
371
372 #ifndef WINDOWSNT
373 /* File name or data must be specified. */
374 if (!STRINGP (attrs[SOUND_FILE])
375 && !STRINGP (attrs[SOUND_DATA]))
376 return 0;
377 #else /* WINDOWSNT */
378 /*
379 Data is not supported in Windows. Therefore a
380 File name MUST be supplied.
381 */
382 if (!STRINGP (attrs[SOUND_FILE]))
383 {
384 return 0;
385 }
386 #endif /* WINDOWSNT */
387
388 /* Volume must be in the range 0..100 or unspecified. */
389 if (!NILP (attrs[SOUND_VOLUME]))
390 {
391 if (INTEGERP (attrs[SOUND_VOLUME]))
392 {
393 if (XINT (attrs[SOUND_VOLUME]) < 0
394 || XINT (attrs[SOUND_VOLUME]) > 100)
395 return 0;
396 }
397 else if (FLOATP (attrs[SOUND_VOLUME]))
398 {
399 if (XFLOAT_DATA (attrs[SOUND_VOLUME]) < 0
400 || XFLOAT_DATA (attrs[SOUND_VOLUME]) > 1)
401 return 0;
402 }
403 else
404 return 0;
405 }
406
407 #ifndef WINDOWSNT
408 /* Device must be a string or unspecified. */
409 if (!NILP (attrs[SOUND_DEVICE])
410 && !STRINGP (attrs[SOUND_DEVICE]))
411 return 0;
412 #endif /* WINDOWSNT */
413 /*
414 Since device is ignored in Windows, it does not matter
415 what it is.
416 */
417 return 1;
418 }
419
420 /* END: Common functions */
421
422 /* BEGIN: Non Windows functions */
423 #ifndef WINDOWSNT
424
425 /* Return S's value as a string if S is a string, otherwise DEFAULT_VALUE. */
426
427 static char const *
428 string_default (Lisp_Object s, char const *default_value)
429 {
430 return STRINGP (s) ? SSDATA (s) : default_value;
431 }
432
433
434 /* Find out the type of the sound file whose file descriptor is FD.
435 S is the sound file structure to fill in. */
436
437 static void
438 find_sound_type (struct sound *s)
439 {
440 if (!wav_init (s) && !au_init (s))
441 error ("Unknown sound format");
442 }
443
444
445 /* Function installed by play-sound-internal with record_unwind_protect_void. */
446
447 static void
448 sound_cleanup (void)
449 {
450 if (current_sound_device->close)
451 current_sound_device->close (current_sound_device);
452 if (current_sound->fd > 0)
453 emacs_close (current_sound->fd);
454 xfree (current_sound_device);
455 xfree (current_sound);
456 }
457
458 /***********************************************************************
459 Byte-order Conversion
460 ***********************************************************************/
461
462 /* Convert 32-bit value VALUE which is in little-endian byte-order
463 to host byte-order. */
464
465 static u_int32_t
466 le2hl (u_int32_t value)
467 {
468 #ifdef WORDS_BIGENDIAN
469 value = bswap_32 (value);
470 #endif
471 return value;
472 }
473
474
475 /* Convert 16-bit value VALUE which is in little-endian byte-order
476 to host byte-order. */
477
478 static u_int16_t
479 le2hs (u_int16_t value)
480 {
481 #ifdef WORDS_BIGENDIAN
482 value = bswap_16 (value);
483 #endif
484 return value;
485 }
486
487
488 /* Convert 32-bit value VALUE which is in big-endian byte-order
489 to host byte-order. */
490
491 static u_int32_t
492 be2hl (u_int32_t value)
493 {
494 #ifndef WORDS_BIGENDIAN
495 value = bswap_32 (value);
496 #endif
497 return value;
498 }
499
500 /***********************************************************************
501 RIFF-WAVE (*.wav)
502 ***********************************************************************/
503
504 /* Try to initialize sound file S from S->header. S->header
505 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
506 sound file. If the file is a WAV-format file, set up interface
507 functions in S and convert header fields to host byte-order.
508 Value is true if the file is a WAV file. */
509
510 static bool
511 wav_init (struct sound *s)
512 {
513 struct wav_header *header = (struct wav_header *) s->header;
514
515 if (s->header_size < sizeof *header
516 || memcmp (s->header, "RIFF", 4) != 0)
517 return 0;
518
519 /* WAV files are in little-endian order. Convert the header
520 if on a big-endian machine. */
521 header->magic = le2hl (header->magic);
522 header->length = le2hl (header->length);
523 header->chunk_type = le2hl (header->chunk_type);
524 header->chunk_format = le2hl (header->chunk_format);
525 header->chunk_length = le2hl (header->chunk_length);
526 header->format = le2hs (header->format);
527 header->channels = le2hs (header->channels);
528 header->sample_rate = le2hl (header->sample_rate);
529 header->bytes_per_second = le2hl (header->bytes_per_second);
530 header->sample_size = le2hs (header->sample_size);
531 header->precision = le2hs (header->precision);
532 header->chunk_data = le2hl (header->chunk_data);
533 header->data_length = le2hl (header->data_length);
534
535 /* Set up the interface functions for WAV. */
536 s->type = RIFF;
537 s->play = wav_play;
538
539 return 1;
540 }
541
542
543 /* Play RIFF-WAVE audio file S on sound device SD. */
544
545 static void
546 wav_play (struct sound *s, struct sound_device *sd)
547 {
548 struct wav_header *header = (struct wav_header *) s->header;
549
550 /* Let the device choose a suitable device-dependent format
551 for the file. */
552 sd->choose_format (sd, s);
553
554 /* Configure the device. */
555 sd->sample_size = header->sample_size;
556 sd->sample_rate = header->sample_rate;
557 sd->bps = header->bytes_per_second;
558 sd->channels = header->channels;
559 sd->configure (sd);
560
561 /* Copy sound data to the device. The WAV file specification is
562 actually more complex. This simple scheme worked with all WAV
563 files I found so far. If someone feels inclined to implement the
564 whole RIFF-WAVE spec, please do. */
565 if (STRINGP (s->data))
566 sd->write (sd, SSDATA (s->data) + sizeof *header,
567 SBYTES (s->data) - sizeof *header);
568 else
569 {
570 char *buffer;
571 ptrdiff_t nbytes = 0;
572 ptrdiff_t blksize = sd->period_size ? sd->period_size (sd) : 2048;
573 ptrdiff_t data_left = header->data_length;
574
575 buffer = alloca (blksize);
576 lseek (s->fd, sizeof *header, SEEK_SET);
577 while (data_left > 0
578 && (nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
579 {
580 /* Don't play possible garbage at the end of file */
581 if (data_left < nbytes) nbytes = data_left;
582 data_left -= nbytes;
583 sd->write (sd, buffer, nbytes);
584 }
585
586 if (nbytes < 0)
587 sound_perror ("Error reading sound file");
588 }
589 }
590
591
592 /***********************************************************************
593 Sun Audio (*.au)
594 ***********************************************************************/
595
596 /* Sun audio file encodings. */
597
598 enum au_encoding
599 {
600 AU_ENCODING_ULAW_8 = 1,
601 AU_ENCODING_8,
602 AU_ENCODING_16,
603 AU_ENCODING_24,
604 AU_ENCODING_32,
605 AU_ENCODING_IEEE32,
606 AU_ENCODING_IEEE64,
607 AU_COMPRESSED = 23,
608 AU_ENCODING_ALAW_8 = 27
609 };
610
611
612 /* Try to initialize sound file S from S->header. S->header
613 contains the first MAX_SOUND_HEADER_BYTES number of bytes from the
614 sound file. If the file is a AU-format file, set up interface
615 functions in S and convert header fields to host byte-order.
616 Value is true if the file is an AU file. */
617
618 static bool
619 au_init (struct sound *s)
620 {
621 struct au_header *header = (struct au_header *) s->header;
622
623 if (s->header_size < sizeof *header
624 || memcmp (s->header, ".snd", 4) != 0)
625 return 0;
626
627 header->magic_number = be2hl (header->magic_number);
628 header->data_offset = be2hl (header->data_offset);
629 header->data_size = be2hl (header->data_size);
630 header->encoding = be2hl (header->encoding);
631 header->sample_rate = be2hl (header->sample_rate);
632 header->channels = be2hl (header->channels);
633
634 /* Set up the interface functions for AU. */
635 s->type = SUN_AUDIO;
636 s->play = au_play;
637
638 return 1;
639 }
640
641
642 /* Play Sun audio file S on sound device SD. */
643
644 static void
645 au_play (struct sound *s, struct sound_device *sd)
646 {
647 struct au_header *header = (struct au_header *) s->header;
648
649 sd->sample_size = 0;
650 sd->sample_rate = header->sample_rate;
651 sd->bps = 0;
652 sd->channels = header->channels;
653 sd->choose_format (sd, s);
654 sd->configure (sd);
655
656 if (STRINGP (s->data))
657 sd->write (sd, SSDATA (s->data) + header->data_offset,
658 SBYTES (s->data) - header->data_offset);
659 else
660 {
661 ptrdiff_t blksize = sd->period_size ? sd->period_size (sd) : 2048;
662 char *buffer;
663 ptrdiff_t nbytes;
664
665 /* Seek */
666 lseek (s->fd, header->data_offset, SEEK_SET);
667
668 /* Copy sound data to the device. */
669 buffer = alloca (blksize);
670 while ((nbytes = emacs_read (s->fd, buffer, blksize)) > 0)
671 sd->write (sd, buffer, nbytes);
672
673 if (nbytes < 0)
674 sound_perror ("Error reading sound file");
675 }
676 }
677
678
679 /***********************************************************************
680 Voxware Driver Interface
681 ***********************************************************************/
682
683 /* This driver is available on GNU/Linux, and the free BSDs. FreeBSD
684 has a compatible own driver aka Luigi's driver. */
685
686
687 /* Open device SD. If SD->file is a string, open that device,
688 otherwise use a default device name. */
689
690 static void
691 vox_open (struct sound_device *sd)
692 {
693 /* Open the sound device (eg /dev/dsp). */
694 char const *file = string_default (sd->file, DEFAULT_SOUND_DEVICE);
695 sd->fd = emacs_open (file, O_WRONLY, 0);
696 if (sd->fd < 0)
697 sound_perror (file);
698 }
699
700
701 /* Configure device SD from parameters in it. */
702
703 static void
704 vox_configure (struct sound_device *sd)
705 {
706 int val;
707 #ifdef USABLE_SIGIO
708 sigset_t blocked;
709 #endif
710
711 eassert (sd->fd >= 0);
712
713 /* On GNU/Linux, it seems that the device driver doesn't like to be
714 interrupted by a signal. Block the ones we know to cause
715 troubles. */
716 turn_on_atimers (0);
717 #ifdef USABLE_SIGIO
718 sigemptyset (&blocked);
719 sigaddset (&blocked, SIGIO);
720 pthread_sigmask (SIG_BLOCK, &blocked, 0);
721 #endif
722
723 val = sd->format;
724 if (ioctl (sd->fd, SNDCTL_DSP_SETFMT, &sd->format) < 0
725 || val != sd->format)
726 sound_perror ("Could not set sound format");
727
728 val = sd->channels != 1;
729 if (ioctl (sd->fd, SNDCTL_DSP_STEREO, &val) < 0
730 || val != (sd->channels != 1))
731 sound_perror ("Could not set stereo/mono");
732
733 /* I think bps and sampling_rate are the same, but who knows.
734 Check this. and use SND_DSP_SPEED for both. */
735 if (sd->sample_rate > 0)
736 {
737 val = sd->sample_rate;
738 if (ioctl (sd->fd, SNDCTL_DSP_SPEED, &sd->sample_rate) < 0)
739 sound_perror ("Could not set sound speed");
740 else if (val != sd->sample_rate)
741 sound_warning ("Could not set sample rate");
742 }
743
744 if (sd->volume > 0)
745 {
746 int volume = sd->volume & 0xff;
747 volume |= volume << 8;
748 /* This may fail if there is no mixer. Ignore the failure. */
749 ioctl (sd->fd, SOUND_MIXER_WRITE_PCM, &volume);
750 }
751
752 turn_on_atimers (1);
753 #ifdef USABLE_SIGIO
754 pthread_sigmask (SIG_UNBLOCK, &blocked, 0);
755 #endif
756 }
757
758
759 /* Close device SD if it is open. */
760
761 static void
762 vox_close (struct sound_device *sd)
763 {
764 if (sd->fd >= 0)
765 {
766 /* On GNU/Linux, it seems that the device driver doesn't like to
767 be interrupted by a signal. Block the ones we know to cause
768 troubles. */
769 #ifdef USABLE_SIGIO
770 sigset_t blocked;
771 sigemptyset (&blocked);
772 sigaddset (&blocked, SIGIO);
773 pthread_sigmask (SIG_BLOCK, &blocked, 0);
774 #endif
775 turn_on_atimers (0);
776
777 /* Flush sound data, and reset the device. */
778 ioctl (sd->fd, SNDCTL_DSP_SYNC, NULL);
779
780 turn_on_atimers (1);
781 #ifdef USABLE_SIGIO
782 pthread_sigmask (SIG_UNBLOCK, &blocked, 0);
783 #endif
784
785 /* Close the device. */
786 emacs_close (sd->fd);
787 sd->fd = -1;
788 }
789 }
790
791
792 /* Choose device-dependent format for device SD from sound file S. */
793
794 static void
795 vox_choose_format (struct sound_device *sd, struct sound *s)
796 {
797 if (s->type == RIFF)
798 {
799 struct wav_header *h = (struct wav_header *) s->header;
800 if (h->precision == 8)
801 sd->format = AFMT_U8;
802 else if (h->precision == 16)
803 sd->format = AFMT_S16_LE;
804 else
805 error ("Unsupported WAV file format");
806 }
807 else if (s->type == SUN_AUDIO)
808 {
809 struct au_header *header = (struct au_header *) s->header;
810 switch (header->encoding)
811 {
812 case AU_ENCODING_ULAW_8:
813 case AU_ENCODING_IEEE32:
814 case AU_ENCODING_IEEE64:
815 sd->format = AFMT_MU_LAW;
816 break;
817
818 case AU_ENCODING_8:
819 case AU_ENCODING_16:
820 case AU_ENCODING_24:
821 case AU_ENCODING_32:
822 sd->format = AFMT_S16_LE;
823 break;
824
825 default:
826 error ("Unsupported AU file format");
827 }
828 }
829 else
830 emacs_abort ();
831 }
832
833
834 /* Initialize device SD. Set up the interface functions in the device
835 structure. */
836
837 static bool
838 vox_init (struct sound_device *sd)
839 {
840 /* Open the sound device (eg /dev/dsp). */
841 char const *file = string_default (sd->file, DEFAULT_SOUND_DEVICE);
842 int fd = emacs_open (file, O_WRONLY, 0);
843 if (fd >= 0)
844 emacs_close (fd);
845 else
846 return 0;
847
848 sd->fd = -1;
849 sd->open = vox_open;
850 sd->close = vox_close;
851 sd->configure = vox_configure;
852 sd->choose_format = vox_choose_format;
853 sd->write = vox_write;
854 sd->period_size = NULL;
855
856 return 1;
857 }
858
859 /* Write NBYTES bytes from BUFFER to device SD. */
860
861 static void
862 vox_write (struct sound_device *sd, const char *buffer, ptrdiff_t nbytes)
863 {
864 if (emacs_write_sig (sd->fd, buffer, nbytes) != nbytes)
865 sound_perror ("Error writing to sound device");
866 }
867
868 #ifdef HAVE_ALSA
869 /***********************************************************************
870 ALSA Driver Interface
871 ***********************************************************************/
872
873 /* This driver is available on GNU/Linux. */
874
875 #ifndef DEFAULT_ALSA_SOUND_DEVICE
876 #define DEFAULT_ALSA_SOUND_DEVICE "default"
877 #endif
878
879 static _Noreturn void
880 alsa_sound_perror (const char *msg, int err)
881 {
882 error ("%s: %s", msg, snd_strerror (err));
883 }
884
885 struct alsa_params
886 {
887 snd_pcm_t *handle;
888 snd_pcm_hw_params_t *hwparams;
889 snd_pcm_sw_params_t *swparams;
890 snd_pcm_uframes_t period_size;
891 };
892
893 /* Open device SD. If SD->file is a string, open that device,
894 otherwise use a default device name. */
895
896 static void
897 alsa_open (struct sound_device *sd)
898 {
899 /* Open the sound device. Default is "default". */
900 struct alsa_params *p = xmalloc (sizeof *p);
901 char const *file = string_default (sd->file, DEFAULT_ALSA_SOUND_DEVICE);
902 int err;
903
904 p->handle = NULL;
905 p->hwparams = NULL;
906 p->swparams = NULL;
907
908 sd->fd = -1;
909 sd->data = p;
910
911
912 err = snd_pcm_open (&p->handle, file, SND_PCM_STREAM_PLAYBACK, 0);
913 if (err < 0)
914 alsa_sound_perror (file, err);
915 }
916
917 static ptrdiff_t
918 alsa_period_size (struct sound_device *sd)
919 {
920 struct alsa_params *p = (struct alsa_params *) sd->data;
921 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
922 return p->period_size * (fact > 0 ? fact : 1);
923 }
924
925 static void
926 alsa_configure (struct sound_device *sd)
927 {
928 int val, err, dir;
929 unsigned uval;
930 struct alsa_params *p = (struct alsa_params *) sd->data;
931 snd_pcm_uframes_t buffer_size;
932
933 eassert (p->handle != 0);
934
935 err = snd_pcm_hw_params_malloc (&p->hwparams);
936 if (err < 0)
937 alsa_sound_perror ("Could not allocate hardware parameter structure", err);
938
939 err = snd_pcm_sw_params_malloc (&p->swparams);
940 if (err < 0)
941 alsa_sound_perror ("Could not allocate software parameter structure", err);
942
943 err = snd_pcm_hw_params_any (p->handle, p->hwparams);
944 if (err < 0)
945 alsa_sound_perror ("Could not initialize hardware parameter structure", err);
946
947 err = snd_pcm_hw_params_set_access (p->handle, p->hwparams,
948 SND_PCM_ACCESS_RW_INTERLEAVED);
949 if (err < 0)
950 alsa_sound_perror ("Could not set access type", err);
951
952 val = sd->format;
953 err = snd_pcm_hw_params_set_format (p->handle, p->hwparams, val);
954 if (err < 0)
955 alsa_sound_perror ("Could not set sound format", err);
956
957 uval = sd->sample_rate;
958 err = snd_pcm_hw_params_set_rate_near (p->handle, p->hwparams, &uval, 0);
959 if (err < 0)
960 alsa_sound_perror ("Could not set sample rate", err);
961
962 val = sd->channels;
963 err = snd_pcm_hw_params_set_channels (p->handle, p->hwparams, val);
964 if (err < 0)
965 alsa_sound_perror ("Could not set channel count", err);
966
967 err = snd_pcm_hw_params (p->handle, p->hwparams);
968 if (err < 0)
969 alsa_sound_perror ("Could not set parameters", err);
970
971
972 err = snd_pcm_hw_params_get_period_size (p->hwparams, &p->period_size, &dir);
973 if (err < 0)
974 alsa_sound_perror ("Unable to get period size for playback", err);
975
976 err = snd_pcm_hw_params_get_buffer_size (p->hwparams, &buffer_size);
977 if (err < 0)
978 alsa_sound_perror ("Unable to get buffer size for playback", err);
979
980 err = snd_pcm_sw_params_current (p->handle, p->swparams);
981 if (err < 0)
982 alsa_sound_perror ("Unable to determine current swparams for playback",
983 err);
984
985 /* Start the transfer when the buffer is almost full */
986 err = snd_pcm_sw_params_set_start_threshold (p->handle, p->swparams,
987 (buffer_size / p->period_size)
988 * p->period_size);
989 if (err < 0)
990 alsa_sound_perror ("Unable to set start threshold mode for playback", err);
991
992 /* Allow the transfer when at least period_size samples can be processed */
993 err = snd_pcm_sw_params_set_avail_min (p->handle, p->swparams, p->period_size);
994 if (err < 0)
995 alsa_sound_perror ("Unable to set avail min for playback", err);
996
997 err = snd_pcm_sw_params (p->handle, p->swparams);
998 if (err < 0)
999 alsa_sound_perror ("Unable to set sw params for playback\n", err);
1000
1001 snd_pcm_hw_params_free (p->hwparams);
1002 p->hwparams = NULL;
1003 snd_pcm_sw_params_free (p->swparams);
1004 p->swparams = NULL;
1005
1006 err = snd_pcm_prepare (p->handle);
1007 if (err < 0)
1008 alsa_sound_perror ("Could not prepare audio interface for use", err);
1009
1010 if (sd->volume > 0)
1011 {
1012 int chn;
1013 snd_mixer_t *handle;
1014 snd_mixer_elem_t *e;
1015 if (snd_mixer_open (&handle, 0) >= 0)
1016 {
1017 char const *file = string_default (sd->file,
1018 DEFAULT_ALSA_SOUND_DEVICE);
1019 if (snd_mixer_attach (handle, file) >= 0
1020 && snd_mixer_load (handle) >= 0
1021 && snd_mixer_selem_register (handle, NULL, NULL) >= 0)
1022 for (e = snd_mixer_first_elem (handle);
1023 e;
1024 e = snd_mixer_elem_next (e))
1025 {
1026 if (snd_mixer_selem_has_playback_volume (e))
1027 {
1028 long pmin, pmax, vol;
1029 snd_mixer_selem_get_playback_volume_range (e, &pmin, &pmax);
1030 vol = pmin + (sd->volume * (pmax - pmin)) / 100;
1031
1032 for (chn = 0; chn <= SND_MIXER_SCHN_LAST; chn++)
1033 snd_mixer_selem_set_playback_volume (e, chn, vol);
1034 }
1035 }
1036 snd_mixer_close (handle);
1037 }
1038 }
1039 }
1040
1041
1042 /* Close device SD if it is open. */
1043
1044 static void
1045 alsa_close (struct sound_device *sd)
1046 {
1047 struct alsa_params *p = (struct alsa_params *) sd->data;
1048 if (p)
1049 {
1050 if (p->hwparams)
1051 snd_pcm_hw_params_free (p->hwparams);
1052 if (p->swparams)
1053 snd_pcm_sw_params_free (p->swparams);
1054 if (p->handle)
1055 {
1056 snd_pcm_drain (p->handle);
1057 snd_pcm_close (p->handle);
1058 }
1059 xfree (p);
1060 }
1061 }
1062
1063 /* Choose device-dependent format for device SD from sound file S. */
1064
1065 static void
1066 alsa_choose_format (struct sound_device *sd, struct sound *s)
1067 {
1068 if (s->type == RIFF)
1069 {
1070 struct wav_header *h = (struct wav_header *) s->header;
1071 if (h->precision == 8)
1072 sd->format = SND_PCM_FORMAT_U8;
1073 else if (h->precision == 16)
1074 sd->format = SND_PCM_FORMAT_S16_LE;
1075 else
1076 error ("Unsupported WAV file format");
1077 }
1078 else if (s->type == SUN_AUDIO)
1079 {
1080 struct au_header *header = (struct au_header *) s->header;
1081 switch (header->encoding)
1082 {
1083 case AU_ENCODING_ULAW_8:
1084 sd->format = SND_PCM_FORMAT_MU_LAW;
1085 break;
1086 case AU_ENCODING_ALAW_8:
1087 sd->format = SND_PCM_FORMAT_A_LAW;
1088 break;
1089 case AU_ENCODING_IEEE32:
1090 sd->format = SND_PCM_FORMAT_FLOAT_BE;
1091 break;
1092 case AU_ENCODING_IEEE64:
1093 sd->format = SND_PCM_FORMAT_FLOAT64_BE;
1094 break;
1095 case AU_ENCODING_8:
1096 sd->format = SND_PCM_FORMAT_S8;
1097 break;
1098 case AU_ENCODING_16:
1099 sd->format = SND_PCM_FORMAT_S16_BE;
1100 break;
1101 case AU_ENCODING_24:
1102 sd->format = SND_PCM_FORMAT_S24_BE;
1103 break;
1104 case AU_ENCODING_32:
1105 sd->format = SND_PCM_FORMAT_S32_BE;
1106 break;
1107
1108 default:
1109 error ("Unsupported AU file format");
1110 }
1111 }
1112 else
1113 emacs_abort ();
1114 }
1115
1116
1117 /* Write NBYTES bytes from BUFFER to device SD. */
1118
1119 static void
1120 alsa_write (struct sound_device *sd, const char *buffer, ptrdiff_t nbytes)
1121 {
1122 struct alsa_params *p = (struct alsa_params *) sd->data;
1123
1124 /* The the third parameter to snd_pcm_writei is frames, not bytes. */
1125 int fact = snd_pcm_format_size (sd->format, 1) * sd->channels;
1126 ptrdiff_t nwritten = 0;
1127 int err;
1128
1129 while (nwritten < nbytes)
1130 {
1131 snd_pcm_uframes_t frames = (nbytes - nwritten)/fact;
1132 if (frames == 0) break;
1133
1134 err = snd_pcm_writei (p->handle, buffer + nwritten, frames);
1135 if (err < 0)
1136 {
1137 if (err == -EPIPE)
1138 { /* under-run */
1139 err = snd_pcm_prepare (p->handle);
1140 if (err < 0)
1141 alsa_sound_perror ("Can't recover from underrun, prepare failed",
1142 err);
1143 }
1144 else if (err == -ESTRPIPE)
1145 {
1146 while ((err = snd_pcm_resume (p->handle)) == -EAGAIN)
1147 sleep (1); /* wait until the suspend flag is released */
1148 if (err < 0)
1149 {
1150 err = snd_pcm_prepare (p->handle);
1151 if (err < 0)
1152 alsa_sound_perror ("Can't recover from suspend, "
1153 "prepare failed",
1154 err);
1155 }
1156 }
1157 else
1158 alsa_sound_perror ("Error writing to sound device", err);
1159
1160 }
1161 else
1162 nwritten += err * fact;
1163 }
1164 }
1165
1166 static void
1167 snd_error_quiet (const char *file, int line, const char *function, int err,
1168 const char *fmt)
1169 {
1170 }
1171
1172 /* Initialize device SD. Set up the interface functions in the device
1173 structure. */
1174
1175 static bool
1176 alsa_init (struct sound_device *sd)
1177 {
1178 /* Open the sound device. Default is "default". */
1179 char const *file = string_default (sd->file, DEFAULT_ALSA_SOUND_DEVICE);
1180 snd_pcm_t *handle;
1181 int err;
1182
1183 snd_lib_error_set_handler ((snd_lib_error_handler_t) snd_error_quiet);
1184 err = snd_pcm_open (&handle, file, SND_PCM_STREAM_PLAYBACK, 0);
1185 snd_lib_error_set_handler (NULL);
1186 if (err < 0)
1187 return 0;
1188 snd_pcm_close (handle);
1189
1190 sd->fd = -1;
1191 sd->open = alsa_open;
1192 sd->close = alsa_close;
1193 sd->configure = alsa_configure;
1194 sd->choose_format = alsa_choose_format;
1195 sd->write = alsa_write;
1196 sd->period_size = alsa_period_size;
1197
1198 return 1;
1199 }
1200
1201 #endif /* HAVE_ALSA */
1202
1203
1204 /* END: Non Windows functions */
1205 #else /* WINDOWSNT */
1206
1207 /* BEGIN: Windows specific functions */
1208
1209 #define SOUND_WARNING(fun, error, text) \
1210 { \
1211 char buf[1024]; \
1212 char err_string[MAXERRORLENGTH]; \
1213 fun (error, err_string, sizeof (err_string)); \
1214 _snprintf (buf, sizeof (buf), "%s\nError: %s", \
1215 text, err_string); \
1216 sound_warning (buf); \
1217 }
1218
1219 static int
1220 do_play_sound (const char *psz_file, unsigned long ui_volume)
1221 {
1222 int i_result = 0;
1223 MCIERROR mci_error = 0;
1224 char sz_cmd_buf[520] = {0};
1225 char sz_ret_buf[520] = {0};
1226 MMRESULT mm_result = MMSYSERR_NOERROR;
1227 unsigned long ui_volume_org = 0;
1228 BOOL b_reset_volume = FALSE;
1229
1230 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1231 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1232 sprintf (sz_cmd_buf,
1233 "open \"%s\" alias GNUEmacs_PlaySound_Device wait",
1234 psz_file);
1235 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1236 if (mci_error != 0)
1237 {
1238 SOUND_WARNING (mciGetErrorString, mci_error,
1239 "The open mciSendString command failed to open "
1240 "the specified sound file.");
1241 i_result = (int) mci_error;
1242 return i_result;
1243 }
1244 if ((ui_volume > 0) && (ui_volume != UINT_MAX))
1245 {
1246 mm_result = waveOutGetVolume ((HWAVEOUT) WAVE_MAPPER, &ui_volume_org);
1247 if (mm_result == MMSYSERR_NOERROR)
1248 {
1249 b_reset_volume = TRUE;
1250 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume);
1251 if (mm_result != MMSYSERR_NOERROR)
1252 {
1253 SOUND_WARNING (waveOutGetErrorText, mm_result,
1254 "waveOutSetVolume failed to set the volume level "
1255 "of the WAVE_MAPPER device.\n"
1256 "As a result, the user selected volume level will "
1257 "not be used.");
1258 }
1259 }
1260 else
1261 {
1262 SOUND_WARNING (waveOutGetErrorText, mm_result,
1263 "waveOutGetVolume failed to obtain the original "
1264 "volume level of the WAVE_MAPPER device.\n"
1265 "As a result, the user selected volume level will "
1266 "not be used.");
1267 }
1268 }
1269 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1270 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1271 strcpy (sz_cmd_buf, "play GNUEmacs_PlaySound_Device wait");
1272 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1273 if (mci_error != 0)
1274 {
1275 SOUND_WARNING (mciGetErrorString, mci_error,
1276 "The play mciSendString command failed to play the "
1277 "opened sound file.");
1278 i_result = (int) mci_error;
1279 }
1280 memset (sz_cmd_buf, 0, sizeof (sz_cmd_buf));
1281 memset (sz_ret_buf, 0, sizeof (sz_ret_buf));
1282 strcpy (sz_cmd_buf, "close GNUEmacs_PlaySound_Device wait");
1283 mci_error = mciSendString (sz_cmd_buf, sz_ret_buf, sizeof (sz_ret_buf), NULL);
1284 if (b_reset_volume == TRUE)
1285 {
1286 mm_result = waveOutSetVolume ((HWAVEOUT) WAVE_MAPPER, ui_volume_org);
1287 if (mm_result != MMSYSERR_NOERROR)
1288 {
1289 SOUND_WARNING (waveOutGetErrorText, mm_result,
1290 "waveOutSetVolume failed to reset the original volume "
1291 "level of the WAVE_MAPPER device.");
1292 }
1293 }
1294 return i_result;
1295 }
1296
1297 /* END: Windows specific functions */
1298
1299 #endif /* WINDOWSNT */
1300
1301 DEFUN ("play-sound-internal", Fplay_sound_internal, Splay_sound_internal, 1, 1, 0,
1302 doc: /* Play sound SOUND.
1303
1304 Internal use only, use `play-sound' instead. */)
1305 (Lisp_Object sound)
1306 {
1307 Lisp_Object attrs[SOUND_ATTR_SENTINEL];
1308 ptrdiff_t count = SPECPDL_INDEX ();
1309
1310 #ifndef WINDOWSNT
1311 Lisp_Object file;
1312 struct gcpro gcpro1, gcpro2;
1313 Lisp_Object args[2];
1314 #else /* WINDOWSNT */
1315 Lisp_Object lo_file;
1316 unsigned long ui_volume_tmp = UINT_MAX;
1317 unsigned long ui_volume = UINT_MAX;
1318 #endif /* WINDOWSNT */
1319
1320 /* Parse the sound specification. Give up if it is invalid. */
1321 if (!parse_sound (sound, attrs))
1322 error ("Invalid sound specification");
1323
1324 #ifndef WINDOWSNT
1325 file = Qnil;
1326 GCPRO2 (sound, file);
1327 current_sound_device = xzalloc (sizeof *current_sound_device);
1328 current_sound = xzalloc (sizeof *current_sound);
1329 record_unwind_protect_void (sound_cleanup);
1330 current_sound->header = alloca (MAX_SOUND_HEADER_BYTES);
1331
1332 if (STRINGP (attrs[SOUND_FILE]))
1333 {
1334 /* Open the sound file. */
1335 current_sound->fd = openp (list1 (Vdata_directory),
1336 attrs[SOUND_FILE], Qnil, &file, Qnil, false);
1337 if (current_sound->fd < 0)
1338 sound_perror ("Could not open sound file");
1339
1340 /* Read the first bytes from the file. */
1341 current_sound->header_size
1342 = emacs_read (current_sound->fd, current_sound->header,
1343 MAX_SOUND_HEADER_BYTES);
1344 if (current_sound->header_size < 0)
1345 sound_perror ("Invalid sound file header");
1346 }
1347 else
1348 {
1349 current_sound->data = attrs[SOUND_DATA];
1350 current_sound->header_size = min (MAX_SOUND_HEADER_BYTES, SBYTES (current_sound->data));
1351 memcpy (current_sound->header, SDATA (current_sound->data),
1352 current_sound->header_size);
1353 }
1354
1355 /* Find out the type of sound. Give up if we can't tell. */
1356 find_sound_type (current_sound);
1357
1358 /* Set up a device. */
1359 current_sound_device->file = attrs[SOUND_DEVICE];
1360
1361 if (INTEGERP (attrs[SOUND_VOLUME]))
1362 current_sound_device->volume = XFASTINT (attrs[SOUND_VOLUME]);
1363 else if (FLOATP (attrs[SOUND_VOLUME]))
1364 current_sound_device->volume = XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1365
1366 args[0] = Qplay_sound_functions;
1367 args[1] = sound;
1368 Frun_hook_with_args (2, args);
1369
1370 #ifdef HAVE_ALSA
1371 if (!alsa_init (current_sound_device))
1372 #endif
1373 if (!vox_init (current_sound_device))
1374 error ("No usable sound device driver found");
1375
1376 /* Open the device. */
1377 current_sound_device->open (current_sound_device);
1378
1379 /* Play the sound. */
1380 current_sound->play (current_sound, current_sound_device);
1381
1382 /* Clean up. */
1383 UNGCPRO;
1384
1385 #else /* WINDOWSNT */
1386
1387 lo_file = Fexpand_file_name (attrs[SOUND_FILE], Vdata_directory);
1388 lo_file = ENCODE_FILE (lo_file);
1389 /* Since UNICOWS.DLL includes only a stub for mciSendStringW, we
1390 need to encode the file in the ANSI codepage. */
1391 lo_file = ansi_encode_filename (lo_file);
1392 if (INTEGERP (attrs[SOUND_VOLUME]))
1393 {
1394 ui_volume_tmp = XFASTINT (attrs[SOUND_VOLUME]);
1395 }
1396 else if (FLOATP (attrs[SOUND_VOLUME]))
1397 {
1398 ui_volume_tmp = XFLOAT_DATA (attrs[SOUND_VOLUME]) * 100;
1399 }
1400 /*
1401 Based on some experiments I have conducted, a value of 100 or less
1402 for the sound volume is much too low. You cannot even hear it.
1403 A value of UINT_MAX indicates that you wish for the sound to played
1404 at the maximum possible volume. A value of UINT_MAX/2 plays the
1405 sound at 50% maximum volume. Therefore the value passed to do_play_sound
1406 (and thus to waveOutSetVolume) must be some fraction of UINT_MAX.
1407 The following code adjusts the user specified volume level appropriately.
1408 */
1409 if ((ui_volume_tmp > 0) && (ui_volume_tmp <= 100))
1410 {
1411 ui_volume = ui_volume_tmp * (UINT_MAX / 100);
1412 }
1413 do_play_sound (SDATA (lo_file), ui_volume);
1414
1415 #endif /* WINDOWSNT */
1416
1417 unbind_to (count, Qnil);
1418 return Qnil;
1419 }
1420 \f
1421 /***********************************************************************
1422 Initialization
1423 ***********************************************************************/
1424
1425 void
1426 syms_of_sound (void)
1427 {
1428 DEFSYM (QCdevice, ":device");
1429 DEFSYM (QCvolume, ":volume");
1430 DEFSYM (Qsound, "sound");
1431 DEFSYM (Qplay_sound_functions, "play-sound-functions");
1432
1433 defsubr (&Splay_sound_internal);
1434 }
1435
1436 #endif /* HAVE_SOUND */