From d3fc8ac6c52c20a6dc2de15d7cf306da8442e414 Mon Sep 17 00:00:00 2001 From: Eric Laurent Date: Tue, 1 Dec 2009 02:17:41 -0800 Subject: [PATCH] Fix issue 2292062: Audio freezes for three seconds when choosing ringtones with a headset connected and music playing. The problem comes from a deadlock with AudioPolicyService mutex: When the second ringtone starts, this mutex is locked by AudioPolicyService::startOutput() which in turn calls setParameters() to change the output device. Audioflinger::ThreadBase::setParameters() signals the parameter change to the AudioFlinger mixer thread and waits for a condition indicating that the parameter change has been processed. At the same time, the mixer thread detects that the audio track corresponding to the first ring tone has been killed and calls its destructor. This calls AudioPolicyService::releaseOutput() which tries to lock the AudioPolicyService mutex. If this happens before the mixer thread can process the setParameters() command we are deadlocked. The deadlock ends because setParameters() uses a timeout when waiting for the condition. This regression was introduced by change 33736 fixing issue 2265163. The fix consists in calling AudioPolicyService::releaseOutput() from Track::destroy() instead of from Track destructor: as detroy() is never called from the mixer thread loop (as opposed to the destructor) the deadlock described above cannot occur. --- libs/audioflinger/AudioFlinger.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/libs/audioflinger/AudioFlinger.cpp b/libs/audioflinger/AudioFlinger.cpp index daec6e885..9ec8de575 100644 --- a/libs/audioflinger/AudioFlinger.cpp +++ b/libs/audioflinger/AudioFlinger.cpp @@ -2277,10 +2277,8 @@ AudioFlinger::PlaybackThread::Track::~Track() LOGV("PlaybackThread::Track destructor"); sp thread = mThread.promote(); if (thread != 0) { - thread->mLock.lock(); + Mutex::Autolock _l(thread->mLock); mState = TERMINATED; - thread->mLock.unlock(); - AudioSystem::releaseOutput(thread->id()); } } @@ -2298,8 +2296,11 @@ void AudioFlinger::PlaybackThread::Track::destroy() { // scope for mLock sp thread = mThread.promote(); if (thread != 0) { - if (!isOutputTrack() && (mState == ACTIVE || mState == RESUMING)) { - AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType); + if (!isOutputTrack()) { + if (mState == ACTIVE || mState == RESUMING) { + AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType); + } + AudioSystem::releaseOutput(thread->id()); } Mutex::Autolock _l(thread->mLock); PlaybackThread *playbackThread = (PlaybackThread *)thread.get();