1 /* nas.c --- XEmacs support for the Network Audio System server.
3 * Author: Richard Caley <R.Caley@ed.ac.uk>
5 * Copyright 1994 Free Software Foundation, Inc.
6 * Copyright 1993 Network Computing Devices, Inc.
8 * Permission to use, copy, modify, distribute, and sell this software and
9 * its documentation for any purpose is hereby granted without fee, provided
10 * that the above copyright notice appear in all copies and that both that
11 * copyright notice and this permission notice appear in supporting
12 * documentation, and that the name Network Computing Devices, Inc. not be
13 * used in advertising or publicity pertaining to distribution of this
14 * software without specific, written prior permission.
16 * THIS SOFTWARE IS PROVIDED 'AS-IS'. NETWORK COMPUTING DEVICES, INC.,
17 * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT
18 * LIMITATION ALL IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
19 * PARTICULAR PURPOSE, OR NONINFRINGEMENT. IN NO EVENT SHALL NETWORK
20 * COMPUTING DEVICES, INC., BE LIABLE FOR ANY DAMAGES WHATSOEVER, INCLUDING
21 * SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, INCLUDING LOSS OF USE, DATA,
22 * OR PROFITS, EVEN IF ADVISED OF THE POSSIBILITY THEREOF, AND REGARDLESS OF
23 * WHETHER IN AN ACTION IN CONTRACT, TORT OR NEGLIGENCE, ARISING OUT OF OR IN
24 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
27 /* Synched up with: Not in FSF. */
29 /* There are four compile-time options.
31 * XTOOLKIT This will be part of an Xt program.
33 * XTEVENTS The playing will be supervised asynchronously by the Xt event
34 * loop. If not set, playing will be completed within the call
37 * ROBUST_PLAY Causes errors in nas to be caught. This means that the
38 * program will attempt not to die if the nas server does.
40 * CACHE_SOUNDS Causes the sounds to be played in buckets in the NAS
41 * server. They are named by their comment field, or if that is
42 * empty by the filename, or for play_sound_data by a name made up
43 * from the sample itself.
47 * 10/8/94, rjc Changed names from netaudio to nas
48 * Added back asynchronous play if nas library has
49 * correct error facilities.
50 * 4/11/94, rjc Added wait_for_sounds to be called when user wants to
51 * be sure all play has finished.
52 * 1998-10-01 rlt Added support for WAVE files.
59 #include "syssignal.h"
71 /* NAS <= 1.2p5 defines {BIG,LITTLE}_ENDIAN in <audio/fileutil.h>,
72 conflicting with GNU libc (at least); newer versions avoid this
75 DO NOT USE THOSE MACROS in this file. Use NAS_{BIG,LITTLE}_ENDIAN.
77 It would be slightly more reliable to do this via configure, but that
78 seems unnecessarily complex.
83 #include <audio/audiolib.h>
84 #include <audio/soundlib.h>
85 #include <audio/snd.h>
86 #include <audio/wave.h>
87 #include <audio/fileutil.h>
89 /* NAS <= 1.2p5 <audio/fileutil.h> doesn't define the NAS_ versions */
90 #ifndef NAS_LITTLE_ENDIAN
91 #define NAS_LITTLE_ENDIAN LITTLE_ENDIAN
92 #define NAS_BIG_ENDIAN BIG_ENDIAN
100 # define CACHE_SOUNDS
103 * For old NAS libraries, force playing to be synchronous
104 * and declare the long jump point locally.
107 # if defined (NAS_NO_ERROR_JUMP)
112 jmp_buf AuXtErrorJump;
115 /* The GETTEXT is correct. --ben */
116 # define warn(str) warn_when_safe (Qnas, Qwarning, "nas: %s ", GETTEXT (str))
118 # define play_sound_file nas_play_sound_file
119 # define play_sound_data nas_play_sound_data
120 # define wait_for_sounds nas_wait_for_sounds
121 # define init_play nas_init_play
122 # define close_down_play nas_close_down_play
125 # define warn(str) fprintf (stderr, "%s\n", (str))
129 # include <X11/Intrinsic.h>
130 # include <audio/Xtutil.h>
133 #if defined (ROBUST_PLAY)
134 static AuBool CatchIoErrorAndJump (AuServer *aud);
135 static AuBool CatchErrorAndJump (AuServer *aud, AuErrorEvent *event);
136 SIGTYPE sigpipe_handle (int signo);
139 extern Lisp_Object Vsynchronous_sounds;
141 static Sound SoundOpenDataForReading (unsigned char *data, int length);
143 static AuServer *aud;
145 /* count of sounds currently being played. */
146 static int sounds_in_play;
150 static Display *aud_server;
151 static XtInputId input_id;
153 static char *aud_server;
154 #endif /* XTOOLKIT */
174 SIGTYPE (*old_sigpipe) (int);
177 char * server = DisplayString (display);
178 XtAppContext app_context = XtDisplayToApplicationContext (display);
180 aud_server = display;
187 old_sigpipe = signal (SIGPIPE, sigpipe_handle);
188 if (setjmp (AuXtErrorJump))
190 signal (SIGPIPE, old_sigpipe);
194 return "error in NAS";
198 #if defined (ROBUST_PLAY) && !defined (NAS_NO_ERROR_JUMP)
199 AuDefaultIOErrorHandler = CatchIoErrorAndJump;
200 AuDefaultErrorHandler = CatchErrorAndJump;
206 aud = AuOpenServer (server, 0, NULL, 0, NULL, &err_message);
213 signal (SIGPIPE, old_sigpipe);
215 if (err_message == NULL)
216 return "Can't connect to audio server";
221 #if defined (ROBUST_PLAY)
222 # if defined (NAS_NO_ERROR_JUMP)
223 aud->funcs.ioerror_handler = CatchIoErrorAndJump;
224 aud->funcs.error_handler = CatchErrorAndJump;
225 # else /* !NAS_NO_ERROR_JUMP */
226 AuDefaultIOErrorHandler = NULL;
227 AuDefaultErrorHandler = NULL;
232 input_id = AuXtAppAddAudioHandler (app_context, aud);
236 AuSetCloseDownMode (aud, AuCloseDownRetainPermanent, NULL);
240 signal (SIGPIPE, old_sigpipe);
249 close_down_play (void)
253 warn ("disconnected from audio server");
256 /********************************************************************\
258 * Callback which is run when the sound finishes playing. *
260 \********************************************************************/
263 doneCB (AuServer *auserver,
264 AuEventHandlerRec *handler,
268 int *in_play_p = (int *) data;
275 /********************************************************************\
277 * Play a sound by playing the relevant bucket, if any or *
278 * downloading it if not. *
280 \********************************************************************/
283 do_caching_play (Sound s,
288 AuBucketAttributes *list, b;
292 AuSetString (AuBucketDescription (&b),
293 AuStringLatin1, strlen (SoundComment (s)), SoundComment (s));
295 list = AuListBuckets (aud, AuCompCommonDescriptionMask, &b, &n, NULL);
303 if ((my_buf= (AuPointer) malloc (SoundNumBytes (s)))==NULL)
308 if (SoundReadFile ((char *) my_buf, SoundNumBytes (s), s) != SoundNumBytes (s))
315 my_buf = (AuPointer) buf;
317 id = AuSoundCreateBucketFromData (aud,
326 else /* found cached sound */
328 id = AuBucketIdentifier (list);
329 AuFreeBucketAttributes (aud, n, list);
334 AuSoundPlayFromBucket (aud,
337 AuFixedPointFromFraction (volume, 100),
338 doneCB, (AuPointer) &sounds_in_play,
344 #endif /* CACHE_SOUNDS */
347 void wait_for_sounds (void);
349 wait_for_sounds (void)
354 while (sounds_in_play>0)
356 AuNextEvent (aud, AuTrue, &ev);
357 AuDispatchEvent (aud, &ev);
361 int play_sound_file (char *sound_file, int volume);
363 play_sound_file (char *sound_file,
366 SIGTYPE (*old_sigpipe) (int);
369 old_sigpipe=signal (SIGPIPE, sigpipe_handle);
370 if (setjmp (AuXtErrorJump))
372 signal (SIGPIPE, old_sigpipe);
378 if (aud_server != NULL)
381 /* attempt to reconect */
382 if ((m=init_play (aud_server))!= NULL)
386 signal (SIGPIPE, old_sigpipe);
393 warn ("Attempt to play with no audio init\n");
395 signal (SIGPIPE, old_sigpipe);
403 AuSoundPlayFromFile (aud,
406 AuFixedPointFromFraction (volume,100),
407 doneCB, (AuPointer) &sounds_in_play,
413 /* Cache the sounds in buckets on the server */
418 if ((s = SoundOpenFileForReading (sound_file))==NULL)
421 signal (SIGPIPE, old_sigpipe);
426 if (SoundComment (s) == NULL || SoundComment (s)[0] == '\0')
428 SoundComment (s) = FileCommentFromFilename (sound_file);
431 do_caching_play (s, volume, NULL);
436 #endif /* CACHE_SOUNDS */
441 if (!NILP (Vsynchronous_sounds))
448 signal (SIGPIPE, old_sigpipe);
454 int play_sound_data (unsigned char *data, int length, int volume);
456 play_sound_data (unsigned char *data,
462 SIGTYPE (*old_sigpipe) (int);
464 #if !defined (XTEVENTS)
469 old_sigpipe = signal (SIGPIPE, sigpipe_handle);
470 if (setjmp (AuXtErrorJump) !=0)
472 signal (SIGPIPE, old_sigpipe);
479 if (aud_server != NULL)
482 /* attempt to reconect */
483 if ((m = init_play (aud_server)) != NULL)
486 signal (SIGPIPE, old_sigpipe);
493 warn ("Attempt to play with no audio init\n");
495 signal (SIGPIPE, old_sigpipe);
501 if ((s=SoundOpenDataForReading (data, length))==NULL)
503 warn ("unknown sound type");
505 signal (SIGPIPE, old_sigpipe);
510 if (SoundFileFormat (s) == SoundFileFormatSnd)
513 offset = ((SndInfo *) (s->formatInfo))->h.dataOffset;
515 else if (SoundFileFormat (s) == SoundFileFormatWave)
517 offset = ((WaveInfo *) (s->formatInfo))->dataOffset;
521 warn ("only understand snd and wave files at the moment");
524 signal (SIGPIPE, old_sigpipe);
531 AuSoundPlayFromData (aud,
535 AuFixedPointFromFraction (volume,100),
536 doneCB, (AuPointer) &sounds_in_play,
542 /* Cache the sounds in buckets on the server */
545 do_caching_play (s, volume, data+offset);
547 #endif /* CACHE_SOUNDS */
553 if (!NILP (Vsynchronous_sounds))
562 signal (SIGPIPE, old_sigpipe);
568 #if defined (ROBUST_PLAY)
570 /********************************************************************\
572 * Code to protect the client from server shutdowns. *
574 * This is unbelievably horrible. *
576 \********************************************************************/
579 CatchIoErrorAndJump (AuServer *old_aud)
582 warn ("Audio Server connection broken");
584 warn ("Audio Server connection broken because of signal");
589 AuXtAppRemoveAudioHandler (aud, input_id);
598 longjmp (AuXtErrorJump, 1);
600 #else /* not XTEVENTS */
606 longjmp (AuXtErrorJump, 1);
608 #endif /* XTEVENTS */
613 sigpipe_handle (int signo)
615 CatchIoErrorAndJump (NULL);
619 CatchErrorAndJump (AuServer *old_aud,
622 return CatchIoErrorAndJump (old_aud);
625 #endif /* ROBUST_PLAY */
627 /********************************************************************\
629 * This code is here because the nas Sound library doesn't *
630 * support playing from a file buffered in memory. It's a fairly *
631 * direct translation of the file-based equivalent. *
633 * Since we don't have a filename, samples with no comment field *
634 * are named by a section of their content. *
636 \********************************************************************/
638 /* Create a name from the sound. */
641 NameFromData (const char *buf,
653 while (i<8 && len >0)
655 while (*buf < 32 && len>0)
670 strcpy (s = (char *) malloc (10), name);
674 strcpy (s = (char *) malloc (15), "short sound");
680 /* Code to do a pseudo-open on a data buffer. Only for snd files at the
685 SndOpenDataForReading (const char *data,
692 if (!(si = (SndInfo *) malloc (sizeof (SndInfo))))
698 memcpy (&si->h, data, sizeof (SndHeader));
700 if (NAS_LITTLE_ENDIAN)
704 swapl (&si->h.magic, n);
705 swapl (&si->h.dataOffset, n);
706 swapl (&si->h.dataSize, n);
707 swapl (&si->h.format, n);
708 swapl (&si->h.sampleRate, n);
709 swapl (&si->h.tracks, n);
712 if (si->h.magic != SND_MAGIC_NUM)
718 size = si->h.dataOffset - sizeof (SndHeader);
722 if (!(si->comment = (char *) malloc (size + 1)))
728 memcpy (si->comment, data+sizeof (SndHeader), size);
730 *(si->comment + size) = 0;
731 if (*si->comment == '\0')
733 NameFromData (data+si->h.dataOffset, length-si->h.dataOffset);
736 si->comment = NameFromData (data+si->h.dataOffset, length-si->h.dataOffset);
738 si->h.dataSize = length-si->h.dataOffset;
745 /* Stuff taken from wave.c from NAS. Just like snd files, NAS can't
746 read wave data from memory, so these functions do that for us. */
748 #define Err() { return NULL; }
749 #define readFourcc(_f) dread(_f, sizeof(RIFF_FOURCC), 1)
750 #define cmpID(_x, _y) \
751 strncmp((char *) (_x), (char *) (_y), sizeof(RIFF_FOURCC))
752 #define PAD2(_x) (((_x) + 1) & ~1)
754 /* These functions here are for faking file I/O from buffer. */
756 /* The "file" position */
757 static size_t file_posn;
758 /* The length of the "file" */
759 static size_t file_len;
760 /* The actual "file" data. */
761 static const void* file_data;
763 /* Like fopen, but for a buffer in memory */
765 dopen (const void* data, size_t length)
772 /* Like fread, but for a buffer in memory */
774 dread (void* buf, size_t size, size_t nitems)
776 size_t nread = size * nitems;
778 if (file_posn + nread <= file_len)
780 memcpy(buf, (char *) file_data + file_posn, size * nitems);
790 /* Like fgetc, but for a buffer in memory */
794 if (file_posn < file_len)
795 return ((char *)file_data)[file_posn++];
800 /* Like fseek, but for a buffer in memory */
802 dseek (long offset, int from)
809 file_posn = file_len + offset;
814 /* Like ftell, but for a buffer in memory */
821 /* Data buffer analogs for FileReadS and FileReadL in NAS. */
823 static unsigned short
824 DataReadS (int swapit)
835 DataReadL (int swapit)
846 readChunk (RiffChunk *c)
851 if ((status = dread(c, sizeof(RiffChunk), 1)))
853 swapl(&c->ckSize, n);
858 /* A very straight-forward translation of WaveOpenFileForReading to
859 read the wave data from a buffer in memory. */
862 WaveOpenDataForReading (const char *data,
871 if (!(wi = (WaveInfo *) malloc(sizeof(WaveInfo))))
875 wi->dataOffset = wi->format = wi->writing = 0;
879 if (!readChunk(&ck) ||
880 cmpID(&ck.ckID, RIFF_RiffID) ||
881 !readFourcc(&fourcc) ||
882 cmpID(&fourcc, RIFF_WaveID))
885 fileSize = PAD2(ck.ckSize) - sizeof(RIFF_FOURCC);
887 while (fileSize >= sizeof(RiffChunk))
892 fileSize -= sizeof(RiffChunk) + PAD2(ck.ckSize);
895 if (!cmpID(&ck.ckID, RIFF_ListID))
897 if (!readFourcc(&fourcc))
901 if (!cmpID(&fourcc, RIFF_ListInfoID))
903 ck.ckSize -= sizeof(RIFF_FOURCC);
913 if (!cmpID(&c.ckID, RIFF_InfoIcmtID))
915 if (!(wi->comment = (char *) malloc(c.ckSize)) ||
916 !dread(wi->comment, c.ckSize, 1))
920 dgetc(); /* eat the pad byte */
923 /* skip unknown chunk */
924 dseek(PAD2(c.ckSize), 1);
926 ck.ckSize -= sizeof(RiffChunk) + PAD2(c.ckSize);
930 /* skip unknown chunk */
931 dseek(PAD2(ck.ckSize) - sizeof(RIFF_FOURCC), 1);
933 /* wave format chunk */
934 else if (!cmpID(&ck.ckID, RIFF_WaveFmtID) && !wi->format)
938 wi->format = DataReadS(NAS_BIG_ENDIAN);
939 wi->channels = DataReadS(NAS_BIG_ENDIAN);
940 wi->sampleRate = DataReadL(NAS_BIG_ENDIAN);
942 /* we don't care about the next two fields */
943 dummy = DataReadL(NAS_BIG_ENDIAN);
944 dummy = DataReadS(NAS_BIG_ENDIAN);
946 if (wi->format != RIFF_WAVE_FORMAT_PCM)
949 wi->bitsPerSample = DataReadS(NAS_BIG_ENDIAN);
951 /* skip any other format specific fields */
952 dseek(PAD2(ck.ckSize - 16), 1);
954 /* wave data chunk */
955 else if (!cmpID(&ck.ckID, RIFF_WaveDataID) && !wi->dataOffset)
959 wi->dataOffset = dtell();
960 wi->dataSize = ck.ckSize;
964 /* seek past the data */
965 if (dseek(wi->dataOffset + PAD2(ck.ckSize), 0) ||
968 /* the seek failed, assume the size is bogus */
970 wi->dataSize = dtell() - wi->dataOffset;
973 wi->dataOffset -= sizeof(long);
976 /* skip unknown chunk */
977 dseek(PAD2(ck.ckSize), 1);
983 wi->numSamples = wi->dataSize / wi->channels / (wi->bitsPerSample >> 3);
986 wi->comment = NameFromData (data + wi->dataOffset,
987 length - wi->dataOffset);
996 SoundOpenDataForReading (unsigned char *data,
1002 if (!(s = (Sound) malloc (sizeof (SoundRec))))
1005 if ((s->formatInfo = SndOpenDataForReading ((char *) data, length)) != NULL)
1007 if (!((int(*)(Sound))(SoundFileInfo[SoundFileFormatSnd].toSound)) (s))
1009 SndCloseFile ((SndInfo *) (s->formatInfo));
1014 else if ((s->formatInfo = WaveOpenDataForReading ((char *) data, length)) != NULL)
1016 if (!((int(*)(Sound))(SoundFileInfo[SoundFileFormatWave].toSound)) (s))
1018 WaveCloseFile ((WaveInfo *) (s->formatInfo));