File: Player.cpp

package info (click to toggle)
storm-lang 0.7.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 52,004 kB
  • sloc: ansic: 261,462; cpp: 140,405; sh: 14,891; perl: 9,846; python: 2,525; lisp: 2,504; asm: 860; makefile: 678; pascal: 70; java: 52; xml: 37; awk: 12
file content (485 lines) | stat: -rw-r--r-- 10,566 bytes parent folder | download | duplicates (4)
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
#include "stdafx.h"
#include "Player.h"
#include "Audio.h"
#include "Exception.h"

namespace sound {

	const Nat Player::bufferPartTime = 1;
	const Nat Player::bufferParts = 3;

#ifdef SOUND_DX
	const Nat Player::sampleDepth = sizeof(float);
#endif
#ifdef SOUND_AL
	const Nat Player::sampleDepth = sizeof(short);
#endif

	const GcType Player::partInfoType = {
		GcType::tArray,
		null,
		null,
		sizeof(Player::PartInfo),
		0,
		{}
	};

	Player::Player(Sound *src) :
		src(src), buffer(),
		lastFilled(0), bufferPlaying(false),
		fVolume(1.0f), tmpBuffer(null) {

		partInfo = runtime::allocArray<PartInfo>(engine(), &partInfoType, bufferParts);
		lock = new (this) Lock();
		finishEvent = new (this) Event();

		// finishEvent.set();
		freq = src->sampleFreq();
		channels = src->channels();

		if (channels > 2)
			WARNING(L"More than two channels may not produce expected results.");

		AudioMgr *mgr = audioMgr(engine());
		// Do not try to start playback if audio initialization failed.
		if (mgr->device()) {
			initBuffer();

			audioMgr(engine())->addPlayer(this);
			fill();
		} else {
			TODO(L"Implement a reasonable fallback for timings.");
		}
	}

	Player::~Player() {
		// Do not close 'src' as it might have already been destroyed.
		src = null;
		lock = null;

		// Bare minimum cleanup. Most other objects might be destroyed.
		if (buffer) {
			destroyBuffer();
			buffer = SoundBuffer();
		}
	}

	void Player::close() {
		Lock::Guard z(lock);

		if (buffer) {
			AudioMgr *mgr = audioMgr(engine());
			mgr->removePlayer(this);
			destroyBuffer();
			buffer = SoundBuffer();
		}

		if (src) {
			src->close();
			src = null;
		}
	}

	void Player::volume(Float to) {
		fVolume = to;

		if (buffer)
			bufferVolume(to);
	}

	Float Player::volume() {
		return fVolume;
	}

	void Player::play() {
		if (buffer) {
			bufferPlay();
			finishEvent->clear();
			bufferPlaying = true;
		}
	}

	void Player::pause() {
		if (buffer) {
			bufferPlaying = false;
			bufferStop();
			// TODO: This will not resume playback exactly where we paused.
		}
	}

	void Player::stop() {
		if (buffer) {
			bufferPlaying = false;
			bufferStop();
			finishEvent->set();

			// Reset position if possible. TODO: Should we do this now? It is probably better to
			// wait until somebody calls 'play' again, or even do the fill in the background. This
			// implementation makes 'stop' unexpectedly expensive.
			Lock::Guard z(lock);
			if (src->seek(0))
				fill();
		}
	}

	Bool Player::playing() {
		return bufferPlaying;
	}

	void Player::wait() {
		finishEvent->wait();
	}

	void Player::waitUntil(Duration t) {
		while (bufferPlaying) {
			Duration at = time();

			if (at >= t)
				break;

			Duration r = t - at;
			if (r > time::ms(400)) {
				// Long interval, yield to other threads.
				os::UThread::sleep(nat(r.inMs() - 100));
			} else {
				// Short interval left, poll as much as we can.
				os::UThread::leave();
			}
		}
	}

	Nat Player::next(nat part) {
		if (++part < bufferParts)
			return part;
		else
			return 0;
	}

	void Player::fill() {
		Lock::Guard z(lock);

		for (nat i = 0; i < bufferParts; i++)
			fill(i);
	}

	/**
	 * Backend specific code.
	 */

#ifdef SOUND_DX

