File: sound.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 (377 lines) | stat: -rw-r--r-- 10,386 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
// sound.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 "localdefs.h"
#include "application.h"
#include "controller.h"
#include "converter.h"
#include "interpolater.h"
#include "sound.h"
#include "soundheader.h"
#include "request.h"
#include "smpte.h"
#include "sndconfig.h"
#include "statusaction.h"
#include "typeconvert.h"
#ifdef NO_TEMPLATES
#include <InterViews/action.h>		/* sgi native CC cant handle templates */
	declareActionCallback(Sound)
	implementActionCallback(Sound)
#else
#include "actioncallback.h"
#endif

// storage for public "class methods" -- macros in sndconfig.h

int Sound::default_SampleRate = SOUND_DEFAULT_RATE;

DataType Sound::default_DataType = SOUND_DEFAULT_TYPE;

char* Sound::default_FileSuffix = SOUND_SUFFIX;

// class methods

const char*
Sound::defaultFileSuffix() { return default_FileSuffix; }

// ctors, etc.

Sound::Sound(double duration, int srate, int nchans, DataType type)
	: Data(type, round(duration*srate), nchans), sr(srate) {
}

Sound::Sound(int len, int srate, int nchans, DataType type)
	: Data(type, len, nchans), sr(srate) {
}

// these protected constructors are used only with Sound::clone()

Sound::Sound(const Sound *s, const Range &selection)
	: Data(s, selection), sr(s->sr) {
}

Sound::Sound(const Sound *s, const Range &selection, const Range &chans)
	: Data(s, selection, chans), sr(s->sr) {
}

Sound::~Sound() {
}

Data *
Sound::newData() { return new Sound(this); }

Data *
Sound::newData(int length) { return new Sound(this, length); }

Data *
Sound::clone(const Range &selection) { return new Sound(this, selection); }

Data *
Sound::clone(const Range &selection, const Range &chans) {
	return new Sound(this, selection, chans);
}

void
Sound::copyFrom(const Data *src) {
	// if copying data with different max sample values
	if(valueLimit() != src->valueLimit() && dataType() < FloatData) {
		boolean wasSetTo = deferRescan(true);
		if(wasSetTo == true)
			((Sound *)src)->checkValues();	// scan if checking was turned off
		boolean sourceIsFloat = src->dataType() >= FloatData;
		double scalingFactor = valueLimit() /
			(sourceIsFloat ? src->maxValue() : src->valueLimit());
		Application::inform("Rescaling for copy...");
		deferRescan(wasSetTo);
		copyRescaledFrom(src, scalingFactor, sourceIsFloat);
	}
	else
		Super::copyFrom(src);
}

double
Sound::duration() const {
	return length()/double(sr);
}

const char *
Sound::fileSuffix() const {
	return dataType() >= FloatData ? SOUND_FLOAT_SUFFIX : defaultFileSuffix();
}

double
Sound::peakAmp() {
	return maxValue();
}

int
Sound::changeSRate(int rate, boolean interp) {
	int status = false;
	if(rate != sr && rate > 0) {
		status = true;
		int oldrate = sr;
		sr = rate;
		boolean was = deferRescan(true);
		if(interp) {	// copy sound and then transpose it back into original
			Data* source = copyOf();
			source->ref();
			Interpolater interp(source, this, double(oldrate)/sr, true);
			if((status = interp.ready()) == true)
				interp.apply();
			Resource::unref(source);
			deferRescan(was);	// to get rescan in Notify()
		}
		if(status) Notify();
		deferRescan(was);		// if !interp, reset here
	}
	return status;
}

// base class method is protected -- made public in Sound class

int
Sound::changeDataType(DataType newType) {
	return Super::changeDataType(newType);
}

// protected methods

Header *
Sound::createHeader(DataFile *file, boolean reading) {
	SoundHeader *hdr = SoundHeader::create(
		file,
		dataType(),
		sRate(),
		nChans(),
		reading ? 0.0 : maxValue(),	// only extract peak if writing
		reading
	);
	if(!reading) configureHeader(hdr);
	return hdr;
}

void
Sound::readFromHeader(Header *h) {
	Super::readFromHeader(h);
	SoundHeader *header = (SoundHeader *) h;
	sr = header->sampleRate();
	double peak = header->peakAmp();
	if(peak != 0.0)
		setMaxValue(peak);
	else
		checkValues();
}

void
Sound::checkValues() {
	double max = scanForMaxValue();
	setMaxValue((max == 0.0) ? 1.0 : max);	// recheck peak amp
}

Range
Sound::limits(int, boolean) const {
	double peak = maxValue();
	return Range(-peak, peak);	// same for all chans
}

// special protected method for use by the Converters

const char *
Sound::getDataPointer() const {
	return rep->getAddressOfContiguousData();
}

int
Sound::play(Converter *converter, StatusAction* wantStop) {
	Sound *playMe = nil;
	int status = true;
	if(converter->hasPlayableFormat(this))
		playMe = this;
	else {
		Application::inform("Converting to playable format...");
		playMe = new Sound(
			duration(), sRate(), nChans(), converter->bestPlayableType()
		);
		playMe->ref();
		playMe->copyFrom(this);
		status = (playMe->length() > 0);	// until Exceptions enabled
	}
	status = status && playMe->doPlay(converter, wantStop);
	if(playMe != this)
		Resource::unref(playMe);
	return status;
}

