aboutsummaryrefslogtreecommitdiff
path: root/archive/hgewin/sound.cpp
blob: 902465299b6b0606824ce43560da75aebe0f46ba (plain) (blame)
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
525
526
527
528
529
530
531
/*
** Haaf's Game Engine 1.8
** Copyright (C) 2003-2007, Relish Games
** hge.relishgames.com
**
** Core functions implementation: audio routines
*/


// This is just enough to get Hammerfight working without using libBA$$.
//  If you want a full HGE audio implementation, you should either use the
//  code in sound_libbass.cpp (and maybe pay for a BA$$ licen$e), or improve
//  this code.
// Well, this code is now improved by Chris Xiong, adding several new interfaces.
// (Such as seeking in sample...)
// Channel functions are fully supported now. However music and streaming are
// still not supported. Some APIs changed for OpenAL is different from BA$$.

#include "hge_impl.h"

#include "AL/al.h"
#include "AL/alc.h"
#include "AL/alext.h"
#include "ogg/ogg.h"
#include "vorbis/vorbisfile.h"
static const char* SOUND_SRC_FN="hge/sound.cpp";
struct oggcbdata
{
	const BYTE *data;
	DWORD size;
	DWORD pos;
};

static size_t oggcb_read(void *ptr, size_t size, size_t nmemb, void *datasource)
{
	oggcbdata *data = (oggcbdata *) datasource;
	const DWORD avail = data->size - data->pos;
	size_t want = nmemb * size;
	if (want > avail)
		want = avail - (avail % size);
	if (want > 0)
	{
		memcpy(ptr, data->data + data->pos, want);
		data->pos += want;
	}
	return want / size;
}

static int oggcb_seek(void *datasource, ogg_int64_t offset, int whence)
{
	oggcbdata *data = (oggcbdata *) datasource;
	ogg_int64_t pos = 0;
	switch (whence)
	{
		case SEEK_SET: pos = offset; break;
		case SEEK_CUR: pos = ((ogg_int64_t) data->pos) + offset; break;
		case SEEK_END: pos = ((ogg_int64_t) data->size) + offset; break;
		default: return -1;
	}

	if ( (pos < 0) || (pos > ((ogg_int64_t) data->size)) )
		return -1;

	data->pos = (DWORD) pos;
	return 0;
}

static int oggcb_close(void *datasource)
{
	return 0;
}

static long oggcb_tell(void *datasource)
{
	oggcbdata *data = (oggcbdata *) datasource;
	return (long) data->pos;
}

static ov_callbacks oggcb = { oggcb_read, oggcb_seek, oggcb_close, oggcb_tell };