	void Player::initBuffer() {
		WAVEFORMATEX fmt = {};
		fmt.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
		fmt.nChannels = channels;
		fmt.nSamplesPerSec = freq;
		fmt.nBlockAlign = channels * sampleDepth;
		fmt.nAvgBytesPerSec = freq * fmt.nBlockAlign;
		fmt.wBitsPerSample = sampleDepth * 8;
		fmt.cbSize = 0;

		DSBUFFERDESC desc = {
			sizeof(desc),
			DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLPOSITIONNOTIFY | DSBCAPS_GLOBALFOCUS,
			bufferSize(),
			0,
			&fmt,
			DS3DALG_DEFAULT,
		};

		IDirectSoundBuffer *b = null;
		AudioMgr *mgr = audioMgr(engine());
		if (!mgr->device())
			return;

		HRESULT r = mgr->device()->CreateSoundBuffer(&desc, &b, NULL);
		if (SUCCEEDED(r)) {
			r = b->QueryInterface(IID_IDirectSoundBuffer8, (void **)&buffer);
		}

		IDirectSoundNotify8 *notify = null;
		if (SUCCEEDED(r)) {
			r = buffer->QueryInterface(IID_IDirectSoundNotify8, (void **)&notify);
		}

		if (SUCCEEDED(r)) {
			event = CreateEvent(NULL, TRUE, FALSE, NULL);

			// Set up notifications. One in the beginning of each section of the buffer.
			DSBPOSITIONNOTIFY n[bufferParts];
			for (nat i = 0; i < bufferParts; i++) {
				n[i].dwOffset = i * partSize();
				n[i].hEventNotify = event.v();
			}

			r = notify->SetNotificationPositions(bufferParts, n);
		}

		if (FAILED(r))
			throw new (this) SoundInitError();

		::release(notify);
		::release(b);
	}

	void Player::destroyBuffer() {
		buffer.release();
		CloseHandle(event.v());
		event = Handle();
	}

	void Player::bufferVolume(float to) {
		// TODO? Transform the 'to' somehow first? Values below ~0.5 are almost not hearable.
		// Re-scale 'to' from [0 - 1] to [DSBVOLUME_MIN - DSBVOLUME_MAX].
		Float v = DSBVOLUME_MIN + to * (Float(DSBVOLUME_MAX) - Float(DSBVOLUME_MIN));
		buffer->SetVolume(LONG(v));
	}

	void Player::bufferPlay() {
		buffer->Play(0, 0, DSBPLAY_LOOPING);
	}

	void Player::bufferStop() {
		buffer->Stop();
	}

	Duration Player::time() {
		DWORD pos = 0;
		buffer->GetCurrentPosition(&pos, NULL);

		nat part = pos / partSize();
		nat64 sample = partInfo->v[part].sample;
		if (!partInfo->v[part].afterEnd)
			sample += (pos % partSize()) / sampleSize();

		sample *= 1000000;
		sample /= freq;

		return time::us(sample);
	}

	void Player::onNotify() {
		DWORD play;
		buffer->GetCurrentPosition(&play, NULL);
		nat playPart = play / partSize();

		if (partInfo->v[playPart].afterEnd) {
			stop();
		} else {
			Lock::Guard z(lock);
			for (nat at = next(lastFilled); at != playPart; at = next(at))
				fill(at);
		}
	}

	void Player::fill(nat part) {
		partInfo->v[part].sample = src->tell();
		partInfo->v[part].afterEnd = false;

		void *buf1 = null, *buf2 = null;
		DWORD size1 = 0, size2 = 0;
		buffer->Lock(partSize() * part, partSize(), &buf1, &size1, &buf2, &size2, 0);

		partInfo->v[part].afterEnd |= fill(buf1, size1);
		partInfo->v[part].afterEnd |= fill(buf2, size2);

		buffer->Unlock(buf1, size1, buf2, size2);

		lastFilled = part;
	}

	bool Player::fill(void *buf, nat size) {
		bool afterEnd = false;
		float *to = (float *)buf;
		nat at = 0;
		size /= sizeof(float);

		// TODO: We do not need to allocate a buffer at each iteration in the loop.
		while (at < size) {
			if (src->more()) {
				sound::Buffer r = src->read(size - at);
				memcpy(to + at, r.dataPtr(), r.filled()*sizeof(float));
				at += r.filled();
			} else {
				afterEnd = true;
				for (; at < size; at++)
					to[at] = 0.0f;
			}
		}

		return afterEnd;
	}

#endif
#ifdef SOUND_AL

	/**
	 * NOTE: In OpenAL the terminology is a bit different compared to DirectSound.
	 *
	 * A sound buffer is a sound source in OpenAL.
	 * A buffer part is a buffer in OpenAL.
	 *
	 * We are using the DirectSound terminology here to keep the naming consistent between the
	 * different backends.
	 */

