It seems possible for two worker threads run concurrently, and when they
do, they trample on the global JNIEnv. The AudioTrack.write call still
uses JNI for efficiency.
The first problem in the OpenSL backend is that it hard codes the frequency to 44kHz.
The second problem is that the OpenSL backend initializes the player too early. I believe it is initializing at the device opening, and not the context creation where the ALC_FREQUENCY parameter is set/bound to.
So the solution is to move the CreateAudioPlayer stuff to this section which seems to be the reset_callback and respect the Frequency parameter passed through to the callback. I compared to the current mainline OpenAL Soft/OpenSL backend and their implementation seems to place the audio player creation in this same place so this at least makes this implementation more consistent with the official one.
This implementation does suggest to me that it doesn't handle multiple contexts well/correctly, but that is a problem independent of this fix.
One tricky modification is that JNI is needed in the opensles.c backend which impacts a function pointer previously not being set and is sensitive to initialization order. This changes the logic slightly to ensure initialization is correct and not overwritten by AudioTrack initialization.
Thanks to Josh Quick for help on the JNI code to get the Android API version number.
Lowering this value may negatively affect the mixing throughput for lots of sources. But this is a balancing act to not make the latency worse than the Audiotrack backend.
I tested on Kindle Fire (2.3), Nexus 7 (4.1), Motorola Xoom (3.?), Galaxy SII (2.3.4). In all cases, the latency seems to be about on par with the Audiotrack backend. Somewhat more subjective, the OpenSL ES backend with this change sounded a little cleaner to me.
I picked 4 somewhat arbitrarily. Being burned by non-power-of-two things before, I liked going from 4 to 8 and the latency improved to where I wanted it.
The latency is not really noticable on the Nexus 7 running 4.1 regardless of this change. This suggests a future fix dynamically change this constant back to 8 if running on 4.1+ if the Apportable values were well picked/tested to begin with.