File: sound.cpp

package info (click to toggle)
scummvm 2.9.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 450,580 kB
  • sloc: cpp: 4,299,825; asm: 28,322; python: 12,901; sh: 11,302; java: 9,289; xml: 7,895; perl: 2,639; ansic: 2,465; yacc: 1,670; javascript: 1,020; makefile: 933; lex: 578; awk: 275; objc: 82; sed: 11; php: 1
file content (407 lines) | stat: -rw-r--r-- 11,660 bytes parent folder | download | duplicates (3)
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
/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "common/memstream.h"

#include "audio/audiostream.h"
#include "audio/decoders/adpcm.h"
#include "audio/decoders/wave.h"

#include "asylum/system/config.h"
#include "asylum/system/sound.h"

#include "asylum/resources/actor.h"
#include "asylum/resources/worldstats.h"

#include "asylum/views/scene.h"

#include "asylum/asylum.h"
#include "asylum/respack.h"

namespace Asylum {

Sound::Sound(AsylumEngine *engine, Audio::Mixer *mixer) : _vm(engine), _mixer(mixer), _musicVolume(-10000) {
}

Sound::~Sound() {
	cleanupQueue();
}

//////////////////////////////////////////////////////////////////////////
// Playing sounds & music
//////////////////////////////////////////////////////////////////////////

void Sound::playSound(ResourceId resourceId, bool looping, int32 volume, int32 panning) {
	debugC(kDebugLevelSound, "[Sound] Playing Sound 0x%08X", resourceId);

	// Cleanup sound queue
	cleanupQueue();

	if (volume <= -10000)
		return;

	if (_vm->checkGameVersion("Demo") && RESOURCE_PACK(resourceId) == kResourcePackSound)
		resourceId = MAKE_RESOURCE(kResourcePackShared, RESOURCE_INDEX(resourceId));

	SoundQueueItem *item = getItem(resourceId);
	if (item) {
		// Duplicate the queue entry
		item = addToQueue(item->resourceId);
	} else {
		// Check that the sound is valid
		if (!isValidSoundResource(resourceId))
			return;

		item = addToQueue(resourceId);
	}

	// Original sets position back to 0
	_mixer->stopHandle(item->handle);

	Audio::Mixer::SoundType soundType;
	switch (RESOURCE_PACK(resourceId)) {
	case kResourcePackShared:
		soundType = Audio::Mixer::kPlainSoundType;
		break;

	case kResourcePackSpeech:
	case kResourcePackSharedSound:
		soundType = Audio::Mixer::kSpeechSoundType;
		break;

	default:
		soundType = Audio::Mixer::kSFXSoundType;
		break;
	}

	ResourceEntry *resource = getResource()->get(resourceId);
	playSoundData(soundType, &item->handle, resource->data, resource->size, looping, volume, panning);
}

void Sound::playMusic(ResourceId resourceId, int32 volume) {
	debugC(kDebugLevelSound, "[Sound] Playing Music 0x%08X", resourceId);
	if (resourceId == kResourceNone) {
		stopMusic();
		return;
	}

	// Sets the music volume
	setMusicVolume(volume);

	// Check if music is already playing
	if (_mixer->isSoundHandleActive(_musicHandle))
		stopMusic();

	if (!isValidSoundResource(resourceId))
		return;

	ResourceEntry *resource = getResource()->get(resourceId);
	playSoundData(Audio::Mixer::kMusicSoundType, &_musicHandle, resource->data, resource->size, true, volume, 0);
}

void Sound::changeMusic(int32 index, int32 musicStatusExt) {
	if (index != getWorld()->musicCurrentResourceIndex) {
		getWorld()->musicResourceIndex = index;
		getWorld()->musicStatusExt = musicStatusExt;
		getWorld()->musicFlag = 1;
	}
}

bool Sound::isPlaying(ResourceId resourceId) {
	return (getPlayingItem(resourceId) != nullptr);
}

//////////////////////////////////////////////////////////////////////////
// Volume & panning
//////////////////////////////////////////////////////////////////////////

void Sound::setVolume(ResourceId resourceId, int32 volume) {
	SoundQueueItem *item = getPlayingItem(resourceId);
	if (!item)
		return;

	convertVolumeFrom(volume);

	_mixer->setChannelVolume(item->handle, (byte)volume);
}

void Sound::setMusicVolume(int32 volume) {
	if (volume < -10000)
		return;

	// Save music volume (we need to be able to return it to the logic code
	_musicVolume = volume;

	convertVolumeFrom(volume);

	_mixer->setChannelVolume(_musicHandle, (byte)volume);
}

void Sound::setPanning(ResourceId resourceId, int32 panning) {
	if (Config.performance == 1)
		return;

	SoundQueueItem *item = getPlayingItem(resourceId);
	if (!item)
		return;

	convertPan(panning);

	_mixer->setChannelBalance(item->handle, (int8)panning);
}

int32 Sound::calculateVolumeAdjustement(const Common::Point &point, int32 attenuation, int32 delta) {
	if (!attenuation)
		return -(delta * delta);

	Actor *player = getScene()->getActor();
	Common::Point adjusted(point);
	Common::Point sumPlayer = *player->getPoint1() + *player->getPoint2();

	if (getSharedData()->getGlobalPoint().x == -1)
		adjusted -= sumPlayer;
	else
		adjusted -= getSharedData()->getGlobalPoint();

	int32 adjustedVolume = getAdjustedVolume(adjusted.x * adjusted.x + adjusted.y * adjusted.y);

	Common::Rational invAtt(100, attenuation);
	Common::Rational v;
	if (invAtt.toInt())
		v = Common::Rational(adjustedVolume, 1) / invAtt;
	else
		v = Common::Rational(delta, 1);

	int32 volume = (v.toInt() - delta) * (v.toInt() - delta);

	if (volume > 10000)
		return -10000;

	return -volume;
}

int32 Sound::getAdjustedVolume(int32 volume) const {
	if (volume < 2)
		return volume;

	uint32 counter = (uint32)(log((double)volume) / log(2.0)) / 2;
	uint32 adjustedVolume = (uint32)pow(2.0, (int32)counter);

	uint32 offset = adjustedVolume;
	uint32 base = adjustedVolume << counter;

	for (;;) {
		--counter;
		if ((int32)counter < 0)
			break;

		offset /= 2;
		uint32 val = base + ((offset + 2 * (uint32)volume) << counter);

		if (val <= (uint32)volume) {
			adjustedVolume += offset;
			base = val;
		}
	}

	return adjustedVolume;
}

int32 Sound::calculatePanningAtPoint(const Common::Point &point) {
	// point.y does not seem to be used at all :S

	int delta = point.x - getWorld()->xLeft;

	if (delta < 0)
		return (getWorld()->reverseStereo ? 10000 : -10000);

	if (delta >= 640)
		return (getWorld()->reverseStereo ? -10000 : 10000);


	int sign, absDelta;
	if (delta > 320) {
		absDelta = delta - 320;
		sign = (getWorld()->reverseStereo ? -1 : 1);
	} else {
		absDelta = 320 - delta;
		sign = (getWorld()->reverseStereo ? 1 : -1);
	}

	Common::Rational v(absDelta, 6);
	int32 volume = v.toInt() * v.toInt();

	if (volume > 10000)
		volume = 10000;

	return volume * sign;
}

//////////////////////////////////////////////////////////////////////////
// Stopping sounds
//////////////////////////////////////////////////////////////////////////
void Sound::stop(ResourceId resourceId) {
	SoundQueueItem *item = getPlayingItem(resourceId);

	if (item != nullptr)
		_mixer->stopHandle(item->handle);
}

void Sound::stopAll(ResourceId resourceId) {
	for (Common::Array<SoundQueueItem>::iterator it = _soundQueue.begin(); it != _soundQueue.end(); it++)
		if (it->resourceId == resourceId)
			_mixer->stopHandle(it->handle);
}

void Sound::stopAll() {
	for (Common::Array<SoundQueueItem>::iterator it = _soundQueue.begin(); it != _soundQueue.end(); it++)
		_mixer->stopHandle(it->handle);
}

void Sound::stopMusic() {
	_mixer->stopHandle(_musicHandle);
}

//////////////////////////////////////////////////////////////////////////
// Helper functions
//////////////////////////////////////////////////////////////////////////

void Sound::playSoundData(Audio::Mixer::SoundType type, Audio::SoundHandle *handle, byte *soundData, uint32 soundDataLength, bool loop, int32 vol, int32 pan) {
	Common::MemoryReadStream *stream = new Common::MemoryReadStream(soundData, soundDataLength);
	Audio::RewindableAudioStream *sndStream = Audio::makeWAVStream(stream, DisposeAfterUse::YES);

	// Convert volume and panning
	convertVolumeFrom(vol);
	convertPan(pan);

	_mixer->playStream(type, handle, Audio::makeLoopingAudioStream(sndStream, loop ? 0 : 1), -1, (byte)vol, (int8)pan);
}

//////////////////////////////////////////////////////////////////////////
// Sound buffer
//////////////////////////////////////////////////////////////////////////

SoundQueueItem *Sound::getItem(ResourceId resourceId) {
	for (uint32 i = 0; i < _soundQueue.size(); i++)
		if (resourceId == _soundQueue[i].resourceId)
			return &_soundQueue[i];

	return nullptr;
}

SoundQueueItem *Sound::getPlayingItem(ResourceId resourceId) {
	for (uint32 i = 0; i < _soundQueue.size(); i++)
		if (resourceId == _soundQueue[i].resourceId
			&& _mixer->isSoundHandleActive(_soundQueue[i].handle))
			return &_soundQueue[i];

	return nullptr;
}

SoundQueueItem *Sound::addToQueue(ResourceId resourceId) {
	debugC(kDebugLevelSound, "[Sound] Queueing Sound 0x%08X", resourceId);
	SoundQueueItem sound;
	sound.resourceId = resourceId;
	_soundQueue.push_back(sound);

	return &_soundQueue.back();
}

void Sound::cleanupQueue() {
	for (uint i = 0; i < _soundQueue.size(); i++) {
		if (_mixer->isSoundHandleActive(_soundQueue[i].handle))
			continue;

		// Remove the finished sound from the queue
		_soundQueue.remove_at(i);
		--i;
	}
}

//////////////////////////////////////////////////////////////////////////
// Helper functions
//////////////////////////////////////////////////////////////////////////
bool Sound::isValidSoundResource(ResourceId resourceId) {
	ResourceEntry *entry = getResource()->get(resourceId);

	if (memcmp(entry->data, "RIFF", 4) != 0)
		return false;

	if (memcmp(&entry->data[8], "WAVE", 4) != 0)
		return false;

	// Original checks for "fmt " and "data" tags and return values to the calling function
	return true;
}

//////////////////////////////////////////////////////////////////////////
// Conversion functions
//
// Those are from engines/agos/sound.cpp (FIXME: Move to common code?)
//////////////////////////////////////////////////////////////////////////

void Sound::convertVolumeFrom(int32 &vol) {
	// DirectSound was originally used, which specifies volume
	// and panning differently than ScummVM does, using a logarithmic scale
	// rather than a linear one.
	//
	// Volume is a value between -10,000 and 0.
	//
	// In both cases, the -10,000 represents -100 dB. When panning, only
	// one speaker's volume is affected - just like in ScummVM - with
	// negative values affecting the left speaker, and positive values
	// affecting the right speaker. Thus -10,000 means the left speaker is
	// silent.

	int32 v = CLIP<int32>(vol, -10000, 0);
	if (v) {
		vol = (int)((double)Audio::Mixer::kMaxChannelVolume * pow(10.0, (double)v / 2000.0) + 0.5);
	} else {
		vol = Audio::Mixer::kMaxChannelVolume;
	}
}

void Sound::convertVolumeTo(int32 &vol) {
	vol = vol ? (int32)log10((vol - 0.5) / Audio::Mixer::kMaxChannelVolume) * 2000 : -9999;
}

void Sound::convertPan(int32 &pan) {
	// DirectSound was originally used, which specifies volume
	// and panning differently than ScummVM does, using a logarithmic scale
	// rather than a linear one.
	//
	// Panning is a value between -10,000 and 10,000.
	//
	// In both cases, the -10,000 represents -100 dB. When panning, only
	// one speaker's volume is affected - just like in ScummVM - with
	// negative values affecting the left speaker, and positive values
	// affecting the right speaker. Thus -10,000 means the left speaker is
	// silent.

	int32 p = CLIP<int32>(pan, -10000, 10000);
	if (p < 0) {
		pan =  129 * (1 - pow(10.0, p /  5000.0));
	} else {
		pan = -129 * (1 - pow(10.0, p / -5000.0));
	}
}

} // end of namespace Asylum