---
title: "Android Audio代码分析14 - testPlaybackHeadPositionIncrease"
author: "jandroid"
date: "2011-10-18T22:35:00Z"
tags: []
slug: "android-audio-14-testplaybackheadpositionincrease"
draft: false
lastmod: "2011-10-20T09:09:34Z"
id: 1202668
url: "https://jandroid.iteye.com/blog/1202668"
---

继续啃AudioTrack的测试代码。

\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*源码\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**  
//Test case 2: getPlaybackHeadPosition() increases after play()  
@LargeTest  
public void testPlaybackHeadPositionIncrease() throws Exception {  
// constants for test  
final String TEST\_NAME = "testPlaybackHeadPositionIncrease";  
final int TEST\_SR = 22050;  
final int TEST\_CONF = AudioFormat.CHANNEL\_OUT\_STEREO;  
final int TEST\_FORMAT = AudioFormat.ENCODING\_PCM\_16BIT;  
final int TEST\_MODE = AudioTrack.MODE\_STREAM;  
final int TEST\_STREAM\_TYPE = AudioManager.STREAM\_MUSIC;

//-------- initialization --------------  
int minBuffSize = AudioTrack.getMinBufferSize(TEST\_SR, TEST\_CONF, TEST\_FORMAT);  
AudioTrack track = new AudioTrack(TEST\_STREAM\_TYPE, TEST\_SR, TEST\_CONF, TEST\_FORMAT,  
minBuffSize, TEST\_MODE);  
byte data\[] = new byte\[minBuffSize/2];  
//-------- test --------------  
assumeTrue(TEST\_NAME, track.getState() == AudioTrack.STATE\_INITIALIZED);  
track.write(data, 0, data.length);  
track.write(data, 0, data.length);  
track.play();  
Thread.sleep(100);  
log(TEST\_NAME, "position ="+ track.getPlaybackHeadPosition());  
assertTrue(TEST\_NAME, track.getPlaybackHeadPosition() &gt; 0);  
//-------- tear down --------------  
track.release();  
}  
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**  
源码路径：  
frameworks\\base\\media\\tests\\mediaframeworktest\\src\\com\\android\\mediaframeworktest\\functional\\MediaAudioTrackTest.java

