File: sgi_dac.C

package info (click to toggle)
mixviews 1.10-3
  • links: PTS
  • area: main
  • in suites: hamm
  • size: 2,440 kB
  • ctags: 6,314
  • sloc: cpp: 31,647; ansic: 2,100; makefile: 1,782; sh: 17
file content (524 lines) | stat: -rw-r--r-- 13,722 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
// sgi_dac.C

/******************************************************************************
 *
 *  MiXViews - an X window system based sound & data editor/processor
 *
 *  Copyright (c) 1993, 1994 Regents of the University of California
 *
 *  Author:     Douglas Scott
 *  Date:       December 13, 1994
 *
 *  Permission to use, copy and modify this software and its documentation
 *  for research and/or educational purposes and without fee is hereby granted,
 *  provided that the above copyright notice appear in all copies and that
 *  both that copyright notice and this permission notice appear in
 *  supporting documentation. The author reserves the right to distribute this
 *  software and its documentation.  The University of California and the author
 *  make no representations about the suitability of this software for any 
 *  purpose, and in no event shall University of California be liable for any
 *  damage, loss of data, or profits resulting from its use.
 *  It is provided "as is" without express or implied warranty.
 *
 ******************************************************************************/


#ifdef __GNUG__
#pragma implementation
#endif

#include <math.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include "sgi_dac.h"
#include "application.h"
#include "statusaction.h"
#include "typeconvert.h"

#undef DEBUG_SGI

char *
SGIConverter::errorStrings[] = {
	"not implemented yet",
	"trying to use an invalid port",
	"trying to use an invalid configuration",
	"trying to use an invalid device",
	"unable to access the device",
	"illegal direction given for port",
	"not able to allocate a port",
	"invalid sample width",
	"an illegal state has occurred",
	"invalid queue size",
	"invalid fillpoint",
	"null buffer pointer",
	"negative count",
	"param/val buffer doesn't make sense",
	"negative buffer length",
	"odd length parameter/value buffer",
	"invalid channel specifier",
	"invalid parameter",
	"attempt to set invalid sample format",
	"invalid sample rate token",
	"invalid size for sample read/write",
	"invalid size for floatmax",
	NULL
};

boolean SGIConverter::dontInterrupt = false;

SGIConverter::SGIConverter() : audio_port_config(nil), audio_port(nil) {
	// need to determine whether audio port is available,
	// but we dont check for 'in use' until config time
	pvbuf[0] = AL_OUTPUT_COUNT;
	if(ALgetparams(AL_DEFAULT_DEVICE, pvbuf, 2) < 0) {
		if(oserror() == AL_BAD_DEVICE_ACCESS) {
			Application::alert("Could not access audio hardware.");
			fail();
		}
	}
	else if(initialize())
		catchSignals(true);
	else
		fail();
}

SGIConverter::~SGIConverter() {
	resetDefaults();
	if(audio_port_config)
		ALfreeconfig(audio_port_config);
	if(audio_port)
		ALcloseport(audio_port);
	catchSignals(false);
}

int
SGIConverter::displayError() {
	int er = oserror();
#ifdef DEBUG_SGI
	fprintf(stderr, "Error # is %d error string is %s\n", er, errorStrings[er]);
#endif
	Application::alert(errorStrings[oserror()]);
	return false;
}

int
SGIConverter::initialize() {
	BUG("SGIConverter::initialize()");
	ALseterrorhandler(nil);		// SGIConverter will handle errors
	audio_port_config = ALnewconfig();
	if(!audio_port_config)
		return displayError();
	else
		return getDefaults();
}

long
SGIConverter::getParameter(long param) const {
	long* p = (long *) &pvbuf[0];
	*p = param;
	ALgetparams(AL_DEFAULT_DEVICE, p, 2);
	return pvbuf[1];
}

int
SGIConverter::setParameter(long param, long value) {
	pvbuf[0] = param;
	pvbuf[1] = value;
	return (ALsetparams(AL_DEFAULT_DEVICE, pvbuf, 2) == 0) ?
		true : displayError();
}

int
SGIConverter::getDefaults() {
	return true;
}

void
SGIConverter::resetDefaults() {
}

boolean
SGIConverter::isPlayableFormat(DataType type) {
	return (type != UnsignedCharData
		&& type != MuLawData && type != IntData);
}

