M7350v1_en_gpl

This commit is contained in:
T
2024-09-09 08:52:07 +00:00
commit f9cc65cfda
65988 changed files with 26357421 additions and 0 deletions
+19
View File
@@ -0,0 +1,19 @@
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_SRC_FILES:= \
android_media_SoundPool.cpp \
SoundPool.cpp \
SoundPoolThread.cpp
LOCAL_SHARED_LIBRARIES := \
libcutils \
libutils \
libbinder \
libandroid_runtime \
libnativehelper \
libmedia
LOCAL_MODULE:= libsoundpool
include $(BUILD_SHARED_LIBRARY)
+190
View File
@@ -0,0 +1,190 @@
Copyright (c) 2005-2008, The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+905
View File
@@ -0,0 +1,905 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//#define LOG_NDEBUG 0
#define LOG_TAG "SoundPool"
#include <utils/Log.h>
//#define USE_SHARED_MEM_BUFFER
// XXX needed for timing latency
#include <utils/Timers.h>
#include <sys/resource.h>
#include <media/AudioTrack.h>
#include <media/mediaplayer.h>
#include "SoundPool.h"
#include "SoundPoolThread.h"
namespace android
{
int kDefaultBufferCount = 4;
uint32_t kMaxSampleRate = 48000;
uint32_t kDefaultSampleRate = 44100;
uint32_t kDefaultFrameCount = 1200;
SoundPool::SoundPool(int maxChannels, int streamType, int srcQuality)
{
LOGV("SoundPool constructor: maxChannels=%d, streamType=%d, srcQuality=%d",
maxChannels, streamType, srcQuality);
// check limits
mMaxChannels = maxChannels;
if (mMaxChannels < 1) {
mMaxChannels = 1;
}
else if (mMaxChannels > 32) {
mMaxChannels = 32;
}
LOGW_IF(maxChannels != mMaxChannels, "App requested %d channels", maxChannels);
mQuit = false;
mDecodeThread = 0;
mStreamType = streamType;
mSrcQuality = srcQuality;
mAllocated = 0;
mNextSampleID = 0;
mNextChannelID = 0;
mCallback = 0;
mUserData = 0;
mChannelPool = new SoundChannel[mMaxChannels];
for (int i = 0; i < mMaxChannels; ++i) {
mChannelPool[i].init(this);
mChannels.push_back(&mChannelPool[i]);
}
// start decode thread
startThreads();
}
SoundPool::~SoundPool()
{
LOGV("SoundPool destructor");
mDecodeThread->quit();
quit();
Mutex::Autolock lock(&mLock);
mChannels.clear();
if (mChannelPool)
delete [] mChannelPool;
// clean up samples
LOGV("clear samples");
mSamples.clear();
if (mDecodeThread)
delete mDecodeThread;
}
void SoundPool::addToRestartList(SoundChannel* channel)
{
Mutex::Autolock lock(&mRestartLock);
if (!mQuit) {
mRestart.push_back(channel);
mCondition.signal();
}
}
void SoundPool::addToStopList(SoundChannel* channel)
{
Mutex::Autolock lock(&mRestartLock);
if (!mQuit) {
mStop.push_back(channel);
mCondition.signal();
}
}
int SoundPool::beginThread(void* arg)
{
SoundPool* p = (SoundPool*)arg;
return p->run();
}
int SoundPool::run()
{
mRestartLock.lock();
while (!mQuit) {
mCondition.wait(mRestartLock);
LOGV("awake");
if (mQuit) break;
while (!mStop.empty()) {
SoundChannel* channel;
LOGV("Getting channel from stop list");
List<SoundChannel* >::iterator iter = mStop.begin();
channel = *iter;
mStop.erase(iter);
mRestartLock.unlock();
if (channel != 0) {
Mutex::Autolock lock(&mLock);
channel->stop();
}
mRestartLock.lock();
if (mQuit) break;
}
while (!mRestart.empty()) {
SoundChannel* channel;
LOGV("Getting channel from list");
List<SoundChannel*>::iterator iter = mRestart.begin();
channel = *iter;
mRestart.erase(iter);
mRestartLock.unlock();
if (channel != 0) {
Mutex::Autolock lock(&mLock);
channel->nextEvent();
}
mRestartLock.lock();
if (mQuit) break;
}
}
mStop.clear();
mRestart.clear();
mCondition.signal();
mRestartLock.unlock();
LOGV("goodbye");
return 0;
}
void SoundPool::quit()
{
mRestartLock.lock();
mQuit = true;
mCondition.signal();
mCondition.wait(mRestartLock);
LOGV("return from quit");
mRestartLock.unlock();
}
bool SoundPool::startThreads()
{
createThreadEtc(beginThread, this, "SoundPool");
if (mDecodeThread == NULL)
mDecodeThread = new SoundPoolThread(this);
return mDecodeThread != NULL;
}
SoundChannel* SoundPool::findChannel(int channelID)
{
for (int i = 0; i < mMaxChannels; ++i) {
if (mChannelPool[i].channelID() == channelID) {
return &mChannelPool[i];
}
}
return NULL;
}
SoundChannel* SoundPool::findNextChannel(int channelID)
{
for (int i = 0; i < mMaxChannels; ++i) {
if (mChannelPool[i].nextChannelID() == channelID) {
return &mChannelPool[i];
}
}
return NULL;
}
int SoundPool::load(const char* path, int priority)
{
LOGV("load: path=%s, priority=%d", path, priority);
Mutex::Autolock lock(&mLock);
sp<Sample> sample = new Sample(++mNextSampleID, path);
mSamples.add(sample->sampleID(), sample);
doLoad(sample);
return sample->sampleID();
}
int SoundPool::load(int fd, int64_t offset, int64_t length, int priority)
{
LOGV("load: fd=%d, offset=%lld, length=%lld, priority=%d",
fd, offset, length, priority);
Mutex::Autolock lock(&mLock);
sp<Sample> sample = new Sample(++mNextSampleID, fd, offset, length);
mSamples.add(sample->sampleID(), sample);
doLoad(sample);
return sample->sampleID();
}
void SoundPool::doLoad(sp<Sample>& sample)
{
LOGV("doLoad: loading sample sampleID=%d", sample->sampleID());
sample->startLoad();
mDecodeThread->loadSample(sample->sampleID());
}
bool SoundPool::unload(int sampleID)
{
LOGV("unload: sampleID=%d", sampleID);
Mutex::Autolock lock(&mLock);
return mSamples.removeItem(sampleID);
}
int SoundPool::play(int sampleID, float leftVolume, float rightVolume,
int priority, int loop, float rate)
{
LOGV("play sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f",
sampleID, leftVolume, rightVolume, priority, loop, rate);
sp<Sample> sample;
SoundChannel* channel;
int channelID;
Mutex::Autolock lock(&mLock);
if (mQuit) {
return 0;
}
// is sample ready?
sample = findSample(sampleID);
if ((sample == 0) || (sample->state() != Sample::READY)) {
LOGW(" sample %d not READY", sampleID);
return 0;
}
dump();
// allocate a channel
channel = allocateChannel_l(priority);
// no channel allocated - return 0
if (!channel) {
LOGV("No channel allocated");
return 0;
}
channelID = ++mNextChannelID;
LOGV("play channel %p state = %d", channel, channel->state());
channel->play(sample, channelID, leftVolume, rightVolume, priority, loop, rate);
return channelID;
}
SoundChannel* SoundPool::allocateChannel_l(int priority)
{
List<SoundChannel*>::iterator iter;
SoundChannel* channel = NULL;
// allocate a channel
if (!mChannels.empty()) {
iter = mChannels.begin();
if (priority >= (*iter)->priority()) {
channel = *iter;
mChannels.erase(iter);
LOGV("Allocated active channel");
}
}
// update priority and put it back in the list
if (channel) {
channel->setPriority(priority);
for (iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
if (priority < (*iter)->priority()) {
break;
}
}
mChannels.insert(iter, channel);
}
return channel;
}
// move a channel from its current position to the front of the list
void SoundPool::moveToFront_l(SoundChannel* channel)
{
for (List<SoundChannel*>::iterator iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
if (*iter == channel) {
mChannels.erase(iter);
mChannels.push_front(channel);
break;
}
}
}
void SoundPool::pause(int channelID)
{
LOGV("pause(%d)", channelID);
Mutex::Autolock lock(&mLock);
SoundChannel* channel = findChannel(channelID);
if (channel) {
channel->pause();
}
}
void SoundPool::autoPause()
{
LOGV("autoPause()");
Mutex::Autolock lock(&mLock);
for (int i = 0; i < mMaxChannels; ++i) {
SoundChannel* channel = &mChannelPool[i];
channel->autoPause();
}
}
void SoundPool::resume(int channelID)
{
LOGV("resume(%d)", channelID);
Mutex::Autolock lock(&mLock);
SoundChannel* channel = findChannel(channelID);
if (channel) {
channel->resume();
}
}
void SoundPool::autoResume()
{
LOGV("autoResume()");
Mutex::Autolock lock(&mLock);
for (int i = 0; i < mMaxChannels; ++i) {
SoundChannel* channel = &mChannelPool[i];
channel->autoResume();
}
}
void SoundPool::stop(int channelID)
{
LOGV("stop(%d)", channelID);
Mutex::Autolock lock(&mLock);
SoundChannel* channel = findChannel(channelID);
if (channel) {
channel->stop();
} else {
channel = findNextChannel(channelID);
if (channel)
channel->clearNextEvent();
}
}
void SoundPool::setVolume(int channelID, float leftVolume, float rightVolume)
{
Mutex::Autolock lock(&mLock);
SoundChannel* channel = findChannel(channelID);
if (channel) {
channel->setVolume(leftVolume, rightVolume);
}
}
void SoundPool::setPriority(int channelID, int priority)
{
LOGV("setPriority(%d, %d)", channelID, priority);
Mutex::Autolock lock(&mLock);
SoundChannel* channel = findChannel(channelID);
if (channel) {
channel->setPriority(priority);
}
}
void SoundPool::setLoop(int channelID, int loop)
{
LOGV("setLoop(%d, %d)", channelID, loop);
Mutex::Autolock lock(&mLock);
SoundChannel* channel = findChannel(channelID);
if (channel) {
channel->setLoop(loop);
}
}
void SoundPool::setRate(int channelID, float rate)
{
LOGV("setRate(%d, %f)", channelID, rate);
Mutex::Autolock lock(&mLock);
SoundChannel* channel = findChannel(channelID);
if (channel) {
channel->setRate(rate);
}
}
// call with lock held
void SoundPool::done_l(SoundChannel* channel)
{
LOGV("done_l(%d)", channel->channelID());
// if "stolen", play next event
if (channel->nextChannelID() != 0) {
LOGV("add to restart list");
addToRestartList(channel);
}
// return to idle state
else {
LOGV("move to front");
moveToFront_l(channel);
}
}
void SoundPool::setCallback(SoundPoolCallback* callback, void* user)
{
Mutex::Autolock lock(&mCallbackLock);
mCallback = callback;
mUserData = user;
}
void SoundPool::notify(SoundPoolEvent event)
{
Mutex::Autolock lock(&mCallbackLock);
if (mCallback != NULL) {
mCallback(event, this, mUserData);
}
}
void SoundPool::dump()
{
for (int i = 0; i < mMaxChannels; ++i) {
mChannelPool[i].dump();
}
}
Sample::Sample(int sampleID, const char* url)
{
init();
mSampleID = sampleID;
mUrl = strdup(url);
LOGV("create sampleID=%d, url=%s", mSampleID, mUrl);
}
Sample::Sample(int sampleID, int fd, int64_t offset, int64_t length)
{
init();
mSampleID = sampleID;
mFd = dup(fd);
mOffset = offset;
mLength = length;
LOGV("create sampleID=%d, fd=%d, offset=%lld, length=%lld", mSampleID, mFd, mLength, mOffset);
}
void Sample::init()
{
mData = 0;
mSize = 0;
mRefCount = 0;
mSampleID = 0;
mState = UNLOADED;
mFd = -1;
mOffset = 0;
mLength = 0;
mUrl = 0;
}
Sample::~Sample()
{
LOGV("Sample::destructor sampleID=%d, fd=%d", mSampleID, mFd);
if (mFd > 0) {
LOGV("close(%d)", mFd);
::close(mFd);
}
mData.clear();
delete mUrl;
}
status_t Sample::doLoad()
{
uint32_t sampleRate;
int numChannels;
int format;
sp<IMemory> p;
LOGV("Start decode");
if (mUrl) {
p = MediaPlayer::decode(mUrl, &sampleRate, &numChannels, &format);
} else {
p = MediaPlayer::decode(mFd, mOffset, mLength, &sampleRate, &numChannels, &format);
LOGV("close(%d)", mFd);
::close(mFd);
mFd = -1;
}
if (p == 0) {
LOGE("Unable to load sample: %s", mUrl);
return -1;
}
LOGV("pointer = %p, size = %u, sampleRate = %u, numChannels = %d",
p->pointer(), p->size(), sampleRate, numChannels);
if (sampleRate > kMaxSampleRate) {
LOGE("Sample rate (%u) out of range", sampleRate);
return - 1;
}
if ((numChannels < 1) || (numChannels > 2)) {
LOGE("Sample channel count (%d) out of range", numChannels);
return - 1;
}
//_dumpBuffer(p->pointer(), p->size());
uint8_t* q = static_cast<uint8_t*>(p->pointer()) + p->size() - 10;
//_dumpBuffer(q, 10, 10, false);
mData = p;
mSize = p->size();
mSampleRate = sampleRate;
mNumChannels = numChannels;
mFormat = format;
mState = READY;
return 0;
}
void SoundChannel::init(SoundPool* soundPool)
{
mSoundPool = soundPool;
}
// call with sound pool lock held
void SoundChannel::play(const sp<Sample>& sample, int nextChannelID, float leftVolume,
float rightVolume, int priority, int loop, float rate)
{
AudioTrack* oldTrack;
AudioTrack* newTrack;
status_t status;
{ // scope for the lock
Mutex::Autolock lock(&mLock);
LOGV("SoundChannel::play %p: sampleID=%d, channelID=%d, leftVolume=%f, rightVolume=%f,"
" priority=%d, loop=%d, rate=%f",
this, sample->sampleID(), nextChannelID, leftVolume, rightVolume,
priority, loop, rate);
// if not idle, this voice is being stolen
if (mState != IDLE) {
LOGV("channel %d stolen - event queued for channel %d", channelID(), nextChannelID);
mNextEvent.set(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
stop_l();
return;
}
// initialize track
int afFrameCount;
int afSampleRate;
int streamType = mSoundPool->streamType();
if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
afFrameCount = kDefaultFrameCount;
}
if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
afSampleRate = kDefaultSampleRate;
}
int numChannels = sample->numChannels();
uint32_t sampleRate = uint32_t(float(sample->sampleRate()) * rate + 0.5);
uint32_t totalFrames = (kDefaultBufferCount * afFrameCount * sampleRate) / afSampleRate;
uint32_t bufferFrames = (totalFrames + (kDefaultBufferCount - 1)) / kDefaultBufferCount;
uint32_t frameCount = 0;
if (loop) {
frameCount = sample->size()/numChannels/
((sample->format() == AudioSystem::PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t));
}
#ifndef USE_SHARED_MEM_BUFFER
// Ensure minimum audio buffer size in case of short looped sample
if(frameCount < totalFrames) {
frameCount = totalFrames;
}
#endif
// mToggle toggles each time a track is started on a given channel.
// The toggle is concatenated with the SoundChannel address and passed to AudioTrack
// as callback user data. This enables the detection of callbacks received from the old
// audio track while the new one is being started and avoids processing them with
// wrong audio audio buffer size (mAudioBufferSize)
unsigned long toggle = mToggle ^ 1;
void *userData = (void *)((unsigned long)this | toggle);
uint32_t channels = (numChannels == 2) ?
AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO;
// do not create a new audio track if current track is compatible with sample parameters
#ifdef USE_SHARED_MEM_BUFFER
newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
channels, sample->getIMemory(), 0, callback, userData);
#else
newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
channels, frameCount, 0, callback, userData, bufferFrames);
#endif
oldTrack = mAudioTrack;
status = newTrack->initCheck();
if (status != NO_ERROR) {
LOGE("Error creating AudioTrack");
goto exit;
}
LOGV("setVolume %p", newTrack);
newTrack->setVolume(leftVolume, rightVolume);
newTrack->setLoop(0, frameCount, loop);
// From now on, AudioTrack callbacks recevieved with previous toggle value will be ignored.
mToggle = toggle;
mAudioTrack = newTrack;
mPos = 0;
mSample = sample;
mChannelID = nextChannelID;
mPriority = priority;
mLoop = loop;
mLeftVolume = leftVolume;
mRightVolume = rightVolume;
mNumChannels = numChannels;
mRate = rate;
clearNextEvent();
mState = PLAYING;
mAudioTrack->start();
mAudioBufferSize = newTrack->frameCount()*newTrack->frameSize();
}
exit:
LOGV("delete oldTrack %p", oldTrack);
delete oldTrack;
if (status != NO_ERROR) {
delete newTrack;
mAudioTrack = NULL;
}
}
void SoundChannel::nextEvent()
{
sp<Sample> sample;
int nextChannelID;
float leftVolume;
float rightVolume;
int priority;
int loop;
float rate;
// check for valid event
{
Mutex::Autolock lock(&mLock);
nextChannelID = mNextEvent.channelID();
if (nextChannelID == 0) {
LOGV("stolen channel has no event");
return;
}
sample = mNextEvent.sample();
leftVolume = mNextEvent.leftVolume();
rightVolume = mNextEvent.rightVolume();
priority = mNextEvent.priority();
loop = mNextEvent.loop();
rate = mNextEvent.rate();
}
LOGV("Starting stolen channel %d -> %d", channelID(), nextChannelID);
play(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
}
void SoundChannel::callback(int event, void* user, void *info)
{
SoundChannel* channel = static_cast<SoundChannel*>((void *)((unsigned long)user & ~1));
channel->process(event, info, (unsigned long)user & 1);
}
void SoundChannel::process(int event, void *info, unsigned long toggle)
{
//LOGV("process(%d)", mChannelID);
Mutex::Autolock lock(&mLock);
AudioTrack::Buffer* b = NULL;
if (event == AudioTrack::EVENT_MORE_DATA) {
b = static_cast<AudioTrack::Buffer *>(info);
}
if (mToggle != toggle) {
LOGV("process wrong toggle %p channel %d", this, mChannelID);
if (b != NULL) {
b->size = 0;
}
return;
}
sp<Sample> sample = mSample;
// LOGV("SoundChannel::process event %d", event);
if (event == AudioTrack::EVENT_MORE_DATA) {
// check for stop state
if (b->size == 0) return;
if (mState == IDLE) {
b->size = 0;
return;
}
if (sample != 0) {
// fill buffer
uint8_t* q = (uint8_t*) b->i8;
size_t count = 0;
if (mPos < (int)sample->size()) {
uint8_t* p = sample->data() + mPos;
count = sample->size() - mPos;
if (count > b->size) {
count = b->size;
}
memcpy(q, p, count);
// LOGV("fill: q=%p, p=%p, mPos=%u, b->size=%u, count=%d", q, p, mPos, b->size, count);
} else if (mPos < mAudioBufferSize) {
count = mAudioBufferSize - mPos;
if (count > b->size) {
count = b->size;
}
memset(q, 0, count);
// LOGV("fill extra: q=%p, mPos=%u, b->size=%u, count=%d", q, mPos, b->size, count);
}
mPos += count;
b->size = count;
//LOGV("buffer=%p, [0]=%d", b->i16, b->i16[0]);
}
} else if (event == AudioTrack::EVENT_UNDERRUN) {
LOGV("process %p channel %d EVENT_UNDERRUN", this, mChannelID);
mSoundPool->addToStopList(this);
} else if (event == AudioTrack::EVENT_LOOP_END) {
LOGV("End loop %p channel %d count %d", this, mChannelID, *(int *)info);
}
}
// call with lock held
bool SoundChannel::doStop_l()
{
if (mState != IDLE) {
setVolume_l(0, 0);
LOGV("stop");
mAudioTrack->stop();
mSample.clear();
mState = IDLE;
mPriority = IDLE_PRIORITY;
return true;
}
return false;
}
// call with lock held and sound pool lock held
void SoundChannel::stop_l()
{
if (doStop_l()) {
mSoundPool->done_l(this);
}
}
// call with sound pool lock held
void SoundChannel::stop()
{
bool stopped;
{
Mutex::Autolock lock(&mLock);
stopped = doStop_l();
}
if (stopped) {
mSoundPool->done_l(this);
}
}
//FIXME: Pause is a little broken right now
void SoundChannel::pause()
{
Mutex::Autolock lock(&mLock);
if (mState == PLAYING) {
LOGV("pause track");
mState = PAUSED;
mAudioTrack->pause();
}
}
void SoundChannel::autoPause()
{
Mutex::Autolock lock(&mLock);
if (mState == PLAYING) {
LOGV("pause track");
mState = PAUSED;
mAutoPaused = true;
mAudioTrack->pause();
}
}
void SoundChannel::resume()
{
Mutex::Autolock lock(&mLock);
if (mState == PAUSED) {
LOGV("resume track");
mState = PLAYING;
mAutoPaused = false;
mAudioTrack->start();
}
}
void SoundChannel::autoResume()
{
Mutex::Autolock lock(&mLock);
if (mAutoPaused && (mState == PAUSED)) {
LOGV("resume track");
mState = PLAYING;
mAutoPaused = false;
mAudioTrack->start();
}
}
void SoundChannel::setRate(float rate)
{
Mutex::Autolock lock(&mLock);
if (mAudioTrack != 0 && mSample.get() != 0) {
uint32_t sampleRate = uint32_t(float(mSample->sampleRate()) * rate + 0.5);
mAudioTrack->setSampleRate(sampleRate);
mRate = rate;
}
}
// call with lock held
void SoundChannel::setVolume_l(float leftVolume, float rightVolume)
{
mLeftVolume = leftVolume;
mRightVolume = rightVolume;
if (mAudioTrack != 0) mAudioTrack->setVolume(leftVolume, rightVolume);
}
void SoundChannel::setVolume(float leftVolume, float rightVolume)
{
Mutex::Autolock lock(&mLock);
setVolume_l(leftVolume, rightVolume);
}
void SoundChannel::setLoop(int loop)
{
Mutex::Autolock lock(&mLock);
if (mAudioTrack != 0 && mSample.get() != 0) {
uint32_t loopEnd = mSample->size()/mNumChannels/
((mSample->format() == AudioSystem::PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t));
mAudioTrack->setLoop(0, loopEnd, loop);
mLoop = loop;
}
}
SoundChannel::~SoundChannel()
{
LOGV("SoundChannel destructor %p", this);
{
Mutex::Autolock lock(&mLock);
clearNextEvent();
doStop_l();
}
// do not call AudioTrack destructor with mLock held as it will wait for the AudioTrack
// callback thread to exit which may need to execute process() and acquire the mLock.
delete mAudioTrack;
}
void SoundChannel::dump()
{
LOGV("mState = %d mChannelID=%d, mNumChannels=%d, mPos = %d, mPriority=%d, mLoop=%d",
mState, mChannelID, mNumChannels, mPos, mPriority, mLoop);
}
void SoundEvent::set(const sp<Sample>& sample, int channelID, float leftVolume,
float rightVolume, int priority, int loop, float rate)
{
mSample =sample;
mChannelID = channelID;
mLeftVolume = leftVolume;
mRightVolume = rightVolume;
mPriority = priority;
mLoop = loop;
mRate =rate;
}
} // end namespace android
+238
View File
@@ -0,0 +1,238 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SOUNDPOOL_H_
#define SOUNDPOOL_H_
#include <utils/threads.h>
#include <utils/List.h>
#include <utils/Vector.h>
#include <utils/KeyedVector.h>
#include <media/AudioTrack.h>
namespace android {
static const int IDLE_PRIORITY = -1;
// forward declarations
class SoundEvent;
class SoundPoolThread;
class SoundPool;
// for queued events
class SoundPoolEvent {
public:
SoundPoolEvent(int msg, int arg1=0, int arg2=0) :
mMsg(msg), mArg1(arg1), mArg2(arg2) {}
int mMsg;
int mArg1;
int mArg2;
enum MessageType { INVALID, SAMPLE_LOADED };
};
// callback function prototype
typedef void SoundPoolCallback(SoundPoolEvent event, SoundPool* soundPool, void* user);
// tracks samples used by application
class Sample : public RefBase {
public:
enum sample_state { UNLOADED, LOADING, READY, UNLOADING };
Sample(int sampleID, const char* url);
Sample(int sampleID, int fd, int64_t offset, int64_t length);
~Sample();
int sampleID() { return mSampleID; }
int numChannels() { return mNumChannels; }
int sampleRate() { return mSampleRate; }
int format() { return mFormat; }
size_t size() { return mSize; }
int state() { return mState; }
uint8_t* data() { return static_cast<uint8_t*>(mData->pointer()); }
status_t doLoad();
void startLoad() { mState = LOADING; }
sp<IMemory> getIMemory() { return mData; }
// hack
void init(int numChannels, int sampleRate, int format, size_t size, sp<IMemory> data ) {
mNumChannels = numChannels; mSampleRate = sampleRate; mFormat = format; mSize = size; mData = data; }
private:
void init();
size_t mSize;
volatile int32_t mRefCount;
uint16_t mSampleID;
uint16_t mSampleRate;
uint8_t mState : 3;
uint8_t mNumChannels : 2;
uint8_t mFormat : 2;
int mFd;
int64_t mOffset;
int64_t mLength;
char* mUrl;
sp<IMemory> mData;
};
// stores pending events for stolen channels
class SoundEvent
{
public:
SoundEvent() : mChannelID(0), mLeftVolume(0), mRightVolume(0),
mPriority(IDLE_PRIORITY), mLoop(0), mRate(0) {}
void set(const sp<Sample>& sample, int channelID, float leftVolume,
float rightVolume, int priority, int loop, float rate);
sp<Sample> sample() { return mSample; }
int channelID() { return mChannelID; }
float leftVolume() { return mLeftVolume; }
float rightVolume() { return mRightVolume; }
int priority() { return mPriority; }
int loop() { return mLoop; }
float rate() { return mRate; }
void clear() { mChannelID = 0; mSample.clear(); }
protected:
sp<Sample> mSample;
int mChannelID;
float mLeftVolume;
float mRightVolume;
int mPriority;
int mLoop;
float mRate;
};
// for channels aka AudioTracks
class SoundChannel : public SoundEvent {
public:
enum state { IDLE, RESUMING, STOPPING, PAUSED, PLAYING };
SoundChannel() : mAudioTrack(0), mState(IDLE), mNumChannels(1),
mPos(0), mToggle(0), mAutoPaused(false) {}
~SoundChannel();
void init(SoundPool* soundPool);
void play(const sp<Sample>& sample, int channelID, float leftVolume, float rightVolume,
int priority, int loop, float rate);
void setVolume_l(float leftVolume, float rightVolume);
void setVolume(float leftVolume, float rightVolume);
void stop_l();
void stop();
void pause();
void autoPause();
void resume();
void autoResume();
void setRate(float rate);
int state() { return mState; }
void setPriority(int priority) { mPriority = priority; }
void setLoop(int loop);
int numChannels() { return mNumChannels; }
void clearNextEvent() { mNextEvent.clear(); }
void nextEvent();
int nextChannelID() { return mNextEvent.channelID(); }
void dump();
private:
static void callback(int event, void* user, void *info);
void process(int event, void *info, unsigned long toggle);
bool doStop_l();
SoundPool* mSoundPool;
AudioTrack* mAudioTrack;
SoundEvent mNextEvent;
Mutex mLock;
int mState;
int mNumChannels;
int mPos;
int mAudioBufferSize;
unsigned long mToggle;
bool mAutoPaused;
};
// application object for managing a pool of sounds
class SoundPool {
friend class SoundPoolThread;
friend class SoundChannel;
public:
SoundPool(int maxChannels, int streamType, int srcQuality);
~SoundPool();
int load(const char* url, int priority);
int load(int fd, int64_t offset, int64_t length, int priority);
bool unload(int sampleID);
int play(int sampleID, float leftVolume, float rightVolume, int priority,
int loop, float rate);
void pause(int channelID);
void autoPause();
void resume(int channelID);
void autoResume();
void stop(int channelID);
void setVolume(int channelID, float leftVolume, float rightVolume);
void setPriority(int channelID, int priority);
void setLoop(int channelID, int loop);
void setRate(int channelID, float rate);
int streamType() const { return mStreamType; }
int srcQuality() const { return mSrcQuality; }
// called from SoundPoolThread
void sampleLoaded(int sampleID);
// called from AudioTrack thread
void done_l(SoundChannel* channel);
// callback function
void setCallback(SoundPoolCallback* callback, void* user);
void* getUserData() { return mUserData; }
private:
SoundPool() {} // no default constructor
bool startThreads();
void doLoad(sp<Sample>& sample);
sp<Sample> findSample(int sampleID) { return mSamples.valueFor(sampleID); }
SoundChannel* findChannel (int channelID);
SoundChannel* findNextChannel (int channelID);
SoundChannel* allocateChannel_l(int priority);
void moveToFront_l(SoundChannel* channel);
void notify(SoundPoolEvent event);
void dump();
// restart thread
void addToRestartList(SoundChannel* channel);
void addToStopList(SoundChannel* channel);
static int beginThread(void* arg);
int run();
void quit();
Mutex mLock;
Mutex mRestartLock;
Condition mCondition;
SoundPoolThread* mDecodeThread;
SoundChannel* mChannelPool;
List<SoundChannel*> mChannels;
List<SoundChannel*> mRestart;
List<SoundChannel*> mStop;
DefaultKeyedVector< int, sp<Sample> > mSamples;
int mMaxChannels;
int mStreamType;
int mSrcQuality;
int mAllocated;
int mNextSampleID;
int mNextChannelID;
bool mQuit;
// callback
Mutex mCallbackLock;
SoundPoolCallback* mCallback;
void* mUserData;
};
} // end namespace android
#endif /*SOUNDPOOL_H_*/
@@ -0,0 +1,114 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//#define LOG_NDEBUG 0
#define LOG_TAG "SoundPoolThread"
#include "utils/Log.h"
#include "SoundPoolThread.h"
namespace android {
void SoundPoolThread::write(SoundPoolMsg msg) {
Mutex::Autolock lock(&mLock);
while (mMsgQueue.size() >= maxMessages) {
mCondition.wait(mLock);
}
// if thread is quitting, don't add to queue
if (mRunning) {
mMsgQueue.push(msg);
mCondition.signal();
}
}
const SoundPoolMsg SoundPoolThread::read() {
Mutex::Autolock lock(&mLock);
while (mMsgQueue.size() == 0) {
mCondition.wait(mLock);
}
SoundPoolMsg msg = mMsgQueue[0];
mMsgQueue.removeAt(0);
mCondition.signal();
return msg;
}
void SoundPoolThread::quit() {
Mutex::Autolock lock(&mLock);
if (mRunning) {
mRunning = false;
mMsgQueue.clear();
mMsgQueue.push(SoundPoolMsg(SoundPoolMsg::KILL, 0));
mCondition.signal();
mCondition.wait(mLock);
}
LOGV("return from quit");
}
SoundPoolThread::SoundPoolThread(SoundPool* soundPool) :
mSoundPool(soundPool)
{
mMsgQueue.setCapacity(maxMessages);
if (createThreadEtc(beginThread, this, "SoundPoolThread")) {
mRunning = true;
}
}
SoundPoolThread::~SoundPoolThread()
{
quit();
}
int SoundPoolThread::beginThread(void* arg) {
LOGV("beginThread");
SoundPoolThread* soundPoolThread = (SoundPoolThread*)arg;
return soundPoolThread->run();
}
int SoundPoolThread::run() {
LOGV("run");
for (;;) {
SoundPoolMsg msg = read();
LOGV("Got message m=%d, mData=%d", msg.mMessageType, msg.mData);
switch (msg.mMessageType) {
case SoundPoolMsg::KILL:
LOGV("goodbye");
return NO_ERROR;
case SoundPoolMsg::LOAD_SAMPLE:
doLoadSample(msg.mData);
break;
default:
LOGW("run: Unrecognized message %d\n",
msg.mMessageType);
break;
}
}
}
void SoundPoolThread::loadSample(int sampleID) {
write(SoundPoolMsg(SoundPoolMsg::LOAD_SAMPLE, sampleID));
}
void SoundPoolThread::doLoadSample(int sampleID) {
sp <Sample> sample = mSoundPool->findSample(sampleID);
status_t status = -1;
if (sample != 0) {
status = sample->doLoad();
}
mSoundPool->notify(SoundPoolEvent(SoundPoolEvent::SAMPLE_LOADED, sampleID, status));
}
} // end namespace android
@@ -0,0 +1,66 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SOUNDPOOLTHREAD_H_
#define SOUNDPOOLTHREAD_H_
#include <utils/threads.h>
#include <utils/Vector.h>
#include <media/AudioTrack.h>
#include "SoundPool.h"
namespace android {
class SoundPoolMsg {
public:
enum MessageType { INVALID, KILL, LOAD_SAMPLE };
SoundPoolMsg() : mMessageType(INVALID), mData(0) {}
SoundPoolMsg(MessageType MessageType, int data) :
mMessageType(MessageType), mData(data) {}
uint16_t mMessageType;
uint16_t mData;
};
/*
* This class handles background requests from the SoundPool
*/
class SoundPoolThread {
public:
SoundPoolThread(SoundPool* SoundPool);
~SoundPoolThread();
void loadSample(int sampleID);
void quit();
void write(SoundPoolMsg msg);
private:
static const size_t maxMessages = 5;
static int beginThread(void* arg);
int run();
void doLoadSample(int sampleID);
const SoundPoolMsg read();
Mutex mLock;
Condition mCondition;
Vector<SoundPoolMsg> mMsgQueue;
SoundPool* mSoundPool;
bool mRunning;
};
} // end namespace android
#endif /*SOUNDPOOLTHREAD_H_*/
@@ -0,0 +1,327 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
//#define LOG_NDEBUG 0
#define LOG_TAG "SoundPool-JNI"
#include <utils/Log.h>
#include <nativehelper/jni.h>
#include <nativehelper/JNIHelp.h>
#include <android_runtime/AndroidRuntime.h>
#include "SoundPool.h"
using namespace android;
static struct fields_t {
jfieldID mNativeContext;
jmethodID mPostEvent;
jclass mSoundPoolClass;
} fields;
static inline SoundPool* MusterSoundPool(JNIEnv *env, jobject thiz) {
return (SoundPool*)env->GetIntField(thiz, fields.mNativeContext);
}
// ----------------------------------------------------------------------------
static int
android_media_SoundPool_load_URL(JNIEnv *env, jobject thiz, jstring path, jint priority)
{
LOGV("android_media_SoundPool_load_URL");
SoundPool *ap = MusterSoundPool(env, thiz);
if (path == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
return 0;
}
const char* s = env->GetStringUTFChars(path, NULL);
int id = ap->load(s, priority);
env->ReleaseStringUTFChars(path, s);
return id;
}
static int
android_media_SoundPool_load_FD(JNIEnv *env, jobject thiz, jobject fileDescriptor,
jlong offset, jlong length, jint priority)
{
LOGV("android_media_SoundPool_load_FD");
SoundPool *ap = MusterSoundPool(env, thiz);
if (ap == NULL) return 0;
return ap->load(getParcelFileDescriptorFD(env, fileDescriptor),
int64_t(offset), int64_t(length), int(priority));
}
static bool
android_media_SoundPool_unload(JNIEnv *env, jobject thiz, jint sampleID) {
LOGV("android_media_SoundPool_unload\n");
SoundPool *ap = MusterSoundPool(env, thiz);
if (ap == NULL) return 0;
return ap->unload(sampleID);
}
static int
android_media_SoundPool_play(JNIEnv *env, jobject thiz, jint sampleID,
jfloat leftVolume, jfloat rightVolume, jint priority, jint loop,
jfloat rate)
{
LOGV("android_media_SoundPool_play\n");
SoundPool *ap = MusterSoundPool(env, thiz);
if (ap == NULL) return 0;
return ap->play(sampleID, leftVolume, rightVolume, priority, loop, rate);
}
static void
android_media_SoundPool_pause(JNIEnv *env, jobject thiz, jint channelID)
{
LOGV("android_media_SoundPool_pause");
SoundPool *ap = MusterSoundPool(env, thiz);
if (ap == NULL) return;
ap->pause(channelID);
}
static void
android_media_SoundPool_resume(JNIEnv *env, jobject thiz, jint channelID)
{
LOGV("android_media_SoundPool_resume");
SoundPool *ap = MusterSoundPool(env, thiz);
if (ap == NULL) return;
ap->resume(channelID);
}
static void
android_media_SoundPool_autoPause(JNIEnv *env, jobject thiz)
{
LOGV("android_media_SoundPool_autoPause");
SoundPool *ap = MusterSoundPool(env, thiz);
if (ap == NULL) return;
ap->autoPause();
}
static void
android_media_SoundPool_autoResume(JNIEnv *env, jobject thiz)
{
LOGV("android_media_SoundPool_autoResume");
SoundPool *ap = MusterSoundPool(env, thiz);
if (ap == NULL) return;
ap->autoResume();
}
static void
android_media_SoundPool_stop(JNIEnv *env, jobject thiz, jint channelID)
{
LOGV("android_media_SoundPool_stop");
SoundPool *ap = MusterSoundPool(env, thiz);
if (ap == NULL) return;
ap->stop(channelID);
}
static void
android_media_SoundPool_setVolume(JNIEnv *env, jobject thiz, jint channelID,
float leftVolume, float rightVolume)
{
LOGV("android_media_SoundPool_setVolume");
SoundPool *ap = MusterSoundPool(env, thiz);
if (ap == NULL) return;
ap->setVolume(channelID, leftVolume, rightVolume);
}
static void
android_media_SoundPool_setPriority(JNIEnv *env, jobject thiz, jint channelID,
int priority)
{
LOGV("android_media_SoundPool_setPriority");
SoundPool *ap = MusterSoundPool(env, thiz);
if (ap == NULL) return;
ap->setPriority(channelID, priority);
}
static void
android_media_SoundPool_setLoop(JNIEnv *env, jobject thiz, jint channelID,
int loop)
{
LOGV("android_media_SoundPool_setLoop");
SoundPool *ap = MusterSoundPool(env, thiz);
if (ap == NULL) return;
ap->setLoop(channelID, loop);
}
static void
android_media_SoundPool_setRate(JNIEnv *env, jobject thiz, jint channelID,
float rate)
{
LOGV("android_media_SoundPool_setRate");
SoundPool *ap = MusterSoundPool(env, thiz);
if (ap == NULL) return;
ap->setRate(channelID, rate);
}
static void android_media_callback(SoundPoolEvent event, SoundPool* soundPool, void* user)
{
LOGV("callback: (%d, %d, %d, %p, %p)", event.mMsg, event.mArg1, event.mArg2, soundPool, user);
JNIEnv *env = AndroidRuntime::getJNIEnv();
env->CallStaticVoidMethod(fields.mSoundPoolClass, fields.mPostEvent, user, event.mMsg, event.mArg1, event.mArg2, NULL);
}
static jint
android_media_SoundPool_native_setup(JNIEnv *env, jobject thiz, jobject weakRef, jint maxChannels, jint streamType, jint srcQuality)
{
LOGV("android_media_SoundPool_native_setup");
SoundPool *ap = new SoundPool(maxChannels, streamType, srcQuality);
if (ap == NULL) {
return -1;
}
// save pointer to SoundPool C++ object in opaque field in Java object
env->SetIntField(thiz, fields.mNativeContext, (int)ap);
// set callback with weak reference
jobject globalWeakRef = env->NewGlobalRef(weakRef);
ap->setCallback(android_media_callback, globalWeakRef);
return 0;
}
static void
android_media_SoundPool_release(JNIEnv *env, jobject thiz)
{
LOGV("android_media_SoundPool_release");
SoundPool *ap = MusterSoundPool(env, thiz);
if (ap != NULL) {
// release weak reference
jobject weakRef = (jobject) ap->getUserData();
if (weakRef != NULL) {
env->DeleteGlobalRef(weakRef);
}
// clear callback and native context
ap->setCallback(NULL, NULL);
env->SetIntField(thiz, fields.mNativeContext, 0);
delete ap;
}
}
// ----------------------------------------------------------------------------
// Dalvik VM type signatures
static JNINativeMethod gMethods[] = {
{ "_load",
"(Ljava/lang/String;I)I",
(void *)android_media_SoundPool_load_URL
},
{ "_load",
"(Ljava/io/FileDescriptor;JJI)I",
(void *)android_media_SoundPool_load_FD
},
{ "unload",
"(I)Z",
(void *)android_media_SoundPool_unload
},
{ "play",
"(IFFIIF)I",
(void *)android_media_SoundPool_play
},
{ "pause",
"(I)V",
(void *)android_media_SoundPool_pause
},
{ "resume",
"(I)V",
(void *)android_media_SoundPool_resume
},
{ "autoPause",
"()V",
(void *)android_media_SoundPool_autoPause
},
{ "autoResume",
"()V",
(void *)android_media_SoundPool_autoResume
},
{ "stop",
"(I)V",
(void *)android_media_SoundPool_stop
},
{ "setVolume",
"(IFF)V",
(void *)android_media_SoundPool_setVolume
},
{ "setPriority",
"(II)V",
(void *)android_media_SoundPool_setPriority
},
{ "setLoop",
"(II)V",
(void *)android_media_SoundPool_setLoop
},
{ "setRate",
"(IF)V",
(void *)android_media_SoundPool_setRate
},
{ "native_setup",
"(Ljava/lang/Object;III)I",
(void*)android_media_SoundPool_native_setup
},
{ "release",
"()V",
(void*)android_media_SoundPool_release
}
};
static const char* const kClassPathName = "android/media/SoundPool";
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env = NULL;
jint result = -1;
jclass clazz;
if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
LOGE("ERROR: GetEnv failed\n");
goto bail;
}
assert(env != NULL);
clazz = env->FindClass(kClassPathName);
if (clazz == NULL) {
LOGE("Can't find %s", kClassPathName);
goto bail;
}
fields.mNativeContext = env->GetFieldID(clazz, "mNativeContext", "I");
if (fields.mNativeContext == NULL) {
LOGE("Can't find SoundPool.mNativeContext");
goto bail;
}
fields.mPostEvent = env->GetStaticMethodID(clazz, "postEventFromNative",
"(Ljava/lang/Object;IIILjava/lang/Object;)V");
if (fields.mPostEvent == NULL) {
LOGE("Can't find android/media/SoundPool.postEventFromNative");
goto bail;
}
// create a reference to class. Technically, we're leaking this reference
// since it's a static object.
fields.mSoundPoolClass = (jclass) env->NewGlobalRef(clazz);
if (AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods)) < 0)
goto bail;
/* success -- return valid version number */
result = JNI_VERSION_1_4;
bail:
return result;
}