#######################说明################################  
//Test case 2: getPlaybackHeadPosition() increases after play()  
// 在上一篇关于getPlaybackHeadPosition的分析中，没有调用play函数，就调用了getPlaybackHeadPosition，所以获取的position应该为0.  
// 而本例子中，在write之后就调用了play，然后sleep了100ms，才调用的getPlaybackHeadPosition。  
// 也就是说，播放了100ms才去获取的位置，此时的位置当然应该大于0  
@LargeTest  
public void testPlaybackHeadPositionIncrease() throws Exception {  
// constants for test  
final String TEST\_NAME = "testPlaybackHeadPositionIncrease";  
final int TEST\_SR = 22050;  
final int TEST\_CONF = AudioFormat.CHANNEL\_OUT\_STEREO;  
final int TEST\_FORMAT = AudioFormat.ENCODING\_PCM\_16BIT;  
final int TEST\_MODE = AudioTrack.MODE\_STREAM;  
final int TEST\_STREAM\_TYPE = AudioManager.STREAM\_MUSIC;

//-------- initialization --------------  
int minBuffSize = AudioTrack.getMinBufferSize(TEST\_SR, TEST\_CONF, TEST\_FORMAT);  
AudioTrack track = new AudioTrack(TEST\_STREAM\_TYPE, TEST\_SR, TEST\_CONF, TEST\_FORMAT,  
minBuffSize, TEST\_MODE);  
byte data\[] = new byte\[minBuffSize/2];  
//-------- test --------------  
assumeTrue(TEST\_NAME, track.getState() == AudioTrack.STATE\_INITIALIZED);  
track.write(data, 0, data.length);  
track.write(data, 0, data.length);  
// 这次的引子是position如何被改变的  
// 既然播放之后，获取的position为正，那么play函数的调用就应该会导致position的改变。  
// 一起来看看play函数如何导致position改变的。  
track.play();  
++++++++++++++++++++++++++++++play++++++++++++++++++++++++++++++++++  
/\**  
\* Starts playing an AudioTrack.  
\* @throws IllegalStateException  
\*/  
public void play()  
throws IllegalStateException {  
if (mState != STATE\_INITIALIZED) {  
throw(new IllegalStateException("play() called on uninitialized AudioTrack."));  
}

synchronized(mPlayStateLock) {  
native\_start();  
++++++++++++++++++++++++++++++android\_media\_AudioTrack\_start++++++++++++++++++++++++++++++++++  
static void  
android\_media\_AudioTrack\_start(JNIEnv \*env, jobject thiz)  
{  
AudioTrack \*lpTrack = (AudioTrack \*)env-&gt;GetIntField(  
thiz, javaAudioTrackFields.nativeTrackInJavaObj);  
if (lpTrack == NULL ) {  
jniThrowException(env, "java/lang/IllegalStateException",  
"Unable to retrieve AudioTrack pointer for start()");  
return;  
}

lpTrack-&gt;start();  
++++++++++++++++++++++++++++++AudioTrack::start++++++++++++++++++++++++++++++++++  
void AudioTrack::start()  
{  
// mAudioTrackThread在函数AudioTrack::set中被赋值。  
sp&lt;AudioTrackThread&gt; t = mAudioTrackThread;  
status\_t status;

LOGV("start %p", this);  
if (t != 0) {  
// 函数exitPending返回成员变量mExitPending  
if (t-&gt;exitPending()) {  
if (t-&gt;requestExitAndWait() == WOULD\_BLOCK) {  
LOGE("AudioTrack::start called from thread");  
return;  
}  
}  
t-&gt;mLock.lock();  
}

if (android\_atomic\_or(1, &mActive) == 0) {  
mNewPosition = mCblk-&gt;server + mUpdatePeriod;  
mCblk-&gt;bufferTimeoutMs = MAX\_STARTUP\_TIMEOUT\_MS;  
mCblk-&gt;waitTimeMs = 0;  
mCblk-&gt;flags &= ~CBLK\_DISABLED\_ON;  
if (t != 0) {  
// 调用的是函数Thread::run  
t-&gt;run("AudioTrackThread", THREAD\_PRIORITY\_AUDIO\_CLIENT);  
+++++++++++++++++++++++++++++++Thread::run+++++++++++++++++++++++++++++++++  
status\_t Thread::run(const char* name, int32\_t priority, size\_t stack)  
{  
Mutex::Autolock \_l(mLock);

if (mRunning) {  
// thread already started  
return INVALID\_OPERATION;  
}

// reset status and exitPending to their default value, so we can  
// try again after an error happened (either below, or in readyToRun())  
mStatus = NO\_ERROR;  
// 在函数exitPending中会返回该成员变量  
mExitPending = false;  
mThread = thread\_id\_t(-1);

// hold a strong reference on ourself  
mHoldSelf = this;

mRunning = true;

bool res;  
// 我们调用函数AudioTrack::set的时候，将threadCanCallJava指定为了false  
if (mCanCallJava) {  
res = createThreadEtc(\_threadLoop,  
this, name, priority, stack, &mThread);  
+++++++++++++++++++++++++++++++createThreadEtc+++++++++++++++++++++++++++++++++  
// Create thread with lots of parameters  
inline bool createThreadEtc(thread\_func\_t entryFunction,  
void \*userData,  
const char* threadName = "android:unnamed\_thread",  
int32\_t threadPriority = PRIORITY\_DEFAULT,  
size\_t threadStackSize = 0,  
thread\_id\_t \*threadId = 0)  
{  
return androidCreateThreadEtc(entryFunction, userData, threadName,  
threadPriority, threadStackSize, threadId) ? true : false;  
+++++++++++++++++++++++++++++++++androidCreateThreadEtc+++++++++++++++++++++++++++++++  
int androidCreateThreadEtc(android\_thread\_func\_t entryFunction,  
void \*userData,  
const char* threadName,  
int32\_t threadPriority,  
size\_t threadStackSize,  
android\_thread\_id\_t \*threadId)  
{  
// gCreateThreadFn被初始化为androidCreateRawThreadEtc。  
// 函数androidSetCreateThreadFunc会对其赋值  
return gCreateThreadFn(entryFunction, userData, threadName,  
threadPriority, threadStackSize, threadId);  
++++++++++++++++++++++++++++++androidSetCreateThreadFunc++++++++++++++++++++++++++++++++++  
void androidSetCreateThreadFunc(android\_create\_thread\_fn func)  
{  
gCreateThreadFn = func;  
}

函数AndroidRuntime::startReg调用了函数androidSetCreateThreadFunc  
+++++++++++++++++++++++++++++AndroidRuntime::startReg+++++++++++++++++++++++++++++++++++  
/*  
\* Register android native functions with the VM.  
\*/  
/\*static\*/ int AndroidRuntime::startReg(JNIEnv* env)  
{  
/*  
\* This hook causes all future threads created in this process to be  
\* attached to the JavaVM. (This needs to go away in favor of JNI  
\* Attach calls.)  
\*/  
androidSetCreateThreadFunc((android\_create\_thread\_fn) javaCreateThreadEtc);  
+++++++++++++++++++++++++++javaCreateThreadEtc+++++++++++++++++++++++++++++++++++++  
/*  
\* This is invoked from androidCreateThreadEtc() via the callback  
\* set with androidSetCreateThreadFunc().  
\*  
\* We need to create the new thread in such a way that it gets hooked  
\* into the VM before it really starts executing.  
\*/  
/\*static\*/ int AndroidRuntime::javaCreateThreadEtc(  
android\_thread\_func\_t entryFunction,  
void* userData,  
const char* threadName,  
int32\_t threadPriority,  
size\_t threadStackSize,  
android\_thread\_id\_t* threadId)  
{  
void\** args = (void\*\*) malloc(3 * sizeof(void\*)); // javaThreadShell must free  
int result;

assert(threadName != NULL);

args\[0] = (void\*) entryFunction;  
args\[1] = userData;  
args\[2] = (void\*) strdup(threadName); // javaThreadShell must free

// 如果可以从java层调用的话，就在thread外包了层壳  
result = androidCreateRawThreadEtc(AndroidRuntime::javaThreadShell, args,  
threadName, threadPriority, threadStackSize, threadId);  
return result;  
}  
\---------------------------javaCreateThreadEtc-------------------------------------

LOGV("--- registering native functions ---\\n");

/*  
\* Every "register" function calls one or more things that return  
\* a local reference (e.g. FindClass). Because we haven't really  
\* started the VM yet, they're all getting stored in the base frame  
\* and never released. Use Push/Pop to manage the storage.  
\*/  
env-&gt;PushLocalFrame(200);

if (register\_jni\_procs(gRegJNI, NELEM(gRegJNI), env) &lt; 0) {  
env-&gt;PopLocalFrame(NULL);  
return -1;  
}  
env-&gt;PopLocalFrame(NULL);

//createJavaThread("fubar", quickTest, (void\*) "hello");

return 0;  
}

函数AndroidRuntime::start调用了函数AndroidRuntime::startReg。  
++++++++++++++++++++++++++++++AndroidRuntime::start++++++++++++++++++++++++++++++++++  
/*  
\* Start the Android runtime. This involves starting the virtual machine  
\* and calling the "static void main(String\[] args)" method in the class  
\* named by "className".  
\*/  
void AndroidRuntime::start(const char* className, const bool startSystemServer)  
{  
LOGD("\\n&gt;&gt;&gt;&gt;&gt;&gt; AndroidRuntime START %s &lt;&lt;&lt;&lt;&lt;&lt;\\n",  
className != NULL ? className : "(unknown)");

char* slashClassName = NULL;  
char* cp;  
JNIEnv* env;

blockSigpipe();

/*  
\* 'startSystemServer == true' means runtime is obslete and not run from  
\* init.rc anymore, so we print out the boot start event here.  
\*/  
if (startSystemServer) {  
/* track our progress through the boot sequence \*/  
const int LOG\_BOOT\_PROGRESS\_START = 3000;  
LOG\_EVENT\_LONG(LOG\_BOOT\_PROGRESS\_START,  
ns2ms(systemTime(SYSTEM\_TIME\_MONOTONIC)));  
}

const char* rootDir = getenv("ANDROID\_ROOT");  
if (rootDir == NULL) {  
rootDir = "/system";  
if (!hasDir("/system")) {  
LOG\_FATAL("No root directory specified, and /android does not exist.");  
goto bail;  
}  
setenv("ANDROID\_ROOT", rootDir, 1);  
}

//const char* kernelHack = getenv("LD\_ASSUME\_KERNEL");  
//LOGD("Found LD\_ASSUME\_KERNEL='%s'\\n", kernelHack);

/* start the virtual machine \*/  
if (startVm(&mJavaVM, &env) != 0)  
goto bail;

/*  
\* Register android functions.  
\*/  
if (startReg(env) &lt; 0) {  
LOGE("Unable to register all android natives\\n");  
goto bail;  
}

/*  
\* We want to call main() with a String array with arguments in it.  
\* At present we only have one argument, the class name. Create an  
\* array to hold it.  
\*/  
jclass stringClass;  
jobjectArray strArray;  
jstring classNameStr;  
jstring startSystemServerStr;

stringClass = env-&gt;FindClass("java/lang/String");  
assert(stringClass != NULL);  
strArray = env-&gt;NewObjectArray(2, stringClass, NULL);  
assert(strArray != NULL);  
classNameStr = env-&gt;NewStringUTF(className);  
assert(classNameStr != NULL);  
env-&gt;SetObjectArrayElement(strArray, 0, classNameStr);  
startSystemServerStr = env-&gt;NewStringUTF(startSystemServer ?  
"true" : "false");  
env-&gt;SetObjectArrayElement(strArray, 1, startSystemServerStr);

/*  
\* Start VM. This thread becomes the main thread of the VM, and will  
\* not return until the VM exits.  
\*/  
jclass startClass;  
jmethodID startMeth;

slashClassName = strdup(className);  
for (cp = slashClassName; \*cp != '\\0'; cp++)  
if (\*cp == '.')  
\*cp = '/';

startClass = env-&gt;FindClass(slashClassName);  
if (startClass == NULL) {  
LOGE("JavaVM unable to locate class '%s'\\n", slashClassName);  
/* keep going \*/  
} else {  
startMeth = env-&gt;GetStaticMethodID(startClass, "main",  
"([Ljava/lang/String;)V");  
if (startMeth == NULL) {  
LOGE("JavaVM unable to find main() in '%s'\\n", className);  
/* keep going \*/  
} else {  
env-&gt;CallStaticVoidMethod(startClass, startMeth, strArray);

#if 0  
if (env-&gt;ExceptionCheck())  
threadExitUncaughtException(env);  
#endif  
}  
}

LOGD("Shutting down VM\\n");  
if (mJavaVM-&gt;DetachCurrentThread() != JNI\_OK)  
LOGW("Warning: unable to detach main thread\\n");  
if (mJavaVM-&gt;DestroyJavaVM() != 0)  
LOGW("Warning: VM did not shut down cleanly\\n");

bail:  
free(slashClassName);  
}  
\------------------------------AndroidRuntime::start----------------------------------  
\-----------------------------AndroidRuntime::startReg-----------------------------------  
\------------------------------androidSetCreateThreadFunc----------------------------------  
}  
\---------------------------------androidCreateThreadEtc-------------------------------  
}  
\-------------------------------createThreadEtc---------------------------------  
} else {  
res = androidCreateRawThreadEtc(\_threadLoop,  
this, name, priority, stack, &mThread);  
+++++++++++++++++++++++++++++++androidCreateRawThreadEtc+++++++++++++++++++++++++++++++++  
函数androidCreateRawThreadEtc有两种实现。

#if defined(HAVE\_PTHREADS)

int androidCreateRawThreadEtc(android\_thread\_func\_t entryFunction,  
void \*userData,  
const char* threadName,  
int32\_t threadPriority,  
size\_t threadStackSize,  
android\_thread\_id\_t \*threadId)  
{  
pthread\_attr\_t attr;  
pthread\_attr\_init(&attr);  
pthread\_attr\_setdetachstate(&attr, PTHREAD\_CREATE\_DETACHED);

#ifdef HAVE\_ANDROID\_OS /* valgrind is rejecting RT-priority create reqs \*/  
if (threadPriority != PRIORITY\_DEFAULT || threadName != NULL) {  
// We could avoid the trampoline if there was a way to get to the  
// android\_thread\_id\_t (pid) from pthread\_t  
thread\_data\_t* t = new thread\_data\_t;  
t-&gt;priority = threadPriority;  
t-&gt;threadName = threadName ? strdup(threadName) : NULL;  
t-&gt;entryFunction = entryFunction;  
t-&gt;userData = userData;  
entryFunction = (android\_thread\_func\_t)&thread\_data\_t::trampoline;  
userData = t;  
}  
#endif

if (threadStackSize) {  
pthread\_attr\_setstacksize(&attr, threadStackSize);  
}

errno = 0;  
pthread\_t thread;  
int result = pthread\_create(&thread, &attr,  
(android\_pthread\_entry)entryFunction, userData);  
if (result != 0) {  
LOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\\n"  
"(android threadPriority=%d)",  
entryFunction, result, errno, threadPriority);  
return 0;  
}

if (threadId != NULL) {  
\*threadId = (android\_thread\_id\_t)thread; // XXX: this is not portable  
}  
return 1;  
}

#elif defined(HAVE\_WIN32\_THREADS)

int androidCreateRawThreadEtc(android\_thread\_func\_t fn,  
void \*userData,  
const char* threadName,  
int32\_t threadPriority,  
size\_t threadStackSize,  
android\_thread\_id\_t \*threadId)  
{  
return doCreateThread( fn, userData, threadId);  
++++++++++++++++++++++++++++++doCreateThread++++++++++++++++++++++++++++++++++  
/*  
\* Create and run a new thread.  
\*/  
static bool doCreateThread(android\_thread\_func\_t fn, void* arg, android\_thread\_id\_t \*id)  
{  
HANDLE hThread;  
struct threadDetails* pDetails = new threadDetails; // must be on heap  
unsigned int thrdaddr;

pDetails-&gt;func = fn;  
pDetails-&gt;arg = arg;

#if defined(HAVE\_\_BEGINTHREADEX)  
hThread = (HANDLE) \_beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,  
&thrdaddr);  
if (hThread == 0)  
#elif defined(HAVE\_CREATETHREAD)  
hThread = CreateThread(NULL, 0,  
(LPTHREAD\_START\_ROUTINE) threadIntermediary,  
(void\*) pDetails, 0, (DWORD\*) &thrdaddr);  
if (hThread == NULL)  
#endif  
{  
LOG(LOG\_WARN, "thread", "WARNING: thread create failed\\n");  
return false;  
}

#if defined(HAVE\_CREATETHREAD)  
/* close the management handle \*/  
CloseHandle(hThread);  
#endif

if (id != NULL) {  
\*id = (android\_thread\_id\_t)thrdaddr;  
}

return true;  
}  
\------------------------------doCreateThread----------------------------------  
}

#endif  
\-------------------------------androidCreateRawThreadEtc---------------------------------  
}

if (res == false) {  
mStatus = UNKNOWN\_ERROR; // something happened!  
mRunning = false;  
mThread = thread\_id\_t(-1);  
mHoldSelf.clear(); // "this" may have gone away after this.

return UNKNOWN\_ERROR;  
}

// Do not refer to mStatus here: The thread is already running (may, in fact  
// already have exited with a valid mStatus result). The NO\_ERROR indication  
// here merely indicates successfully starting the thread and does not  
// imply successful termination/execution.  
return NO\_ERROR;  
}

// 在上面创建线程的时候，我们传入的是函数\_threadLoop。  
++++++++++++++++++++++++++++Thread::\_threadLoop++++++++++++++++++++++++++++++++++++  
int Thread::\_threadLoop(void* user)  
{  
Thread* const self = static\_cast&lt;Thread\*&gt;(user);  
sp&lt;Thread&gt; strong(self-&gt;mHoldSelf);  
wp&lt;Thread&gt; weak(strong);  
self-&gt;mHoldSelf.clear();

#if HAVE\_ANDROID\_OS  
// this is very useful for debugging with gdb  
self-&gt;mTid = gettid();  
#endif

bool first = true;

do {  
bool result;  
if (first) {  
first = false;  
self-&gt;mStatus = self-&gt;readyToRun();  
result = (self-&gt;mStatus == NO\_ERROR);

if (result && !self-&gt;mExitPending) {  
// Binder threads (and maybe others) rely on threadLoop  
// running at least once after a successful ::readyToRun()  
// (unless, of course, the thread has already been asked to exit  
// at that point).  
// This is because threads are essentially used like this:  
// (new ThreadSubclass())-&gt;run();  
// The caller therefore does not retain a strong reference to  
// the thread and the thread would simply disappear after the  
// successful ::readyToRun() call instead of entering the  
// threadLoop at least once.  
// 可见，最终调用的还是各thread的threadLoop函数  
result = self-&gt;threadLoop();  
+++++++++++++++++++++++++++AudioTrack::AudioTrackThread::threadLoop+++++++++++++++++++++++++++++++++++++  
bool AudioTrack::AudioTrackThread::threadLoop()  
{  
// 调用的其实是函数AudioTrack::processAudioBuffer  
return mReceiver.processAudioBuffer(this);  
++++++++++++++++++++++++++++AudioTrack::processAudioBuffer++++++++++++++++++++++++++++++++++++  
bool AudioTrack::processAudioBuffer(const sp&lt;AudioTrackThread&gt;& thread)  
{  
Buffer audioBuffer;  
uint32\_t frames;  
size\_t writtenSize;

// Manage underrun callback  
if (mActive && (mCblk-&gt;framesReady() == 0)) {  
LOGV("Underrun user: %x, server: %x, flags %04x", mCblk-&gt;user, mCblk-&gt;server, mCblk-&gt;flags);  
if ((mCblk-&gt;flags & CBLK\_UNDERRUN\_MSK) == CBLK\_UNDERRUN\_OFF) {  
mCbf(EVENT\_UNDERRUN, mUserData, 0);  
if (mCblk-&gt;server == mCblk-&gt;frameCount) {  
// 函数指针mCbf指向的是函数audioCallback  
mCbf(EVENT\_BUFFER\_END, mUserData, 0);  
++++++++++++++++++++++++++++audioCallback++++++++++++++++++++++++++++++++++++  
static void audioCallback(int event, void* user, void \*info) {  
if (event == AudioTrack::EVENT\_MORE\_DATA) {  
// set size to 0 to signal we're not using the callback to write more data  
AudioTrack::Buffer* pBuff = (AudioTrack::Buffer\*)info;  
pBuff-&gt;size = 0;

} else if (event == AudioTrack::EVENT\_MARKER) {  
audiotrack\_callback\_cookie \*callbackInfo = (audiotrack\_callback\_cookie \*)user;  
JNIEnv \*env = AndroidRuntime::getJNIEnv();  
if (user && env) {  
env-&gt;CallStaticVoidMethod(  
callbackInfo-&gt;audioTrack\_class,  
javaAudioTrackFields.postNativeEventInJava,  
callbackInfo-&gt;audioTrack\_ref, event, 0,0, NULL);  
if (env-&gt;ExceptionCheck()) {  
env-&gt;ExceptionDescribe();  
env-&gt;ExceptionClear();  
}  
}

} else if (event == AudioTrack::EVENT\_NEW\_POS) {  
audiotrack\_callback\_cookie \*callbackInfo = (audiotrack\_callback\_cookie \*)user;  
JNIEnv \*env = AndroidRuntime::getJNIEnv();  
if (user && env) {  
env-&gt;CallStaticVoidMethod(  
callbackInfo-&gt;audioTrack\_class,  
javaAudioTrackFields.postNativeEventInJava,  
callbackInfo-&gt;audioTrack\_ref, event, 0,0, NULL);  
if (env-&gt;ExceptionCheck()) {  
env-&gt;ExceptionDescribe();  
env-&gt;ExceptionClear();  
}  
}  
}  
}  
\----------------------------audioCallback------------------------------------  
}  
mCblk-&gt;flags |= CBLK\_UNDERRUN\_ON;  
if (mSharedBuffer != 0) return false;  
}  
}

// Manage loop end callback  
while (mLoopCount &gt; mCblk-&gt;loopCount) {  
int loopCount = -1;  
mLoopCount--;  
if (mLoopCount &gt;= 0) loopCount = mLoopCount;

mCbf(EVENT\_LOOP\_END, mUserData, (void \*)&loopCount);  
}

// Manage marker callback  
if (!mMarkerReached && (mMarkerPosition &gt; 0)) {  
if (mCblk-&gt;server &gt;= mMarkerPosition) {  
mCbf(EVENT\_MARKER, mUserData, (void \*)&mMarkerPosition);  
mMarkerReached = true;  
}  
}

// Manage new position callback  
if (mUpdatePeriod &gt; 0) {  
while (mCblk-&gt;server &gt;= mNewPosition) {  
mCbf(EVENT\_NEW\_POS, mUserData, (void \*)&mNewPosition);  
mNewPosition += mUpdatePeriod;  
}  
}

// If Shared buffer is used, no data is requested from client.  
if (mSharedBuffer != 0) {  
frames = 0;  
} else {  
frames = mRemainingFrames;  
}

do {

audioBuffer.frameCount = frames;

// Calling obtainBuffer() with a wait count of 1  
// limits wait time to WAIT\_PERIOD\_MS. This prevents from being  
// stuck here not being able to handle timed events (position, markers, loops).  
status\_t err = obtainBuffer(&audioBuffer, 1);  
if (err &lt; NO\_ERROR) {  
if (err != TIMED\_OUT) {  
LOGE\_IF(err != status\_t(NO\_MORE\_BUFFERS), "Error obtaining an audio buffer, giving up.");  
return false;  
}  
break;  
}  
if (err == status\_t(STOPPED)) return false;

// Divide buffer size by 2 to take into account the expansion  
// due to 8 to 16 bit conversion: the callback must fill only half  
// of the destination buffer  
if (mFormat == AudioSystem::PCM\_8\_BIT && !(mFlags & AudioSystem::OUTPUT\_FLAG\_DIRECT)) {  
audioBuffer.size &gt;&gt;= 1;  
}

size\_t reqSize = audioBuffer.size;  
mCbf(EVENT\_MORE\_DATA, mUserData, &audioBuffer);  
writtenSize = audioBuffer.size;

// Sanity check on returned size  
if (ssize\_t(writtenSize) &lt;= 0) {  
// The callback is done filling buffers  
// Keep this thread going to handle timed events and  
// still try to get more data in intervals of WAIT\_PERIOD\_MS  
// but don't just loop and block the CPU, so wait  
usleep(WAIT\_PERIOD\_MS\*1000);  
break;  
}  
if (writtenSize &gt; reqSize) writtenSize = reqSize;

if (mFormat == AudioSystem::PCM\_8\_BIT && !(mFlags & AudioSystem::OUTPUT\_FLAG\_DIRECT)) {  
// 8 to 16 bit conversion  
const int8\_t \*src = audioBuffer.i8 + writtenSize-1;  
int count = writtenSize;  
int16\_t \*dst = audioBuffer.i16 + writtenSize-1;  
while(count--) {  
\*dst-- = (int16\_t)(\*src--^0x80) &lt;&lt; 8;  
}  
writtenSize &lt;&lt;= 1;  
}

audioBuffer.size = writtenSize;  
// NOTE: mCblk-&gt;frameSize is not equal to AudioTrack::frameSize() for  
// 8 bit PCM data: in this case, mCblk-&gt;frameSize is based on a sampel size of  
// 16 bit.  
audioBuffer.frameCount = writtenSize/mCblk-&gt;frameSize;

frames -= audioBuffer.frameCount;

releaseBuffer(&audioBuffer);  
}  
while (frames);

if (frames == 0) {  
mRemainingFrames = mNotificationFramesAct;  
} else {  
mRemainingFrames = frames;  
}  
return true;  
}  
\----------------------------AudioTrack::processAudioBuffer------------------------------------  
}  
\---------------------------AudioTrack::AudioTrackThread::threadLoop-------------------------------------  
}  
} else {  
result = self-&gt;threadLoop();  
}

if (result == false || self-&gt;mExitPending) {  
self-&gt;mExitPending = true;  
self-&gt;mLock.lock();  
self-&gt;mRunning = false;  
// clear thread ID so that requestExitAndWait() does not exit if  
// called by a new thread using the same thread ID as this one.  
self-&gt;mThread = thread\_id\_t(-1);  
self-&gt;mThreadExitedCondition.broadcast();  
self-&gt;mThread = thread\_id\_t(-1); // thread id could be reused  
self-&gt;mLock.unlock();  
break;  
}

// Release our strong reference, to let a chance to the thread  
// to die a peaceful death.  
strong.clear();  
// And immediately, re-acquire a strong reference for the next loop  
strong = weak.promote();  
} while(strong != 0);

return 0;  
}  
\----------------------------Thread::\_threadLoop------------------------------------  
\-------------------------------Thread::run---------------------------------  
} else {  
setpriority(PRIO\_PROCESS, 0, THREAD\_PRIORITY\_AUDIO\_CLIENT);  
}

if (mCblk-&gt;flags & CBLK\_INVALID\_MSK) {  
LOGW("start() track %p invalidated, creating a new one", this);  
// no need to clear the invalid flag as this cblk will not be used anymore  
// force new track creation  
status = DEAD\_OBJECT;  
} else {  
// mAudioTrack在函数AudioTrack::createTrack中被赋值，其最终指向的其实是一个TrackHandle对象  
status = mAudioTrack-&gt;start();  
+++++++++++++++++++++++++++AudioFlinger::TrackHandle::start+++++++++++++++++++++++++++++++++++++  
status\_t AudioFlinger::TrackHandle::start() {  
return mTrack-&gt;start();  
+++++++++++++++++++++++++++++++AudioFlinger::PlaybackThread::Track::start+++++++++++++++++++++++++++++++++  
status\_t AudioFlinger::PlaybackThread::Track::start()  
{  
status\_t status = NO\_ERROR;  
LOGV("start(%d), calling thread %d session %d",  
mName, IPCThreadState::self()-&gt;getCallingPid(), mSessionId);  
sp&lt;ThreadBase&gt; thread = mThread.promote();  
if (thread != 0) {  
Mutex::Autolock \_l(thread-&gt;mLock);  
int state = mState;  
// here the track could be either new, or restarted  
// in both cases "unstop" the track  
if (mState == PAUSED) {  
mState = TrackBase::RESUMING;  
LOGV("PAUSED =&gt; RESUMING (%d) on thread %p", mName, this);  
} else {  
mState = TrackBase::ACTIVE;  
LOGV("? =&gt; ACTIVE (%d) on thread %p", mName, this);  
}

if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {  
thread-&gt;mLock.unlock();  
status = AudioSystem::startOutput(thread-&gt;id(),  
(AudioSystem::stream\_type)mStreamType,  
mSessionId);  
+++++++++++++++++++++++AudioSystem::startOutput+++++++++++++++++++++++++++++++++++++++++  
status\_t AudioSystem::startOutput(audio\_io\_handle\_t output,  
AudioSystem::stream\_type stream,  
int session)  
{  
const sp&lt;IAudioPolicyService&gt;& aps = AudioSystem::get\_audio\_policy\_service();  
if (aps == 0) return PERMISSION\_DENIED;  
return aps-&gt;startOutput(output, stream, session);  
++++++++++++++++++++++++AudioPolicyService::startOutput++++++++++++++++++++++++++++++++++++++++  
status\_t AudioPolicyService::startOutput(audio\_io\_handle\_t output,  
AudioSystem::stream\_type stream,  
int session)  
{  
if (mpPolicyManager == NULL) {  
return NO\_INIT;  
}  
LOGV("startOutput() tid %d", gettid());  
Mutex::Autolock \_l(mLock);  
return mpPolicyManager-&gt;startOutput(output, stream, session);  
+++++++++++++++++++++++++++AudioPolicyManagerBase::startOutput+++++++++++++++++++++++++++++++++++++  
status\_t AudioPolicyManagerBase::startOutput(audio\_io\_handle\_t output,  
AudioSystem::stream\_type stream,  
int session)  
{  
LOGV("startOutput() output %d, stream %d, session %d", output, stream, session);  
// 函数AudioPolicyManagerBase::addOutput调用了函数mOutputs.add往mOutputs添加成员  
ssize\_t index = mOutputs.indexOfKey(output);  
+++++++++++++++++++++++++++++AudioPolicyManagerBase::addOutput+++++++++++++++++++++++++++++++++++  
void AudioPolicyManagerBase::addOutput(audio\_io\_handle\_t id, AudioOutputDescriptor \*outputDesc)  
{  
outputDesc-&gt;mId = id;  
mOutputs.add(id, outputDesc);  
}

类AudioPolicyManagerBase中有几处调用了函数AudioPolicyManagerBase::addOutput。  
一般是调用mpClientInterface-&gt;openOutput函数后，会调用函数AudioPolicyManagerBase::addOutput将output添加到mOutputs。  
（mpClientInterface其实是一个AudioPolicyService对象）  
例如：  
函数AudioPolicyManagerBase::getOutput和AudioPolicyManagerBase的构造函数。  
创建AudioTrack对象的时候，在函数AudioTrack::set中会调用函数AudioPolicyManagerBase::getOutput。  
AudioPolicyManagerBase对象是在AudioPolicyService的构造函数中被创建。  
\-----------------------------AudioPolicyManagerBase::addOutput-----------------------------------  
if (index &lt; 0) {  
LOGW("startOutput() unknow output %d", output);  
return BAD\_VALUE;  
}

// 在mOutputs中，output作为key，outputDesc作为value。  
AudioOutputDescriptor \*outputDesc = mOutputs.valueAt(index);  
// 函数getStrategy就是根据stream type返回特定的strategy。  
routing\_strategy strategy = getStrategy((AudioSystem::stream\_type)stream);

#ifdef WITH\_A2DP  
if (mA2dpOutput != 0 && !a2dpUsedForSonification() && strategy == STRATEGY\_SONIFICATION) {  
setStrategyMute(STRATEGY\_MEDIA, true, mA2dpOutput);  
++++++++++++++++++++++++++++AudioPolicyManagerBase::setStrategyMute++++++++++++++++++++++++++++++++++++  
void AudioPolicyManagerBase::setStrategyMute(routing\_strategy strategy, bool on, audio\_io\_handle\_t output, int delayMs)  
{  
LOGV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);  
// 将strategy对应的stream全部mute  
for (int stream = 0; stream &lt; AudioSystem::NUM\_STREAM\_TYPES; stream++) {  
if (getStrategy((AudioSystem::stream\_type)stream) == strategy) {  
setStreamMute(stream, on, output, delayMs);  
+++++++++++++++++++++++++++++AudioPolicyManagerBase::setStreamMute+++++++++++++++++++++++++++++++++++  
void AudioPolicyManagerBase::setStreamMute(int stream, bool on, audio\_io\_handle\_t output, int delayMs)  
{  
StreamDescriptor &streamDesc = mStreams\[stream];  
++++++++++++++++++++++++++++++StreamDescriptor++++++++++++++++++++++++++++++++++  
// stream descriptor used for volume control  
class StreamDescriptor  
{  
public:  
StreamDescriptor()  
: mIndexMin(0), mIndexMax(1), mIndexCur(1), mCanBeMuted(true) {}

void dump(char* buffer, size\_t size);

int mIndexMin; // min volume index  
int mIndexMax; // max volume index  
int mIndexCur; // current volume index  
bool mCanBeMuted; // true is the stream can be muted  
};  
\------------------------------StreamDescriptor----------------------------------  
AudioOutputDescriptor \*outputDesc = mOutputs.valueFor(output);  
++++++++++++++++++++++++++++++AudioOutputDescriptor++++++++++++++++++++++++++++++++++  
// descriptor for audio outputs. Used to maintain current configuration of each opened audio output  
// and keep track of the usage of this output by each audio stream type.  
class AudioOutputDescriptor  
{  
public:  
AudioOutputDescriptor();

status\_t dump(int fd);

uint32\_t device();  
void changeRefCount(AudioSystem::stream\_type, int delta);  
uint32\_t refCount();  
uint32\_t strategyRefCount(routing\_strategy strategy);  
bool isUsedByStrategy(routing\_strategy strategy) { return (strategyRefCount(strategy) != 0);}  
bool isDuplicated() { return (mOutput1 != NULL && mOutput2 != NULL); }

audio\_io\_handle\_t mId; // output handle  
uint32\_t mSamplingRate; //  
uint32\_t mFormat; //  
uint32\_t mChannels; // output configuration  
uint32\_t mLatency; //  
AudioSystem::output\_flags mFlags; //  
uint32\_t mDevice; // current device this output is routed to  
uint32\_t mRefCount\[AudioSystem::NUM\_STREAM\_TYPES]; // number of streams of each type using this output  
AudioOutputDescriptor \*mOutput1; // used by duplicated outputs: first output  
AudioOutputDescriptor \*mOutput2; // used by duplicated outputs: second output  
float mCurVolume\[AudioSystem::NUM\_STREAM\_TYPES]; // current stream volume  
int mMuteCount\[AudioSystem::NUM\_STREAM\_TYPES]; // mute request counter  
};  
\------------------------------AudioOutputDescriptor----------------------------------

LOGV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d", stream, on, output, outputDesc-&gt;mMuteCount\[stream]);

if (on) {  
if (outputDesc-&gt;mMuteCount\[stream] == 0) {  
if (streamDesc.mCanBeMuted) {  
checkAndSetVolume(stream, 0, output, outputDesc-&gt;device(), delayMs);  
++++++++++++++++++++++++++++AudioPolicyManagerBase::checkAndSetVolume++++++++++++++++++++++++++++++++++++  
status\_t AudioPolicyManagerBase::checkAndSetVolume(int stream, int index, audio\_io\_handle\_t output, uint32\_t device, int delayMs, bool force)  
{

// do not change actual stream volume if the stream is muted  
if (mOutputs.valueFor(output)-&gt;mMuteCount\[stream] != 0) {  
LOGV("checkAndSetVolume() stream %d muted count %d", stream, mOutputs.valueFor(output)-&gt;mMuteCount\[stream]);  
return NO\_ERROR;  
}

// do not change in call volume if bluetooth is connected and vice versa  
if ((stream == AudioSystem::VOICE\_CALL && mForceUse\[AudioSystem::FOR\_COMMUNICATION] == AudioSystem::FORCE\_BT\_SCO) ||  
(stream == AudioSystem::BLUETOOTH\_SCO && mForceUse\[AudioSystem::FOR\_COMMUNICATION] != AudioSystem::FORCE\_BT\_SCO)) {  
LOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",  
stream, mForceUse\[AudioSystem::FOR\_COMMUNICATION]);  
return INVALID\_OPERATION;  
}

float volume = computeVolume(stream, index, output, device);  
+++++++++++++++++++++++++++++++AudioPolicyManagerBase::computeVolume+++++++++++++++++++++++++++++++++  
float AudioPolicyManagerBase::computeVolume(int stream, int index, audio\_io\_handle\_t output, uint32\_t device)  
{  
float volume = 1.0;  
AudioOutputDescriptor \*outputDesc = mOutputs.valueFor(output);  
StreamDescriptor &streamDesc = mStreams\[stream];

if (device == 0) {  
device = outputDesc-&gt;device();  
}

int volInt = (100 * (index - streamDesc.mIndexMin)) / (streamDesc.mIndexMax - streamDesc.mIndexMin);  
volume = AudioSystem::linearToLog(volInt);  
+++++++++++++++++++++++++++++++AudioSystem::linearToLog+++++++++++++++++++++++++++++++++  
float AudioSystem::linearToLog(int volume)  
{  
// float v = volume ? exp(float(100 - volume) * dBConvert) : 0;  
// LOGD("linearToLog(%d)=%f", volume, v);  
// return v;  
return volume ? exp(float(100 - volume) * dBConvert) : 0;  
}  
\-------------------------------AudioSystem::linearToLog---------------------------------

// if a headset is connected, apply the following rules to ring tones and notifications  
// to avoid sound level bursts in user's ears:  
// - always attenuate ring tones and notifications volume by 6dB  
// - if music is playing, always limit the volume to current music volume,  
// with a minimum threshold at -36dB so that notification is always perceived.  
if ((device &  
(AudioSystem::DEVICE\_OUT\_BLUETOOTH\_A2DP |  
AudioSystem::DEVICE\_OUT\_BLUETOOTH\_A2DP\_HEADPHONES |  
AudioSystem::DEVICE\_OUT\_WIRED\_HEADSET |  
AudioSystem::DEVICE\_OUT\_WIRED\_HEADPHONE)) &&  
((getStrategy((AudioSystem::stream\_type)stream) == STRATEGY\_SONIFICATION) ||  
(stream == AudioSystem::SYSTEM)) &&  
streamDesc.mCanBeMuted) {  
// Attenuation applied to STRATEGY\_SONIFICATION streams when a headset is connected: 6dB  
// #define SONIFICATION\_HEADSET\_VOLUME\_FACTOR 0.5  
volume \*= SONIFICATION\_HEADSET\_VOLUME\_FACTOR;  
// when the phone is ringing we must consider that music could have been paused just before  
// by the music application and behave as if music was active if the last music track was  
// just stopped  
// 函数AudioPolicyManagerBase::setPhoneState中有对mLimitRingtoneVolume赋值  
++++++++++++++++++++++++++++++mLimitRingtoneVolume++++++++++++++++++++++++++++++++++  
// Flag that ringtone volume must be limited to music volume until we exit MODE\_RINGTONE  
if (state == AudioSystem::MODE\_RINGTONE &&  
(hwOutputDesc-&gt;mRefCount\[AudioSystem::MUSIC] ||  
(systemTime() - mMusicStopTime) &lt; seconds(SONIFICATION\_HEADSET\_MUSIC\_DELAY))) {  
mLimitRingtoneVolume = true;  
} else {  
mLimitRingtoneVolume = false;  
}  
\------------------------------mLimitRingtoneVolume----------------------------------  
if (outputDesc-&gt;mRefCount\[AudioSystem::MUSIC] || mLimitRingtoneVolume) {  
float musicVol = computeVolume(AudioSystem::MUSIC, mStreams\[AudioSystem::MUSIC].mIndexCur, output, device);  
float minVol = (musicVol &gt; SONIFICATION\_HEADSET\_VOLUME\_MIN) ? musicVol : SONIFICATION\_HEADSET\_VOLUME\_MIN;  
if (volume &gt; minVol) {  
volume = minVol;  
LOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);  
}  
}  
}

return volume;  
}  
\-------------------------------AudioPolicyManagerBase::computeVolume---------------------------------  
// We actually change the volume if:  
// - the float value returned by computeVolume() changed  
// - the force flag is set  
if (volume != mOutputs.valueFor(output)-&gt;mCurVolume\[stream] ||  
force) {  
mOutputs.valueFor(output)-&gt;mCurVolume\[stream] = volume;  
LOGV("setStreamVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);  
if (stream == AudioSystem::VOICE\_CALL ||  
stream == AudioSystem::DTMF ||  
stream == AudioSystem::BLUETOOTH\_SCO) {  
// offset value to reflect actual hardware volume that never reaches 0  
// 1% corresponds roughly to first step in VOICE\_CALL stream volume setting (see AudioService.java)  
volume = 0.01 + 0.99 * volume;  
}  
mpClientInterface-&gt;setStreamVolume((AudioSystem::stream\_type)stream, volume, output, delayMs);  
+++++++++++++++++++++++++++++AudioPolicyService::setStreamVolume+++++++++++++++++++++++++++++++++++  
status\_t AudioPolicyService::setStreamVolume(AudioSystem::stream\_type stream,  
float volume,  
audio\_io\_handle\_t output,  
int delayMs)  
{  
// mAudioCommandThread在AudioPolicyService的构造函数中被创建  
return mAudioCommandThread-&gt;volumeCommand((int)stream, volume, (int)output, delayMs);  
++++++++++++++++++++++++++++++AudioPolicyService::AudioCommandThread::volumeCommand++++++++++++++++++++++++++++++++++  
status\_t AudioPolicyService::AudioCommandThread::volumeCommand(int stream,  
float volume,  
int output,  
int delayMs)  
{  
status\_t status = NO\_ERROR;

AudioCommand \*command = new AudioCommand();  
command-&gt;mCommand = SET\_VOLUME;  
VolumeData \*data = new VolumeData();  
data-&gt;mStream = stream;  
data-&gt;mVolume = volume;  
data-&gt;mIO = output;  
command-&gt;mParam = data;  
if (delayMs == 0) {  
command-&gt;mWaitStatus = true;  
} else {  
command-&gt;mWaitStatus = false;  
}  
Mutex::Autolock \_l(mLock);  
insertCommand\_l(command, delayMs);  
+++++++++++++++++++++++++++++++++AudioPolicyService::AudioCommandThread::insertCommand\_l+++++++++++++++++++++++++++++++  
// insertCommand\_l() must be called with mLock held  
void AudioPolicyService::AudioCommandThread::insertCommand\_l(AudioCommand \*command, int delayMs)  
{  
ssize\_t i;  
Vector &lt;AudioCommand \*&gt; removedCommands;

command-&gt;mTime = systemTime() + milliseconds(delayMs);

// acquire wake lock to make sure delayed commands are processed  
if (mName != "" && mAudioCommands.isEmpty()) {  
acquire\_wake\_lock(PARTIAL\_WAKE\_LOCK, mName.string());  
}

// check same pending commands with later time stamps and eliminate them  
// 如果command队列中，存在正在等待的相同的command，如果其延迟比新加入的还要晚，则删除这些command  
// 从后往前遍历  
for (i = mAudioCommands.size()-1; i &gt;= 0; i--) {  
AudioCommand \*command2 = mAudioCommands\[i];  
// commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands  
// command在队列中是按照时间戳排序的，开头的时间戳最短  
// 从后往前遍历，碰到比自己小的时间戳，说明前面所有command 的时间戳都比新command的时间戳要小，也就没必要再比较了  
if (command2-&gt;mTime &lt;= command-&gt;mTime) break;  
// 只比较相同的command类型  
if (command2-&gt;mCommand != command-&gt;mCommand) continue;

switch (command-&gt;mCommand) {  
// 如果是设置参数，因为要设置的参数比较多，只把要设置的相同类型的参数删掉  
// 如果队列中command设置的所有的参数类型与新command的所有参数类型完全相同，则将原来的command删除  
case SET\_PARAMETERS: {  
ParametersData \*data = (ParametersData \*)command-&gt;mParam;  
ParametersData \*data2 = (ParametersData \*)command2-&gt;mParam;  
if (data-&gt;mIO != data2-&gt;mIO) break;  
LOGV("Comparing parameter command %s to new command %s",  
data2-&gt;mKeyValuePairs.string(), data-&gt;mKeyValuePairs.string());  
AudioParameter param = AudioParameter(data-&gt;mKeyValuePairs);  
AudioParameter param2 = AudioParameter(data2-&gt;mKeyValuePairs);  
for (size\_t j = 0; j &lt; param.size(); j++) {  
String8 key;  
String8 value;  
param.getAt(j, key, value);  
for (size\_t k = 0; k &lt; param2.size(); k++) {  
String8 key2;  
String8 value2;  
param2.getAt(k, key2, value2);  
if (key2 == key) {  
param2.remove(key2);  
LOGV("Filtering out parameter %s", key2.string());  
break;  
}  
}  
}  
// if all keys have been filtered out, remove the command.  
// otherwise, update the key value pairs  
if (param2.size() == 0) {  
removedCommands.add(command2);  
} else {  
data2-&gt;mKeyValuePairs = param2.toString();  
}  
} break;

// 如果是设置音量，比较它们是否是要设置同一个output上的相同的stream的音量  
// 如果是，则删除原command  
case SET\_VOLUME: {  
VolumeData \*data = (VolumeData \*)command-&gt;mParam;  
VolumeData \*data2 = (VolumeData \*)command2-&gt;mParam;  
if (data-&gt;mIO != data2-&gt;mIO) break;  
if (data-&gt;mStream != data2-&gt;mStream) break;  
LOGV("Filtering out volume command on output %d for stream %d",  
data-&gt;mIO, data-&gt;mStream);  
removedCommands.add(command2);  
} break;  
case START\_TONE:  
case STOP\_TONE:  
default:  
break;  
}  
}

// remove filtered commands  
for (size\_t j = 0; j &lt; removedCommands.size(); j++) {  
// removed commands always have time stamps greater than current command  
for (size\_t k = i + 1; k &lt; mAudioCommands.size(); k++) {  
if (mAudioCommands\[k] == removedCommands\[j]) {  
LOGV("suppressing command: %d", mAudioCommands\[k]-&gt;mCommand);  
mAudioCommands.removeAt(k);  
break;  
}  
}  
}  
removedCommands.clear();

// insert command at the right place according to its time stamp  
LOGV("inserting command: %d at index %d, num commands %d",  
command-&gt;mCommand, (int)i+1, mAudioCommands.size());  
// 将command加入到队列mAudioCommands中，位置i是根据时间戳算出来的  
// 函数AudioPolicyService::AudioCommandThread::threadLoop中会处理mAudioCommands中的command  
mAudioCommands.insertAt(command, i + 1);  
+++++++++++++++++++++++++++++++++AudioPolicyService::AudioCommandThread::threadLoop+++++++++++++++++++++++++++++++  
bool AudioPolicyService::AudioCommandThread::threadLoop()  
{  
nsecs\_t waitTime = INT64\_MAX;

mLock.lock();  
while (!exitPending())  
{  
while(!mAudioCommands.isEmpty()) {  
nsecs\_t curTime = systemTime();  
// commands are sorted by increasing time stamp: execute them from index 0 and up  
if (mAudioCommands\[0]-&gt;mTime &lt;= curTime) {  
// 每次总是取第一个command进行处理，因为第一个command 的时间戳永远是最早的  
AudioCommand \*command = mAudioCommands\[0];  
mAudioCommands.removeAt(0);  
mLastCommand = \*command;

switch (command-&gt;mCommand) {  
case START\_TONE: {  
mLock.unlock();  
ToneData \*data = (ToneData \*)command-&gt;mParam;  
LOGV("AudioCommandThread() processing start tone %d on stream %d",  
data-&gt;mType, data-&gt;mStream);  
if (mpToneGenerator != NULL)  
delete mpToneGenerator;  
mpToneGenerator = new ToneGenerator(data-&gt;mStream, 1.0);  
mpToneGenerator-&gt;startTone(data-&gt;mType);  
delete data;  
mLock.lock();  
}break;  
case STOP\_TONE: {  
mLock.unlock();  
LOGV("AudioCommandThread() processing stop tone");  
if (mpToneGenerator != NULL) {  
mpToneGenerator-&gt;stopTone();  
delete mpToneGenerator;  
mpToneGenerator = NULL;  
}  
mLock.lock();  
}break;  
case SET\_VOLUME: {  
VolumeData \*data = (VolumeData \*)command-&gt;mParam;  
LOGV("AudioCommandThread() processing set volume stream %d, \\  
volume %f, output %d", data-&gt;mStream, data-&gt;mVolume, data-&gt;mIO);  
command-&gt;mStatus = AudioSystem::setStreamVolume(data-&gt;mStream,  
data-&gt;mVolume,  
data-&gt;mIO);  
++++++++++++++++++++++++++++++AudioSystem::setStreamVolume++++++++++++++++++++++++++++++++++  
status\_t AudioSystem::setStreamVolume(int stream, float value, int output)  
{  
if (uint32\_t(stream) &gt;= NUM\_STREAM\_TYPES) return BAD\_VALUE;  
const sp&lt;IAudioFlinger&gt;& af = AudioSystem::get\_audio\_flinger();  
if (af == 0) return PERMISSION\_DENIED;  
af-&gt;setStreamVolume(stream, value, output);  
++++++++++++++++++++++++++++++AudioFlinger::setStreamVolume++++++++++++++++++++++++++++++++++  
status\_t AudioFlinger::setStreamVolume(int stream, float value, int output)  
{  
// check calling permissions  
if (!settingsAllowed()) {  
return PERMISSION\_DENIED;  
}

if (stream &lt; 0 || uint32\_t(stream) &gt;= AudioSystem::NUM\_STREAM\_TYPES) {  
return BAD\_VALUE;  
}

AutoMutex lock(mLock);  
PlaybackThread \*thread = NULL;  
if (output) {  
thread = checkPlaybackThread\_l(output);  
if (thread == NULL) {  
return BAD\_VALUE;  
}  
}

mStreamTypes\[stream].volume = value;

// 如果没有找到output对应的playback thread，则将所有的playback thread中的对应stream的音量全部改变  
// 否则只改变对应的playback thread中对应stream的音量  
if (thread == NULL) {  
for (uint32\_t i = 0; i &lt; mPlaybackThreads.size(); i++) {  
mPlaybackThreads.valueAt(i)-&gt;setStreamVolume(stream, value);  
}  
} else {  
thread-&gt;setStreamVolume(stream, value);  
++++++++++++++++++++++++++++++AudioFlinger::PlaybackThread::setStreamVolume++++++++++++++++++++++++++++++++++  
status\_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)  
{  
#ifdef LVMX  
int audioOutputType = LifeVibes::getMixerType(mId, mType);  
if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {  
LifeVibes::setStreamVolume(audioOutputType, stream, value);  
}  
#endif  
// 只是改变了软件音量  
// mStreamTypes中保存的音量，在函数AudioFlinger::MixerThread::prepareTracks\_l中有被使用  
mStreamTypes\[stream].volume = value;  
+++++++++++++++++++++++++++++mStreamTypes+++++++++++++++++++++++++++++++++++  
// read original volumes with volume control  
float typeVolume = mStreamTypes\[track-&gt;type()].volume;  
#ifdef LVMX  
bool streamMute=false;  
// read the volume from the LivesVibes audio engine.  
if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))  
{  
LifeVibes::getStreamVolumes(audioOutputType, track-&gt;type(), &typeVolume, &streamMute);  
if (streamMute) {  
typeVolume = 0;  
}  
}  
#endif  
float v = masterVolume * typeVolume;  
vl = (uint32\_t)(v * cblk-&gt;volume\[0]) &lt;&lt; 12;  
vr = (uint32\_t)(v * cblk-&gt;volume\[1]) &lt;&lt; 12;

va = (uint32\_t)(v * cblk-&gt;sendLevel);  
}  
// Delegate volume control to effect in track effect chain if needed  
// 转换后的音量在此处有被使用  
// chain-&gt;setVolume\_l函数中不仅使用了音量，也有去改变音量  
if (chain != 0 && chain-&gt;setVolume\_l(&vl, &vr)) {  
++++++++++++++++++++++++++++++AudioFlinger::EffectChain::setVolume\_l++++++++++++++++++++++++++++++++++  
// setVolume\_l() must be called with PlaybackThread::mLock held  
bool AudioFlinger::EffectChain::setVolume\_l(uint32\_t \*left, uint32\_t \*right)  
{  
uint32\_t newLeft = \*left;  
uint32\_t newRight = \*right;  
bool hasControl = false;  
int ctrlIdx = -1;  
size\_t size = mEffects.size();

// first update volume controller  
for (size\_t i = size; i &gt; 0; i--) {  
if (mEffects\[i - 1]-&gt;isProcessEnabled() &&  
(mEffects\[i - 1]-&gt;desc().flags & EFFECT\_FLAG\_VOLUME\_MASK) == EFFECT\_FLAG\_VOLUME\_CTRL) {  
ctrlIdx = i - 1;  
hasControl = true;  
break;  
}  
}

if (ctrlIdx == mVolumeCtrlIdx && \*left == mLeftVolume && \*right == mRightVolume) {  
if (hasControl) {  
\*left = mNewLeftVolume;  
\*right = mNewRightVolume;  
}  
return hasControl;  
}

mVolumeCtrlIdx = ctrlIdx;  
mLeftVolume = newLeft;  
mRightVolume = newRight;

// second get volume update from volume controller  
if (ctrlIdx &gt;= 0) {  
mEffects\[ctrlIdx]-&gt;setVolume(&newLeft, &newRight, true);  
+++++++++++++++++++++++++++++AudioFlinger::EffectModule::setVolume+++++++++++++++++++++++++++++++++++  
status\_t AudioFlinger::EffectModule::setVolume(uint32\_t \*left, uint32\_t \*right, bool controller)  
{  
Mutex::Autolock \_l(mLock);  
status\_t status = NO\_ERROR;

// Send volume indication if EFFECT\_FLAG\_VOLUME\_IND is set and read back altered volume  
// if controller flag is set (Note that controller == TRUE =&gt; EFFECT\_FLAG\_VOLUME\_CTRL set)  
if (isProcessEnabled() &&  
((mDescriptor.flags & EFFECT\_FLAG\_VOLUME\_MASK) == EFFECT\_FLAG\_VOLUME\_CTRL ||  
(mDescriptor.flags & EFFECT\_FLAG\_VOLUME\_MASK) == EFFECT\_FLAG\_VOLUME\_IND)) {  
status\_t cmdStatus;  
uint32\_t volume\[2];  
uint32\_t \*pVolume = NULL;  
uint32\_t size = sizeof(volume);  
volume\[0] = \*left;  
volume\[1] = \*right;  
if (controller) {  
pVolume = volume;  
}  
status = (\*mEffectInterface)-&gt;command(mEffectInterface,  
EFFECT\_CMD\_SET\_VOLUME,  
size,  
volume,  
&size,  
pVolume);  
if (controller && status == NO\_ERROR && size == sizeof(volume)) {  
\*left = volume\[0];  
\*right = volume\[1];  
}  
}  
return status;  
}  
\-----------------------------AudioFlinger::EffectModule::setVolume-----------------------------------  
mNewLeftVolume = newLeft;  
mNewRightVolume = newRight;  
}  
// then indicate volume to all other effects in chain.  
// Pass altered volume to effects before volume controller  
// and requested volume to effects after controller  
uint32\_t lVol = newLeft;  
uint32\_t rVol = newRight;

for (size\_t i = 0; i &lt; size; i++) {  
if ((int)i == ctrlIdx) continue;  
// this also works for ctrlIdx == -1 when there is no volume controller  
if ((int)i &gt; ctrlIdx) {  
lVol = \*left;  
rVol = \*right;  
}  
mEffects\[i]-&gt;setVolume(&lVol, &rVol, false);  
}  
\*left = newLeft;  
\*right = newRight;

return hasControl;  
}  
\------------------------------AudioFlinger::EffectChain::setVolume\_l----------------------------------  
// Do not ramp volume if volume is controlled by effect  
param = AudioMixer::VOLUME;  
track-&gt;mHasVolumeController = true;  
} else {  
// force no volume ramp when volume controller was just disabled or removed  
// from effect chain to avoid volume spike  
if (track-&gt;mHasVolumeController) {  
param = AudioMixer::VOLUME;  
}  
track-&gt;mHasVolumeController = false;  
}

// Convert volumes from 8.24 to 4.12 format  
int16\_t left, right, aux;  
uint32\_t v\_clamped = (vl + (1 &lt;&lt; 11)) &gt;&gt; 12;  
if (v\_clamped &gt; MAX\_GAIN\_INT) v\_clamped = MAX\_GAIN\_INT;  
left = int16\_t(v\_clamped);  
v\_clamped = (vr + (1 &lt;&lt; 11)) &gt;&gt; 12;  
if (v\_clamped &gt; MAX\_GAIN\_INT) v\_clamped = MAX\_GAIN\_INT;  
right = int16\_t(v\_clamped);

if (va &gt; MAX\_GAIN\_INT) va = MAX\_GAIN\_INT;  
aux = int16\_t(va);

#ifdef LVMX  
if ( tracksConnectedChanged || stateChanged )  
{  
// only do the ramp when the volume is changed by the user / application  
param = AudioMixer::VOLUME;  
}  
#endif

// XXX: these things DON'T need to be done each time  
mAudioMixer-&gt;setBufferProvider(track);  
mAudioMixer-&gt;enable(AudioMixer::MIXING);

// setParameter函数将volume信息设置到track对象中  
// 函数process\_\_OneTrack16BitsStereoNoResampling中会根据音量对数据进行处理  
mAudioMixer-&gt;setParameter(param, AudioMixer::VOLUME0, (void \*)left);  
mAudioMixer-&gt;setParameter(param, AudioMixer::VOLUME1, (void \*)right);  
mAudioMixer-&gt;setParameter(param, AudioMixer::AUXLEVEL, (void \*)aux);  
\-----------------------------mStreamTypes-----------------------------------  
return NO\_ERROR;  
}  
\------------------------------AudioFlinger::PlaybackThread::setStreamVolume----------------------------------  
}

return NO\_ERROR;  
}  
\------------------------------AudioFlinger::setStreamVolume----------------------------------  
return NO\_ERROR;  
}  
\------------------------------AudioSystem::setStreamVolume----------------------------------  
if (command-&gt;mWaitStatus) {  
command-&gt;mCond.signal();  
mWaitWorkCV.wait(mLock);  
}  
delete data;  
}break;  
case SET\_PARAMETERS: {  
ParametersData \*data = (ParametersData \*)command-&gt;mParam;  
LOGV("AudioCommandThread() processing set parameters string %s, io %d",  
data-&gt;mKeyValuePairs.string(), data-&gt;mIO);  
command-&gt;mStatus = AudioSystem::setParameters(data-&gt;mIO, data-&gt;mKeyValuePairs);  
if (command-&gt;mWaitStatus) {  
command-&gt;mCond.signal();  
mWaitWorkCV.wait(mLock);  
}  
delete data;  
}break;  
case SET\_VOICE\_VOLUME: {  
VoiceVolumeData \*data = (VoiceVolumeData \*)command-&gt;mParam;  
LOGV("AudioCommandThread() processing set voice volume volume %f",  
data-&gt;mVolume);  
// 这个命令会因函数AudioPolicyManagerBase::checkAndSetVolume中调用mpClientInterface-&gt;setVoiceVolume函数引起  
// 这儿也展开看看  
command-&gt;mStatus = AudioSystem::setVoiceVolume(data-&gt;mVolume);  
++++++++++++++++++++++++++++++AudioSystem::setVoiceVolume++++++++++++++++++++++++++++++++++  
status\_t AudioSystem::setVoiceVolume(float value)  
{  
const sp&lt;IAudioFlinger&gt;& af = AudioSystem::get\_audio\_flinger();  
if (af == 0) return PERMISSION\_DENIED;  
return af-&gt;setVoiceVolume(value);  
++++++++++++++++++++++++++++++AudioFlinger::setVoiceVolume++++++++++++++++++++++++++++++++++  
status\_t AudioFlinger::setVoiceVolume(float value)  
{  
// check calling permissions  
if (!settingsAllowed()) {  
return PERMISSION\_DENIED;  
}

AutoMutex lock(mHardwareLock);  
mHardwareStatus = AUDIO\_SET\_VOICE\_VOLUME;  
status\_t ret = mAudioHardware-&gt;setVoiceVolume(value);  
+++++++++++++++++++++++++++++AudioHardwareALSA::setVoiceVolume+++++++++++++++++++++++++++++++++++  
status\_t AudioHardwareALSA::setVoiceVolume(float volume)  
{  
/* could not set this params on SPDIF card, will return directly \*/  
if (!strcmp(mCurCard,SPDIF))  
return INVALID\_OPERATION;  
// The voice volume is used by the VOICE\_CALL audio stream.

if (mMixer)  
return mMixer-&gt;setVolume(AudioSystem::DEVICE\_OUT\_EARPIECE, volume, volume);  
+++++++++++++++++++++++++++++AudioFlinger::setVoiceVolume+++++++++++++++++++++++++++++++++++  
status\_t ALSAMixer::setVolume(uint32\_t device, float left, float right)  
{  
for (int j = 0; mixerProp\[j]\[SND\_PCM\_STREAM\_PLAYBACK].device; j++)  
if (mixerProp\[j]\[SND\_PCM\_STREAM\_PLAYBACK].device & device) {

mixer\_info\_t \*info = mixerProp\[j]\[SND\_PCM\_STREAM\_PLAYBACK].mInfo;  
if (!info || !info-&gt;elem) return INVALID\_OPERATION;

long minVol = info-&gt;min;  
long maxVol = info-&gt;max;

// Make sure volume is between bounds.  
long vol = minVol + left * (maxVol - minVol);  
if (vol &gt; maxVol) vol = maxVol;  
if (vol &lt; minVol) vol = minVol;

info-&gt;volume = vol;  
snd\_mixer\_selem\_set\_playback\_volume\_all (info-&gt;elem, vol);  
+++++++++++++++++++++++++++++snd\_mixer\_selem\_set\_playback\_volume\_all+++++++++++++++++++++++++++++++++++  
/\**  
\* \\brief Set value of playback volume control for all channels of a mixer simple element  
\* \\param elem Mixer simple element handle  
\* \\param value control value  
\* \\return 0 on success otherwise a negative error code  
\*/  
int snd\_mixer\_selem\_set\_playback\_volume\_all(snd\_mixer\_elem\_t \*elem, long value)  
{  
snd\_mixer\_selem\_channel\_id\_t chn;  
int err;

for (chn = 0; chn &lt; 32; chn++) {  
if (!snd\_mixer\_selem\_has\_playback\_channel(elem, chn))  
+++++++++++++++++++++++++++++++snd\_mixer\_selem\_has\_playback\_channel+++++++++++++++++++++++++++++++++  
/\**  
\* \\brief Get info about channels of playback stream of a mixer simple element  
\* \\param elem Mixer simple element handle  
\* \\param channel Mixer simple element channel identifier  
\* \\return 0 if channel is not present, 1 if present  
\*/  
int snd\_mixer\_selem\_has\_playback\_channel(snd\_mixer\_elem\_t \*elem, snd\_mixer\_selem\_channel\_id\_t channel)  
{  
CHECK\_BASIC(elem);  
return sm\_selem\_ops(elem)-&gt;is(elem, SM\_PLAY, SM\_OPS\_IS\_CHANNEL, (int)channel);  
}  
\-------------------------------snd\_mixer\_selem\_has\_playback\_channel---------------------------------  
continue;  
err = snd\_mixer\_selem\_set\_playback\_volume(elem, chn, value);  
+++++++++++++++++++++++++++++snd\_mixer\_selem\_set\_playback\_volume+++++++++++++++++++++++++++++++++++  
/\**  
\* \\brief Set value of playback volume control of a mixer simple element  
\* \\param elem Mixer simple element handle  
\* \\param channel mixer simple element channel identifier  
\* \\param value control value  
\* \\return 0 on success otherwise a negative error code  
\*/  
int snd\_mixer\_selem\_set\_playback\_volume(snd\_mixer\_elem\_t \*elem, snd\_mixer\_selem\_channel\_id\_t channel, long value)  
{  
CHECK\_BASIC(elem);  
CHECK\_DIR\_CHN(elem, SM\_CAP\_PVOLUME, SM\_CAP\_PVOLUME\_JOIN, channel);  
// #define sm\_selem\_ops(x)((sm\_selem\_t \*)((x)-&gt;private\_data))-&gt;ops  
return sm\_selem\_ops(elem)-&gt;set\_volume(elem, SM\_PLAY, channel, value);  
+++++++++++++++++++++++++++++sm\_selem\_t+++++++++++++++++++++++++++++++++++  
typedef struct \_sm\_selem {  
snd\_mixer\_selem\_id\_t \*id;  
struct sm\_elem\_ops \*ops;  
unsigned int caps;  
unsigned int capture\_group;  
} sm\_selem\_t;  
\-----------------------------sm\_selem\_t-----------------------------------  
}  
\-----------------------------snd\_mixer\_selem\_set\_playback\_volume-----------------------------------  
if (err &lt; 0)  
return err;  
if (chn == 0 && snd\_mixer\_selem\_has\_playback\_volume\_joined(elem))  
+++++++++++++++++++++++++++++++++snd\_mixer\_selem\_has\_playback\_volume\_joined+++++++++++++++++++++++++++++++  
/\**  
\* \\brief Return info about playback volume control of a mixer simple element  
\* \\param elem Mixer simple element handle  
\* \\return 0 if control is separated per channel, 1 if control acts on all channels together  
\*/  
int snd\_mixer\_selem\_has\_playback\_volume\_joined(snd\_mixer\_elem\_t \*elem)  
{  
CHECK\_BASIC(elem);  
return COND\_CAPS(elem, SM\_CAP\_PVOLUME\_JOIN);  
}  
\---------------------------------snd\_mixer\_selem\_has\_playback\_volume\_joined-------------------------------  
return 0;  
}  
return 0;  
}  
\-----------------------------snd\_mixer\_selem\_set\_playback\_volume\_all-----------------------------------  
}

return NO\_ERROR;  
}  
\-----------------------------AudioFlinger::setVoiceVolume-----------------------------------  
else  
return INVALID\_OPERATION;  
}  
\-----------------------------AudioHardwareALSA::setVoiceVolume-----------------------------------  
mHardwareStatus = AUDIO\_HW\_IDLE;

return ret;  
}  
\------------------------------AudioFlinger::setVoiceVolume----------------------------------  
}  
\------------------------------AudioSystem::setVoiceVolume----------------------------------  
if (command-&gt;mWaitStatus) {  
command-&gt;mCond.signal();  
mWaitWorkCV.wait(mLock);  
}  
delete data;  
}break;  
default:  
LOGW("AudioCommandThread() unknown command %d", command-&gt;mCommand);  
}  
delete command;  
waitTime = INT64\_MAX;  
} else {  
waitTime = mAudioCommands\[0]-&gt;mTime - curTime;  
break;  
}  
}  
// release delayed commands wake lock  
if (mName != "" && mAudioCommands.isEmpty()) {  
release\_wake\_lock(mName.string());  
}  
LOGV("AudioCommandThread() going to sleep");  
mWaitWorkCV.waitRelative(mLock, waitTime);  
LOGV("AudioCommandThread() waking up");  
}  
mLock.unlock();  
return false;  
}  
\---------------------------------AudioPolicyService::AudioCommandThread::threadLoop-------------------------------  
}  
\---------------------------------AudioPolicyService::AudioCommandThread::insertCommand\_l-------------------------------  
LOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",  
stream, volume, output);  
mWaitWorkCV.signal();  
if (command-&gt;mWaitStatus) {  
command-&gt;mCond.wait(mLock);  
status = command-&gt;mStatus;  
mWaitWorkCV.signal();  
}  
return status;  
}  
\------------------------------AudioPolicyService::AudioCommandThread::volumeCommand----------------------------------  
}  
\-----------------------------AudioPolicyService::setStreamVolume-----------------------------------  
}

if (stream == AudioSystem::VOICE\_CALL ||  
stream == AudioSystem::BLUETOOTH\_SCO) {  
float voiceVolume;  
// Force voice volume to max for bluetooth SCO as volume is managed by the headset  
if (stream == AudioSystem::VOICE\_CALL) {  
voiceVolume = (float)index/(float)mStreams\[stream].mIndexMax;  
} else {  
voiceVolume = 1.0;  
}  
if (voiceVolume != mLastVoiceVolume && output == mHardwareOutput) {  
mpClientInterface-&gt;setVoiceVolume(voiceVolume, delayMs);  
mLastVoiceVolume = voiceVolume;  
}  
}

return NO\_ERROR;  
}  
\----------------------------AudioPolicyManagerBase::checkAndSetVolume------------------------------------  
}  
}  
// increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored  
outputDesc-&gt;mMuteCount\[stream]++;  
} else {  
if (outputDesc-&gt;mMuteCount\[stream] == 0) {  
LOGW("setStreamMute() unmuting non muted stream!");  
return;  
}  
if (--outputDesc-&gt;mMuteCount\[stream] == 0) {  
checkAndSetVolume(stream, streamDesc.mIndexCur, output, outputDesc-&gt;device(), delayMs);  
}  
}  
}  
\-----------------------------AudioPolicyManagerBase::setStreamMute-----------------------------------  
}  
}  
}  
\----------------------------AudioPolicyManagerBase::setStrategyMute------------------------------------  
}  
#endif

// incremenent usage count for this stream on the requested output:  
// NOTE that the usage count is the same for duplicated output and hardware output which is  
// necassary for a correct control of hardware output routing by startOutput() and stopOutput()  
outputDesc-&gt;changeRefCount(stream, 1);

setOutputDevice(output, getNewDevice(output));  
++++++++++++++++++++++++++++AudioPolicyManagerBase::setOutputDevice++++++++++++++++++++++++++++++++++++  
void AudioPolicyManagerBase::setOutputDevice(audio\_io\_handle\_t output, uint32\_t device, bool force, int delayMs)  
{  
LOGV("setOutputDevice() output %d device %x delayMs %d", output, device, delayMs);  
AudioOutputDescriptor \*outputDesc = mOutputs.valueFor(output);

if (outputDesc-&gt;isDuplicated()) {  
setOutputDevice(outputDesc-&gt;mOutput1-&gt;mId, device, force, delayMs);  
setOutputDevice(outputDesc-&gt;mOutput2-&gt;mId, device, force, delayMs);  
return;  
}  
#ifdef WITH\_A2DP  
// filter devices according to output selected  
if (output == mA2dpOutput) {  
device &= AudioSystem::DEVICE\_OUT\_ALL\_A2DP;  
} else {  
device &= ~AudioSystem::DEVICE\_OUT\_ALL\_A2DP;  
}  
#endif

uint32\_t prevDevice = (uint32\_t)outputDesc-&gt;device();  
// Do not change the routing if:  
// - the requestede device is 0  
// - the requested device is the same as current device and force is not specified.  
// Doing this check here allows the caller to call setOutputDevice() without conditions  
if ((device == 0 || device == prevDevice) && !force) {  
LOGV("setOutputDevice() setting same device %x or null device for output %d", device, output);  
return;  
}

outputDesc-&gt;mDevice = device;  
// mute media streams if both speaker and headset are selected  
if (output == mHardwareOutput && AudioSystem::popCount(device) == 2) {  
setStrategyMute(STRATEGY\_MEDIA, true, output);  
// wait for the PCM output buffers to empty before proceeding with the rest of the command  
usleep(outputDesc-&gt;mLatency\*2\*1000);  
}

// do the routing  
AudioParameter param = AudioParameter();  
param.addInt(String8(AudioParameter::keyRouting), (int)device);  
mpClientInterface-&gt;setParameters(mHardwareOutput, param.toString(), delayMs);  
+++++++++++++++++++++++++++++AudioPolicyService::setParameters+++++++++++++++++++++++++++++++++++  
void AudioPolicyService::setParameters(audio\_io\_handle\_t ioHandle,  
const String8& keyValuePairs,  
int delayMs)  
{  
mAudioCommandThread-&gt;parametersCommand((int)ioHandle, keyValuePairs, delayMs);  
+++++++++++++++++++++++++++++AudioPolicyService::AudioCommandThread::parametersCommand+++++++++++++++++++++++++++++++++++  
status\_t AudioPolicyService::AudioCommandThread::parametersCommand(int ioHandle,  
const String8& keyValuePairs,  
int delayMs)  
{  
status\_t status = NO\_ERROR;

AudioCommand \*command = new AudioCommand();  
command-&gt;mCommand = SET\_PARAMETERS;  
ParametersData \*data = new ParametersData();  
data-&gt;mIO = ioHandle;  
data-&gt;mKeyValuePairs = keyValuePairs;  
command-&gt;mParam = data;  
if (delayMs == 0) {  
command-&gt;mWaitStatus = true;  
} else {  
command-&gt;mWaitStatus = false;  
}  
Mutex::Autolock \_l(mLock);  
// 将command添加到队列  
// command的处理还是在函数AudioPolicyService::AudioCommandThread::threadLoop中  
// 这儿只摘取了set parameter的片段  
insertCommand\_l(command, delayMs);  
++++++++++++++++++++++++++++++++case SET\_PARAMETERS++++++++++++++++++++++++++++++++  
case SET\_PARAMETERS: {  
ParametersData \*data = (ParametersData \*)command-&gt;mParam;  
LOGV("AudioCommandThread() processing set parameters string %s, io %d",  
data-&gt;mKeyValuePairs.string(), data-&gt;mIO);  
command-&gt;mStatus = AudioSystem::setParameters(data-&gt;mIO, data-&gt;mKeyValuePairs);  
++++++++++++++++++++++++++++++++AudioSystem::setParameters++++++++++++++++++++++++++++++++  
status\_t AudioSystem::setParameters(audio\_io\_handle\_t ioHandle, const String8& keyValuePairs) {  
const sp&lt;IAudioFlinger&gt;& af = AudioSystem::get\_audio\_flinger();  
if (af == 0) return PERMISSION\_DENIED;  
return af-&gt;setParameters(ioHandle, keyValuePairs);  
++++++++++++++++++++++++++++++++AudioFlinger::setParameters++++++++++++++++++++++++++++++++  
status\_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)  
{  
status\_t result;

LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",  
ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()-&gt;getCallingPid());  
// check calling permissions  
if (!settingsAllowed()) {  
return PERMISSION\_DENIED;  
}

#ifdef LVMX  
AudioParameter param = AudioParameter(keyValuePairs);  
LifeVibes::setParameters(ioHandle,keyValuePairs);  
String8 key = String8(AudioParameter::keyRouting);  
int device;  
if (NO\_ERROR != param.getInt(key, device)) {  
device = -1;  
}

key = String8(LifevibesTag);  
String8 value;  
int musicEnabled = -1;  
if (NO\_ERROR == param.get(key, value)) {  
if (value == LifevibesEnable) {  
mLifeVibesClientPid = IPCThreadState::self()-&gt;getCallingPid();  
musicEnabled = 1;  
} else if (value == LifevibesDisable) {  
mLifeVibesClientPid = -1;  
musicEnabled = 0;  
}  
}  
#endif

// ioHandle == 0 means the parameters are global to the audio hardware interface  
if (ioHandle == 0) {  
AutoMutex lock(mHardwareLock);  
mHardwareStatus = AUDIO\_SET\_PARAMETER;  
// 函数setParameters其实是个空的，并没有实现。  
// 类AudioHardwareALSA中没有实现，基类AudioHardwareBase中是个空的  
result = mAudioHardware-&gt;setParameters(keyValuePairs);  
#ifdef LVMX  
if (musicEnabled != -1) {  
LifeVibes::enableMusic((bool) musicEnabled);  
}  
#endif  
mHardwareStatus = AUDIO\_HW\_IDLE;  
return result;  
}

// hold a strong ref on thread in case closeOutput() or closeInput() is called  
// and the thread is exited once the lock is released  
sp&lt;ThreadBase&gt; thread;  
{  
Mutex::Autolock \_l(mLock);  
thread = checkPlaybackThread\_l(ioHandle);  
if (thread == NULL) {  
thread = checkRecordThread\_l(ioHandle);  
}  
}  
if (thread != NULL) {  
result = thread-&gt;setParameters(keyValuePairs);  
+++++++++++++++++++++++++++++++AudioFlinger::ThreadBase::setParameters+++++++++++++++++++++++++++++++++  
status\_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)  
{  
status\_t status;

LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());  
Mutex::Autolock \_l(mLock);

// checkForNewParameters\_l函数会使用mNewParameters，如函数AudioFlinger::MixerThread::checkForNewParameters\_l  
mNewParameters.add(keyValuePairs);  
+++++++++++++++++++++++++++++++AudioFlinger::MixerThread::checkForNewParameters\_l+++++++++++++++++++++++++++++++++  
// checkForNewParameters\_l() must be called with ThreadBase::mLock held  
bool AudioFlinger::MixerThread::checkForNewParameters\_l()  
{  
bool reconfig = false;

while (!mNewParameters.isEmpty()) {  
status\_t status = NO\_ERROR;  
String8 keyValuePair = mNewParameters\[0];  
AudioParameter param = AudioParameter(keyValuePair);  
int value;

if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO\_ERROR) {  
reconfig = true;  
}  
if (param.getInt(String8(AudioParameter::keyFormat), value) == NO\_ERROR) {  
if (value != AudioSystem::PCM\_16\_BIT) {  
status = BAD\_VALUE;  
} else {  
reconfig = true;  
}  
}  
if (param.getInt(String8(AudioParameter::keyChannels), value) == NO\_ERROR) {  
if (value != AudioSystem::CHANNEL\_OUT\_STEREO) {  
status = BAD\_VALUE;  
} else {  
reconfig = true;  
}  
}  
if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO\_ERROR) {  
// do not accept frame count changes if tracks are open as the track buffer  
// size depends on frame count and correct behavior would not be garantied  
// if frame count is changed after track creation  
if (!mTracks.isEmpty()) {  
status = INVALID\_OPERATION;  
} else {  
reconfig = true;  
}  
}  
if (param.getInt(String8(AudioParameter::keyRouting), value) == NO\_ERROR) {  
// forward device change to effects that have requested to be  
// aware of attached audio device.  
mDevice = (uint32\_t)value;  
for (size\_t i = 0; i &lt; mEffectChains.size(); i++) {  
mEffectChains\[i]-&gt;setDevice\_l(mDevice);  
}  
}

if (status == NO\_ERROR) {  
// mOutput在父类PlaybackThread的构造函数中被赋值，其值是通过构造函数参数传过去的  
// MixerThread对象是在函数AudioFlinger::openOutput中创建的  
// 其中的output是调用函数AudioHardwareALSA::openOutputStream得到的  
// 其中setParameters函数的实现是调用父类ALSAStreamOps的setParameters函数。  
status = mOutput-&gt;setParameters(keyValuePair);  
++++++++++++++++++++++++++++++AudioStreamOutALSA::setParameters++++++++++++++++++++++++++++++++++  
virtual status\_t setParameters(const String8& keyValuePairs) {  
return ALSAStreamOps::setParameters(keyValuePairs);  
++++++++++++++++++++++++++++++ALSAStreamOps::setParameters++++++++++++++++++++++++++++++++++  
status\_t ALSAStreamOps::setParameters(const String8& keyValuePairs)  
{  
AudioParameter param = AudioParameter(keyValuePairs);  
String8 key = String8(AudioParameter::keyRouting);  
status\_t status = NO\_ERROR;  
int device;  
LOGV("setParameters() %s", keyValuePairs.string());

if (param.getInt(key, device) == NO\_ERROR) {  
// mParent其实是AudioHardwareALSA对象  
// mALSADevice的赋值在AudioHardwareALSA的构造函数中  
// 通过调用函数module-&gt;methods-&gt;open得到，真正调用的函数是s\_device\_open  
// mParent-&gt;mALSADevice-&gt;route其实是函数s\_route  
mParent-&gt;mALSADevice-&gt;route(mHandle, (uint32\_t)device, mParent-&gt;mode());  
++++++++++++++++++++++++++++++s\_route++++++++++++++++++++++++++++++++++  
static status\_t s\_route(alsa\_handle\_t \*handle, uint32\_t devices, int mode)  
{  
status\_t status = NO\_ERROR;

LOGD("route called for devices %08x in mode %d...", devices, mode);  
// below Always noting to do, so we open device every time.  
#if 0  
if (handle-&gt;handle && handle-&gt;curDev == devices && handle-&gt;curMode == mode)  
; // Nothing to do  
else if (handle-&gt;handle && (handle-&gt;devices & devices))  
setAlsaControls(handle, devices, mode);  
else {  
LOGE("Why are we routing to a device that isn't supported by this object?!?!?!?!");  
status = s\_open(handle, devices, mode);  
}  
#else  
/* fix me if I was wrong here to judge the current sound card. In facat, in s\_open, it will reconfig the controls \*/  
setAlsaControls(handle, devices, mode);  
+++++++++++++++++++++++++++++++++++setAlsaControls+++++++++++++++++++++++++++++  
void setAlsaControls(alsa\_handle\_t \*handle, uint32\_t devices, int mode)  
{  
AlsaControlSet set = (AlsaControlSet) handle-&gt;modPrivate;  
const char \*card = deviceName(handle, devices, mode, 0);  
set(devices, mode, card);  
}  
\-----------------------------------setAlsaControls-----------------------------  
status = s\_open(handle, devices, mode);  
#endif  
return status;  
}  
\------------------------------s\_route----------------------------------  
param.remove(key);  
}

if (param.size()) {  
status = BAD\_VALUE;  
}  
return status;  
}  
\------------------------------ALSAStreamOps::setParameters----------------------------------  
}  
\------------------------------AudioStreamOutALSA::setParameters----------------------------------  
if (!mStandby && status == INVALID\_OPERATION) {  
mOutput-&gt;standby();  
mStandby = true;  
mBytesWritten = 0;  
status = mOutput-&gt;setParameters(keyValuePair);  
}  
if (status == NO\_ERROR && reconfig) {  
delete mAudioMixer;  
readOutputParameters();  
+++++++++++++++++++++++++++++++AudioFlinger::PlaybackThread::readOutputParameters+++++++++++++++++++++++++++++++++  
void AudioFlinger::PlaybackThread::readOutputParameters()  
{  
mSampleRate = mOutput-&gt;sampleRate();  
mChannels = mOutput-&gt;channels();  
mChannelCount = (uint16\_t)AudioSystem::popCount(mChannels);  
mFormat = mOutput-&gt;format();  
mFrameSize = (uint16\_t)mOutput-&gt;frameSize();  
mFrameCount = mOutput-&gt;bufferSize() / mFrameSize;

// FIXME - Current mixer implementation only supports stereo output: Always  
// Allocate a stereo buffer even if HW output is mono.  
if (mMixBuffer != NULL) delete\[] mMixBuffer;  
mMixBuffer = new int16\_t\[mFrameCount * 2];  
memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16\_t));

// force reconfiguration of effect chains and engines to take new buffer size and audio  
// parameters into account  
// Note that mLock is not held when readOutputParameters() is called from the constructor  
// but in this case nothing is done below as no audio sessions have effect yet so it doesn't  
// matter.  
// create a copy of mEffectChains as calling moveEffectChain\_l() can reorder some effect chains  
Vector&lt; sp&lt;EffectChain&gt; &gt; effectChains = mEffectChains;  
for (size\_t i = 0; i &lt; effectChains.size(); i ++) {  
mAudioFlinger-&gt;moveEffectChain\_l(effectChains\[i]-&gt;sessionId(), this, this, false);  
}  
}  
\-------------------------------AudioFlinger::PlaybackThread::readOutputParameters---------------------------------  
mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);  
for (size\_t i = 0; i &lt; mTracks.size() ; i++) {  
int name = getTrackName\_l();  
if (name &lt; 0) break;  
mTracks\[i]-&gt;mName = name;  
// limit track sample rate to 2 x new output sample rate  
if (mTracks\[i]-&gt;mCblk-&gt;sampleRate &gt; 2 * sampleRate()) {  
mTracks\[i]-&gt;mCblk-&gt;sampleRate = 2 * sampleRate();  
}  
}  
sendConfigEvent\_l(AudioSystem::OUTPUT\_CONFIG\_CHANGED);  
++++++++++++++++++++++++++++++++++AudioFlinger::ThreadBase::sendConfigEvent\_l++++++++++++++++++++++++++++++  
// sendConfigEvent\_l() must be called with ThreadBase::mLock held  
void AudioFlinger::ThreadBase::sendConfigEvent\_l(int event, int param)  
{  
ConfigEvent \*configEvent = new ConfigEvent();  
configEvent-&gt;mEvent = event;  
configEvent-&gt;mParam = param;  
// 函数AudioFlinger::ThreadBase::processConfigEvents会处理mConfigEvents中的event  
mConfigEvents.add(configEvent);  
++++++++++++++++++++++++++++++++++AudioFlinger::ThreadBase::processConfigEvents++++++++++++++++++++++++++++++  
void AudioFlinger::ThreadBase::processConfigEvents()  
{  
mLock.lock();  
while(!mConfigEvents.isEmpty()) {  
LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());  
ConfigEvent \*configEvent = mConfigEvents\[0];  
mConfigEvents.removeAt(0);  
// release mLock before locking AudioFlinger mLock: lock order is always  
// AudioFlinger then ThreadBase to avoid cross deadlock  
mLock.unlock();  
mAudioFlinger-&gt;mLock.lock();  
audioConfigChanged\_l(configEvent-&gt;mEvent, configEvent-&gt;mParam);  
+++++++++++++++++++++++++++++++++++AudioFlinger::audioConfigChanged\_l+++++++++++++++++++++++++++++  
// audioConfigChanged\_l() must be called with AudioFlinger::mLock held  
void AudioFlinger::audioConfigChanged\_l(int event, int ioHandle, void \*param2)  
{  
size\_t size = mNotificationClients.size();  
for (size\_t i = 0; i &lt; size; i++) {  
// 函数AudioFlinger::registerClient会往mNotificationClients中add 对象  
mNotificationClients.valueAt(i)-&gt;client()-&gt;ioConfigChanged(event, ioHandle, param2);  
++++++++++++++++++++++++++++++++++AudioFlinger::registerClient++++++++++++++++++++++++++++++  
void AudioFlinger::registerClient(const sp&lt;IAudioFlingerClient&gt;& client)  
{

Mutex::Autolock \_l(mLock);

int pid = IPCThreadState::self()-&gt;getCallingPid();  
if (mNotificationClients.indexOfKey(pid) &lt; 0) {  
sp&lt;NotificationClient&gt; notificationClient = new NotificationClient(this,  
client,  
pid);  
LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);

mNotificationClients.add(pid, notificationClient);

sp&lt;IBinder&gt; binder = client-&gt;asBinder();  
binder-&gt;linkToDeath(notificationClient);

// the config change is always sent from playback or record threads to avoid deadlock  
// with AudioSystem::gLock  
for (size\_t i = 0; i &lt; mPlaybackThreads.size(); i++) {  
mPlaybackThreads.valueAt(i)-&gt;sendConfigEvent(AudioSystem::OUTPUT\_OPENED);  
}

for (size\_t i = 0; i &lt; mRecordThreads.size(); i++) {  
mRecordThreads.valueAt(i)-&gt;sendConfigEvent(AudioSystem::INPUT\_OPENED);  
}  
}  
}  
函数AudioSystem::get\_audio\_flinger中调用了函数AudioFlinger::registerClient。  
+++++++++++++++++++++++++++++++AudioSystem::get\_audio\_flinger+++++++++++++++++++++++++++++++++  
// establish binder interface to AudioFlinger service  
const sp&lt;IAudioFlinger&gt;& AudioSystem::get\_audio\_flinger()  
{  
Mutex::Autolock \_l(gLock);  
if (gAudioFlinger.get() == 0) {  
sp&lt;IServiceManager&gt; sm = defaultServiceManager();  
sp&lt;IBinder&gt; binder;  
do {  
binder = sm-&gt;getService(String16("media.audio\_flinger"));  
if (binder != 0)  
break;  
LOGW("AudioFlinger not published, waiting...");  
usleep(500000); // 0.5 s  
} while(true);  
if (gAudioFlingerClient == NULL) {  
// 上面调用的函数ioConfigChanged其实是函数AudioSystem::AudioFlingerClient::ioConfigChanged  
gAudioFlingerClient = new AudioFlingerClient();  
++++++++++++++++++++++++++++++AudioSystem::AudioFlingerClient::ioConfigChanged++++++++++++++++++++++++++++++++++  
void AudioSystem::AudioFlingerClient::ioConfigChanged(int event, int ioHandle, void \*param2) {  
LOGV("ioConfigChanged() event %d", event);  
OutputDescriptor \*desc;  
uint32\_t stream;

if (ioHandle == 0) return;

Mutex::Autolock \_l(AudioSystem::gLock);

switch (event) {  
case STREAM\_CONFIG\_CHANGED:  
if (param2 == 0) break;  
stream = \*(uint32\_t \*)param2;  
LOGV("ioConfigChanged() STREAM\_CONFIG\_CHANGED stream %d, output %d", stream, ioHandle);  
if (gStreamOutputMap.indexOfKey(stream) &gt;= 0) {  
gStreamOutputMap.replaceValueFor(stream, ioHandle);  
}  
break;  
case OUTPUT\_OPENED: {  
if (gOutputs.indexOfKey(ioHandle) &gt;= 0) {  
LOGV("ioConfigChanged() opening already existing output! %d", ioHandle);  
break;  
}  
if (param2 == 0) break;  
desc = (OutputDescriptor \*)param2;

OutputDescriptor \*outputDesc = new OutputDescriptor(\*desc);  
gOutputs.add(ioHandle, outputDesc);  
LOGV("ioConfigChanged() new output samplingRate %d, format %d channels %d frameCount %d latency %d",  
outputDesc-&gt;samplingRate, outputDesc-&gt;format, outputDesc-&gt;channels, outputDesc-&gt;frameCount, outputDesc-&gt;latency);  
} break;  
case OUTPUT\_CLOSED: {  
if (gOutputs.indexOfKey(ioHandle) &lt; 0) {  
LOGW("ioConfigChanged() closing unknow output! %d", ioHandle);  
break;  
}  
LOGV("ioConfigChanged() output %d closed", ioHandle);

gOutputs.removeItem(ioHandle);  
for (int i = gStreamOutputMap.size() - 1; i &gt;= 0 ; i--) {  
if (gStreamOutputMap.valueAt(i) == ioHandle) {  
gStreamOutputMap.removeItemsAt(i);  
}  
}  
} break;  
// 我们上面添加的是这个event  
case OUTPUT\_CONFIG\_CHANGED: {  
int index = gOutputs.indexOfKey(ioHandle);  
if (index &lt; 0) {  
LOGW("ioConfigChanged() modifying unknow output! %d", ioHandle);  
break;  
}  
if (param2 == 0) break;  
desc = (OutputDescriptor \*)param2;

LOGV("ioConfigChanged() new config for output %d samplingRate %d, format %d channels %d frameCount %d latency %d",  
ioHandle, desc-&gt;samplingRate, desc-&gt;format,  
desc-&gt;channels, desc-&gt;frameCount, desc-&gt;latency);  
OutputDescriptor \*outputDesc = gOutputs.valueAt(index);  
delete outputDesc;  
outputDesc = new OutputDescriptor(\*desc);  
gOutputs.replaceValueFor(ioHandle, outputDesc);  
} break;  
case INPUT\_OPENED:  
case INPUT\_CLOSED:  
case INPUT\_CONFIG\_CHANGED:  
break;

}  
}  
\-------------------------------AudioSystem::AudioFlingerClient::ioConfigChanged---------------------------------  
} else {  
if (gAudioErrorCallback) {  
gAudioErrorCallback(NO\_ERROR);  
}  
}  
binder-&gt;linkToDeath(gAudioFlingerClient);  
gAudioFlinger = interface\_cast&lt;IAudioFlinger&gt;(binder);  
gAudioFlinger-&gt;registerClient(gAudioFlingerClient);  
}  
LOGE\_IF(gAudioFlinger==0, "no AudioFlinger!?");

return gAudioFlinger;  
}  
\-------------------------------AudioSystem::get\_audio\_flinger---------------------------------  
\----------------------------------AudioFlinger::registerClient------------------------------  
}  
}  
\-----------------------------------AudioFlinger::audioConfigChanged\_l-----------------------------  
mAudioFlinger-&gt;mLock.unlock();  
delete configEvent;  
mLock.lock();  
}  
mLock.unlock();  
}  
\----------------------------------AudioFlinger::ThreadBase::processConfigEvents------------------------------  
LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);  
mWaitWorkCV.signal();  
}  
\----------------------------------AudioFlinger::ThreadBase::sendConfigEvent\_l------------------------------  
}  
}

mNewParameters.removeAt(0);

mParamStatus = status;  
mParamCond.signal();  
mWaitWorkCV.wait(mLock);  
}  
return reconfig;  
}  
\-------------------------------AudioFlinger::MixerThread::checkForNewParameters\_l---------------------------------  
mWaitWorkCV.signal();  
// wait condition with timeout in case the thread loop has exited  
// before the request could be processed  
if (mParamCond.waitRelative(mLock, seconds(2)) == NO\_ERROR) {  
status = mParamStatus;  
mWaitWorkCV.signal();  
} else {  
status = TIMED\_OUT;  
}  
return status;  
}  
\-------------------------------AudioFlinger::ThreadBase::setParameters---------------------------------  
#ifdef LVMX  
if ((NO\_ERROR == result) && (device != -1)) {  
LifeVibes::setDevice(LifeVibes::threadIdToAudioOutputType(thread-&gt;id()), device);  
}  
#endif  
return result;  
}  
return BAD\_VALUE;  
}  
\--------------------------------AudioFlinger::setParameters--------------------------------  
}  
\--------------------------------AudioSystem::setParameters--------------------------------  
if (command-&gt;mWaitStatus) {  
command-&gt;mCond.signal();  
mWaitWorkCV.wait(mLock);  
}  
delete data;  
}break;  
\--------------------------------case SET\_PARAMETERS--------------------------------  
LOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",  
keyValuePairs.string(), ioHandle, delayMs);  
mWaitWorkCV.signal();  
if (command-&gt;mWaitStatus) {  
command-&gt;mCond.wait(mLock);  
status = command-&gt;mStatus;  
mWaitWorkCV.signal();  
}  
return status;  
}  
\-----------------------------AudioPolicyService::AudioCommandThread::parametersCommand-----------------------------------  
}  
\-----------------------------AudioPolicyService::setParameters-----------------------------------  
// update stream volumes according to new device  
applyStreamVolumes(output, device, delayMs);  
+++++++++++++++++++++++++++++AudioPolicyManagerBase::applyStreamVolumes+++++++++++++++++++++++++++++++++++  
void AudioPolicyManagerBase::applyStreamVolumes(audio\_io\_handle\_t output, uint32\_t device, int delayMs)  
{  
LOGV("applyStreamVolumes() for output %d and device %x", output, device);

for (int stream = 0; stream &lt; AudioSystem::NUM\_STREAM\_TYPES; stream++) {  
checkAndSetVolume(stream, mStreams\[stream].mIndexCur, output, device, delayMs);  
}  
}  
\-----------------------------AudioPolicyManagerBase::applyStreamVolumes-----------------------------------