int
SGIConverter::checkDataType(DataType type) {
	long sampwidth = AL_SAMPLE_16;
	long format;
	switch(type) {
	case FloatData: format = AL_SAMPFMT_FLOAT;  break;
	case DoubleData: format = AL_SAMPFMT_DOUBLE;  break;
	case ShortData:  format = AL_SAMPFMT_TWOSCOMP;  break;
	case SignedCharData:
		format = AL_SAMPFMT_TWOSCOMP;
		sampwidth = AL_SAMPLE_8;
		break;
	}
	if(ALsetsampfmt(audio_port_config, format) < 0 ||
			ALsetwidth(audio_port_config, sampwidth) < 0)
		return displayError();
	else if(type >= FloatData)
		ALsetfloatmax(audio_port_config, peakAmplitude());
	return true;
}

int
SGIConverter::checkSampleRate(int sampleRate) {
	if(willRecord()) {
		int status = true;
		// if we are using the digital inputs, the rate cannot be set.
		// we can only check for a match
		pvbuf[0] = AL_INPUT_RATE;
		pvbuf[2] = AL_INPUT_SOURCE;
		pvbuf[4] = AL_DIGITAL_INPUT_RATE;
		ALgetparams(AL_DEFAULT_DEVICE, pvbuf, 6);
		if(pvbuf[1] == AL_RATE_AES_1 || pvbuf[3] == AL_INPUT_DIGITAL) {
			// we are using digital input -- just check for match
			if(ALgetdefault(AL_DEFAULT_DEVICE, AL_DIGITAL_INPUT_RATE) >= 0) {
				if(pvbuf[5] != sampleRate) {
					char msg[128];
					sprintf(msg, "Digital input sample rate (%ld) != sound sample rate (%d)", pvbuf[5], sampleRate);
					Application::alert(msg);
					status = false;
				}
			}
			else {
				Application::alert("Unable to determine digital input sample rate.");
				status = false;
			}
			return status;
		}
	}
	// if non-digital input, or playing sound, set the sample rate
	return setParameter(
		willRecord() ? AL_INPUT_RATE : AL_OUTPUT_RATE, long(sampleRate)
	);
}

int
SGIConverter::checkChannels(int chans) {
	if(chans == 3 || chans > 4) {
		Application::alert("Only mono, stereo, or quad files may be played.");
		return false;
	}
	ALsetchannels(audio_port_config, chans);
	return true;
}

// Needed to redefine this here to check port use before doing any config

int
SGIConverter::configure(Sound* sound, GoingTo wantTo) {
	// need to determine whether audio is in use (other than us).
	if(dontInterrupt && getParameter(AL_OUTPUT_COUNT) > 1) {
		Application::alert("Audio hardware currently in use.");
		return false;
	}
	return Super::configure(sound, wantTo);
}

int
SGIConverter::doConfigure() {
	BUG("SGIConverter::doConfigure()");
#ifdef DEBUG_SGI
	fprintf(stderr, "Queue size set to %ld.\n", bestQueueSize());
#endif
	if(ALsetqueuesize(audio_port_config, bestQueueSize()) < 0)
		return displayError();
	if(audio_port) ALcloseport(audio_port);
	if((audio_port = ALopenport("mxv", willRecord() ? "r" : "w",
			audio_port_config)) == 0) {
		int err = oserror();
		if(err == AL_BAD_NO_PORTS)
			Application::alert("No audio ports currently available.");
		else if(err == AL_BAD_OUT_OF_MEM)
			Application::alert("Not enough memory to open audio port.");
		else
			Application::alert("ALopenport() failed.");
		return false;
	}
	if(ALsetfillpoint(audio_port, bestQueueSize()/4) < 0)
		return displayError();
	return true;
}

// read and write 1/10 second of sound for all formats, so queue is twice
// that size, or 1/5 second

long
SGIConverter::bestQueueSize() {
	return round(float(channels()) * sampleRate() / 5.0);
}

long
SGIConverter::writeSamps() { return bestQueueSize()/2; }

long
SGIConverter::readSamps() { return bestQueueSize()/2; }

inline long min(long x, long y) { return (x < y) ? x : y; }