int
Sound::doPlay(Converter *converter, StatusAction* wantStop) {
	if(converter->configure(this, Converter::Play)) {
		return converter->start(wantStop, nil);
	}
	return false;
}

int
Sound::record(Converter *converter, StatusAction* wantStop) {
	return doRecord(converter, wantStop);
}

int
Sound::doRecord(Converter *converter, StatusAction* wantStop) {
	if(converter->configure(this, Converter::Record)) {
		return converter->start(
			wantStop,
#ifdef NO_TEMPLATES
			new Sound_ActionCallback(this, &Sound::Notify)
#else
			new ActionCallback<Sound>(this, &Sound::Notify)
#endif
		);
	}
	return false;
}

void
Sound::rescale() {
	boolean wasSetTo = deferRescan(false);	// we need to rescan here
	if(wasSetTo == true)
		checkValues();	// check first if checking was turned off
	// rather than rescanning again after rescaling, defer check and
	// simply set the peak to valueLimit()
	double oldpeak = maxValue();
	if(oldpeak != 0.0) {
		deferRescan(true);
		setMaxValue(valueLimit());
		scaleSelf(valueLimit()/oldpeak);
		deferRescan(wasSetTo);
	}
}

Range
Sound::frameRange(RangeUnit units) const {
    return (units == FrameTimeUnit) ? Range(0.0, duration())
	: (units == FrameSmpteUnit) ? Range(0.0, SMPTE::frames(duration()) - 1)
	: Super::frameRange(units);
}

const char * 
Sound::frameRangeLabel(RangeUnit units) const {
	return (units == FrameTimeUnit) ? "Time in Seconds" :
		(units == FrameSmpteUnit) ? "SMPTE Frames" :
		(units == FrameUnit) ? "Sample Number"
		: Super::frameRangeLabel(units);
}

void
Sound::information(Controller *controller) {
	char str[128];
	AlertRequest request("Soundfile Information:");
	request.setBell(false);
	request.appendLabel("------------");
	request.appendLabel("Filename: ", controller->fileName());
	request.appendLabel("Sample Rate: ", toString(str, sRate()));
	request.appendLabel("Duration (seconds): ",
		toString(str, duration()));
	request.appendLabel("File Size (Mb): ",
		toString(str, sizeInBytes()/1000000.0));
	request.appendLabel("NSamps: ", toString(str, length()));
	request.appendLabel("NChans: ", toString(str, nChans()));
	int typeIndex = powerOfTwoToLinearEnum(dataType());
	static char* labels[] = {
		"unknown",
		"8-bit linear", "8-bit unsigned", "mu law",
		"16-bit linear", "32-bit linear", "floating point",
		"double-precision float", "unknown"
	};
	request.appendLabel("Sample Format: ", labels[typeIndex]);
	request.appendLabel("Peak Amplitude: ", toString(str, maxValue()));
	controller->handleRequest(request);
}

#ifdef sgi

#include "aiff_header.h"
#include "datafile.h"

// these kludges are needed since AIFF sounds have special i/o routines

int
Sound::read(DataFile *f, Header* header) {
	BUG("Sound::read()");
	if(header == nil)
		header = createHeader(f, true);
	if(((SoundHeader *) header)->headerType() != SoundHeader::Aifc)
		return Super::read(f, header);	// not AIFC file
	header->ref();
	int status = false;
	if(status = header->read(f)) {		// supposed to be =, not ==
		if(header->dataSize() == 0)
			Application::alert("Warning:  file contains 0 frames.");
		Resource::unref(rep);
		// since compressed sounds cannot use file size in bytes as an indicator
		// of the # of frames to read, just use readSize/dataSize as fraction.
		double fractionToRead = double(f->readSize()) / f->dataSize();
		AIFFSoundHeader* ah = (AIFFSoundHeader *) header;
		int len = round(ah->frameCount() * fractionToRead);
		rep = DataRep::create(header->dataType(), max(len, 8), header->nChans());
		rep->ref();
		char* data =  (char *) getDataPointer();
		long samps = ah->readSound(&data, long(len));
		if(samps > 0L) {    // not checked against len since it uses internal frame count
			readFromHeader(header);
			boolean was = deferRescan(true);
			Notify();					// update views but dont rescan first
			deferRescan(was);
			modified(false);
		}
		else status = false;
	}
	Resource::unref(header);
	return status;
}

int
Sound::write(DataFile* f) {
	BUG("Sound::write(f)");
    Header* header = createHeader(f, false);
	if(((SoundHeader *) header)->headerType() != SoundHeader::Aifc)
		return write(f, header);	// not AIFC file
	header->ref();
    AIFFSoundHeader* aheader = (AIFFSoundHeader *) header;
    int status = false;
	if((status = aheader->write(f)) == true) {
		char* data =  (char *) getDataPointer();
		status = (aheader->writeSound(data, long(length())) == length());
	}
    Resource::unref(aheader);
    modified(modified() && (status != true));
	return status;
}

#endif /* sgi */