static void *decompress_vorbis(const BYTE *data, const DWORD size, ALsizei *decompressed_size, ALenum *fmt, ALsizei *freq)
{
#ifdef __POWERPC__
	const int bigendian = 1;
#else
	const int bigendian = 0;
#endif

	oggcbdata cbdata = { data, size, 0 };
	OggVorbis_File vf;
	memset(&vf, '\0', sizeof (vf));
	if (ov_open_callbacks(&cbdata, &vf, NULL, 0, oggcb) == 0)
    {
        int bitstream = 0;
        vorbis_info *info = ov_info(&vf, -1);

        *decompressed_size = 0;
        *fmt = (info->channels == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
        *freq = info->rate;

        if ((info->channels != 1) && (info->channels != 2))
        {
            ov_clear(&vf);
            return NULL;
        }

        char buf[1024 * 16];
        long rc = 0;
        size_t allocated = 64 * 1024;
        BYTE *retval = (ALubyte *) malloc(allocated);
        while ( (rc = ov_read(&vf, buf, sizeof (buf), bigendian, 2, 1, &bitstream)) != 0 )
        {
            if (rc > 0)
            {
                *decompressed_size += rc;
                if ((unsigned)*decompressed_size >= allocated)
                {
                    allocated *= 2;
                    ALubyte *tmp = (ALubyte *) realloc(retval, allocated);
                    if (tmp == NULL)
                    {
                        free(retval);
                        retval = NULL;
                        break;
                    }
                    retval = tmp;
                }
                memcpy(retval + (*decompressed_size - rc), buf, rc);
            }
        }
        ov_clear(&vf);
        return retval;
    }

    return NULL;
}

#define MAX_SIDS 128
static int sidcount = 0;
static ALuint sids[MAX_SIDS];

static ALuint get_source()
{
    for (int i = 0; i < sidcount; i++)
    {
        ALint state = AL_PLAYING;
        alGetSourceiv(sids[i], AL_SOURCE_STATE, &state);
        if ((state != AL_PLAYING) && (state != AL_PAUSED))
            return sids[i];
    }
    if (sidcount >= MAX_SIDS)
        return 0;

    ALuint sid = 0;
    alGenSources(1, &sid);
    if (sid == 0)
        return 0;
    sids[sidcount++] = sid;
    return sid;
}


HEFFECT CALL HGE_Impl::Effect_Load(const char *filename, DWORD size)
{
	DWORD _size;
	void *data;

	if(hOpenAL)
	{
		if(bSilent) return 1;

		if(size) { data=(void *)filename; _size=size; }
		else
		{
			data=Resource_Load(filename, &_size);
			if(!data) return 0;
		}

		const BYTE *magic = (const BYTE *) data;
		const bool isOgg = ( (_size > 4) &&
		                     (magic[0] == 'O') && (magic[1] == 'g') &&
		                     (magic[2] == 'g') && (magic[3] == 'S') );
		if (!isOgg)
		{
			if(!size) Resource_Free(data);
			return 0;
		}
		void *allocation_decompressed = NULL;
		void *decompressed = NULL;
		ALsizei decompressed_size = 0;
		ALsizei freq = 0;
		ALenum fmt = AL_FORMAT_STEREO16;
		if (isOgg)
		{
			/*if (alIsExtensionPresent((const ALchar *) "AL_EXT_vorbis"))//useless
			{
				fmt = alGetEnumValue((const ALchar *) "AL_FORMAT_VORBIS_EXT");
				decompressed = data;
				decompressed_size = _size;
			}
			else
			{*/
				allocation_decompressed = decompress_vorbis((const BYTE *) data, _size, &decompressed_size, &fmt, &freq);
				decompressed = allocation_decompressed;
			//}
		}

		ALuint bid = 0;
		alGenBuffers(1, &bid);
		alBufferData(bid, fmt, decompressed, decompressed_size, freq);
		free(allocation_decompressed);  // not delete[] !
		if(!size) Resource_Free(data);
		return (HEFFECT) bid;
	}
	else return 0;
}

HCHANNEL CALL HGE_Impl::Effect_Play(HEFFECT eff)
{
	return Effect_PlayEx(eff, 1.0f, 0, 1.0f, false);
}

HCHANNEL CALL HGE_Impl::Effect_PlayEx(HEFFECT eff, float volume, float pan, float pitch, bool loop)
{
	if(hOpenAL)
	{
		const ALuint sid = get_source(); // find an unused sid, or generate a new one.
		if (sid != 0)
		{
			if (volume < 0) volume = 0; else if (volume > 1.0) volume = 1.0;
			if (pan < -1.0) pan = -1.0; else if (pan > 1.0) pan = 1.0;
			alSourceStop(sid);
			alSourcei(sid, AL_BUFFER, (ALint) eff);
			alSourcef(sid, AL_GAIN, volume);
			alSourcef(sid, AL_PITCH, pitch);
			alSource3f(sid, AL_POSITION, pan, 0.0f, 0.0f);
			alSourcei(sid, AL_LOOPING, loop ? AL_TRUE : AL_FALSE);
			alSourcePlay(sid);
		}
		return sid;
	}
	else return 0;
}

void CALL HGE_Impl::Effect_Free(HEFFECT eff)
{
	if(hOpenAL)
	{
		ALuint bid = (ALuint) eff;
		alDeleteBuffers(1, &bid);
	}
}
//Castrate!!
HMUSIC CALL HGE_Impl::Music_Load(const char *filename, DWORD size){return 0;}

HCHANNEL CALL HGE_Impl::Music_Play(HMUSIC mus, bool loop, int volume, int order, int row){return 0;}

void CALL HGE_Impl::Music_Free(HMUSIC mus){}

void CALL HGE_Impl::Music_SetAmplification(HMUSIC music, int ampl){}

int CALL HGE_Impl::Music_GetAmplification(HMUSIC music){return -1;}

int CALL HGE_Impl::Music_GetLength(HMUSIC music){return -1;}

void CALL HGE_Impl::Music_SetPos(HMUSIC music, int order, int row){}

bool CALL HGE_Impl::Music_GetPos(HMUSIC music, int *order, int *row){return false;}

void CALL HGE_Impl::Music_SetInstrVolume(HMUSIC music, int instr, int volume){}

int CALL HGE_Impl::Music_GetInstrVolume(HMUSIC music, int instr){return -1;}

void CALL HGE_Impl::Music_SetChannelVolume(HMUSIC music, int channel, int volume){}

int CALL HGE_Impl::Music_GetChannelVolume(HMUSIC music, int channel){return -1;}

HSTREAM CALL HGE_Impl::Stream_Load(const char *filename, DWORD size){return 0;}

void CALL HGE_Impl::Stream_Free(HSTREAM stream){}

HCHANNEL CALL HGE_Impl::Stream_Play(HSTREAM stream, bool loop, int volume){return 0;}

void CALL HGE_Impl::Channel_SetPanning(HCHANNEL chn, float pan)
{
	if(pan>1.0)pan=1.0;
	if(pan<-1.0)pan=-1.0;
	if(hOpenAL)
	{
		alSource3f((ALuint) chn, AL_POSITION, pan, 0.0f, 0.0f);
	}
}

void CALL HGE_Impl::Channel_SetVolume(HCHANNEL chn, float volume)
{
	if(hOpenAL)
	{
		if (volume < 0) volume = 0; else if (volume > 1.0f) volume = 1.0f;
		alSourcef((ALuint) chn, AL_GAIN, volume);
	}
}

void CALL HGE_Impl::Channel_SetPitch(HCHANNEL chn, float pitch)
{
	if(hOpenAL)
	{
		alSourcef((ALuint) chn, AL_PITCH, pitch);
	}
}

void CALL HGE_Impl::Channel_Pause(HCHANNEL chn)
{
	if(hOpenAL)
	{
		alSourcePause((ALuint) chn);
	}
}

void CALL HGE_Impl::Channel_Resume(HCHANNEL chn)
{
	if(hOpenAL)
	{
		alSourcePlay((ALuint) chn);
	}
}

void CALL HGE_Impl::Channel_Stop(HCHANNEL chn)
{
	if(hOpenAL)
	{
		alSourceStop((ALuint) chn);
	}
}

void CALL HGE_Impl::Channel_PauseAll()
{
	if(hOpenAL)
	{
		ALCcontext *ctx = alcGetCurrentContext();
		alcSuspendContext(ctx);
	}
}

void CALL HGE_Impl::Channel_ResumeAll()
{
	if(hOpenAL)
	{
		ALCcontext *ctx = alcGetCurrentContext();
		alcProcessContext(ctx);
	}
}

void CALL HGE_Impl::Channel_StopAll()
{
	if(hOpenAL)
	{
		for (int i = 0; i < sidcount; i++)
			alSourceStop(sids[i]);
	}
}

bool CALL HGE_Impl::Channel_IsPlaying(HCHANNEL chn)
{
	if(hOpenAL)
	{
		ALint state = AL_STOPPED;
		alGetSourceiv((ALuint) chn, AL_SOURCE_STATE, &state);
		return state == AL_PLAYING;
	}
	else return false;
}
//The following features are ported to OpenAL by Chris
float CALL HGE_Impl::Channel_GetLength(HCHANNEL chn)
//WARNING!!:In OpenAL We pass HEFFECT insteat HCHANNEL in!
//This should be fixed.
{
	//Well, you developers should know this "by heart".
	if (hOpenAL)
	{
		ALint sizeInBytes;
		ALint channels;
		ALint bits;
		ALuint bufferID=chn;
		alGetBufferi(bufferID, AL_SIZE, &sizeInBytes);
		alGetBufferi(bufferID, AL_CHANNELS, &channels);
		alGetBufferi(bufferID, AL_BITS, &bits);
		int lengthInSamples = sizeInBytes * 8 / (channels * bits);
		ALint frequency;
		alGetBufferi(bufferID, AL_FREQUENCY, &frequency);
		float durationInSeconds = (float)lengthInSamples / (float)frequency;
		return durationInSeconds;
	}
	return -1;
}

float CALL HGE_Impl::Channel_GetPos(HCHANNEL chn)
{
	if (hOpenAL)
	{
		ALfloat res;
		alGetSourcef((ALuint)chn,AL_SEC_OFFSET,&res);
		return (float)res;
	}
	else return -1.0f;
}

void CALL HGE_Impl::Channel_SetPos(HCHANNEL chn, float fSeconds)
{
	if (hOpenAL)
	{
		alSourcef((ALuint)chn,AL_SEC_OFFSET,(ALfloat)fSeconds);
	}
}

int CALL HGE_Impl::Channel_GetPos_BySample(HCHANNEL chn)
{
	if (hOpenAL)
	{
		ALint res;
		alGetSourcei((ALuint)chn,AL_SAMPLE_OFFSET,&res);
		return (int)res;
	}
	else return -1;
}

void CALL HGE_Impl::Channel_SetPos_BySample(HCHANNEL chn, int iSample)
{
	if (hOpenAL)
	{
		alSourcei((ALuint)chn,AL_SAMPLE_OFFSET,(ALint)iSample);
	}
}

void CALL HGE_Impl::Channel_SlideTo(HCHANNEL channel, float time, int volume, int pan, float pitch){}

bool CALL HGE_Impl::Channel_IsSliding(HCHANNEL channel){return false;}


//////// Implementation ////////


bool HGE_Impl::_SoundInit()
{
	if(!bUseSound || hOpenAL) return true;

	bSilent=false;

	sidcount = 0;
	memset(sids, '\0', sizeof (sids));

    System_Log("%s: Starting OpenAL init",SOUND_SRC_FN);

	ALCdevice *dev = alcOpenDevice(NULL);
	if (!dev)
	{
		System_Log("%s: alcOpenDevice(NULL) failed, using no sound",SOUND_SRC_FN);
		bSilent=true;
		return true;
	}

	ALint caps[] = { ALC_FREQUENCY, nSampleRate, 0 };
	ALCcontext *ctx = alcCreateContext(dev, caps);
	if (!ctx)
	{
		alcCloseDevice(dev);
		System_Log("%s: alcCreateContext(NULL) failed, using no sound",SOUND_SRC_FN);
		bSilent=true;
		return true;
	}

	alcMakeContextCurrent(ctx);
	alcProcessContext(ctx);

    System_Log("%s: OpenAL initialized successfully.",SOUND_SRC_FN);
    System_Log("%s: AL_VENDOR: %s",SOUND_SRC_FN, (char *) alGetString(AL_VENDOR));
    System_Log("%s: AL_RENDERER: %s",SOUND_SRC_FN, (char *) alGetString(AL_RENDERER));
    System_Log("%s: AL_VERSION: %s",SOUND_SRC_FN,(char *) alGetString(AL_VERSION));
    System_Log("%s: AL_EXTENSIONS: %s",SOUND_SRC_FN,(char *) alGetString(AL_EXTENSIONS));

	hOpenAL = (void *) 0x1;   // something non-NULL (!!! FIXME: this should eventually be a library handle).

	_SetFXVolume(nFXVolume);
	//_SetMusVolume(nMusVolume);
	//_SetStreamVolume(nStreamVolume);

	return true;
}

void HGE_Impl::_SoundDone()
{
	CStreamList *stmItem=streams, *stmNext;

	if(hOpenAL)
	{
		for (int i = 0; i < sidcount; i++)
			alSourceStop(sids[i]);
		alDeleteSources(sidcount, sids);
		sidcount = 0;
		memset(sids, '\0', sizeof (sids));

		ALCcontext *ctx = alcGetCurrentContext();
		ALCdevice *dev = alcGetContextsDevice(ctx);
		alcMakeContextCurrent(NULL);
		alcSuspendContext(ctx);
		alcDestroyContext(ctx);
		alcCloseDevice(dev);

		hOpenAL=0;

		while(stmItem)
		{
			stmNext=stmItem->next;
			Resource_Free(stmItem->data);
			delete stmItem;
			stmItem=stmNext;
		}
		streams=0;
	}
}

void HGE_Impl::_SetMusVolume(int vol){}

void HGE_Impl::_SetStreamVolume(int vol){}

void HGE_Impl::_SetFXVolume(int vol)
{
	if(hOpenAL)
	{
		alListenerf(AL_GAIN, ((ALfloat) vol) / 100.0f);
	}
}