-
Notifications
You must be signed in to change notification settings - Fork 1
/
Audio.h
2079 lines (1902 loc) · 80.3 KB
/
Audio.h
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***********************************************************************************************
* AL Gore Library: An MSVC++ class implementation that wraps OpenAL and ALURE using other libs*
***********************************************************************************************
* This file is distributed under the Revised BSD License, also known as the "New" BSD License *
* See the text of the "New BSD License" for rules about using this file in your project. *
***********************************************************************************************
* Copyright (c) 2010 Herbert Elwood Gilliland III ; All rights reserved. *
***********************************************************************************************/
#pragma once
#include <al.h>
#include <alc.h>
//#include <AL/alu.h>
#include <AL/alure.h>
#include <efx.h>
#include <EFX-Util.h>
#include <efx-creative.h>
//#include <al/xram.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <math.h>
#include <sndfile.h>
#include <string.h>
using namespace std;
#include <vector>
#ifndef null
#define null NULL
#endif
#include "ListItem.h"
#include "LinkedList.h"
// Forward declarations to rectify identities
class ALSource;
class ALBuffer;
class ALWaveForm;
class ALWaveForms;
class ALSound;
class ALUREStream;
class ALSoundManager;
#if defined(LATER)
class EFX;
#endif
/*
* Definitions brought in from somewhere when building in Ecere, now here because they worked.
*/
#define RANGE(a, b, c) ((b) < (a) ? (a) : ((b) > (c) ? (c) : (b)))
// EFX help (where we got the .h): Dmytry Lavrov (Public Domain code samples)
//EAX
//const GUID DSPROPSETID_EAX20_ListenerProperties = { 0x306a6a8, 0xb224, 0x11d2, { 0x99, 0xe5, 0x0, 0x0, 0xe8, 0xd8, 0xc7, 0x22 } };
//const GUID DSPROPSETID_EAX20_BufferProperties = { 0x306a6a7, 0xb224, 0x11d2, { 0x99, 0xe5, 0x0, 0x0, 0xe8, 0xd8, 0xc7, 0x22 } };
//#ifndef(AL_FORMAT_VORBIS_EXT)
//#define AL_FORMAT_VORBIS_EXT 0x10003
//#endif
#ifndef ALC_EXT_EFX
#define AL_FILTER_TYPE 0x8001
#define AL_EFFECT_TYPE 0x8001
#define AL_FILTER_NULL 0x0000
#define AL_FILTER_LOWPASS 0x0001
#define AL_FILTER_HIGHPASS 0x0002
#define AL_FILTER_BANDPASS 0x0003
#define AL_EFFECT_NULL 0x0000
#define AL_EFFECT_EAXREVERB 0x8000
#define AL_EFFECT_REVERB 0x0001
#define AL_EFFECT_CHORUS 0x0002
#define AL_EFFECT_DISTORTION 0x0003
#define AL_EFFECT_ECHO 0x0004
#define AL_EFFECT_FLANGER 0x0005
#define AL_EFFECT_FREQUENCY_SHIFTER 0x0006
#define AL_EFFECT_VOCAL_MORPHER 0x0007
#define AL_EFFECT_PITCH_SHIFTER 0x0008
#define AL_EFFECT_RING_MODULATOR 0x0009
#define AL_EFFECT_AUTOWAH 0x000A
#define AL_EFFECT_COMPRESSOR 0x000B
#define AL_EFFECT_EQUALIZER 0x000C
#define ALC_EFX_MAJOR_VERSION 0x20001
#define ALC_EFX_MINOR_VERSION 0x20002
#define ALC_MAX_AUXILIARY_SENDS 0x20003
#endif
#ifndef ALC_MONO_SOURCES
#define ALC_MONO_SOURCES 0x1010
#define ALC_STEREO_SOURCES 0x1011
#endif
#ifndef AL_EFFECT_EAXREVERB
#define AL_EFFECT_EAXREVERB 0x8000
#endif
#ifndef ALC_CAPTURE_DEVICE_SPECIFIER
/**
* The Specifier string for default device
*/
#define ALC_DEFAULT_DEVICE_SPECIFIER 0x1004
#define ALC_DEVICE_SPECIFIER 0x1005
#define ALC_EXTENSIONS 0x1006
#define ALC_MAJOR_VERSION 0x1000
#define ALC_MINOR_VERSION 0x1001
#define ALC_ATTRIBUTES_SIZE 0x1002
#define ALC_ALL_ATTRIBUTES 0x1003
/**
* Capture extension
*/
#define ALC_CAPTURE_DEVICE_SPECIFIER 0x310
#define ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER 0x311
#define ALC_CAPTURE_SAMPLES 0x312
#endif
/*
* Implementation of OpenAL via an audio API base class.
*/
// Be very careful with these two parameters
// It is very dependant on the audio hardware your
// user is using. It you get too large, it may work
// on one persons system but not on another.
// TODO Write a hardware test !
#define MAX_AUDIO_BUFFERS 64
#define MAX_AUDIO_SOURCES 16
enum ALState { empty=0, stopped=1, paused=2, playing=3 };
enum ALSoundFormat { mono8=AL_FORMAT_MONO8, mono16=AL_FORMAT_MONO16, stereo8=AL_FORMAT_STEREO8, stereo16=AL_FORMAT_STEREO16 };
void OUTPUT(char * fmt, ...);
/*
* Compare strings, case insensitive.
*/
#define LOWER(c) ((c) >= 'A' && (c) <= 'Z' ? (c)+'a'-'A' : (c))
bool contains( const char *astr, const char *bstr );
// Used during Init(), maybe it shouldn't die() here...
void checkForErrors(void);
static const int indentation = 4;
static const int maxmimumWidth = 79;
void printChar(int c, int *width);
void indent(int *width);
void printList(const char *header, char separator, const char *list);
struct SoundVector
{
public:
float x,y,z,a,b,c;
SoundVector(void) { x=y=z=a=b=c=0; }
//SoundVector() { y=1.0f; }
float *asFloat3( ) { return &x; }
float *asFloat6( ) { return &x; }
};
//int unusedBuffers, unusedSources;
void GetALCErrorString(ALenum err);
bool ALError( char *tb );
class ALBuffer : public ListItem {
public:
ALuint id;
inline bool valid() { if ( alIsBuffer( id ) ) return true; return false; }
float duration() {
ALint bits, channels, freq, size;
alGetBufferi(id, AL_BITS, &bits);
alGetBufferi(id, AL_CHANNELS, &channels);
alGetBufferi(id, AL_FREQUENCY, &freq);
alGetBufferi(id, AL_SIZE, &size);
if(ALError("ALBuffer:duration()")) { return 0.0f; }
return (float) ((size / channels * 8 / bits ) / freq);
}
bool Close() {
if ( valid() ) alDeleteBuffers(1, &(id)); if ( ALError( "ALBuffer:Close:alDeleteBuffers") ) return false; //unusedBuffers++;
return true;
}
ALBuffer() {
id=0;
}
~ALBuffer() { Close(); }
};
class ALBuffers : public LinkedList {
public:
void ClearInvalid() {
ALBuffer *b;
for ( b=(ALBuffer *) first; b; b=(ALBuffer *) (b->next) ) { if ( !b->valid() ) { Remove(b); delete b; } }
}
ALBuffer *New() {
ALBuffer *b;
alGetError();
//if ( unusedBuffers <= 0 ) { OUTPUT( "No unused buffers available when requesting New() buffer\n" ); delete b; return null; }
b= new ALBuffer;
alGenBuffers(1,&(b->id)); if(ALError("ALBuffer:alGenBuffers")) { delete b; return null; } //unusedBuffers--;
//OUTPUT( "#%d buffer created with ID of %d\n", unusedBuffers, b.id );
Append(b);
return b;
}
~ALBuffers() {
ALBuffer *d,*n;
for ( d=(ALBuffer *) first; d; d=n ) {
n=(ALBuffer *) (d->next);
delete d;
}
}
};
class ALSource : public ListItem {
public:
ALuint id;
SoundVector position, velocity;
float pitch,gain;
float rolloff;
ALboolean loop,relative;
ALState state;
ALSource() { pitch=1.0f; gain=1.0f; rolloff=0.0f; loop=AL_FALSE; relative=AL_FALSE; id=0; state=(ALState) 0; }
inline bool valid() { if ( alIsSource( id ) ) return true; return false; }
void bindBuffer( ALBuffer buffer );
void bindSound( ALSound *sound );
void bindStream( ALUREStream *stream );
void Detach() {
if ( state == empty ) { OUTPUT( "ALSource:Detach:Empty source attempted. (Cannot dump a buffer from an empty source)\n" ); return; }
else if ( state != stopped ) { Stop(); }
if ( valid() ) { alSourcei(id,AL_BUFFER,0); state=empty; alGetError(); }
}
inline void Stop() { if ( valid() && state == playing ) { alGetError(); alSourceStop(id); alGetError(); state=stopped; } }
inline void Pause() { if ( valid() && state == playing ) { alGetError(); alSourcePause(id); alGetError(); state=paused; } }
inline void Play() { if ( valid() && state != playing ) { ALError("ALSound:Pre-Play()"); alSourcePlay(id); ALError("ALSound:Play() had an error."); alGetError(); state=playing; } }
inline void Resume() { Play(); }
// void PauseAll() { if ( valid() && state == playing ) Pause(); if ( next ) next.PauseAll(); }
// void ResumeAll() { if ( valid() && state == paused ) Resume(); if ( next ) next.ResumeAll(); }
bool Close( ) {
if ( valid() ) {
if ( state != empty ) Detach();
alDeleteSources(1, &(id)); if ( ALError( "ALSource:Close:alDeleteSources") ) return false;
//unusedSources++;
return true;
}
return false;
}
// void rehead( ALSource a ) { ALSource b=this; for ( ; b; b=b.next ) b.head=a; }
~ALSource() { Close(); }
};
class ALSources : public LinkedList
{
// List functions for managing a multi-source list.
ALSource *AddNew()
{
ALSource *s = null;
ALuint id;
alGenSources(1,&id);
if(!ALError("ALSource:WAV:alGenSources")) { Append(s = new ALSource); s->id; }
return s;
}
~ALSources () {
ALSource *d,*n;
for ( d=(ALSource *) first; d; d=n ) {
n=(ALSource *) (d->next);
delete d;
}
}
};
/*
ALURE stream
*/
class ALUREStream : public ListItem {
public:
ALSoundManager *manager;
alureStream *stream;
char name[512];
int bufferSize;
int usesBuffers;
unsigned int samples;
float duration;
float refreshRate;
// ALuint *buf;
ALSource *source;
bool created;
int loops;
bool badError;
SoundVector position, velocity;
float pitch,gain;
float threadDelay;
bool terminated;
ALUREStream() {
manager=null;
stream=null;
name[0]='\0';
bufferSize=128*1024;
usesBuffers=3;//3;
threadDelay=0.01f;
samples=0;
duration=0;
refreshRate=1.0f/60.0f;
source=null;
created=false;
loops=0;
badError=false;
pitch=gain=1.0f;
threadDelay=1.0f/60.0f;
terminated=false;
}
~ALUREStream()
{
if ( Playing() ) Stop();
alureDestroyStream(stream, 0, null);// usesBuffers, buf);
delete source;
//unusedBuffers+=usesBuffers;
}
inline bool Playing() { return ( source && source->state == playing ); }
// uint Main() { Sleep(threadDelay); DelayExpired(); return 0; }
inline void Pause() { if (created && Playing() ) { alurePauseSource(source->id); } }
inline void Resume() { if (created && !Playing() ) { alureResumeSource(source->id); } }
inline void Stop() { if (created) { alureStopSource(source->id,AL_TRUE); } } //terminated = true; ((GuiApplication)__thisModule).Unlock(); Wait(); ((GuiApplication)__thisModule).Lock(); } }
inline void Rewind() { if (created) { Stop(); alureRewindStream(stream); } }
bool LoadIntoSource(char *fn, ALSource *s, bool CalcSize ) {
sprintf_s( name, "%s", fn );
if ( !source ) { OUTPUT("ALUREStream:Create complains the required source was not provided.\n" ); return false; }
//if ( usesBuffers > unusedBuffers ) { OUTPUT("ALUREStream:Create Not enough buffers available. Requested: %d Available: %d\n", usesBuffers, unusedBuffers ); return false; }
alGetError();
source=s;
// if ( buf ) { OUTPUT( "ALUREStream:Create warns, the buffers were already created, was .Create() mistakenly called twice?\n" ); delete buf; }
//buf=new ALuint[usesBuffers];
//unusedBuffers-=usesBuffers;
stream=alureCreateStreamFromFile((ALchar *) fn,bufferSize,0/*usesBuffers*/,null);//buf);
if ( !stream ) { OUTPUT( "ALUREStream:Create could not load the file: %s\n", fn, alureGetErrorString()); return false; }
if ( CalcSize ) CalculateSize(fn);
return (created=true);
}
virtual void OnComplete() { /*OUTPUT( "EOS!\n" );*/ }
static void eos_callback( void * a, ALuint b ) {
ALUREStream *s=(ALUREStream *) a;
s->OnComplete();
}
bool Play() {
if ( !this ) { OUTPUT( "ALUREStream:Play:Called on a null object.\n" ); return false; }
if ( !source ) { OUTPUT( "ALUREStream:Play:No source defined for the stream '%s'. Did it load properly?\n", name ); return false; }
if ( source->state == stopped ) {
OUTPUT ( "Play() was called on a stream.\n" );
alGetError();
// alSourceQueueBuffers(source.id,usesBuffers,buf);
// if ( ALError("ALUREStream:Play:alSourceQueueBuffers") ) { OUTPUT( "ALUREStream:Play failed to queue buffers.\n" ); return false; }
// alSourcePlay(source.id);
alurePlaySourceStream(source->id,stream,usesBuffers,loops/*# of loops*/,(eos_callback),this);
source->state=playing;
// if ( ALError("ALUREStream:Play:alSourcePlay") ) { OUTPUT( "ALUREStream:Play failed to start source.\n" ); return false; }
// this.timer.delay = (1.0f/refreshRate);
// this.timer.Start();
// Create();
} else if ( source->state == paused || source->state==stopped ) { source->Resume(); return true; }
else if ( source->state == empty ) { OUTPUT( "ALUREStream:Play called on an empty source (no buffer selected).\n" ); return false; }
else if ( source->state == playing ) { OUTPUT( "ALUREStream:Play() called on a playing stream.\n" ); return true; }
return true;
}
virtual void BetweenFrames() { }
virtual void OnError() { }
// Slightly inefficient, but precise.
int CalculateSize( char * fn ) {
ALuint total = 0;
ALuint b;
ALint freq = 0;
alureStream *s;
s = alureCreateStreamFromFile( (ALchar *) fn, 19200, 1, &b);
if(s) {
do {
ALint size, bits, channels;
alGetBufferi(b, AL_SIZE, &size);
alGetBufferi(b, AL_BITS, &bits);
alGetBufferi(b, AL_CHANNELS, &channels);
if(!freq) alGetBufferi(b, AL_FREQUENCY, &freq);
total += size / channels * 8 / bits;
} while(alureBufferDataFromStream(s, 1, &b) > 0);
alureDestroyStream(s,1,&b);
}
duration=(float)total/(float)freq;
samples=(unsigned int) total;
}
};
class ALUREStreams : public LinkedList {
public:
void DeleteAll() {
ALUREStream *s,*n;
for ( s=(ALUREStream *)first; s; s=n ) { n=(ALUREStream *) s->next; delete s; }
first=last=null; count=0;
}
~ALUREStreams() {
ALUREStream *d,*n;
for ( d=(ALUREStream *) first; d; d=n ) {
n=(ALUREStream *) (d->next);
delete d;
}
}
};
class ALCaptureStream {
ALSoundFormat format;
int sampleFactor;
public:
unsigned int frequency;
unsigned int bufferSize;
int samples;
ALCint available;
ALCdevice *captureDevice;
char deviceName[512];
bool capturing;
unsigned short *target;
int ofs;
ALCaptureStream() {
frequency=bufferSize=samples=0;
capturing=false;
target=null;
ofs=0;
format=stereo16;
sampleFactor=4;
deviceName[0]='\0';
}
void Format( ALSoundFormat value ) {
switch ( value ) {
case mono8: sampleFactor=1; break;
case mono16: case stereo8: sampleFactor=2; break;
case stereo16: sampleFactor=4; break;
}
}
void Start() { if ( captureDevice ) { alcCaptureStart(captureDevice); capturing=true; } }
unsigned short *Acquire() {
if ( capturing ) {
unsigned short *buffer;
alcGetIntegerv(captureDevice, ALC_CAPTURE_SAMPLES, 1, &available);
buffer = new unsigned short[available*sampleFactor];
memset(buffer,0,available);
alcCaptureSamples(captureDevice,buffer,(ALuint) available);
return buffer;
}
return null;
}
void AcquireTo( unsigned short **buf ) {
if ( capturing ) {
if ( *buf ) delete *buf;
alcGetIntegerv(captureDevice, ALC_CAPTURE_SAMPLES, 1, &available);
*buf = new unsigned short[available*sampleFactor];
target = *buf;
alcCaptureSamples(captureDevice,*buf,(ALuint) available);
} else {
delete *buf; *buf=null;
}
}
void AcquireAppend( unsigned short *pre ) {
if ( capturing ) {
unsigned short *post=&(pre[ofs]);
alcGetIntegerv(captureDevice, ALC_CAPTURE_SAMPLES, 1, &available);
ofs+=available;
alcCaptureSamples(captureDevice,post,(ALuint) available);
}
}
void Stop() {
if ( captureDevice ) { alcCaptureStop(captureDevice); capturing=false; OnCaptureComplete(); }
}
virtual void OnCaptureComplete() { }
bool Init( char *name ) {
sprintf_s( deviceName, "%s", name );
captureDevice = alcCaptureOpenDevice( (ALCchar *) name, frequency, format, (ALCsizei) bufferSize );
if ( !captureDevice ) {
OUTPUT( "ALCaptureStream:Init:alcCaptureOpenDevice -> unable to open a device\n" );
return false;
}
return true;
}
~ALCaptureStream() {
// needs destructor! this code is untested
}
};
#ifndef M_PI
#define M_PI 3.14159265358979323846264338
#endif
enum SoundFileFormats { /* Major formats. */
wav=SF_FORMAT_WAV , /* Microsoft WAV format (little endian default). */
aiff=SF_FORMAT_AIFF , /* Apple/SGI AIFF format (big endian). */
au=SF_FORMAT_AU , /* Sun/NeXT AU format (big endian). */
raw=SF_FORMAT_RAW , /* RAW PCM data. */
paf=SF_FORMAT_PAF , /* Ensoniq PARIS file format. */
svx=SF_FORMAT_SVX , /* Amiga IFF / SVX8 / SV16 format. */
nist=SF_FORMAT_NIST , /* Sphere NIST format. */
voc=SF_FORMAT_VOC , /* VOC files. */
ircam=SF_FORMAT_IRCAM , /* Berkeley/IRCAM/CARL */
wav64riff=SF_FORMAT_W64 , /* Sonic Foundry's 64 bit RIFF/WAV */
matlab42=SF_FORMAT_MAT4 , /* Matlab (tm) V4.2 / GNU Octave 2.0 */
matlab50=SF_FORMAT_MAT5 , /* Matlab (tm) V5.0 / GNU Octave 2.1 */
pvf=SF_FORMAT_PVF , /* Portable Voice Format */
xi=SF_FORMAT_XI , /* Fasttracker 2 Extended Instrument */
htk=SF_FORMAT_HTK , /* HMM Tool Kit format */
midisds=SF_FORMAT_SDS , /* Midi Sample Dump Standard */
avr=SF_FORMAT_AVR , /* Audio Visual Research */
waveformatex=SF_FORMAT_WAVEX, /* MS WAVE with WAVEFORMATEX */
sd2=SF_FORMAT_SD2 , /* Sound Designer 2 */
flac=SF_FORMAT_FLAC , /* FLAC lossless file format */
caf=SF_FORMAT_CAF , /* Core Audio File format */
wve=SF_FORMAT_WVE , /* Psion WVE format */
ogg=SF_FORMAT_OGG , /* Xiph OGG container */
mpc2d=SF_FORMAT_MPC2K , /* Akai MPC 2000 sampler */
rf64wav=SF_FORMAT_RF64 , /* RF64 WAV file */
};
/* OR'd Subtypes from here on. */
enum SoundFileFormatOptions {
pcms8=SF_FORMAT_PCM_S8 , /* Signed 8 bit data */
pcm16=SF_FORMAT_PCM_16 , /* Signed 16 bit data */
pcm24=SF_FORMAT_PCM_24 , /* Signed 24 bit data */
pcm32=SF_FORMAT_PCM_32 , /* Signed 32 bit data */
pcmu8=SF_FORMAT_PCM_U8 , /* Unsigned 8 bit data (WAV and RAW only) */
float32=SF_FORMAT_FLOAT , /* 32 bit float data */
float64=SF_FORMAT_DOUBLE, /* 64 bit float data */
ulaw=SF_FORMAT_ULAW , /* U-Law encoded. */
alaw=SF_FORMAT_ALAW , /* A-Law encoded. */
ima_adpcm=SF_FORMAT_IMA_ADPCM,/* IMA ADPCM. */
ms_adpcm=SF_FORMAT_MS_ADPCM, /* Microsoft ADPCM. */
gsm610=SF_FORMAT_GSM610 , /* GSM 6.10 encoding. */
vox_adpcm=SF_FORMAT_VOX_ADPCM,/* OKI / Dialogix ADPCM */
g721_adpcm_32kbs=SF_FORMAT_G721_32, /* 32kbs G721 ADPCM encoding. */
g723_adpcm_24kbs=SF_FORMAT_G723_24, /* 24kbs G723 ADPCM encoding. */
g723_adpcm_40kbs=SF_FORMAT_G723_40, /* 40kbs G723 ADPCM encoding. */
dwvw_12=SF_FORMAT_DWVW_12, /* 12 bit Delta Width Variable Word encoding. */
dwvw_16=SF_FORMAT_DWVW_16, /* 16 bit Delta Width Variable Word encoding. */
dwvw_24=SF_FORMAT_DWVW_24, /* 24 bit Delta Width Variable Word encoding. */
dwvw_n =SF_FORMAT_DWVW_N , /* N bit Delta Width Variable Word encoding. */
dpcm_8=SF_FORMAT_DPCM_8 , /* 8 bit differential PCM (XI only) */
dpcm_16=SF_FORMAT_DPCM_16, /* 16 bit differential PCM (XI only) */
vorbis=SF_FORMAT_VORBIS , /* Xiph Vorbis encoding. */
/* Endian-ness options. */
endian_default=SF_ENDIAN_FILE, /* Default file endian-ness. */
endian_little=SF_ENDIAN_LITTLE, /* Force little endian-ness. */
endian_big=SF_ENDIAN_BIG, /* Force big endian-ness. */
endian_cpu=SF_ENDIAN_CPU, /* Force CPU endian-ness. */
sub=SF_FORMAT_SUBMASK ,
type=SF_FORMAT_TYPEMASK ,
endmask=SF_FORMAT_ENDMASK
};
enum ChannelTypes {
mono=1,
stereo=2
};
class ALWaveForm : public ListItem {
public:
SF_FORMAT_INFO info;
SF_INFO sfinfo;
SNDFILE *file;
char filename[512];
int formatOptions;
int sampleRate;
int sampleCount;
int bytesize;
ChannelTypes channels;
std::vector<short> data;
float duration, amplitude, leftFrequency, rightFrequency;
ALBuffer buffer;
ALWaveForm() {
sampleRate = 44100;
memset(&info,0,sizeof(info));
formatOptions=0;
sampleCount = sampleRate; // 1 second
amplitude = (1.0f * 0x7F000000);
channels=stereo;
leftFrequency = 344.0f / (float) sampleRate;
rightFrequency= 466.0f / (float) sampleRate;
memset (&sfinfo, 0, sizeof (sfinfo)) ;
sfinfo.samplerate = sampleRate ;
sfinfo.frames = sampleCount ;
sfinfo.channels = (int) channels ;
sfinfo.format = (SF_FORMAT_WAV | SF_FORMAT_PCM_24) ;
filename[0]='\0';
bytesize=0;
duration=0.0f;
file=null;
}
~ALWaveForm() { }
void SetDuration( float value ) { sampleCount = (int) (sampleRate * value); duration=value; sfinfo.frames=(int) sampleCount; }
void SetSampleRate( int value ) { sampleRate=value; sfinfo.samplerate=value; sampleCount = (int) (value * duration); sfinfo.frames=(int) sampleCount; }
void SetChannels( ChannelTypes value ) { channels=value; sfinfo.channels=(int) value; }
virtual bool Process( ALWaveForm w ) { return false; }
virtual int EquationMono( int k ) { return (int) (amplitude * (float) sin(leftFrequency * 2 * k * M_PI)); }
virtual int EquationStereo( int k, bool left ) { return (int) (amplitude * (float) sin( (left ? leftFrequency : rightFrequency) * 2 * k * M_PI)); }
void Render() {
int k;
data.clear();
data.resize(sampleCount*(int) channels);
sfinfo.samplerate = sampleRate ;
sfinfo.frames = sampleCount ;
sfinfo.channels = (int) channels ;
if ( channels == mono ) for ( k=0; k<sampleCount; k++ ) data[k] = (short) EquationMono(k);
else for ( k=0; k<sampleCount; k++ ) { data[2*k] = (short) EquationStereo(k,true); data[2*k+1] = (short) EquationStereo(k,false); }
}
bool Load( char *path, char * fn ) {
char buf[1024];
sprintf_s( buf, "%s/%s", path ? path : "", fn );
sf_count_t got, total, running = 0;
OUTPUT( "Loading audio file: %s\n", fn );
if ( file ) OUTPUT( "ALWaveForm: file pointer was already in use when Load(\"%s\") was called, this may cause file handles to be left open without a reference. Do not do this.\n", fn );
sprintf_s( filename, "%s", fn );
memset (&sfinfo, 0, sizeof (sfinfo)) ;
if ((file = sf_open (fn, SFM_READ, &sfinfo)) == NULL) {
OUTPUT ("\nALWaveForm: failed to open sound file '%s': %s\n\n", fn, sf_strerror (NULL)) ;
return false;
}
total=sfinfo.samplerate * 2 * sfinfo.channels;
data.resize((unsigned int) total);
while ((got=sf_readf_short(file, &data[(unsigned int) running], (total-running)/sfinfo.channels)) > 0 ) {
total *= 2;
data.resize((unsigned int) total);
got *= sfinfo.channels;
running += got;
}
data.resize((unsigned int) total);
bytesize=(int) (running * sizeof(short));
file=null;
ALError("ALWaveForm:Load() general error check failed.");
alGenBuffers(1,&(buffer.id));
if(ALError("ALBuffer:alGenBuffers")) { buffer.id=0; return false; }
//unusedBuffers--;
alBufferData( buffer.id, ((channels==mono)?AL_FORMAT_MONO16:AL_FORMAT_STEREO16), &data[0], bytesize, sfinfo.samplerate );
ALError( "ALWaveForm:Load:alBufferData" );
return true;
}
void setFormat( SoundFileFormats f ) { formatOptions = (int) f; sfinfo.format = formatOptions ; }
void addFormatOption ( SoundFileFormatOptions o ) { formatOptions |= (int) o; sfinfo.format = formatOptions ; }
void printInfo() {
char buffer [128] ;
int format, major_count, subtype_count, m, s;
memset (&sfinfo, 0, sizeof (sfinfo));
buffer [0] = 0;
sf_command (NULL, SFC_GET_LIB_VERSION, &data[0], data.size());
if (strlen (buffer) < 1) { OUTPUT ("Line %d: could not retrieve lib version.\n", __LINE__); exit (1); }
OUTPUT ("libSndFile version %s\n\n", buffer);
sf_command (NULL, SFC_GET_FORMAT_MAJOR_COUNT, &major_count, sizeof (int));
sf_command (NULL, SFC_GET_FORMAT_SUBTYPE_COUNT, &subtype_count, sizeof (int));
sfinfo.channels = 1;
for (m = 0 ; m < major_count ; m++) {
info.format = m;
sf_command (NULL, SFC_GET_FORMAT_MAJOR, &info, sizeof (info));
OUTPUT ("%s (extension \"%s\")\n", info.name, info.extension);
format = info.format;
for (s = 0 ; s < subtype_count ; s++) {
info.format = s;
sf_command (NULL, SFC_GET_FORMAT_SUBTYPE, &info, sizeof (info));
format = (format & SF_FORMAT_TYPEMASK) | info.format;
sfinfo.format = format;
if (sf_format_check (&sfinfo)) OUTPUT (" %s\n", info.name);
}
puts ("");
}
puts ("");
}
bool OpenFile( char * fn ) { memset (&sfinfo, 0, sizeof (sfinfo)); return (file = sf_open (fn, SFM_READ, &sfinfo)) != null; }
bool Save( char * fn ) {
if ( file ) OUTPUT( "ALWaveForm: file pointer was already in use when Save(\"%s\") was called, this may cause file handles to be left open without a reference. Do not do this.\n", fn );
if (! (file = sf_open (fn, SFM_WRITE, &sfinfo))) {
OUTPUT ("ALWaveForm: Write Error - Not able to open output file.\n") ;
return false;
}
if (sf_writef_short (file, &data[0], sampleCount) != sampleCount) puts(sf_strerror (file)) ;
sf_close (file);
file=null;
}
void Close() { sf_close(file); file=null; }
};
class ALWaveForms : public LinkedList {
public:
ALWaveForm *find( char *fn ) {
ALWaveForm *s;
for ( s=(ALWaveForm *) first; s; s=(ALWaveForm *) (s->next) )
if ( contains(fn,s->filename) ) return s;
return null;
}
ALWaveForm *findOrLoad( char *path, char *fn ) {
ALWaveForm *w=find(fn);
if ( !w ) { w=new ALWaveForm; w->Load(path,fn); Append(w); }
return w;
}
void DeleteAll() {
ALWaveForm *s,*n;
for ( s=(ALWaveForm *)first; s; s=n ) { n=(ALWaveForm *) s->next; delete s; }
first=last=null; count=0;
}
~ALWaveForms() { }
};
class ALSound : public ListItem {
public:
ALWaveForm *waveform;
char name[512];
ALuint id;
float duration;
bool deleteMe;
ALenum format;
ALvoid *data;
ALsizei size,freq;
ALboolean loop, relative;
ALSource *source; // sources are points of emitting sound.
SoundVector position, velocity, direction;
float pitch,gain,min_gain,max_gain,distance,rolloff;
bool boundToSource;
bool lastFramePlayState;
bool Restart;
ALSound() {
waveform=null;
name[0]='\0';
id=0;
duration=0.0f;
deleteMe=false;
format=0;
data=null;
size=freq=0;
loop=relative=false;
source=null;
}
void Release() { alSourceStop( id ); }
int NextAvailableID( int max ) {
ALSound *s;
int i;
bool *notavailable= new bool[max];
for ( s=this; s; s=(ALSound *) s->next ) notavailable[s->id-1]=true;
for ( i=0; i<max; i++ ) if ( notavailable[i] == false ) { delete notavailable; return i+1; }
delete notavailable;
return -1;
}
bool Play( )
{
int sourceAudioState = 0;
WhenPlayed();
if ( !source ) { OUTPUT( "Audio %s had no source.\n", waveform->filename ); return false; }
alGetError();
alGetSourcei( source->id, AL_SOURCE_STATE, &sourceAudioState );
if ( sourceAudioState == AL_PLAYING ) {
if ( Restart ) Stop(); else return false;
}
alSourcePlay( source->id );
if ( ALError( "ALSound:Play:alSourcePlay") ) return false;
lastFramePlayState=true;
source->state=playing;
alGetError();
return true;
}
bool Pause( ) {
WhenPaused();
alGetError();
alSourcePause( source->id );
if ( ALError( "ALSound:Pause:alSourcePause") ) return false;
lastFramePlayState=false;
source->state=paused;
alGetError();
return true;
}
bool Playing() {
int sourceAudioState = 0;
if ( !source ) return false;
alGetSourcei( source->id, AL_SOURCE_STATE, &sourceAudioState );
if ( sourceAudioState == AL_PLAYING ) source->state=playing;
if ( sourceAudioState == AL_PAUSED ) source->state=paused;
return ( source->state == playing );
}
// If the sound was paused the sound will resume, else it will play from the beginning.
bool Resume( )
{
int sourceAudioState = 0;
WhenResumed();
alGetError();
alGetSourcei( source->id, AL_SOURCE_STATE, &sourceAudioState );
if ( sourceAudioState == AL_PLAYING ) return true;
if ( sourceAudioState == AL_PAUSED ) { alSourcePlay( source->id ); if ( ALError( "Resume:alSourcePlay") ) return false; }
if ( ALError( "ALSound:Resume:alSourcePlay") ) return false;
lastFramePlayState=true;
source->state=playing;
alGetError();
return true;
}
// Make sure the audio source ident is valid and usable
bool Stop( )
{
alGetError();
alSourceStop( source->id );
if ( ALError( "ALSound:Stop:alSourceStop") ) return false;
lastFramePlayState=false;
source->state=stopped;
alGetError();
return true;
}
bool Position( )
{
alGetError();
alSourcefv(source->id, AL_POSITION, position.asFloat3() ); if ( ALError( "ALSound:position:alSourcefv:AL_POSITION" ) ) return false;
return true;
}
bool SetPVD( )
{
if ( !Playing() ) return true;
alGetError();
alSourcefv(source->id, AL_POSITION, position.asFloat3() ); if ( ALError( "ALSound:SetPVD:alSourcefv:AL_POSITION" ) ) return false;
alSourcefv(source->id, AL_VELOCITY, velocity.asFloat3() ); if ( ALError( "ALSound:SetPVD:alSourcefv:AL_VELOCITY" ) ) return false;
alSourcefv(source->id, AL_DIRECTION, direction.asFloat3() ); if ( ALError( "ALSound:SetPVD:alSourcefv:AL_DIRECTION" ) ) return false;
alGetError();
return true;
}
bool SetSound( float maxDistance, float minGain, float maxGain, float rollOff )
{
alGetError();
alSourcef(source->id, AL_MAX_DISTANCE, distance=maxDistance ); if ( ALError( "ALSound:SetSound:alSourcef:AL_MAX_DISTANCE" ) ) return false;
alSourcef(source->id, AL_MIN_GAIN, min_gain=minGain ); if ( ALError( "ALSound:SetSound:alSourcef:AL_MIN_GAIN" ) ) return false;
alSourcef(source->id, AL_MAX_GAIN, max_gain=maxGain ); if ( ALError( "ALSound:SetSound:alSourcef:AL_MAX_GAIN" ) ) return false;
alSourcef(source->id, AL_ROLLOFF_FACTOR, rolloff =rollOff ); if ( ALError( "ALSound:SetSound:alSourcef:AL_ROLLOFF_FACTOR" ) ) return false;
return true;
}
ALSource *UpdateSource()
{
alGetError();
// alSourcei (source.id, AL_BUFFER, buffer.id );
alSourcef (source->id, AL_PITCH, pitch );
alSourcef (source->id, AL_GAIN, gain );
alSourcef (source->id, AL_MAX_DISTANCE, distance ); if ( ALError( "ALSound:AddSource:AL_MAX_DISTANCE" ) ) { delete source; return null; }
alSourcef (source->id, AL_MIN_GAIN, min_gain ); if ( ALError( "ALSound:AddSource:AL_MIN_GAIN" ) ) { delete source; return null; }
alSourcef (source->id, AL_MAX_GAIN, max_gain ); if ( ALError( "ALSound:AddSource:AL_MAX_GAIN" ) ) { delete source; return null; }
alSourcef (source->id, AL_ROLLOFF_FACTOR, rolloff ); if ( ALError( "ALSound:AddSource:AL_ROLLOFF_FACTOR" ) ) { delete source; return null; }
alSourcefv(source->id, AL_POSITION, position.asFloat3() ); if ( ALError( "ALSound:AddSource:AL_POSITION" ) ) { delete source; return null; }
alSourcefv(source->id, AL_VELOCITY, velocity.asFloat3() ); if ( ALError( "ALSound:AddSource:AL_VELOCITY" ) ) { delete source; return null; }
alSourcefv(source->id, AL_DIRECTION, direction.asFloat3() ); if ( ALError( "ALSound:AddSource:AL_DIRECTION" ) ) { delete source; return null; }
alSourcei (source->id, AL_LOOPING, (ALboolean) loop );
alSourcePlay(source->id);
return source;
}
void AssignSource( ALSource *s ) {
alGetError();
if ( source ) { OUTPUT( "ALSound:AssignSource:Error! Attempted to assign a source when there already was one.\n" ); return; }
source=s;
alSourcei (source->id, AL_BUFFER, waveform->buffer.id );
UpdateSource();
}
ALSource *AddSource()
{
if ( !source ) {
ALSource *s=new ALSource;
alGetError();
alGenSources(1, &(s->id));
if (alGetError() != AL_NO_ERROR) { OUTPUT("ALSound:AddSource(): Error generating audio source."); delete s; return null; }
alSourcei (s->id, AL_BUFFER, waveform->buffer.id );
alSourcef (s->id, AL_PITCH, pitch );
alSourcef (s->id, AL_GAIN, gain );
alSourcef (s->id, AL_MAX_DISTANCE, distance ); if ( ALError( "ALSound:AddSource:AL_MAX_DISTANCE" ) ) { delete s; return null; }
alSourcef (s->id, AL_MIN_GAIN, min_gain ); if ( ALError( "ALSound:AddSource:AL_MIN_GAIN" ) ) { delete s; return null; }
alSourcef (s->id, AL_MAX_GAIN, max_gain ); if ( ALError( "ALSound:AddSource:AL_MAX_GAIN" ) ) { delete s; return null; }
alSourcef (s->id, AL_ROLLOFF_FACTOR, rolloff ); if ( ALError( "ALSound:AddSource:AL_ROLLOFF_FACTOR" ) ) { delete s; return null; }
alSourcefv(s->id, AL_POSITION, position.asFloat3() ); if ( ALError( "ALSound:AddSource:AL_POSITION" ) ) { delete s; return null; }
alSourcefv(s->id, AL_VELOCITY, velocity.asFloat3() ); if ( ALError( "ALSound:AddSource:AL_VELOCITY" ) ) { delete s; return null; }
alSourcefv(s->id, AL_DIRECTION, direction.asFloat3() ); if ( ALError( "ALSound:AddSource:AL_DIRECTION" ) ) { delete s; return null; }
alSourcei (s->id, AL_LOOPING, (ALboolean) loop );
alSourcePlay(s->id);
this->source=s;
return s;
}
OUTPUT( "ALSound:AddSource() - source Already Created; File: %s\n", waveform->filename );
return this->source;
}
void PrintInfo( ) {
}
bool *ThrowASwitch;
virtual void WhenPlayed ( ){ }
virtual void WhenPaused ( ){ }
virtual void WhenResumed ( ){ }
virtual void WhenComplete ( ){ if ( ThrowASwitch ) *ThrowASwitch=true; }
virtual void BetweenFrames( ){ }
void _BetweenFrames() {
int state;
alGetSourcei(source->id, AL_SOURCE_STATE, &state);
if ( AL_PLAYING == state ) BetweenFrames();
if ( !(AL_PLAYING == state) && lastFramePlayState ) {
WhenComplete();
this->Release();
this->deleteMe=true; //OUTPUT( "%s sound cleared for deletion.\n", name );
}
lastFramePlayState=(AL_PLAYING == state);
}
~ALSound() {
// OUTPUT( "Deleting sound %s\n", name );
if ( Playing() ) Stop();
if ( waveform ) delete waveform;
if ( source ) delete source;
}
};
class ALSounds : public LinkedList
{
public:
bool inList( char *fn ) {
ALSound *s;
for ( s=(ALSound *)first; s; s=(ALSound *)(s->next) ) if ( contains(fn,s->name) ) return true;
return false;
}
ALSound *findInList( char *fn ) {
ALSound *s;
for ( s=(ALSound *)first; s; s=(ALSound *)(s->next) ) if ( contains(fn,s->name) ) return s;
return null;
}
void DeleteDone() {
ALSound *s,*n;
for ( s=(ALSound *)first; s; s=n ) { n=(ALSound *) s->next; Remove(s); if ( s->deleteMe ) delete s; }
}
void DeleteAll() {
ALSound *s,*n;
for ( s=(ALSound *)first; s; s=n ) { n=(ALSound *) s->next; delete s; }
first=last=null; count=0;
}
~ALSounds() {
ALSound *d,*n;
for ( d=(ALSound *) first; d; d=n ) {
n=(ALSound *) (d->next);
delete d;
}
}
};
class ALCDeviceContext : public ListItem {
public:
ALCcontext* context;
ALCdevice* device;
char *deviceName;
bool closed;
ALCDeviceContext() { context=null; device=null; deviceName=null; closed=false; }
void PickDefault() {
device=alcOpenDevice(null);