// if changing from a combined headset + speaker route, unmute media streams  
if (output == mHardwareOutput && AudioSystem::popCount(prevDevice) == 2) {  
setStrategyMute(STRATEGY\_MEDIA, false, output, delayMs);  
}  
}  
\----------------------------AudioPolicyManagerBase::setOutputDevice------------------------------------

// handle special case for sonification while in call  
if (isInCall()) {  
handleIncallSonification(stream, true, false);  
}

// apply volume rules for current stream and device if necessary  
checkAndSetVolume(stream, mStreams\[stream].mIndexCur, output, outputDesc-&gt;device());

return NO\_ERROR;  
}  
\---------------------------AudioPolicyManagerBase::startOutput-------------------------------------  
}  
\-----------------------AudioPolicyService::startOutput-----------------------------------------  
}  
\-----------------------AudioSystem::startOutput-----------------------------------------  
thread-&gt;mLock.lock();  
}  
if (status == NO\_ERROR) {  
PlaybackThread \*playbackThread = (PlaybackThread \*)thread.get();  
playbackThread-&gt;addTrack\_l(this);  
} else {  
mState = state;  
}  
} else {  
status = BAD\_VALUE;  
}  
return status;  
}  
\----------------------------AudioFlinger::PlaybackThread::Track::start------------------------------------  
}  
\---------------------------AudioFlinger::TrackHandle::start-------------------------------------  
}  
// 如果状态为DEAD\_OBJECT，则创建一个AudioTrack对象，并调用其start函数  
if (status == DEAD\_OBJECT) {  
LOGV("start() dead IAudioTrack: creating a new one");  
status = createTrack(mStreamType, mCblk-&gt;sampleRate, mFormat, mChannelCount,  
mFrameCount, mFlags, mSharedBuffer, getOutput(), false);  
if (status == NO\_ERROR) {  
status = mAudioTrack-&gt;start();  
if (status == NO\_ERROR) {  
mNewPosition = mCblk-&gt;server + mUpdatePeriod;  
}  
}  
}  
if (status != NO\_ERROR) {  
LOGV("start() failed");  
android\_atomic\_and(~1, &mActive);  
if (t != 0) {  
t-&gt;requestExit();  
} else {  
setpriority(PRIO\_PROCESS, 0, ANDROID\_PRIORITY\_NORMAL);  
}  
}  
}

if (t != 0) {  
t-&gt;mLock.unlock();  
}  
}  
\------------------------------AudioTrack::start----------------------------------  
}  
\------------------------------android\_media\_AudioTrack\_start----------------------------------  
mPlayState = PLAYSTATE\_PLAYING;  
}  
}  
\------------------------------play----------------------------------  
Thread.sleep(100);  
log(TEST\_NAME, "position ="+ track.getPlaybackHeadPosition());  
assertTrue(TEST\_NAME, track.getPlaybackHeadPosition() &gt; 0);  
//-------- tear down --------------  
track.release();  
}  
###########################################################