int
SGIConverter::doConversion(StatusAction* askedToStop) {
	BUG("SGIConverter::doConversion()");
	lockMemory();
	addr databuffer = addr(pointerToData());
	int sampsize = sampleSize();
	long nsamps = dataSize()/sampsize;		// total samples to write
	long bufsamps = writeSamps();			// size of each write in samples
	bufsamps = min(bufsamps, nsamps);
	long bufsize = bufsamps * sampsize;		// size of each write in bytes
#ifdef DEBUG_SGI
	fprintf(stderr, "Playing %ld samps = %ld bytes\n", nsamps, nsamps * sampsize);
	fprintf(stderr, "Buffer is %ld samps = %ld bytes\n", bufsamps, bufsize);
	fprintf(stderr, "Starting conversion...\n");
#endif
	Application::inform("Playing...");
	boolean stopped = false;
	while(nsamps > 0) {
		if((*askedToStop)()) {
			stopped = true;
			break;
		}
		if(ALgetfillable(audio_port) < bufsamps)
			continue;
		if(ALwritesamps(audio_port, databuffer, bufsamps) < 0)
			return error("Error in ALwritesamps().");
		databuffer += bufsize;
		nsamps -= bufsamps;
		bufsamps = min(bufsamps, nsamps);
#ifdef DEBUG_SGI
		fprintf(stderr, "\t%ld samps written, nsamps= %ld\n", bufsamps, nsamps);
#endif
	}
	if(!stopped) waitForStop(askedToStop);
	return stop();
}

int
SGIConverter::doRecording(StatusAction* askedToStop) {
	int sampsize = sampleSize();
	long nsamps = (dataSize()/sampsize);	// total samples to read
	long bufsamps = readSamps();		// size of each read in samples
	bufsamps = min(bufsamps, nsamps);
	long bufsize = bufsamps * sampsize;	// size of each read in bytes
#ifdef DEBUG_SGI
	fprintf(stderr, "Recording %ld samps = %ld bytes\n", nsamps, nsamps * sampsize);
	fprintf(stderr, "Buffer is %ld samps = %ld bytes\n", bufsamps, bufsize);
#endif
	lockMemory();
	char *databuffer = (char *) pointerToData();
	Application::inform("Recording...");
	while(nsamps > 0) {
		if((*askedToStop)())
			return stop();
		if(ALreadsamps(audio_port, databuffer, bufsamps) < 0)
			return error("Error in ALreadsamps().");
		databuffer += bufsize;
		nsamps -= bufsamps;
#ifdef DEBUG_SGI
		fprintf(stderr, "       %ld samps read, nsamps= %ld\n", bufsamps, nsamps);
#endif
		bufsamps = min(bufsamps, nsamps);
	}
#ifdef DEBUG_SGI
		fprintf(stderr, "At bottom, calling stop()\n");
#endif
	stop();
	return true;
}

SGIConverter::InputSource
SGIConverter::currentInputSource() {
	long source = getParameter(AL_INPUT_SOURCE);
	return (source == AL_INPUT_LINE) ? Line
		: (source == AL_INPUT_MIC) ? Mike :
		Digital;
}

int
SGIConverter::setInputSource(InputSource source) {
	return setParameter(AL_INPUT_SOURCE,
		(source == Mike) ? AL_INPUT_MIC
		: (source == Line) ? AL_INPUT_LINE
		: AL_INPUT_DIGITAL
	);
}

int
SGIConverter::currentPlayLevel() const {
	long param = getParameter(AL_LEFT_SPEAKER_GAIN);
	double value = 0.0;
	if(param > 0) value = 0.5 + 41.5534304 * log10(double(param));
	return (param == 0) ? 0 : int(min(100.0, max(0.0, value)));
}

int
SGIConverter::currentRecordLevel() const {
	long param = getParameter(AL_LEFT_INPUT_ATTEN);
#ifdef DEBUG_SGI
	fprintf(stderr, "getParameter returns %ld for record\n", param);
#endif
	return max(0, round(100 - (10 * param)/16.0));
}

boolean
SGIConverter::setPlayLevel(int volume){
	long gain = round(pow(10.0, 0.02406540183 * volume));
	int status = setParameter(AL_LEFT_SPEAKER_GAIN, gain);
	return status && setParameter(AL_RIGHT_SPEAKER_GAIN, gain);
}

