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.
53 * 2002-10-16 Jon Trulson modifed this to work with NAS releases
54 * 1.5f and higher. We were using the private variable
55 * SoundFileInfo that doesn't exist anymore. But preserve
56 * backward compatibility. This will not work for some
57 * versions of NAS around 1.5b to 1.5f or so. Known to
58 * work on 1.2p5 and 1.6.
65 #include "syssignal.h"
77 /* NAS <= 1.2p5 defines {BIG,LITTLE}_ENDIAN in <audio/fileutil.h>,
78 conflicting with GNU libc (at least); newer versions avoid this
81 DO NOT USE THOSE MACROS in this file. Use NAS_{BIG,LITTLE}_ENDIAN.
83 It would be slightly more reliable to do this via configure, but that
84 seems unnecessarily complex.
89 #include <audio/audiolib.h>
90 #include <audio/soundlib.h>
91 #include <audio/snd.h>
92 #include <audio/wave.h>
93 #include <audio/fileutil.h>
95 /* NAS <= 1.2p5 <audio/fileutil.h> doesn't define the NAS_ versions */
96 #ifndef NAS_LITTLE_ENDIAN
97 #define NAS_LITTLE_ENDIAN LITTLE_ENDIAN
98 #define NAS_BIG_ENDIAN BIG_ENDIAN
106 # define CACHE_SOUNDS
109 * For old NAS libraries, force playing to be synchronous
110 * and declare the long jump point locally.
113 # if defined (NAS_NO_ERROR_JUMP)
118 jmp_buf AuXtErrorJump;
121 /* The GETTEXT is correct. --ben */
122 # define warn(str) warn_when_safe (Qnas, Qwarning, "nas: %s ", GETTEXT (str))
124 # define play_sound_file nas_play_sound_file
125 # define play_sound_data nas_play_sound_data
126 # define wait_for_sounds nas_wait_for_sounds
127 # define init_play nas_init_play
128 # define close_down_play nas_close_down_play
131 # define warn(str) fprintf (stderr, "%s\n", (str))
135 # include <X11/Intrinsic.h>
136 # include <audio/Xtutil.h>
139 #if defined (ROBUST_PLAY)
140 static AuBool CatchIoErrorAndJump (AuServer *aud);
141 static AuBool CatchErrorAndJump (AuServer *aud, AuErrorEvent *event);
142 SIGTYPE sigpipe_handle (int signo);
145 extern Lisp_Object Vsynchronous_sounds;
147 static Sound SoundOpenDataForReading (unsigned char *data, int length);
149 static AuServer *aud;
151 /* count of sounds currently being played. */
152 static int sounds_in_play;
156 static Display *aud_server;
157 static XtInputId input_id;
159 static char *aud_server;
160 #endif /* XTOOLKIT */
180 SIGTYPE (*old_sigpipe) (int);
183 char * server = DisplayString (display);
184 XtAppContext app_context = XtDisplayToApplicationContext (display);
186 aud_server = display;
193 old_sigpipe = signal (SIGPIPE, sigpipe_handle);
194 if (setjmp (AuXtErrorJump))
196 signal (SIGPIPE, old_sigpipe);
200 return "error in NAS";
204 #if defined (ROBUST_PLAY) && !defined (NAS_NO_ERROR_JUMP)
205 AuDefaultIOErrorHandler = CatchIoErrorAndJump;
206 AuDefaultErrorHandler = CatchErrorAndJump;
212 aud = AuOpenServer (server, 0, NULL, 0, NULL, &err_message);
219 signal (SIGPIPE, old_sigpipe);
221 if (err_message == NULL)
222 return "Can't connect to audio server";
227 #if defined (ROBUST_PLAY)
228 # if defined (NAS_NO_ERROR_JUMP)
229 aud->funcs.ioerror_handler = CatchIoErrorAndJump;
230 aud->funcs.error_handler = CatchErrorAndJump;
231 # else /* !NAS_NO_ERROR_JUMP */
232 AuDefaultIOErrorHandler = NULL;
233 AuDefaultErrorHandler = NULL;
238 input_id = AuXtAppAddAudioHandler (app_context, aud);
242 AuSetCloseDownMode (aud, AuCloseDownRetainPermanent, NULL);
246 signal (SIGPIPE, old_sigpipe);
255 close_down_play (void)
259 warn ("disconnected from audio server");
262 /********************************************************************\
264 * Callback which is run when the sound finishes playing. *
266 \********************************************************************/
269 doneCB (AuServer *auserver,
270 AuEventHandlerRec *handler,
274 int *in_play_p = (int *) data;
281 /********************************************************************\
283 * Play a sound by playing the relevant bucket, if any or *
284 * downloading it if not. *
286 \********************************************************************/
289 do_caching_play (Sound s,
294 AuBucketAttributes *list, b;
298 AuSetString (AuBucketDescription (&b),
299 AuStringLatin1, strlen (SoundComment (s)), SoundComment (s));
301 list = AuListBuckets (aud, AuCompCommonDescriptionMask, &b, &n, NULL);
309 if ((my_buf= (AuPointer) malloc (SoundNumBytes (s)))==NULL)
314 if (SoundReadFile ((char *) my_buf, SoundNumBytes (s), s) != SoundNumBytes (s))
321 my_buf = (AuPointer) buf;
323 id = AuSoundCreateBucketFromData (aud,
332 else /* found cached sound */
334 id = AuBucketIdentifier (list);
335 AuFreeBucketAttributes (aud, n, list);
340 AuSoundPlayFromBucket (aud,
343 AuFixedPointFromFraction (volume, 100),
344 doneCB, (AuPointer) &sounds_in_play,
350 #endif /* CACHE_SOUNDS */
353 void wait_for_sounds (void);
355 wait_for_sounds (void)
360 while (sounds_in_play>0)
362 AuNextEvent (aud, AuTrue, &ev);
363 AuDispatchEvent (aud, &ev);
367 int play_sound_file (char *sound_file, int volume);
369 play_sound_file (char *sound_file,
372 SIGTYPE (*old_sigpipe) (int);
375 old_sigpipe=signal (SIGPIPE, sigpipe_handle);
376 if (setjmp (AuXtErrorJump))
378 signal (SIGPIPE, old_sigpipe);
384 if (aud_server != NULL)
387 /* attempt to reconect */
388 if ((m=init_play (aud_server))!= NULL)
392 signal (SIGPIPE, old_sigpipe);
399 warn ("Attempt to play with no audio init\n");
401 signal (SIGPIPE, old_sigpipe);
409 AuSoundPlayFromFile (aud,
412 AuFixedPointFromFraction (volume,100),
413 doneCB, (AuPointer) &sounds_in_play,
419 /* Cache the sounds in buckets on the server */
424 if ((s = SoundOpenFileForReading (sound_file))==NULL)
427 signal (SIGPIPE, old_sigpipe);
432 if (SoundComment (s) == NULL || SoundComment (s)[0] == '\0')
434 SoundComment (s) = FileCommentFromFilename (sound_file);
437 do_caching_play (s, volume, NULL);
442 #endif /* CACHE_SOUNDS */
447 if (!NILP (Vsynchronous_sounds))
454 signal (SIGPIPE, old_sigpipe);
460 int play_sound_data (unsigned char *data, int length, int volume);
462 play_sound_data (unsigned char *data,
468 SIGTYPE (*old_sigpipe) (int);
470 #if !defined (XTEVENTS)
475 old_sigpipe = signal (SIGPIPE, sigpipe_handle);
476 if (setjmp (AuXtErrorJump) !=0)
478 signal (SIGPIPE, old_sigpipe);
485 if (aud_server != NULL)
488 /* attempt to reconect */
489 if ((m = init_play (aud_server)) != NULL)
492 signal (SIGPIPE, old_sigpipe);
499 warn ("Attempt to play with no audio init\n");
501 signal (SIGPIPE, old_sigpipe);
507 if ((s=SoundOpenDataForReading (data, length))==NULL)
509 warn ("unknown sound type");
511 signal (SIGPIPE, old_sigpipe);
516 if (SoundFileFormat (s) == SoundFileFormatSnd)
519 offset = ((SndInfo *) (s->formatInfo))->h.dataOffset;
521 else if (SoundFileFormat (s) == SoundFileFormatWave)
523 offset = ((WaveInfo *) (s->formatInfo))->dataOffset;
527 warn ("only understand snd and wave files at the moment");
530 signal (SIGPIPE, old_sigpipe);
537 AuSoundPlayFromData (aud,
541 AuFixedPointFromFraction (volume,100),
542 doneCB, (AuPointer) &sounds_in_play,
548 /* Cache the sounds in buckets on the server */
551 do_caching_play (s, volume, data+offset);
553 #endif /* CACHE_SOUNDS */
559 if (!NILP (Vsynchronous_sounds))
568 signal (SIGPIPE, old_sigpipe);
574 #if defined (ROBUST_PLAY)
576 /********************************************************************\
578 * Code to protect the client from server shutdowns. *
580 * This is unbelievably horrible. *
582 \********************************************************************/
585 CatchIoErrorAndJump (AuServer *old_aud)
588 warn ("Audio Server connection broken");
590 warn ("Audio Server connection broken because of signal");
595 AuXtAppRemoveAudioHandler (aud, input_id);
604 longjmp (AuXtErrorJump, 1);
606 #else /* not XTEVENTS */
612 longjmp (AuXtErrorJump, 1);
614 #endif /* XTEVENTS */
619 sigpipe_handle (int signo)
621 CatchIoErrorAndJump (NULL);
625 CatchErrorAndJump (AuServer *old_aud,
628 return CatchIoErrorAndJump (old_aud);
631 #endif /* ROBUST_PLAY */
633 /********************************************************************\
635 * This code is here because the nas Sound library doesn't *
636 * support playing from a file buffered in memory. It's a fairly *
637 * direct translation of the file-based equivalent. *
639 * Since we don't have a filename, samples with no comment field *
640 * are named by a section of their content. *
642 \********************************************************************/
644 /* Create a name from the sound. */
647 NameFromData (const char *buf,
659 while (i<8 && len >0)
661 while (*buf < 32 && len>0)
676 strcpy (s = (char *) malloc (10), name);
680 strcpy (s = (char *) malloc (15), "short sound");
686 /* Code to do a pseudo-open on a data buffer. Only for snd files at the
691 SndOpenDataForReading (const char *data,
698 if (!(si = (SndInfo *) malloc (sizeof (SndInfo))))
704 memcpy (&si->h, data, sizeof (SndHeader));
706 if (NAS_LITTLE_ENDIAN)
710 swapl (&si->h.magic, n);
711 swapl (&si->h.dataOffset, n);
712 swapl (&si->h.dataSize, n);
713 swapl (&si->h.format, n);
714 swapl (&si->h.sampleRate, n);
715 swapl (&si->h.tracks, n);
718 if (si->h.magic != SND_MAGIC_NUM)
724 size = si->h.dataOffset - sizeof (SndHeader);
728 if (!(si->comment = (char *) malloc (size + 1)))
734 memcpy (si->comment, data+sizeof (SndHeader), size);
736 *(si->comment + size) = 0;
737 if (*si->comment == '\0')
739 NameFromData (data+si->h.dataOffset, length-si->h.dataOffset);
742 si->comment = NameFromData (data+si->h.dataOffset, length-si->h.dataOffset);
744 si->h.dataSize = length-si->h.dataOffset;
751 /* Stuff taken from wave.c from NAS. Just like snd files, NAS can't
752 read wave data from memory, so these functions do that for us. */
754 #define Err() { free (wi); return NULL; }
755 #define readFourcc(_f) dread(_f, sizeof(RIFF_FOURCC), 1)
756 #define cmpID(_x, _y) \
757 strncmp((char *) (_x), (char *) (_y), sizeof(RIFF_FOURCC))
758 #define PAD2(_x) (((_x) + 1) & ~1)
760 /* These functions here are for faking file I/O from buffer. */
762 /* The "file" position */
763 static size_t file_posn;
764 /* The length of the "file" */
765 static size_t file_len;
766 /* The actual "file" data. */
767 static const void* file_data;
769 /* Like fopen, but for a buffer in memory */
771 dopen (const void* data, size_t length)
778 /* Like fread, but for a buffer in memory */
780 dread (void* buf, size_t size, size_t nitems)
782 size_t nread = size * nitems;
784 if (file_posn + nread <= file_len)
786 memcpy(buf, (char *) file_data + file_posn, size * nitems);
796 /* Like fgetc, but for a buffer in memory */
800 if (file_posn < file_len)
801 return ((char *)file_data)[file_posn++];
806 /* Like fseek, but for a buffer in memory */
808 dseek (long offset, int from)
815 file_posn = file_len + offset;
820 /* Like ftell, but for a buffer in memory */
827 /* Data buffer analogs for FileReadS and FileReadL in NAS. */
829 static unsigned short
830 DataReadS (int swapit)
841 DataReadL (int swapit)
852 readChunk (RiffChunk *c)
857 if ((status = dread(c, sizeof(RiffChunk), 1)))
859 swapl(&c->ckSize, n);
864 /* A very straight-forward translation of WaveOpenFileForReading to
865 read the wave data from a buffer in memory. */
868 WaveOpenDataForReading (const char *data,
877 if (!(wi = (WaveInfo *) malloc(sizeof(WaveInfo))))
881 wi->dataOffset = wi->format = wi->writing = 0;
885 if (!readChunk(&ck) ||
886 cmpID(&ck.ckID, RIFF_RiffID) ||
887 !readFourcc(&fourcc) ||
888 cmpID(&fourcc, RIFF_WaveID))
891 fileSize = PAD2(ck.ckSize) - sizeof(RIFF_FOURCC);
893 while (fileSize >= (AuInt32) sizeof(RiffChunk))
898 fileSize -= sizeof(RiffChunk) + PAD2(ck.ckSize);
901 if (!cmpID(&ck.ckID, RIFF_ListID))
903 if (!readFourcc(&fourcc))
907 if (!cmpID(&fourcc, RIFF_ListInfoID))
909 ck.ckSize -= sizeof(RIFF_FOURCC);
919 if (!cmpID(&c.ckID, RIFF_InfoIcmtID))
921 if (!(wi->comment = (char *) malloc(c.ckSize)) ||
922 !dread(wi->comment, c.ckSize, 1))
926 dgetc(); /* eat the pad byte */
929 /* skip unknown chunk */
930 dseek(PAD2(c.ckSize), 1);
932 ck.ckSize -= sizeof(RiffChunk) + PAD2(c.ckSize);
936 /* skip unknown chunk */
937 dseek(PAD2(ck.ckSize) - sizeof(RIFF_FOURCC), 1);
939 /* wave format chunk */
940 else if (!cmpID(&ck.ckID, RIFF_WaveFmtID) && !wi->format)
944 wi->format = DataReadS(NAS_BIG_ENDIAN);
945 wi->channels = DataReadS(NAS_BIG_ENDIAN);
946 wi->sampleRate = DataReadL(NAS_BIG_ENDIAN);
948 /* we don't care about the next two fields */
949 dummy = DataReadL(NAS_BIG_ENDIAN);
950 dummy = DataReadS(NAS_BIG_ENDIAN);
952 if (wi->format != RIFF_WAVE_FORMAT_PCM)
955 wi->bitsPerSample = DataReadS(NAS_BIG_ENDIAN);
957 /* skip any other format specific fields */
958 dseek(PAD2(ck.ckSize - 16), 1);
960 /* wave data chunk */
961 else if (!cmpID(&ck.ckID, RIFF_WaveDataID) && !wi->dataOffset)
965 wi->dataOffset = dtell();
966 wi->dataSize = ck.ckSize;
970 /* seek past the data */
971 if (dseek(wi->dataOffset + PAD2(ck.ckSize), 0) ||
974 /* the seek failed, assume the size is bogus */
976 wi->dataSize = dtell() - wi->dataOffset;
979 wi->dataOffset -= sizeof(long);
982 /* skip unknown chunk */
983 dseek(PAD2(ck.ckSize), 1);
989 wi->numSamples = wi->dataSize / wi->channels / (wi->bitsPerSample >> 3);
992 wi->comment = NameFromData (data + wi->dataOffset,
993 length - wi->dataOffset);
1002 SoundOpenDataForReading (unsigned char *data,
1007 #if (AudioLibraryVersionMajor >= 2 ) && (AudioLibraryVersionMinor >= 3)
1008 SoundFileInfoProc toProc;
1011 if (!(s = (Sound) malloc (sizeof (SoundRec))))
1014 if ((s->formatInfo = SndOpenDataForReading ((char *) data, length)) != NULL)
1016 #if (AudioLibraryVersionMajor >= 2 ) && (AudioLibraryVersionMinor >= 3)
1017 if ((toProc = SoundFileGetProc(SoundFileFormatSnd,
1018 SoundFileInfoProcTo)) == NULL)
1020 SndCloseFile ((SndInfo *) (s->formatInfo));
1025 if (!((*toProc)(s)))
1027 if (!((int(*)(Sound))(SoundFileInfo[SoundFileFormatSnd].toSound)) (s))
1030 SndCloseFile ((SndInfo *) (s->formatInfo));
1035 else if ((s->formatInfo = WaveOpenDataForReading ((char *) data, length)) != NULL)
1037 #if (AudioLibraryVersionMajor >= 2 ) && (AudioLibraryVersionMinor >= 3)
1038 if ((toProc = SoundFileGetProc(SoundFileFormatWave,
1039 SoundFileInfoProcTo)) == NULL)
1041 WaveCloseFile ((WaveInfo *) (s->formatInfo));
1046 if (!((*toProc)(s)))
1048 if (!((int(*)(Sound))(SoundFileInfo[SoundFileFormatWave].toSound)) (s))
1051 WaveCloseFile ((WaveInfo *) (s->formatInfo));