	void Player::initBuffer() {
		ALuint source = 0;
		alGenSources(1, &source);
		buffer = source;

		if (!buffer)
			throw new (this) SoundInitError();

		alSourcef(source, AL_PITCH, 1);
		alSourcef(source, AL_GAIN, 1);
		alSource3f(source, AL_POSITION, 0, 0, 0);
		alSource3f(source, AL_VELOCITY, 0, 0, 0);
		alSourcei(source, AL_LOOPING, AL_FALSE);

		// Create one buffer for each part.
		for (Nat i = 0; i < partInfo->count; i++) {
			ALuint buf = 0;
			alGenBuffers(1, &buf);
			if (!buf)
				throw new (this) SoundInitError();

			partInfo->v[i].alBuffer = buf;
		}

		if (!tmpBuffer)
			tmpBuffer = malloc(partSize());
	}

	void Player::destroyBuffer() {
		free(tmpBuffer);
		tmpBuffer = null;

		ALuint source = buffer;
		alDeleteSources(1, &source);

		// Destroy the buffers as well.
		for (Nat i = 0; i < partInfo->count; i++) {
			ALuint buf = (ALuint)partInfo->v[i].alBuffer;
			alDeleteBuffers(1, &buf);
		}
	}

	void Player::bufferVolume(float to) {
		alSourcef(buffer, AL_GAIN, to);
	}

	void Player::bufferPlay() {
		alSourcePlay(buffer);
	}

	void Player::bufferStop() {
		alSourceStop(buffer);

		// Unqueue all buffers.
		for (Nat i = 0; i < partInfo->count; i++) {
			ALuint buf = (ALuint)partInfo->v[i].alBuffer;
			alSourceUnqueueBuffers(buffer, 1, &buf);
		}
	}

	static ALint getSource(ALuint source, ALenum param) {
		ALint result = 0;
		alGetSourcei(source, param, &result);
		return result;
	}

	Duration Player::time() {
		// TODO: Handle paused state as well.
		if (!playing())
			return time::us(0);

		// 'sample' is the samples in the processed buffers and the current buffer.
		Word sample = getSource(buffer, AL_SAMPLE_OFFSET);

		Nat part = next(lastFilled);
		sample += partInfo->v[part].sample;

		sample *= 1000000;
		sample /= freq;

		return time::us(sample);
	}

	void Player::onNotify() {
		ALint processed = getSource(buffer, AL_BUFFERS_PROCESSED);
		time();

		// Anything to do?
		if (processed <= 0)
			return;

		Lock::Guard z(lock);

		// Fill any processed parts.
		for (ALint i = 0; i < processed; i++) {
			nat part = next(lastFilled);

			// At the end of the stream?
			if (partInfo->v[part].afterEnd)
				stop();

			// We need to unqueue the buffer before we can fill it.
			ALuint buf = (ALuint)partInfo->v[part].alBuffer;
			alSourceUnqueueBuffers(buffer, 1, &buf);

			// Then fill and queue again. Updates 'lastFilled'.
			fill(part);
		}

		// See if we were too slow refilling the buffer.
		if (bufferPlaying && getSource(buffer, AL_SOURCE_STATE) == AL_STOPPED) {
			// Start playing again now that we have queued some more data.
			alSourcePlay(buffer);
		}
	}

	void Player::fill(nat part) {
		partInfo->v[part].sample = src->tell();
		partInfo->v[part].afterEnd = fill(tmpBuffer, partSize());

		ALuint partBuffer = partInfo->v[part].alBuffer;
		ALenum format = channels == 2 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16;
		alBufferData(partBuffer, format, tmpBuffer, partSize(), freq);
		alSourceQueueBuffers(buffer, 1, &partBuffer);

		lastFilled = part;
	}

	inline float clamp(float v, float max, float min) {
		return std::max(std::min(v, max), min);
	}

	inline short convert(float src) {
		return short(clamp(src * 32767, 32767, -32768));
	}

	bool Player::fill(void *buf, nat size) {
		bool afterEnd = false;
		short *to = (short *)buf;

		nat at = 0;
		size /= sizeof(short);

		while (at < size) {
			if (src->more()) {
				sound::Buffer r = src->read(size - at);
				for (Nat i = 0; i < r.filled(); i++)
					to[at++] = convert(r[i]);
			} else {
				afterEnd = true;
				for (; at < size; at++)
					to[at] = 0;
			}
		}

		return afterEnd;
	}

#endif
}