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