annotate org/ear.org @ 25:f4c7260d397a

removed uint problem for Windows compilation
author Robert McIntyre <rlm@mit.edu>
date Fri, 18 Nov 2011 20:06:50 -0700
parents 616215c81d23
children cdf320cb5949
rev   line source
rlm@15 1 #+title: Simulated Sense of Hearing
rlm@0 2 #+author: Robert McIntyre
rlm@0 3 #+email: rlm@mit.edu
rlm@15 4 #+description: Simulating multiple listeners and the sense of hearing in jMonkeyEngine3
rlm@15 5 #+keywords: simulated hearing, openal, clojure, jMonkeyEngine3, LWJGL, AI
rlm@15 6 #+SETUPFILE: ../../aurellem/org/setup.org
rlm@15 7 #+INCLUDE: ../../aurellem/org/level-0.org
rlm@0 8 #+BABEL: :exports both :noweb yes :cache no :mkdirp yes
rlm@0 9
rlm@15 10 * Hearing
rlm@0 11
rlm@20 12 I want to be able to place ears in a similar manner to how I place
rlm@0 13 the eyes. I want to be able to place ears in a unique spatial
rlm@20 14 position, and receive as output at every tick the F.F.T. of whatever
rlm@0 15 signals are happening at that point.
rlm@0 16
rlm@15 17 Hearing is one of the more difficult senses to simulate, because there
rlm@15 18 is less support for obtaining the actual sound data that is processed
rlm@15 19 by jMonkeyEngine3.
rlm@15 20
rlm@15 21 jMonkeyEngine's sound system works as follows:
rlm@15 22
rlm@20 23 - jMonkeyEngine uses the =AppSettings= for the particular application
rlm@15 24 to determine what sort of =AudioRenderer= should be used.
rlm@15 25 - although some support is provided for multiple AudioRendering
rlm@15 26 backends, jMonkeyEngine at the time of this writing will either
rlm@20 27 pick no AudioRenderer at all, or the =LwjglAudioRenderer=
rlm@15 28 - jMonkeyEngine tries to figure out what sort of system you're
rlm@20 29 running and extracts the appropriate native libraries.
rlm@18 30 - the =LwjglAudioRenderer= uses the [[http://lwjgl.org/][=LWJGL=]] (LightWeight Java Game
rlm@18 31 Library) bindings to interface with a C library called [[http://kcat.strangesoft.net/openal.html][=OpenAL=]]
rlm@15 32 - =OpenAL= calculates the 3D sound localization and feeds a stream of
rlm@15 33 sound to any of various sound output devices with which it knows
rlm@15 34 how to communicate.
rlm@15 35
rlm@15 36 A consequence of this is that there's no way to access the actual
rlm@20 37 sound data produced by =OpenAL=. Even worse, =OpenAL= only supports
rlm@15 38 one /listener/, which normally isn't a problem for games, but becomes
rlm@15 39 a problem when trying to make multiple AI creatures that can each hear
rlm@15 40 the world from a different perspective.
rlm@15 41
rlm@15 42 To make many AI creatures in jMonkeyEngine that can each hear the
rlm@15 43 world from their own perspective, it is necessary to go all the way
rlm@15 44 back to =OpenAL= and implement support for simulated hearing there.
rlm@15 45
rlm@19 46 * Extending =OpenAL=
rlm@15 47 ** =OpenAL= Devices
rlm@15 48
rlm@15 49 =OpenAL= goes to great lengths to support many different systems, all
rlm@20 50 with different sound capabilities and interfaces. It accomplishes this
rlm@15 51 difficult task by providing code for many different sound backends in
rlm@15 52 pseudo-objects called /Devices/. There's a device for the Linux Open
rlm@20 53 Sound System and the Advanced Linux Sound Architecture, there's one
rlm@15 54 for Direct Sound on Windows, there's even one for Solaris. =OpenAL=
rlm@15 55 solves the problem of platform independence by providing all these
rlm@15 56 Devices.
rlm@15 57
rlm@15 58 Wrapper libraries such as LWJGL are free to examine the system on
rlm@20 59 which they are running and then select an appropriate device for that
rlm@15 60 system.
rlm@15 61
rlm@15 62 There are also a few "special" devices that don't interface with any
rlm@15 63 particular system. These include the Null Device, which doesn't do
rlm@20 64 anything, and the Wave Device, which writes whatever sound it receives
rlm@15 65 to a file, if everything has been set up correctly when configuring
rlm@15 66 =OpenAL=.
rlm@15 67
rlm@15 68 Actual mixing of the sound data happens in the Devices, and they are
rlm@15 69 the only point in the sound rendering process where this data is
rlm@15 70 available.
rlm@15 71
rlm@15 72 Therefore, in order to support multiple listeners, and get the sound
rlm@15 73 data in a form that the AIs can use, it is necessary to create a new
rlm@15 74 Device, which supports this features.
rlm@15 75
rlm@15 76 ** The Send Device
rlm@15 77 Adding a device to OpenAL is rather tricky -- there are five separate
rlm@15 78 files in the =OpenAL= source tree that must be modified to do so. I've
rlm@15 79 documented this process [[./add-new-device.org][here]] for anyone who is interested.
rlm@15 80
rlm@18 81
rlm@18 82 Onward to that actual Device!
rlm@18 83
rlm@18 84 again, my objectives are:
rlm@18 85
rlm@18 86 - Support Multiple Listeners from jMonkeyEngine3
rlm@18 87 - Get access to the rendered sound data for further processing from
rlm@18 88 clojure.
rlm@18 89
rlm@18 90 ** =send.c=
rlm@18 91
rlm@18 92 ** Header
rlm@18 93 #+srcname: send-header
rlm@15 94 #+begin_src C
rlm@15 95 #include "config.h"
rlm@15 96 #include <stdlib.h>
rlm@15 97 #include "alMain.h"
rlm@15 98 #include "AL/al.h"
rlm@15 99 #include "AL/alc.h"
rlm@15 100 #include "alSource.h"
rlm@15 101 #include <jni.h>
rlm@15 102
rlm@15 103 //////////////////// Summary
rlm@15 104
rlm@15 105 struct send_data;
rlm@15 106 struct context_data;
rlm@15 107
rlm@15 108 static void addContext(ALCdevice *, ALCcontext *);
rlm@15 109 static void syncContexts(ALCcontext *master, ALCcontext *slave);
rlm@15 110 static void syncSources(ALsource *master, ALsource *slave,
rlm@15 111 ALCcontext *masterCtx, ALCcontext *slaveCtx);
rlm@15 112
rlm@15 113 static void syncSourcei(ALuint master, ALuint slave,
rlm@15 114 ALCcontext *masterCtx, ALCcontext *ctx2, ALenum param);
rlm@15 115 static void syncSourcef(ALuint master, ALuint slave,
rlm@15 116 ALCcontext *masterCtx, ALCcontext *ctx2, ALenum param);
rlm@15 117 static void syncSource3f(ALuint master, ALuint slave,
rlm@15 118 ALCcontext *masterCtx, ALCcontext *ctx2, ALenum param);
rlm@15 119
rlm@15 120 static void swapInContext(ALCdevice *, struct context_data *);
rlm@15 121 static void saveContext(ALCdevice *, struct context_data *);
rlm@15 122 static void limitContext(ALCdevice *, ALCcontext *);
rlm@15 123 static void unLimitContext(ALCdevice *);
rlm@15 124
rlm@15 125 static void init(ALCdevice *);
rlm@15 126 static void renderData(ALCdevice *, int samples);
rlm@15 127
rlm@15 128 #define UNUSED(x) (void)(x)
rlm@18 129 #+end_src
rlm@15 130
rlm@20 131 The main idea behind the Send device is to take advantage of the fact
rlm@18 132 that LWJGL only manages one /context/ when using OpenAL. A /context/
rlm@18 133 is like a container that holds samples and keeps track of where the
rlm@18 134 listener is. In order to support multiple listeners, the Send device
rlm@18 135 identifies the LWJGL context as the master context, and creates any
rlm@18 136 number of slave contexts to represent additional listeners. Every
rlm@18 137 time the device renders sound, it synchronizes every source from the
rlm@18 138 master LWJGL context to the slave contexts. Then, it renders each
rlm@18 139 context separately, using a different listener for each one. The
rlm@18 140 rendered sound is made available via JNI to jMonkeyEngine.
rlm@18 141
rlm@18 142 To recap, the process is:
rlm@18 143 - Set the LWJGL context as "master" in the =init()= method.
rlm@18 144 - Create any number of additional contexts via =addContext()=
rlm@18 145 - At every call to =renderData()= sync the master context with the
rlm@20 146 slave contexts with =syncContexts()=
rlm@18 147 - =syncContexts()= calls =syncSources()= to sync all the sources
rlm@18 148 which are in the master context.
rlm@18 149 - =limitContext()= and =unLimitContext()= make it possible to render
rlm@18 150 only one context at a time.
rlm@18 151
rlm@18 152 ** Necessary State
rlm@21 153 #+srcname: send-state
rlm@18 154 #+begin_src C
rlm@15 155 //////////////////// State
rlm@15 156
rlm@15 157 typedef struct context_data {
rlm@15 158 ALfloat ClickRemoval[MAXCHANNELS];
rlm@15 159 ALfloat PendingClicks[MAXCHANNELS];
rlm@15 160 ALvoid *renderBuffer;
rlm@15 161 ALCcontext *ctx;
rlm@15 162 } context_data;
rlm@15 163
rlm@15 164 typedef struct send_data {
rlm@15 165 ALuint size;
rlm@15 166 context_data **contexts;
rlm@15 167 ALuint numContexts;
rlm@15 168 ALuint maxContexts;
rlm@15 169 } send_data;
rlm@18 170 #+end_src
rlm@15 171
rlm@18 172 Switching between contexts is not the normal operation of a Device,
rlm@18 173 and one of the problems with doing so is that a Device normally keeps
rlm@18 174 around a few pieces of state such as the =ClickRemoval= array above
rlm@18 175 which will become corrupted if the contexts are not done in
rlm@18 176 parallel. The solution is to create a copy of this normally global
rlm@18 177 device state for each context, and copy it back and forth into and out
rlm@18 178 of the actual device state whenever a context is rendered.
rlm@15 179
rlm@18 180 ** Synchronization Macros
rlm@21 181 #+srcname: sync-macros
rlm@18 182 #+begin_src C
rlm@15 183 //////////////////// Context Creation / Synchronization
rlm@15 184
rlm@15 185 #define _MAKE_SYNC(NAME, INIT_EXPR, GET_EXPR, SET_EXPR) \
rlm@15 186 void NAME (ALuint sourceID1, ALuint sourceID2, \
rlm@15 187 ALCcontext *ctx1, ALCcontext *ctx2, \
rlm@15 188 ALenum param){ \
rlm@15 189 INIT_EXPR; \
rlm@15 190 ALCcontext *current = alcGetCurrentContext(); \
rlm@15 191 alcMakeContextCurrent(ctx1); \
rlm@15 192 GET_EXPR; \
rlm@15 193 alcMakeContextCurrent(ctx2); \
rlm@15 194 SET_EXPR; \
rlm@15 195 alcMakeContextCurrent(current); \
rlm@15 196 }
rlm@15 197
rlm@15 198 #define MAKE_SYNC(NAME, TYPE, GET, SET) \
rlm@15 199 _MAKE_SYNC(NAME, \
rlm@15 200 TYPE value, \
rlm@15 201 GET(sourceID1, param, &value), \
rlm@15 202 SET(sourceID2, param, value))
rlm@15 203
rlm@15 204 #define MAKE_SYNC3(NAME, TYPE, GET, SET) \
rlm@15 205 _MAKE_SYNC(NAME, \
rlm@15 206 TYPE value1; TYPE value2; TYPE value3;, \
rlm@15 207 GET(sourceID1, param, &value1, &value2, &value3), \
rlm@15 208 SET(sourceID2, param, value1, value2, value3))
rlm@15 209
rlm@15 210 MAKE_SYNC( syncSourcei, ALint, alGetSourcei, alSourcei);
rlm@15 211 MAKE_SYNC( syncSourcef, ALfloat, alGetSourcef, alSourcef);
rlm@15 212 MAKE_SYNC3(syncSource3i, ALint, alGetSource3i, alSource3i);
rlm@15 213 MAKE_SYNC3(syncSource3f, ALfloat, alGetSource3f, alSource3f);
rlm@15 214
rlm@18 215 #+end_src
rlm@18 216
rlm@20 217 Setting the state of an =OpenAL= source is done with the =alSourcei=,
rlm@18 218 =alSourcef=, =alSource3i=, and =alSource3f= functions. In order to
rlm@20 219 completely synchronize two sources, it is necessary to use all of
rlm@18 220 them. These macros help to condense the otherwise repetitive
rlm@20 221 synchronization code involving these similar low-level =OpenAL= functions.
rlm@18 222
rlm@18 223 ** Source Synchronization
rlm@21 224 #+srcname: sync-sources
rlm@18 225 #+begin_src C
rlm@15 226 void syncSources(ALsource *masterSource, ALsource *slaveSource,
rlm@15 227 ALCcontext *masterCtx, ALCcontext *slaveCtx){
rlm@15 228 ALuint master = masterSource->source;
rlm@15 229 ALuint slave = slaveSource->source;
rlm@15 230 ALCcontext *current = alcGetCurrentContext();
rlm@15 231
rlm@15 232 syncSourcef(master,slave,masterCtx,slaveCtx,AL_PITCH);
rlm@15 233 syncSourcef(master,slave,masterCtx,slaveCtx,AL_GAIN);
rlm@15 234 syncSourcef(master,slave,masterCtx,slaveCtx,AL_MAX_DISTANCE);
rlm@15 235 syncSourcef(master,slave,masterCtx,slaveCtx,AL_ROLLOFF_FACTOR);
rlm@15 236 syncSourcef(master,slave,masterCtx,slaveCtx,AL_REFERENCE_DISTANCE);
rlm@15 237 syncSourcef(master,slave,masterCtx,slaveCtx,AL_MIN_GAIN);
rlm@15 238 syncSourcef(master,slave,masterCtx,slaveCtx,AL_MAX_GAIN);
rlm@15 239 syncSourcef(master,slave,masterCtx,slaveCtx,AL_CONE_OUTER_GAIN);
rlm@15 240 syncSourcef(master,slave,masterCtx,slaveCtx,AL_CONE_INNER_ANGLE);
rlm@15 241 syncSourcef(master,slave,masterCtx,slaveCtx,AL_CONE_OUTER_ANGLE);
rlm@15 242 syncSourcef(master,slave,masterCtx,slaveCtx,AL_SEC_OFFSET);
rlm@15 243 syncSourcef(master,slave,masterCtx,slaveCtx,AL_SAMPLE_OFFSET);
rlm@15 244 syncSourcef(master,slave,masterCtx,slaveCtx,AL_BYTE_OFFSET);
rlm@15 245
rlm@15 246 syncSource3f(master,slave,masterCtx,slaveCtx,AL_POSITION);
rlm@15 247 syncSource3f(master,slave,masterCtx,slaveCtx,AL_VELOCITY);
rlm@15 248 syncSource3f(master,slave,masterCtx,slaveCtx,AL_DIRECTION);
rlm@15 249
rlm@15 250 syncSourcei(master,slave,masterCtx,slaveCtx,AL_SOURCE_RELATIVE);
rlm@15 251 syncSourcei(master,slave,masterCtx,slaveCtx,AL_LOOPING);
rlm@15 252
rlm@15 253 alcMakeContextCurrent(masterCtx);
rlm@15 254 ALint source_type;
rlm@15 255 alGetSourcei(master, AL_SOURCE_TYPE, &source_type);
rlm@15 256
rlm@15 257 // Only static sources are currently synchronized!
rlm@15 258 if (AL_STATIC == source_type){
rlm@15 259 ALint master_buffer;
rlm@15 260 ALint slave_buffer;
rlm@15 261 alGetSourcei(master, AL_BUFFER, &master_buffer);
rlm@15 262 alcMakeContextCurrent(slaveCtx);
rlm@15 263 alGetSourcei(slave, AL_BUFFER, &slave_buffer);
rlm@15 264 if (master_buffer != slave_buffer){
rlm@15 265 alSourcei(slave, AL_BUFFER, master_buffer);
rlm@15 266 }
rlm@15 267 }
rlm@15 268
rlm@15 269 // Synchronize the state of the two sources.
rlm@15 270 alcMakeContextCurrent(masterCtx);
rlm@15 271 ALint masterState;
rlm@15 272 ALint slaveState;
rlm@15 273
rlm@15 274 alGetSourcei(master, AL_SOURCE_STATE, &masterState);
rlm@15 275 alcMakeContextCurrent(slaveCtx);
rlm@15 276 alGetSourcei(slave, AL_SOURCE_STATE, &slaveState);
rlm@15 277
rlm@15 278 if (masterState != slaveState){
rlm@15 279 switch (masterState){
rlm@15 280 case AL_INITIAL : alSourceRewind(slave); break;
rlm@15 281 case AL_PLAYING : alSourcePlay(slave); break;
rlm@15 282 case AL_PAUSED : alSourcePause(slave); break;
rlm@15 283 case AL_STOPPED : alSourceStop(slave); break;
rlm@15 284 }
rlm@15 285 }
rlm@15 286 // Restore whatever context was previously active.
rlm@15 287 alcMakeContextCurrent(current);
rlm@15 288 }
rlm@18 289 #+end_src
rlm@20 290 This function is long because it has to exhaustively go through all the
rlm@18 291 possible state that a source can have and make sure that it is the
rlm@18 292 same between the master and slave sources. I'd like to take this
rlm@18 293 moment to salute the [[http://connect.creativelabs.com/openal/Documentation/Forms/AllItems.aspx][=OpenAL= Reference Manual]], which provides a very
rlm@18 294 good description of =OpenAL='s internals.
rlm@15 295
rlm@18 296 ** Context Synchronization
rlm@21 297 #+srcname: sync-contexts
rlm@18 298 #+begin_src C
rlm@15 299 void syncContexts(ALCcontext *master, ALCcontext *slave){
rlm@15 300 /* If there aren't sufficient sources in slave to mirror
rlm@15 301 the sources in master, create them. */
rlm@15 302 ALCcontext *current = alcGetCurrentContext();
rlm@15 303
rlm@15 304 UIntMap *masterSourceMap = &(master->SourceMap);
rlm@15 305 UIntMap *slaveSourceMap = &(slave->SourceMap);
rlm@15 306 ALuint numMasterSources = masterSourceMap->size;
rlm@15 307 ALuint numSlaveSources = slaveSourceMap->size;
rlm@15 308
rlm@15 309 alcMakeContextCurrent(slave);
rlm@15 310 if (numSlaveSources < numMasterSources){
rlm@15 311 ALuint numMissingSources = numMasterSources - numSlaveSources;
rlm@15 312 ALuint newSources[numMissingSources];
rlm@15 313 alGenSources(numMissingSources, newSources);
rlm@15 314 }
rlm@15 315
rlm@20 316 /* Now, slave is guaranteed to have at least as many sources
rlm@15 317 as master. Sync each source from master to the corresponding
rlm@15 318 source in slave. */
rlm@15 319 int i;
rlm@15 320 for(i = 0; i < masterSourceMap->size; i++){
rlm@15 321 syncSources((ALsource*)masterSourceMap->array[i].value,
rlm@15 322 (ALsource*)slaveSourceMap->array[i].value,
rlm@15 323 master, slave);
rlm@15 324 }
rlm@15 325 alcMakeContextCurrent(current);
rlm@15 326 }
rlm@18 327 #+end_src
rlm@15 328
rlm@18 329 Most of the hard work in Context Synchronization is done in
rlm@18 330 =syncSources()=. The only thing that =syncContexts()= has to worry
rlm@20 331 about is automatically creating new sources whenever a slave context
rlm@18 332 does not have the same number of sources as the master context.
rlm@18 333
rlm@19 334 ** Context Creation
rlm@21 335 #+srcname: context-creation
rlm@18 336 #+begin_src C
rlm@15 337 static void addContext(ALCdevice *Device, ALCcontext *context){
rlm@15 338 send_data *data = (send_data*)Device->ExtraData;
rlm@15 339 // expand array if necessary
rlm@15 340 if (data->numContexts >= data->maxContexts){
rlm@15 341 ALuint newMaxContexts = data->maxContexts*2 + 1;
rlm@15 342 data->contexts = realloc(data->contexts, newMaxContexts*sizeof(context_data));
rlm@15 343 data->maxContexts = newMaxContexts;
rlm@15 344 }
rlm@15 345 // create context_data and add it to the main array
rlm@15 346 context_data *ctxData;
rlm@15 347 ctxData = (context_data*)calloc(1, sizeof(*ctxData));
rlm@15 348 ctxData->renderBuffer =
rlm@15 349 malloc(BytesFromDevFmt(Device->FmtType) *
rlm@15 350 Device->NumChan * Device->UpdateSize);
rlm@15 351 ctxData->ctx = context;
rlm@15 352
rlm@15 353 data->contexts[data->numContexts] = ctxData;
rlm@15 354 data->numContexts++;
rlm@15 355 }
rlm@18 356 #+end_src
rlm@15 357
rlm@18 358 Here, the slave context is created, and it's data is stored in the
rlm@18 359 device-wide =ExtraData= structure. The =renderBuffer= that is created
rlm@18 360 here is where the rendered sound samples for this slave context will
rlm@18 361 eventually go.
rlm@15 362
rlm@19 363 ** Context Switching
rlm@21 364 #+srcname: context-switching
rlm@18 365 #+begin_src C
rlm@15 366 //////////////////// Context Switching
rlm@15 367
rlm@15 368 /* A device brings along with it two pieces of state
rlm@15 369 * which have to be swapped in and out with each context.
rlm@15 370 */
rlm@15 371 static void swapInContext(ALCdevice *Device, context_data *ctxData){
rlm@15 372 memcpy(Device->ClickRemoval, ctxData->ClickRemoval, sizeof(ALfloat)*MAXCHANNELS);
rlm@15 373 memcpy(Device->PendingClicks, ctxData->PendingClicks, sizeof(ALfloat)*MAXCHANNELS);
rlm@15 374 }
rlm@15 375
rlm@15 376 static void saveContext(ALCdevice *Device, context_data *ctxData){
rlm@15 377 memcpy(ctxData->ClickRemoval, Device->ClickRemoval, sizeof(ALfloat)*MAXCHANNELS);
rlm@15 378 memcpy(ctxData->PendingClicks, Device->PendingClicks, sizeof(ALfloat)*MAXCHANNELS);
rlm@15 379 }
rlm@15 380
rlm@15 381 static ALCcontext **currentContext;
rlm@15 382 static ALuint currentNumContext;
rlm@15 383
rlm@15 384 /* By default, all contexts are rendered at once for each call to aluMixData.
rlm@20 385 * This function uses the internals of the ALCdevice struct to temporally
rlm@15 386 * cause aluMixData to only render the chosen context.
rlm@15 387 */
rlm@15 388 static void limitContext(ALCdevice *Device, ALCcontext *ctx){
rlm@15 389 currentContext = Device->Contexts;
rlm@15 390 currentNumContext = Device->NumContexts;
rlm@15 391 Device->Contexts = &ctx;
rlm@15 392 Device->NumContexts = 1;
rlm@15 393 }
rlm@15 394
rlm@15 395 static void unLimitContext(ALCdevice *Device){
rlm@15 396 Device->Contexts = currentContext;
rlm@15 397 Device->NumContexts = currentNumContext;
rlm@15 398 }
rlm@18 399 #+end_src
rlm@15 400
rlm@20 401 =OpenAL= normally renders all Contexts in parallel, outputting the
rlm@18 402 whole result to the buffer. It does this by iterating over the
rlm@18 403 Device->Contexts array and rendering each context to the buffer in
rlm@20 404 turn. By temporally setting Device->NumContexts to 1 and adjusting
rlm@18 405 the Device's context list to put the desired context-to-be-rendered
rlm@18 406 into position 0, we can get trick =OpenAL= into rendering each slave
rlm@18 407 context separate from all the others.
rlm@15 408
rlm@18 409 ** Main Device Loop
rlm@21 410 #+srcname: main-loop
rlm@18 411 #+begin_src C
rlm@15 412 //////////////////// Main Device Loop
rlm@15 413
rlm@18 414 /* Establish the LWJGL context as the master context, which will
rlm@15 415 * be synchronized to all the slave contexts
rlm@15 416 */
rlm@15 417 static void init(ALCdevice *Device){
rlm@15 418 ALCcontext *masterContext = alcGetCurrentContext();
rlm@15 419 addContext(Device, masterContext);
rlm@15 420 }
rlm@15 421
rlm@15 422
rlm@15 423 static void renderData(ALCdevice *Device, int samples){
rlm@15 424 if(!Device->Connected){return;}
rlm@15 425 send_data *data = (send_data*)Device->ExtraData;
rlm@15 426 ALCcontext *current = alcGetCurrentContext();
rlm@15 427
rlm@15 428 ALuint i;
rlm@15 429 for (i = 1; i < data->numContexts; i++){
rlm@15 430 syncContexts(data->contexts[0]->ctx , data->contexts[i]->ctx);
rlm@15 431 }
rlm@15 432
rlm@25 433 if ((ALuint) samples > Device->UpdateSize){
rlm@15 434 printf("exceeding internal buffer size; dropping samples\n");
rlm@15 435 printf("requested %d; available %d\n", samples, Device->UpdateSize);
rlm@15 436 samples = (int) Device->UpdateSize;
rlm@15 437 }
rlm@15 438
rlm@15 439 for (i = 0; i < data->numContexts; i++){
rlm@15 440 context_data *ctxData = data->contexts[i];
rlm@15 441 ALCcontext *ctx = ctxData->ctx;
rlm@15 442 alcMakeContextCurrent(ctx);
rlm@15 443 limitContext(Device, ctx);
rlm@15 444 swapInContext(Device, ctxData);
rlm@15 445 aluMixData(Device, ctxData->renderBuffer, samples);
rlm@15 446 saveContext(Device, ctxData);
rlm@15 447 unLimitContext(Device);
rlm@15 448 }
rlm@15 449 alcMakeContextCurrent(current);
rlm@15 450 }
rlm@18 451 #+end_src
rlm@15 452
rlm@18 453 The main loop synchronizes the master LWJGL context with all the slave
rlm@18 454 contexts, then walks each context, rendering just that context to it's
rlm@18 455 audio-sample storage buffer.
rlm@15 456
rlm@19 457 ** JNI Methods
rlm@19 458
rlm@19 459 At this point, we have the ability to create multiple listeners by
rlm@19 460 using the master/slave context trick, and the rendered audio data is
rlm@19 461 waiting patiently in internal buffers, one for each listener. We need
rlm@19 462 a way to transport this information to Java, and also a way to drive
rlm@19 463 this device from Java. The following JNI interface code is inspired
rlm@19 464 by the way LWJGL interfaces with =OpenAL=.
rlm@19 465
rlm@19 466 *** step
rlm@21 467 #+srcname: jni-step
rlm@18 468 #+begin_src C
rlm@15 469 //////////////////// JNI Methods
rlm@15 470
rlm@15 471 #include "com_aurellem_send_AudioSend.h"
rlm@15 472
rlm@15 473 /*
rlm@15 474 * Class: com_aurellem_send_AudioSend
rlm@15 475 * Method: nstep
rlm@15 476 * Signature: (JI)V
rlm@15 477 */
rlm@15 478 JNIEXPORT void JNICALL Java_com_aurellem_send_AudioSend_nstep
rlm@15 479 (JNIEnv *env, jclass clazz, jlong device, jint samples){
rlm@15 480 UNUSED(env);UNUSED(clazz);UNUSED(device);
rlm@15 481 renderData((ALCdevice*)((intptr_t)device), samples);
rlm@15 482 }
rlm@19 483 #+end_src
rlm@19 484 This device, unlike most of the other devices in =OpenAL=, does not
rlm@19 485 render sound unless asked. This enables the system to slow down or
rlm@19 486 speed up depending on the needs of the AIs who are using it to
rlm@19 487 listen. If the device tried to render samples in real-time, a
rlm@19 488 complicated AI whose mind takes 100 seconds of computer time to
rlm@19 489 simulate 1 second of AI-time would miss almost all of the sound in
rlm@19 490 its environment.
rlm@15 491
rlm@19 492
rlm@19 493 *** getSamples
rlm@21 494 #+srcname: jni-get-samples
rlm@19 495 #+begin_src C
rlm@15 496 /*
rlm@15 497 * Class: com_aurellem_send_AudioSend
rlm@15 498 * Method: ngetSamples
rlm@15 499 * Signature: (JLjava/nio/ByteBuffer;III)V
rlm@15 500 */
rlm@15 501 JNIEXPORT void JNICALL Java_com_aurellem_send_AudioSend_ngetSamples
rlm@15 502 (JNIEnv *env, jclass clazz, jlong device, jobject buffer, jint position,
rlm@15 503 jint samples, jint n){
rlm@15 504 UNUSED(clazz);
rlm@15 505
rlm@15 506 ALvoid *buffer_address =
rlm@15 507 ((ALbyte *)(((char*)(*env)->GetDirectBufferAddress(env, buffer)) + position));
rlm@15 508 ALCdevice *recorder = (ALCdevice*) ((intptr_t)device);
rlm@15 509 send_data *data = (send_data*)recorder->ExtraData;
rlm@15 510 if ((ALuint)n > data->numContexts){return;}
rlm@15 511 memcpy(buffer_address, data->contexts[n]->renderBuffer,
rlm@15 512 BytesFromDevFmt(recorder->FmtType) * recorder->NumChan * samples);
rlm@15 513 }
rlm@19 514 #+end_src
rlm@15 515
rlm@19 516 This is the transport layer between C and Java that will eventually
rlm@19 517 allow us to access rendered sound data from clojure.
rlm@19 518
rlm@19 519 *** Listener Management
rlm@19 520
rlm@19 521 =addListener=, =setNthListenerf=, and =setNthListener3f= are
rlm@19 522 necessary to change the properties of any listener other than the
rlm@19 523 master one, since only the listener of the current active context is
rlm@19 524 affected by the normal =OpenAL= listener calls.
rlm@21 525 #+srcname: listener-manage
rlm@19 526 #+begin_src C
rlm@15 527 /*
rlm@15 528 * Class: com_aurellem_send_AudioSend
rlm@15 529 * Method: naddListener
rlm@15 530 * Signature: (J)V
rlm@15 531 */
rlm@15 532 JNIEXPORT void JNICALL Java_com_aurellem_send_AudioSend_naddListener
rlm@15 533 (JNIEnv *env, jclass clazz, jlong device){
rlm@15 534 UNUSED(env); UNUSED(clazz);
rlm@15 535 //printf("creating new context via naddListener\n");
rlm@15 536 ALCdevice *Device = (ALCdevice*) ((intptr_t)device);
rlm@15 537 ALCcontext *new = alcCreateContext(Device, NULL);
rlm@15 538 addContext(Device, new);
rlm@15 539 }
rlm@15 540
rlm@15 541 /*
rlm@15 542 * Class: com_aurellem_send_AudioSend
rlm@15 543 * Method: nsetNthListener3f
rlm@15 544 * Signature: (IFFFJI)V
rlm@15 545 */
rlm@15 546 JNIEXPORT void JNICALL Java_com_aurellem_send_AudioSend_nsetNthListener3f
rlm@15 547 (JNIEnv *env, jclass clazz, jint param,
rlm@15 548 jfloat v1, jfloat v2, jfloat v3, jlong device, jint contextNum){
rlm@15 549 UNUSED(env);UNUSED(clazz);
rlm@15 550
rlm@15 551 ALCdevice *Device = (ALCdevice*) ((intptr_t)device);
rlm@15 552 send_data *data = (send_data*)Device->ExtraData;
rlm@15 553
rlm@15 554 ALCcontext *current = alcGetCurrentContext();
rlm@15 555 if ((ALuint)contextNum > data->numContexts){return;}
rlm@15 556 alcMakeContextCurrent(data->contexts[contextNum]->ctx);
rlm@15 557 alListener3f(param, v1, v2, v3);
rlm@15 558 alcMakeContextCurrent(current);
rlm@15 559 }
rlm@15 560
rlm@15 561 /*
rlm@15 562 * Class: com_aurellem_send_AudioSend
rlm@15 563 * Method: nsetNthListenerf
rlm@15 564 * Signature: (IFJI)V
rlm@15 565 */
rlm@15 566 JNIEXPORT void JNICALL Java_com_aurellem_send_AudioSend_nsetNthListenerf
rlm@15 567 (JNIEnv *env, jclass clazz, jint param, jfloat v1, jlong device,
rlm@15 568 jint contextNum){
rlm@15 569
rlm@15 570 UNUSED(env);UNUSED(clazz);
rlm@15 571
rlm@15 572 ALCdevice *Device = (ALCdevice*) ((intptr_t)device);
rlm@15 573 send_data *data = (send_data*)Device->ExtraData;
rlm@15 574
rlm@15 575 ALCcontext *current = alcGetCurrentContext();
rlm@15 576 if ((ALuint)contextNum > data->numContexts){return;}
rlm@15 577 alcMakeContextCurrent(data->contexts[contextNum]->ctx);
rlm@15 578 alListenerf(param, v1);
rlm@15 579 alcMakeContextCurrent(current);
rlm@15 580 }
rlm@19 581 #+end_src
rlm@15 582
rlm@20 583 *** Initialization
rlm@19 584 =initDevice= is called from the Java side after LWJGL has created its
rlm@19 585 context, and before any calls to =addListener=. It establishes the
rlm@19 586 LWJGL context as the master context.
rlm@19 587
rlm@20 588 =getAudioFormat= is a convenience function that uses JNI to build up a
rlm@19 589 =javax.sound.sampled.AudioFormat= object from data in the Device. This
rlm@19 590 way, there is no ambiguity about what the bits created by =step= and
rlm@19 591 returned by =getSamples= mean.
rlm@21 592 #+srcname: jni-init
rlm@19 593 #+begin_src C
rlm@15 594 /*
rlm@15 595 * Class: com_aurellem_send_AudioSend
rlm@15 596 * Method: ninitDevice
rlm@15 597 * Signature: (J)V
rlm@15 598 */
rlm@15 599 JNIEXPORT void JNICALL Java_com_aurellem_send_AudioSend_ninitDevice
rlm@15 600 (JNIEnv *env, jclass clazz, jlong device){
rlm@15 601 UNUSED(env);UNUSED(clazz);
rlm@15 602 ALCdevice *Device = (ALCdevice*) ((intptr_t)device);
rlm@15 603 init(Device);
rlm@15 604 }
rlm@15 605
rlm@15 606 /*
rlm@15 607 * Class: com_aurellem_send_AudioSend
rlm@15 608 * Method: ngetAudioFormat
rlm@15 609 * Signature: (J)Ljavax/sound/sampled/AudioFormat;
rlm@15 610 */
rlm@15 611 JNIEXPORT jobject JNICALL Java_com_aurellem_send_AudioSend_ngetAudioFormat
rlm@15 612 (JNIEnv *env, jclass clazz, jlong device){
rlm@15 613 UNUSED(clazz);
rlm@15 614 jclass AudioFormatClass =
rlm@15 615 (*env)->FindClass(env, "javax/sound/sampled/AudioFormat");
rlm@15 616 jmethodID AudioFormatConstructor =
rlm@15 617 (*env)->GetMethodID(env, AudioFormatClass, "<init>", "(FIIZZ)V");
rlm@15 618
rlm@15 619 ALCdevice *Device = (ALCdevice*) ((intptr_t)device);
rlm@15 620 int isSigned;
rlm@15 621 switch (Device->FmtType)
rlm@15 622 {
rlm@15 623 case DevFmtUByte:
rlm@15 624 case DevFmtUShort: isSigned = 0; break;
rlm@15 625 default : isSigned = 1;
rlm@15 626 }
rlm@15 627 float frequency = Device->Frequency;
rlm@15 628 int bitsPerFrame = (8 * BytesFromDevFmt(Device->FmtType));
rlm@15 629 int channels = Device->NumChan;
rlm@15 630 jobject format = (*env)->
rlm@15 631 NewObject(
rlm@15 632 env,AudioFormatClass,AudioFormatConstructor,
rlm@15 633 frequency,
rlm@15 634 bitsPerFrame,
rlm@15 635 channels,
rlm@15 636 isSigned,
rlm@15 637 0);
rlm@15 638 return format;
rlm@15 639 }
rlm@19 640 #+end_src
rlm@15 641
rlm@22 642 ** Boring Device management stuff
rlm@19 643 This code is more-or-less copied verbatim from the other =OpenAL=
rlm@19 644 backends. It's the basis for =OpenAL='s primitive object system.
rlm@21 645 #+srcname: device-init
rlm@19 646 #+begin_src C
rlm@20 647 //////////////////// Device Initialization / Management
rlm@15 648
rlm@15 649 static const ALCchar sendDevice[] = "Multiple Audio Send";
rlm@15 650
rlm@15 651 static ALCboolean send_open_playback(ALCdevice *device,
rlm@15 652 const ALCchar *deviceName)
rlm@15 653 {
rlm@15 654 send_data *data;
rlm@15 655 // stop any buffering for stdout, so that I can
rlm@20 656 // see the printf statements in my terminal immediately
rlm@15 657 setbuf(stdout, NULL);
rlm@15 658
rlm@15 659 if(!deviceName)
rlm@15 660 deviceName = sendDevice;
rlm@15 661 else if(strcmp(deviceName, sendDevice) != 0)
rlm@15 662 return ALC_FALSE;
rlm@15 663 data = (send_data*)calloc(1, sizeof(*data));
rlm@15 664 device->szDeviceName = strdup(deviceName);
rlm@15 665 device->ExtraData = data;
rlm@15 666 return ALC_TRUE;
rlm@15 667 }
rlm@15 668
rlm@15 669 static void send_close_playback(ALCdevice *device)
rlm@15 670 {
rlm@15 671 send_data *data = (send_data*)device->ExtraData;
rlm@15 672 alcMakeContextCurrent(NULL);
rlm@15 673 ALuint i;
rlm@15 674 // Destroy all slave contexts. LWJGL will take care of
rlm@15 675 // its own context.
rlm@15 676 for (i = 1; i < data->numContexts; i++){
rlm@15 677 context_data *ctxData = data->contexts[i];
rlm@15 678 alcDestroyContext(ctxData->ctx);
rlm@15 679 free(ctxData->renderBuffer);
rlm@15 680 free(ctxData);
rlm@15 681 }
rlm@15 682 free(data);
rlm@15 683 device->ExtraData = NULL;
rlm@15 684 }
rlm@15 685
rlm@15 686 static ALCboolean send_reset_playback(ALCdevice *device)
rlm@15 687 {
rlm@15 688 SetDefaultWFXChannelOrder(device);
rlm@15 689 return ALC_TRUE;
rlm@15 690 }
rlm@15 691
rlm@15 692 static void send_stop_playback(ALCdevice *Device){
rlm@15 693 UNUSED(Device);
rlm@15 694 }
rlm@15 695
rlm@15 696 static const BackendFuncs send_funcs = {
rlm@15 697 send_open_playback,
rlm@15 698 send_close_playback,
rlm@15 699 send_reset_playback,
rlm@15 700 send_stop_playback,
rlm@15 701 NULL,
rlm@15 702 NULL, /* These would be filled with functions to */
rlm@15 703 NULL, /* handle capturing audio if we we into that */
rlm@15 704 NULL, /* sort of thing... */
rlm@15 705 NULL,
rlm@15 706 NULL
rlm@15 707 };
rlm@15 708
rlm@15 709 ALCboolean alc_send_init(BackendFuncs *func_list){
rlm@15 710 *func_list = send_funcs;
rlm@15 711 return ALC_TRUE;
rlm@15 712 }
rlm@15 713
rlm@15 714 void alc_send_deinit(void){}
rlm@15 715
rlm@15 716 void alc_send_probe(enum DevProbe type)
rlm@15 717 {
rlm@15 718 switch(type)
rlm@15 719 {
rlm@15 720 case DEVICE_PROBE:
rlm@15 721 AppendDeviceList(sendDevice);
rlm@15 722 break;
rlm@15 723 case ALL_DEVICE_PROBE:
rlm@15 724 AppendAllDeviceList(sendDevice);
rlm@15 725 break;
rlm@15 726 case CAPTURE_DEVICE_PROBE:
rlm@15 727 break;
rlm@15 728 }
rlm@15 729 }
rlm@15 730 #+end_src
rlm@15 731
rlm@19 732 * The Java interface, =AudioSend=
rlm@15 733
rlm@19 734 The Java interface to the Send Device follows naturally from the JNI
rlm@19 735 definitions. It is included here for completeness. The only thing here
rlm@19 736 of note is the =deviceID=. This is available from LWJGL, but to only
rlm@20 737 way to get it is reflection. Unfortunately, there is no other way to
rlm@19 738 control the Send device than to obtain a pointer to it.
rlm@15 739
rlm@19 740 #+include: "../java/src/com/aurellem/send/AudioSend.java" src java :exports code
rlm@15 741
rlm@19 742 * Finally, Ears in clojure!
rlm@15 743
rlm@20 744 Now that the infrastructure is complete (modulo a few patches to
rlm@19 745 jMonkeyEngine3 to support accessing this modified version of =OpenAL=
rlm@19 746 that are not worth discussing), the clojure ear abstraction is rather
rlm@19 747 simple. Just as there were =SceneProcessors= for vision, there are
rlm@19 748 now =SoundProcessors= for hearing.
rlm@15 749
rlm@19 750 #+include "../../jmeCapture/src/com/aurellem/capture/audio/SoundProcessor.java" src java
rlm@15 751
rlm@15 752 #+srcname: ears
rlm@0 753 #+begin_src clojure
rlm@19 754 (ns cortex.hearing
rlm@19 755 "Simulate the sense of hearing in jMonkeyEngine3. Enables multiple
rlm@19 756 listeners at different positions in the same world. Passes vectors
rlm@20 757 of floats in the range [-1.0 -- 1.0] in PCM format to any arbitrary
rlm@19 758 function."
rlm@19 759 {:author "Robert McIntyre"}
rlm@19 760 (:use (cortex world util))
rlm@19 761 (:import java.nio.ByteBuffer)
rlm@19 762 (:import org.tritonus.share.sampled.FloatSampleTools)
rlm@19 763 (:import com.aurellem.capture.audio.SoundProcessor)
rlm@19 764 (:import javax.sound.sampled.AudioFormat))
rlm@19 765
rlm@0 766 (defn sound-processor
rlm@19 767 "Deals with converting ByteBuffers into Vectors of floats so that
rlm@19 768 the continuation functions can be defined in terms of immutable
rlm@19 769 stuff."
rlm@0 770 [continuation]
rlm@0 771 (proxy [SoundProcessor] []
rlm@0 772 (cleanup [])
rlm@0 773 (process
rlm@19 774 [#^ByteBuffer audioSamples numSamples #^AudioFormat audioFormat]
rlm@19 775 (let [bytes (byte-array numSamples)
rlm@19 776 floats (float-array numSamples)]
rlm@19 777 (.get audioSamples bytes 0 numSamples)
rlm@19 778 (FloatSampleTools/byte2floatInterleaved
rlm@19 779 bytes 0 floats 0
rlm@19 780 (/ numSamples (.getFrameSize audioFormat)) audioFormat)
rlm@19 781 (continuation
rlm@19 782 (vec floats))))))
rlm@0 783
rlm@0 784 (defn add-ear
rlm@19 785 "Add an ear to the world. The continuation function will be called
rlm@0 786 on the FFT or the sounds which the ear hears in the given
rlm@0 787 timeframe. Sound is 3D."
rlm@0 788 [world listener continuation]
rlm@0 789 (let [renderer (.getAudioRenderer world)]
rlm@0 790 (.addListener renderer listener)
rlm@0 791 (.registerSoundProcessor renderer listener
rlm@0 792 (sound-processor continuation))
rlm@0 793 listener))
rlm@0 794 #+end_src
rlm@0 795
rlm@19 796 * Example
rlm@0 797
rlm@0 798 #+srcname: test-hearing
rlm@0 799 #+begin_src clojure :results silent
rlm@19 800 (ns test.hearing
rlm@19 801 (:use (cortex world util hearing))
rlm@19 802 (:import (com.jme3.audio AudioNode Listener))
rlm@19 803 (:import com.jme3.scene.Node))
rlm@0 804
rlm@0 805 (defn setup-fn [world]
rlm@0 806 (let [listener (Listener.)]
rlm@19 807 (add-ear world listener #(println-repl (nth % 0)))))
rlm@0 808
rlm@0 809 (defn play-sound [node world value]
rlm@0 810 (if (not value)
rlm@0 811 (do
rlm@0 812 (.playSource (.getAudioRenderer world) node))))
rlm@0 813
rlm@19 814 (defn test-basic-hearing []
rlm@19 815 (.start
rlm@19 816 (let [node1 (AudioNode. (asset-manager) "Sounds/pure.wav" false false)]
rlm@19 817 (world
rlm@19 818 (Node.)
rlm@19 819 {"key-space" (partial play-sound node1)}
rlm@19 820 setup-fn
rlm@19 821 no-op))))
rlm@0 822 #+end_src
rlm@0 823
rlm@19 824 This extremely basic program prints out the first sample it encounters
rlm@19 825 at every time stamp. You can see the rendered sound begin printed at
rlm@19 826 the REPL.
rlm@15 827
rlm@22 828 - As a bonus, this method of capturing audio for AI can also be used
rlm@22 829 to capture perfect audio from a jMonkeyEngine application, for use
rlm@22 830 in demos and the like.
rlm@22 831
rlm@22 832
rlm@0 833 * COMMENT Code Generation
rlm@0 834
rlm@15 835 #+begin_src clojure :tangle ../../cortex/src/cortex/hearing.clj
rlm@15 836 <<ears>>
rlm@0 837 #+end_src
rlm@0 838
rlm@15 839 #+begin_src clojure :tangle ../../cortex/src/test/hearing.clj
rlm@0 840 <<test-hearing>>
rlm@0 841 #+end_src
rlm@0 842
rlm@0 843
rlm@15 844 #+begin_src C :tangle ../Alc/backends/send.c
rlm@21 845 <<send-header>>
rlm@21 846 <<send-state>>
rlm@21 847 <<sync-macros>>
rlm@21 848 <<sync-sources>>
rlm@21 849 <<sync-contexts>>
rlm@21 850 <<context-creation>>
rlm@21 851 <<context-switching>>
rlm@21 852 <<main-loop>>
rlm@21 853 <<jni-step>>
rlm@21 854 <<jni-get-samples>>
rlm@21 855 <<listener-manage>>
rlm@21 856 <<jni-init>>
rlm@21 857 <<device-init>>
rlm@15 858 #+end_src
rlm@19 859
rlm@19 860