boolean
SGIConverter::setRecordLevel(int volume){
	long gain = long(16.0 * ((100 - volume)/10.0));
#ifdef DEBUG_SGI
	fprintf(stderr, "setting record parameter to %ld from volume of %d\n", gain, volume);
#endif
	int status = setParameter(AL_LEFT_INPUT_ATTEN, gain);
	return status && setParameter(AL_RIGHT_INPUT_ATTEN, gain);
}

boolean
SGIConverter::setSpeakerOutput(boolean isOn) {
	return setParameter(AL_SPEAKER_MUTE_CTL,
		isOn ? AL_SPEAKER_MUTE_OFF : AL_SPEAKER_MUTE_ON);
}

int
SGIConverter::pause() {
	return false;
}

int
SGIConverter::resume() {
	return false;
}

int
SGIConverter::stop() {
	BUG("SGIConverter::stop()");
	int status = true;
	if(running()) {
#ifdef DEBUG_SGI
		long buf[10];
		buf[0] = AL_ERROR_NUMBER;
		buf[2] = AL_ERROR_TYPE;
		buf[4] = AL_ERROR_LENGTH;
		buf[6] = AL_ERROR_LOCATION_LSP;
		buf[8] = AL_ERROR_LOCATION_MSP;
		if(audio_port) {
			ALgetstatus(audio_port, buf, 10);
			if(buf[1] > 0)
				fprintf(stderr, "Last audio port error:  %d at frame %d: %s\n",
				        buf[3], buf[5],
					    (buf[3] < sizeof(errorStrings)) ?
						errorStrings[buf[3]] : "");
		}
#endif
		if(audio_port) ALcloseport(audio_port);
		unlockMemory();
		resetDefaults();
		status = Super::stop();
	}
	return status;
}

int
SGIConverter::lockMemory() {
	// fix memory in RAM to avoid swapping
	return (mpin((void *) pointerToData(), unsigned(dataSize())) == 0);	
}

int
SGIConverter::unlockMemory() {
	// let it swap
	return (munpin((void *) pointerToData(), unsigned(dataSize())) == 0);	
}

int
SGIConverter::waitForStop(StatusAction* askedToStop) {
	BUG("SGIConverter::waitForStop()");
	while(ALgetfilled(audio_port) > 0) {	
		if((*askedToStop)())
			break;
		sginap(1);		// allow audio buffer to drain
	}
	return true;
}

int
SGIConverter::sampleSize() {
	return type_to_sampsize(dataType());
}

#ifdef __GNUG__
typedef void (*SignalFun)(...);
#elif defined(sgi) 
#if defined(__sigargs)
typedef void (*SignalFun)(__sigargs);	// since this varies with OS version
#else
typedef void (*SignalFun)(...);
#endif /* sgi */
#else
typedef void (*SignalFun)(int);
#endif

void
SGIConverter::catchSignals(boolean flag) {
	if(flag) {
		signal(SIGHUP, SignalFun(signalExit));
		signal(SIGINT, SignalFun(signalExit));
		signal(SIGQUIT, SignalFun(signalQuit));
		signal(SIGBUS, SignalFun(signalQuit));
		signal(SIGSEGV, SignalFun(signalQuit));
		signal(SIGTERM, SignalFun(signalExit));
	}
	else {
		signal(SIGHUP, SIG_DFL);
		signal(SIGINT, SIG_DFL);
		signal(SIGQUIT, SIG_DFL);
		signal(SIGBUS, SIG_DFL);
		signal(SIGSEGV, SIG_DFL);
		signal(SIGTERM, SIG_DFL);
	}
}

void
SGIConverter::ignoreSignals(boolean flag) {
	if(flag) {
#ifdef SIGTSTP
		signal(SIGTSTP, SignalFun(signalIgnore));
#endif
	}
	else {
#ifdef SIGTSTP
		signal(SIGTSTP, SIG_DFL);
#endif
	}
}

// these are declared static to allow passing to signal()

void
SGIConverter::signalExit(...) {
	fprintf(stderr, "\nCaught signal.  Exiting...\n");
	fflush(stderr);
	Converter::destroyInstance();
	exit(0);
}

void
SGIConverter::signalIgnore(...) {
	fprintf(stderr, "\nCaught signal during play or record...ignoring.\n");
}

void
SGIConverter::signalQuit(...) {
	fprintf(stderr, "\nCaught deadly signal.  Aborting...\n");
	fflush(stderr);
 	abort();
}