[automerger skipped] Merge "AudioFlinger: Use audio_utils::mutex" into udc-dev-plus-aosp am: 65427d50cb am: 05101a67de -s ours
am skip reason: Merged-In Iba9e1e8f6d5f9ad2e31ea4e09598f2829ece3f02 with SHA-1 85a074502c is already in history
Original change: https://googleplex-android-review.googlesource.com/c/platform/frameworks/av/+/24829131
Change-Id: If884764b966944f7e0f8b0d65b9bfe8bc747f834
Signed-off-by: Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>
diff --git a/camera/Android.bp b/camera/Android.bp
index b3f70f4..a3fd7f9 100644
--- a/camera/Android.bp
+++ b/camera/Android.bp
@@ -144,6 +144,7 @@
srcs: [
"aidl/android/hardware/CameraExtensionSessionStats.aidl",
"aidl/android/hardware/ICameraService.aidl",
+ "aidl/android/hardware/CameraIdRemapping.aidl",
"aidl/android/hardware/ICameraServiceListener.aidl",
"aidl/android/hardware/ICameraServiceProxy.aidl",
"aidl/android/hardware/camera2/ICameraDeviceCallbacks.aidl",
diff --git a/camera/aidl/android/hardware/CameraIdRemapping.aidl b/camera/aidl/android/hardware/CameraIdRemapping.aidl
new file mode 100644
index 0000000..453f696
--- /dev/null
+++ b/camera/aidl/android/hardware/CameraIdRemapping.aidl
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2023 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.
+ */
+
+package android.hardware;
+
+/**
+ * Specifies a remapping of Camera Ids.
+ *
+ * Example: For a given package, a remapping of camera id0 to id1 specifies
+ * that any operation to perform on id0 should instead be performed on id1.
+ *
+ * @hide
+ */
+parcelable CameraIdRemapping {
+ /**
+ * Specifies remapping of Camera Ids per package.
+ */
+ parcelable PackageIdRemapping {
+ /** Package Name (e.g. com.android.xyz). */
+ @utf8InCpp String packageName;
+ /**
+ * Ordered list of Camera Ids to replace. Only Camera Ids present in this list will be
+ * affected.
+ */
+ @utf8InCpp List<String> cameraIdsToReplace;
+ /**
+ * Ordered list of updated Camera Ids, where updatedCameraIds[i] corresponds to
+ * the updated camera id for cameraIdsToReplace[i].
+ */
+ @utf8InCpp List<String> updatedCameraIds;
+ }
+
+ /**
+ * List of Camera Id remappings to perform.
+ */
+ List<PackageIdRemapping> packageIdRemappings;
+}
diff --git a/camera/aidl/android/hardware/ICameraService.aidl b/camera/aidl/android/hardware/ICameraService.aidl
index ed37b2d..409a930 100644
--- a/camera/aidl/android/hardware/ICameraService.aidl
+++ b/camera/aidl/android/hardware/ICameraService.aidl
@@ -29,6 +29,7 @@
import android.hardware.camera2.impl.CameraMetadataNative;
import android.hardware.ICameraServiceListener;
import android.hardware.CameraInfo;
+import android.hardware.CameraIdRemapping;
import android.hardware.CameraStatus;
import android.hardware.CameraExtensionSessionStats;
@@ -131,6 +132,22 @@
int targetSdkVersion);
/**
+ * Remap Camera Ids in the CameraService.
+ *
+ * Once this is in effect, all binder calls in the ICameraService that
+ * use logicalCameraId should consult remapping state to arrive at the
+ * correct cameraId to perform the operation on.
+ *
+ * Note: Before the new cameraIdRemapping state is applied, the previous
+ * state is cleared.
+ *
+ * @param cameraIdRemapping the camera ids to remap. Sending an unpopulated
+ * cameraIdRemapping object will result in clearing of any previous
+ * cameraIdRemapping state in the camera service.
+ */
+ void remapCameraIds(in CameraIdRemapping cameraIdRemapping);
+
+ /**
* Remove listener for changes to camera device and flashlight state.
*/
void removeListener(ICameraServiceListener listener);
diff --git a/media/codec2/sfplugin/CCodec.cpp b/media/codec2/sfplugin/CCodec.cpp
index 86fd8ab..1153fb6 100644
--- a/media/codec2/sfplugin/CCodec.cpp
+++ b/media/codec2/sfplugin/CCodec.cpp
@@ -46,6 +46,7 @@
#include <media/stagefright/BufferProducerWrapper.h>
#include <media/stagefright/MediaCodecConstants.h>
#include <media/stagefright/PersistentSurface.h>
+#include <media/stagefright/RenderedFrameInfo.h>
#include <utils/NativeHandle.h>
#include "C2OMXNode.h"
@@ -672,8 +673,7 @@
}
void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
- mCodec->mCallback->onOutputFramesRendered(
- {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
+ mCodec->mCallback->onOutputFramesRendered({RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
}
void onOutputBuffersChanged() override {
@@ -2137,7 +2137,7 @@
}
std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
- status_t err = mChannel->prepareInitialInputBuffers(&clientInputBuffers);
+ status_t err = mChannel->prepareInitialInputBuffers(&clientInputBuffers, true);
if (err != OK) {
if (err == NO_MEMORY) {
// NO_MEMORY happens here when all the buffers are still
@@ -2160,7 +2160,6 @@
const std::unique_ptr<Config> &config = *configLocked;
return config->mBuffersBoundToCodec;
}());
-
{
Mutexed<State>::Locked state(mState);
if (state->get() != RESUMING) {
diff --git a/media/codec2/sfplugin/CCodecBufferChannel.cpp b/media/codec2/sfplugin/CCodecBufferChannel.cpp
index c93b7d0..38fe2ed 100644
--- a/media/codec2/sfplugin/CCodecBufferChannel.cpp
+++ b/media/codec2/sfplugin/CCodecBufferChannel.cpp
@@ -25,6 +25,8 @@
#include <atomic>
#include <list>
#include <numeric>
+#include <thread>
+#include <chrono>
#include <C2AllocatorGralloc.h>
#include <C2PlatformSupport.h>
@@ -1042,6 +1044,15 @@
if (desiredRenderTimeNs < nowNs) {
desiredRenderTimeNs = nowNs;
}
+
+ // If the render time is more than a second from now, then pretend the frame is supposed to be
+ // rendered immediately, because that's what SurfaceFlinger heuristics will do. This is a tight
+ // coupling, but is really the only way to optimize away unnecessary present fence checks in
+ // processRenderedFrames.
+ if (desiredRenderTimeNs > nowNs + 1*1000*1000*1000LL) {
+ desiredRenderTimeNs = nowNs;
+ }
+
// We've just queued a frame to the surface, so keep track of it and later check to see if it is
// actually rendered.
TrackedFrame frame;
@@ -1615,22 +1626,31 @@
}
status_t CCodecBufferChannel::prepareInitialInputBuffers(
- std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers) {
+ std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers, bool retry) {
if (mInputSurface) {
return OK;
}
size_t numInputSlots = mInput.lock()->numSlots;
-
- {
- Mutexed<Input>::Locked input(mInput);
- while (clientInputBuffers->size() < numInputSlots) {
- size_t index;
- sp<MediaCodecBuffer> buffer;
- if (!input->buffers->requestNewBuffer(&index, &buffer)) {
- break;
+ int retryCount = 1;
+ for (; clientInputBuffers->empty() && retryCount >= 0; retryCount--) {
+ {
+ Mutexed<Input>::Locked input(mInput);
+ while (clientInputBuffers->size() < numInputSlots) {
+ size_t index;
+ sp<MediaCodecBuffer> buffer;
+ if (!input->buffers->requestNewBuffer(&index, &buffer)) {
+ break;
+ }
+ clientInputBuffers->emplace(index, buffer);
}
- clientInputBuffers->emplace(index, buffer);
+ }
+ if (!retry || (retryCount <= 0)) {
+ break;
+ }
+ if (clientInputBuffers->empty()) {
+ // wait: buffer may be in transit from component.
+ std::this_thread::sleep_for(std::chrono::milliseconds(4));
}
}
if (clientInputBuffers->empty()) {
diff --git a/media/codec2/sfplugin/CCodecBufferChannel.h b/media/codec2/sfplugin/CCodecBufferChannel.h
index 1b5c031..045a25f 100644
--- a/media/codec2/sfplugin/CCodecBufferChannel.h
+++ b/media/codec2/sfplugin/CCodecBufferChannel.h
@@ -140,7 +140,8 @@
* initial input buffers.
*/
status_t prepareInitialInputBuffers(
- std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers);
+ std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers,
+ bool retry = false);
/**
* Request initial input buffers as prepared in clientInputBuffers.
diff --git a/media/libaudioclient/aidl/android/media/ISoundDose.aidl b/media/libaudioclient/aidl/android/media/ISoundDose.aidl
index 6cb22ef..d80b6bf 100644
--- a/media/libaudioclient/aidl/android/media/ISoundDose.aidl
+++ b/media/libaudioclient/aidl/android/media/ISoundDose.aidl
@@ -55,6 +55,30 @@
*/
oneway void setCsdEnabled(boolean enabled);
+ /**
+ * Structure containing a device identifier by address and type together with
+ * the categorization whether it is a headphone or not.
+ */
+ @JavaDerive(toString = true)
+ parcelable AudioDeviceCategory {
+ @utf8InCpp String address;
+ int internalAudioType;
+ boolean csdCompatible;
+ }
+
+ /**
+ * Resets the list of stored device categories for the native layer. Should
+ * only be called once at boot time after parsing the existing AudioDeviceCategories.
+ */
+ oneway void initCachedAudioDeviceCategories(in AudioDeviceCategory[] audioDevices);
+
+ /**
+ * Sets whether a device for a given address and type is a headphone or not.
+ * This is used to determine whether we compute the CSD on the given device
+ * since we can not rely completely on the device annotations.
+ */
+ oneway void setAudioDeviceCategory(in AudioDeviceCategory audioDevice);
+
/* -------------------------- Test API methods --------------------------
/** Get the currently used RS2 upper bound. */
float getOutputRs2UpperBound();
diff --git a/media/libaudiofoundation/AudioContainers.cpp b/media/libaudiofoundation/AudioContainers.cpp
index 202a400..3034b9a 100644
--- a/media/libaudiofoundation/AudioContainers.cpp
+++ b/media/libaudiofoundation/AudioContainers.cpp
@@ -119,4 +119,15 @@
return ss.str();
}
+std::string dumpMixerBehaviors(const MixerBehaviorSet& mixerBehaviors) {
+ std::stringstream ss;
+ for (auto it = mixerBehaviors.begin(); it != mixerBehaviors.end(); ++it) {
+ if (it != mixerBehaviors.begin()) {
+ ss << ", ";
+ }
+ ss << (*it);
+ }
+ return ss.str();
+}
+
} // namespace android
diff --git a/media/libaudiofoundation/include/media/AudioContainers.h b/media/libaudiofoundation/include/media/AudioContainers.h
index 88dcee9..f22ee40 100644
--- a/media/libaudiofoundation/include/media/AudioContainers.h
+++ b/media/libaudiofoundation/include/media/AudioContainers.h
@@ -126,6 +126,8 @@
std::string dumpDeviceTypes(const DeviceTypeSet& deviceTypes);
+std::string dumpMixerBehaviors(const MixerBehaviorSet& mixerBehaviors);
+
/**
* Return human readable string for device types.
*/
diff --git a/media/libeffects/visualizer/aidl/VisualizerContext.cpp b/media/libeffects/visualizer/aidl/VisualizerContext.cpp
index 5d0d08d..a1726ad 100644
--- a/media/libeffects/visualizer/aidl/VisualizerContext.cpp
+++ b/media/libeffects/visualizer/aidl/VisualizerContext.cpp
@@ -223,8 +223,7 @@
deltaSamples = kMaxCaptureBufSize;
}
- int32_t capturePoint;
- //capturePoint = (int32_t)mCaptureIdx - deltaSamples;
+ int32_t capturePoint, captureSamples = mCaptureSamples;
__builtin_sub_overflow((int32_t) mCaptureIdx, deltaSamples, &capturePoint);
// a negative capturePoint means we wrap the buffer.
if (capturePoint < 0) {
@@ -232,13 +231,14 @@
if (size > mCaptureSamples) {
size = mCaptureSamples;
}
+ // first part of two stages copy, capture to the end of buffer and reset the size/point
result.insert(result.end(), &mCaptureBuf[kMaxCaptureBufSize + capturePoint],
&mCaptureBuf[kMaxCaptureBufSize + capturePoint + size]);
- mCaptureSamples -= size;
+ captureSamples -= size;
capturePoint = 0;
}
result.insert(result.end(), &mCaptureBuf[capturePoint],
- &mCaptureBuf[capturePoint + mCaptureSamples]);
+ &mCaptureBuf[capturePoint + captureSamples]);
mLastCaptureIdx = mCaptureIdx;
return result;
}
diff --git a/media/libstagefright/ACodec.cpp b/media/libstagefright/ACodec.cpp
index a91b24a..cf29a25 100644
--- a/media/libstagefright/ACodec.cpp
+++ b/media/libstagefright/ACodec.cpp
@@ -43,6 +43,7 @@
#include <media/stagefright/MediaDefs.h>
#include <media/stagefright/OMXClient.h>
#include <media/stagefright/PersistentSurface.h>
+#include <media/stagefright/RenderedFrameInfo.h>
#include <media/stagefright/SurfaceUtils.h>
#include <media/hardware/HardwareAPI.h>
#include <media/MediaBufferHolder.h>
@@ -64,11 +65,14 @@
#include "include/SharedMemoryBuffer.h"
#include <media/stagefright/omx/OMXUtils.h>
+#include <server_configurable_flags/get_flags.h>
+
namespace android {
typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
using hardware::media::omx::V1_0::Status;
+using server_configurable_flags::GetServerConfigurableFlag;
enum {
kMaxIndicesToCheck = 32, // used when enumerating supported formats and profiles
@@ -81,6 +85,11 @@
}
+static bool areRenderMetricsEnabled() {
+ std::string v = GetServerConfigurableFlag("media_native", "render_metrics_enabled", "false");
+ return v == "true";
+}
+
// OMX errors are directly mapped into status_t range if
// there is no corresponding MediaError status code.
// Use the statusFromOMXError(int32_t omxError) function.
@@ -563,6 +572,9 @@
ACodec::ACodec()
: mSampleRate(0),
mNodeGeneration(0),
+ mAreRenderMetricsEnabled(areRenderMetricsEnabled()),
+ mIsWindowToDisplay(false),
+ mHasPresentFenceTimes(false),
mUsingNativeWindow(false),
mNativeWindowUsageBits(0),
mLastNativeWindowDataSpace(HAL_DATASPACE_UNKNOWN),
@@ -634,7 +646,8 @@
if (!mBufferChannel) {
mBufferChannel = std::make_shared<ACodecBufferChannel>(
new AMessage(kWhatInputBufferFilled, this),
- new AMessage(kWhatOutputBufferDrained, this));
+ new AMessage(kWhatOutputBufferDrained, this),
+ new AMessage(kWhatPollForRenderedBuffers, this));
}
return mBufferChannel;
}
@@ -744,6 +757,7 @@
// if we have not yet started the codec, we can simply set the native window
if (mBuffers[kPortIndexInput].size() == 0) {
mNativeWindow = surface;
+ initializeFrameTracking();
return OK;
}
@@ -852,6 +866,7 @@
mNativeWindow = nativeWindow;
mNativeWindowUsageBits = usageBits;
+ initializeFrameTracking();
return OK;
}
@@ -962,7 +977,6 @@
BufferInfo info;
info.mStatus = BufferInfo::OWNED_BY_US;
info.mFenceFd = -1;
- info.mRenderInfo = NULL;
info.mGraphicBuffer = NULL;
info.mNewGraphicBuffer = false;
@@ -1230,6 +1244,7 @@
*bufferCount = def.nBufferCountActual;
*bufferSize = def.nBufferSize;
+ initializeFrameTracking();
return err;
}
@@ -1268,7 +1283,6 @@
info.mStatus = BufferInfo::OWNED_BY_US;
info.mFenceFd = fenceFd;
info.mIsReadFence = false;
- info.mRenderInfo = NULL;
info.mGraphicBuffer = graphicBuffer;
info.mNewGraphicBuffer = false;
info.mDequeuedAt = mDequeueCounter;
@@ -1345,7 +1359,6 @@
BufferInfo info;
info.mStatus = BufferInfo::OWNED_BY_NATIVE_WINDOW;
info.mFenceFd = -1;
- info.mRenderInfo = NULL;
info.mGraphicBuffer = NULL;
info.mNewGraphicBuffer = false;
info.mDequeuedAt = mDequeueCounter;
@@ -1441,42 +1454,6 @@
return err;
}
-void ACodec::updateRenderInfoForDequeuedBuffer(
- ANativeWindowBuffer *buf, int fenceFd, BufferInfo *info) {
-
- info->mRenderInfo =
- mRenderTracker.updateInfoForDequeuedBuffer(
- buf, fenceFd, info - &mBuffers[kPortIndexOutput][0]);
-
- // check for any fences already signaled
- notifyOfRenderedFrames(false /* dropIncomplete */, info->mRenderInfo);
-}
-
-void ACodec::onFrameRendered(int64_t mediaTimeUs, nsecs_t systemNano) {
- if (mRenderTracker.onFrameRendered(mediaTimeUs, systemNano) != OK) {
- mRenderTracker.dumpRenderQueue();
- }
-}
-
-void ACodec::notifyOfRenderedFrames(bool dropIncomplete, FrameRenderTracker::Info *until) {
- std::list<FrameRenderTracker::Info> done =
- mRenderTracker.checkFencesAndGetRenderedFrames(until, dropIncomplete);
-
- // unlink untracked frames
- for (std::list<FrameRenderTracker::Info>::const_iterator it = done.cbegin();
- it != done.cend(); ++it) {
- ssize_t index = it->getIndex();
- if (index >= 0 && (size_t)index < mBuffers[kPortIndexOutput].size()) {
- mBuffers[kPortIndexOutput][index].mRenderInfo = NULL;
- } else if (index >= 0) {
- // THIS SHOULD NEVER HAPPEN
- ALOGE("invalid index %zd in %zu", index, mBuffers[kPortIndexOutput].size());
- }
- }
-
- mCallback->onOutputFramesRendered(done);
-}
-
void ACodec::onFirstTunnelFrameReady() {
mCallback->onFirstTunnelFrameReady();
}
@@ -1531,7 +1508,6 @@
info->mStatus = BufferInfo::OWNED_BY_US;
info->setWriteFence(fenceFd, "dequeueBufferFromNativeWindow");
- updateRenderInfoForDequeuedBuffer(buf, fenceFd, info);
return info;
}
}
@@ -1576,18 +1552,105 @@
oldest->mNewGraphicBuffer = true;
oldest->mStatus = BufferInfo::OWNED_BY_US;
oldest->setWriteFence(fenceFd, "dequeueBufferFromNativeWindow for oldest");
- mRenderTracker.untrackFrame(oldest->mRenderInfo);
- oldest->mRenderInfo = NULL;
ALOGV("replaced oldest buffer #%u with age %u, graphicBuffer %p",
(unsigned)(oldest - &mBuffers[kPortIndexOutput][0]),
mDequeueCounter - oldest->mDequeuedAt,
oldest->mGraphicBuffer->handle);
-
- updateRenderInfoForDequeuedBuffer(buf, fenceFd, oldest);
return oldest;
}
+void ACodec::initializeFrameTracking() {
+ mTrackedFrames.clear();
+
+ int isWindowToDisplay = 0;
+ mNativeWindow->query(mNativeWindow.get(), NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER,
+ &isWindowToDisplay);
+ mIsWindowToDisplay = isWindowToDisplay == 1;
+ // No frame tracking is needed if we're not sending frames to the display
+ if (!mIsWindowToDisplay) {
+ // Return early so we don't call into SurfaceFlinger (requiring permissions)
+ return;
+ }
+
+ int hasPresentFenceTimes = 0;
+ mNativeWindow->query(mNativeWindow.get(), NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT,
+ &hasPresentFenceTimes);
+ mHasPresentFenceTimes = hasPresentFenceTimes == 1;
+ if (!mHasPresentFenceTimes) {
+ ALOGI("Using latch times for frame rendered signals - present fences not supported");
+ }
+
+ status_t err = native_window_enable_frame_timestamps(mNativeWindow.get(), true);
+ if (err) {
+ ALOGE("Failed to enable frame timestamps (%d)", err);
+ }
+}
+
+void ACodec::trackReleasedFrame(int64_t frameId, int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
+ // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
+ // so track the frame as if the desired render time is now.
+ int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
+ if (desiredRenderTimeNs < nowNs) {
+ desiredRenderTimeNs = nowNs;
+ }
+
+ // If the render time is more than a second from now, then pretend the frame is supposed to be
+ // rendered immediately, because that's what SurfaceFlinger heuristics will do. This is a tight
+ // coupling, but is really the only way to optimize away unnecessary present fence checks in
+ // processRenderedFrames.
+ if (desiredRenderTimeNs > nowNs + 1*1000*1000*1000LL) {
+ desiredRenderTimeNs = nowNs;
+ }
+
+ // We've just queued a frame to the surface, so keep track of it and later check to see if it is
+ // actually rendered.
+ TrackedFrame frame;
+ frame.id = frameId;
+ frame.mediaTimeUs = mediaTimeUs;
+ frame.desiredRenderTimeNs = desiredRenderTimeNs;
+ mTrackedFrames.push_back(frame);
+}
+
+void ACodec::pollForRenderedFrames() {
+ std::list<RenderedFrameInfo> renderedFrameInfos;
+ // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
+ // in fact, been rendered.
+ int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
+ while (!mTrackedFrames.empty()) {
+ TrackedFrame & frame = mTrackedFrames.front();
+ // Frames that should have been rendered at least 100ms in the past are checked
+ if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
+ break;
+ }
+
+ status_t err;
+ nsecs_t latchOrPresentTimeNs = NATIVE_WINDOW_TIMESTAMP_INVALID;
+ err = native_window_get_frame_timestamps(mNativeWindow.get(), frame.id,
+ /* outRequestedPresentTime */ nullptr, /* outAcquireTime */ nullptr,
+ mHasPresentFenceTimes ? nullptr : &latchOrPresentTimeNs, // latch time
+ /* outFirstRefreshStartTime */ nullptr, /* outLastRefreshStartTime */ nullptr,
+ /* outGpuCompositionDoneTime */ nullptr,
+ mHasPresentFenceTimes ? &latchOrPresentTimeNs : nullptr, // display present time,
+ /* outDequeueReadyTime */ nullptr, /* outReleaseTime */ nullptr);
+ if (err) {
+ ALOGE("Failed to get frame timestamps for %lld: %d", (long long) frame.id, err);
+ }
+ // If we don't have a render time by now, then consider the frame as dropped
+ if (latchOrPresentTimeNs != NATIVE_WINDOW_TIMESTAMP_PENDING &&
+ latchOrPresentTimeNs != NATIVE_WINDOW_TIMESTAMP_INVALID) {
+ renderedFrameInfos.push_back(RenderedFrameInfo(frame.mediaTimeUs,
+ latchOrPresentTimeNs));
+ }
+
+ mTrackedFrames.pop_front();
+ }
+
+ if (!renderedFrameInfos.empty()) {
+ mCallback->onOutputFramesRendered(renderedFrameInfos);
+ }
+}
+
status_t ACodec::freeBuffersOnPort(OMX_U32 portIndex) {
if (portIndex == kPortIndexInput) {
mBufferChannel->setInputBufferArray({});
@@ -1663,11 +1726,6 @@
::close(info->mFenceFd);
}
- if (portIndex == kPortIndexOutput) {
- mRenderTracker.untrackFrame(info->mRenderInfo, i);
- info->mRenderInfo = NULL;
- }
-
// remove buffer even if mOMXNode->freeBuffer fails
mBuffers[portIndex].erase(mBuffers[portIndex].begin() + i);
return err;
@@ -6032,22 +6090,10 @@
sp<RefBase> obj;
CHECK(msg->findObject("messages", &obj));
sp<MessageList> msgList = static_cast<MessageList *>(obj.get());
-
- bool receivedRenderedEvents = false;
for (std::list<sp<AMessage>>::const_iterator it = msgList->getList().cbegin();
it != msgList->getList().cend(); ++it) {
(*it)->setWhat(ACodec::kWhatOMXMessageItem);
mCodec->handleMessage(*it);
- int32_t type;
- CHECK((*it)->findInt32("type", &type));
- if (type == omx_message::FRAME_RENDERED) {
- receivedRenderedEvents = true;
- }
- }
-
- if (receivedRenderedEvents) {
- // NOTE: all buffers are rendered in this case
- mCodec->notifyOfRenderedFrames();
}
return true;
}
@@ -6609,15 +6655,6 @@
info->mDequeuedAt = ++mCodec->mDequeueCounter;
info->mStatus = BufferInfo::OWNED_BY_US;
- if (info->mRenderInfo != NULL) {
- // The fence for an emptied buffer must have signaled, but there still could be queued
- // or out-of-order dequeued buffers in the render queue prior to this buffer. Drop these,
- // as we will soon requeue this buffer to the surface. While in theory we could still keep
- // track of buffers that are requeued to the surface, it is better to add support to the
- // buffer-queue to notify us of released buffers and their fences (in the future).
- mCodec->notifyOfRenderedFrames(true /* dropIncomplete */);
- }
-
// byte buffers cannot take fences, so wait for any fence now
if (mCodec->mNativeWindow == NULL) {
(void)mCodec->waitForFence(fenceFd, "onOMXFillBufferDone");
@@ -6824,14 +6861,6 @@
mCodec->mLastHdr10PlusBuffer = hdr10PlusInfo;
}
- // save buffers sent to the surface so we can get render time when they return
- int64_t mediaTimeUs = -1;
- buffer->meta()->findInt64("timeUs", &mediaTimeUs);
- if (mediaTimeUs >= 0) {
- mCodec->mRenderTracker.onFrameQueued(
- mediaTimeUs, info->mGraphicBuffer, new Fence(::dup(info->mFenceFd)));
- }
-
int64_t timestampNs = 0;
if (!msg->findInt64("timestampNs", ×tampNs)) {
// use media timestamp if client did not request a specific render timestamp
@@ -6845,11 +6874,25 @@
err = native_window_set_buffers_timestamp(mCodec->mNativeWindow.get(), timestampNs);
ALOGW_IF(err != NO_ERROR, "failed to set buffer timestamp: %d", err);
+ uint64_t frameId;
+ err = native_window_get_next_frame_id(mCodec->mNativeWindow.get(), &frameId);
+
info->checkReadFence("onOutputBufferDrained before queueBuffer");
err = mCodec->mNativeWindow->queueBuffer(
mCodec->mNativeWindow.get(), info->mGraphicBuffer.get(), info->mFenceFd);
- // TODO(b/266211548): Poll the native window for rendered buffers, since when queueing
- // buffers, the frame event history delta is retrieved.
+
+ int64_t mediaTimeUs = -1;
+ buffer->meta()->findInt64("timeUs", &mediaTimeUs);
+ if (mCodec->mAreRenderMetricsEnabled && mCodec->mIsWindowToDisplay) {
+ mCodec->trackReleasedFrame(frameId, mediaTimeUs, timestampNs);
+ mCodec->pollForRenderedFrames();
+ } else {
+ // When the surface is an intermediate surface, onFrameRendered is triggered immediately
+ // when the frame is queued to the non-display surface
+ mCodec->mCallback->onOutputFramesRendered({RenderedFrameInfo(mediaTimeUs,
+ timestampNs)});
+ }
+
info->mFenceFd = -1;
if (err == OK) {
info->mStatus = BufferInfo::OWNED_BY_NATIVE_WINDOW;
@@ -7076,7 +7119,6 @@
++mCodec->mNodeGeneration;
mCodec->mComponentName = componentName;
- mCodec->mRenderTracker.setComponentName(componentName);
mCodec->mFlags = 0;
if (componentName.endsWith(".secure")) {
@@ -7713,7 +7755,6 @@
void ACodec::ExecutingState::stateEntered() {
ALOGV("[%s] Now Executing", mCodec->mComponentName.c_str());
- mCodec->mRenderTracker.clear(systemTime(CLOCK_MONOTONIC));
mCodec->processDeferredMessages();
}
@@ -7824,7 +7865,15 @@
mCodec->signalSubmitOutputMetadataBufferIfEOS_workaround();
}
}
- return true;
+ handled = true;
+ break;
+ }
+
+ case kWhatPollForRenderedBuffers:
+ {
+ mCodec->pollForRenderedFrames();
+ handled = true;
+ break;
}
default:
@@ -8520,7 +8569,7 @@
}
bool ACodec::ExecutingState::onOMXFrameRendered(int64_t mediaTimeUs, nsecs_t systemNano) {
- mCodec->onFrameRendered(mediaTimeUs, systemNano);
+ mCodec->mCallback->onOutputFramesRendered({RenderedFrameInfo(mediaTimeUs, systemNano)});
return true;
}
@@ -8694,7 +8743,7 @@
bool ACodec::OutputPortSettingsChangedState::onOMXFrameRendered(
int64_t mediaTimeUs, nsecs_t systemNano) {
- mCodec->onFrameRendered(mediaTimeUs, systemNano);
+ mCodec->mCallback->onOutputFramesRendered({RenderedFrameInfo(mediaTimeUs, systemNano)});
return true;
}
@@ -8725,10 +8774,6 @@
OMX_CommandPortEnable, kPortIndexOutput);
}
- // Clear the RenderQueue in which queued GraphicBuffers hold the
- // actual buffer references in order to free them early.
- mCodec->mRenderTracker.clear(systemTime(CLOCK_MONOTONIC));
-
if (err == OK) {
err = mCodec->allocateBuffersOnPort(kPortIndexOutput);
ALOGE_IF(err != OK, "Failed to allocate output port buffers after port "
@@ -9112,8 +9157,6 @@
// the native window for rendering. Let's get those back as well.
mCodec->waitUntilAllPossibleNativeWindowBuffersAreReturnedToUs();
- mCodec->mRenderTracker.clear(systemTime(CLOCK_MONOTONIC));
-
mCodec->mCallback->onFlushCompleted();
mCodec->mPortEOS[kPortIndexInput] =
diff --git a/media/libstagefright/ACodecBufferChannel.cpp b/media/libstagefright/ACodecBufferChannel.cpp
index 8f2bed2..ad42813 100644
--- a/media/libstagefright/ACodecBufferChannel.cpp
+++ b/media/libstagefright/ACodecBufferChannel.cpp
@@ -32,6 +32,7 @@
#include <media/stagefright/foundation/ABuffer.h>
#include <media/stagefright/foundation/AMessage.h>
#include <media/stagefright/foundation/AUtils.h>
+#include <media/stagefright/ACodec.h>
#include <media/stagefright/MediaCodec.h>
#include <media/MediaCodecBuffer.h>
#include <system/window.h>
@@ -87,9 +88,11 @@
}
ACodecBufferChannel::ACodecBufferChannel(
- const sp<AMessage> &inputBufferFilled, const sp<AMessage> &outputBufferDrained)
+ const sp<AMessage> &inputBufferFilled, const sp<AMessage> &outputBufferDrained,
+ const sp<AMessage> &pollForRenderedBuffers)
: mInputBufferFilled(inputBufferFilled),
mOutputBufferDrained(outputBufferDrained),
+ mPollForRenderedBuffers(pollForRenderedBuffers),
mHeapSeqNum(-1) {
}
@@ -488,7 +491,7 @@
}
void ACodecBufferChannel::pollForRenderedBuffers() {
- // TODO(b/266211548): Poll the native window for rendered buffers.
+ mPollForRenderedBuffers->post();
}
status_t ACodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
diff --git a/media/libstagefright/MediaCodec.cpp b/media/libstagefright/MediaCodec.cpp
index e75ca2e..7e645b0 100644
--- a/media/libstagefright/MediaCodec.cpp
+++ b/media/libstagefright/MediaCodec.cpp
@@ -79,6 +79,7 @@
#include <media/stagefright/MediaErrors.h>
#include <media/stagefright/OMXClient.h>
#include <media/stagefright/PersistentSurface.h>
+#include <media/stagefright/RenderedFrameInfo.h>
#include <media/stagefright/SurfaceUtils.h>
#include <nativeloader/dlext_namespaces.h>
#include <private/android_filesystem_config.h>
@@ -210,6 +211,7 @@
// Render metrics
static const char *kCodecPlaybackDurationSec = "android.media.mediacodec.playback-duration-sec";
static const char *kCodecFirstRenderTimeUs = "android.media.mediacodec.first-render-time-us";
+static const char *kCodecLastRenderTimeUs = "android.media.mediacodec.last-render-time-us";
static const char *kCodecFramesReleased = "android.media.mediacodec.frames-released";
static const char *kCodecFramesRendered = "android.media.mediacodec.frames-rendered";
static const char *kCodecFramesDropped = "android.media.mediacodec.frames-dropped";
@@ -879,7 +881,7 @@
const sp<AMessage> &outputFormat) override;
virtual void onInputSurfaceDeclined(status_t err) override;
virtual void onSignaledInputEOS(status_t err) override;
- virtual void onOutputFramesRendered(const std::list<FrameRenderTracker::Info> &done) override;
+ virtual void onOutputFramesRendered(const std::list<RenderedFrameInfo> &done) override;
virtual void onOutputBuffersChanged() override;
virtual void onFirstTunnelFrameReady() override;
private:
@@ -988,7 +990,7 @@
notify->post();
}
-void CodecCallback::onOutputFramesRendered(const std::list<FrameRenderTracker::Info> &done) {
+void CodecCallback::onOutputFramesRendered(const std::list<RenderedFrameInfo> &done) {
sp<AMessage> notify(mNotify->dup());
notify->setInt32("what", kWhatOutputFramesRendered);
if (MediaCodec::CreateFramesRenderedMessage(done, notify)) {
@@ -1297,6 +1299,7 @@
const VideoRenderQualityMetrics &m = mVideoRenderQualityTracker.getMetrics();
if (m.frameReleasedCount > 0) {
mediametrics_setInt64(mMetricsHandle, kCodecFirstRenderTimeUs, m.firstRenderTimeUs);
+ mediametrics_setInt64(mMetricsHandle, kCodecLastRenderTimeUs, m.lastRenderTimeUs);
mediametrics_setInt64(mMetricsHandle, kCodecFramesReleased, m.frameReleasedCount);
mediametrics_setInt64(mMetricsHandle, kCodecFramesRendered, m.frameRenderedCount);
mediametrics_setInt64(mMetricsHandle, kCodecFramesSkipped, m.frameSkippedCount);
@@ -6085,12 +6088,10 @@
return onQueueInputBuffer(msg);
}
-//static
-size_t MediaCodec::CreateFramesRenderedMessage(
- const std::list<FrameRenderTracker::Info> &done, sp<AMessage> &msg) {
+template<typename T>
+static size_t CreateFramesRenderedMessageInternal(const std::list<T> &done, sp<AMessage> &msg) {
size_t index = 0;
- for (std::list<FrameRenderTracker::Info>::const_iterator it = done.cbegin();
- it != done.cend(); ++it) {
+ for (typename std::list<T>::const_iterator it = done.cbegin(); it != done.cend(); ++it) {
if (it->getRenderTimeNs() < 0) {
continue; // dropped frame from tracking
}
@@ -6101,6 +6102,18 @@
return index;
}
+//static
+size_t MediaCodec::CreateFramesRenderedMessage(
+ const std::list<RenderedFrameInfo> &done, sp<AMessage> &msg) {
+ return CreateFramesRenderedMessageInternal(done, msg);
+}
+
+//static
+size_t MediaCodec::CreateFramesRenderedMessage(
+ const std::list<FrameRenderTracker::Info> &done, sp<AMessage> &msg) {
+ return CreateFramesRenderedMessageInternal(done, msg);
+}
+
status_t MediaCodec::onReleaseOutputBuffer(const sp<AMessage> &msg) {
size_t index;
CHECK(msg->findSize("index", &index));
@@ -6192,7 +6205,9 @@
// presentation timestamp is used instead, which almost certainly occurs in the past,
// since it's almost always a zero-based offset from the start of the stream. In these
// scenarios, we expect the frame to be rendered with no delay.
- int64_t delayUs = noRenderTime ? 0 : renderTimeNs / 1000 - ALooper::GetNowUs();
+ int64_t nowUs = ALooper::GetNowUs();
+ int64_t renderTimeUs = renderTimeNs / 1000;
+ int64_t delayUs = renderTimeUs < nowUs ? 0 : renderTimeUs - nowUs;
delayUs += 100 * 1000; /* 100ms in microseconds */
status_t err =
mMsgPollForRenderedBuffers->postUnique(/* token= */ mMsgPollForRenderedBuffers,
diff --git a/media/libstagefright/VideoRenderQualityTracker.cpp b/media/libstagefright/VideoRenderQualityTracker.cpp
index fbd8577..e920bd1 100644
--- a/media/libstagefright/VideoRenderQualityTracker.cpp
+++ b/media/libstagefright/VideoRenderQualityTracker.cpp
@@ -455,6 +455,8 @@
if (mMetrics.firstRenderTimeUs == 0) {
mMetrics.firstRenderTimeUs = actualRenderTimeUs;
}
+ // Capture the timestamp at which the last frame was rendered
+ mMetrics.lastRenderTimeUs = actualRenderTimeUs;
mMetrics.frameRenderedCount++;
diff --git a/media/libstagefright/codecs/on2/enc/SoftVP8Encoder.cpp b/media/libstagefright/codecs/on2/enc/SoftVP8Encoder.cpp
index 04737a9..9198b7c 100644
--- a/media/libstagefright/codecs/on2/enc/SoftVP8Encoder.cpp
+++ b/media/libstagefright/codecs/on2/enc/SoftVP8Encoder.cpp
@@ -120,6 +120,11 @@
OMX_ERRORTYPE SoftVP8Encoder::internalGetVp8Params(
OMX_VIDEO_PARAM_VP8TYPE* vp8Params) {
+ if (!isValidOMXParam(vp8Params)) {
+ android_errorWriteLog(0x534e4554, "273936274");
+ return OMX_ErrorBadParameter;
+ }
+
if (vp8Params->nPortIndex != kOutputPortIndex) {
return OMX_ErrorUnsupportedIndex;
}
@@ -133,6 +138,11 @@
OMX_ERRORTYPE SoftVP8Encoder::internalSetVp8Params(
const OMX_VIDEO_PARAM_VP8TYPE* vp8Params) {
+ if (!isValidOMXParam(vp8Params)) {
+ android_errorWriteLog(0x534e4554, "273937171");
+ return OMX_ErrorBadParameter;
+ }
+
if (vp8Params->nPortIndex != kOutputPortIndex) {
return OMX_ErrorUnsupportedIndex;
}
diff --git a/media/libstagefright/codecs/on2/enc/SoftVP9Encoder.cpp b/media/libstagefright/codecs/on2/enc/SoftVP9Encoder.cpp
index 1ea1c85..f8495c2 100644
--- a/media/libstagefright/codecs/on2/enc/SoftVP9Encoder.cpp
+++ b/media/libstagefright/codecs/on2/enc/SoftVP9Encoder.cpp
@@ -119,6 +119,11 @@
OMX_ERRORTYPE SoftVP9Encoder::internalGetVp9Params(
OMX_VIDEO_PARAM_VP9TYPE *vp9Params) {
+ if (!isValidOMXParam(vp9Params)) {
+ android_errorWriteLog(0x534e4554, "273936553");
+ return OMX_ErrorBadParameter;
+ }
+
if (vp9Params->nPortIndex != kOutputPortIndex) {
return OMX_ErrorUnsupportedIndex;
}
@@ -133,6 +138,11 @@
OMX_ERRORTYPE SoftVP9Encoder::internalSetVp9Params(
const OMX_VIDEO_PARAM_VP9TYPE *vp9Params) {
+ if (!isValidOMXParam(vp9Params)) {
+ android_errorWriteLog(0x534e4554, "273937136");
+ return OMX_ErrorBadParameter;
+ }
+
if (vp9Params->nPortIndex != kOutputPortIndex) {
return OMX_ErrorUnsupportedIndex;
}
diff --git a/media/libstagefright/codecs/on2/enc/SoftVPXEncoder.cpp b/media/libstagefright/codecs/on2/enc/SoftVPXEncoder.cpp
index e9b4341..cbedb72 100644
--- a/media/libstagefright/codecs/on2/enc/SoftVPXEncoder.cpp
+++ b/media/libstagefright/codecs/on2/enc/SoftVPXEncoder.cpp
@@ -485,6 +485,11 @@
OMX_ERRORTYPE SoftVPXEncoder::internalGetAndroidVpxParams(
OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE *vpxAndroidParams) {
+ if (!isValidOMXParam(vpxAndroidParams)) {
+ android_errorWriteLog(0x534e4554, "273936601");
+ return OMX_ErrorBadParameter;
+ }
+
if (vpxAndroidParams->nPortIndex != kOutputPortIndex) {
return OMX_ErrorUnsupportedIndex;
}
@@ -501,6 +506,10 @@
OMX_ERRORTYPE SoftVPXEncoder::internalSetAndroidVpxParams(
const OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE *vpxAndroidParams) {
+ if (!isValidOMXParam(vpxAndroidParams)) {
+ android_errorWriteLog(0x534e4554, "273937551");
+ return OMX_ErrorBadParameter;
+ }
if (vpxAndroidParams->nPortIndex != kOutputPortIndex) {
return OMX_ErrorUnsupportedIndex;
}
diff --git a/media/libstagefright/colorconversion/ColorConverter.cpp b/media/libstagefright/colorconversion/ColorConverter.cpp
index f91a8b2..6c26c28 100644
--- a/media/libstagefright/colorconversion/ColorConverter.cpp
+++ b/media/libstagefright/colorconversion/ColorConverter.cpp
@@ -363,6 +363,7 @@
int32_t _g_u;
int32_t _g_v;
int32_t _b_u;
+ int32_t _c16; // 16 for limited range matrix, 0 for full rance
};
/*
@@ -425,18 +426,18 @@
*
* clip range 8-bit: [-277, 535], 10-bit: [-1111, 2155]
*/
-const struct ColorConverter::Coeffs BT601_FULL = { 256, 359, 88, 183, 454 };
-const struct ColorConverter::Coeffs BT601_LIMITED = { 298, 409, 100, 208, 516 };
-const struct ColorConverter::Coeffs BT601_LTD_10BIT = { 299, 410, 101, 209, 518 };
+const struct ColorConverter::Coeffs BT601_FULL = { 256, 359, 88, 183, 454, 0 };
+const struct ColorConverter::Coeffs BT601_LIMITED = { 298, 409, 100, 208, 516, 16 };
+const struct ColorConverter::Coeffs BT601_LTD_10BIT = { 299, 410, 101, 209, 518, 16 };
/**
* BT.709: K_R = 0.2126; K_B = 0.0722
*
* clip range 8-bit: [-289, 547], 10-bit: [-1159, 2202]
*/
-const struct ColorConverter::Coeffs BT709_FULL = { 256, 403, 48, 120, 475 };
-const struct ColorConverter::Coeffs BT709_LIMITED = { 298, 459, 55, 136, 541 };
-const struct ColorConverter::Coeffs BT709_LTD_10BIT = { 290, 460, 55, 137, 542 };
+const struct ColorConverter::Coeffs BT709_FULL = { 256, 403, 48, 120, 475, 0 };
+const struct ColorConverter::Coeffs BT709_LIMITED = { 298, 459, 55, 136, 541, 16 };
+const struct ColorConverter::Coeffs BT709_LTD_10BIT = { 299, 460, 55, 137, 542, 16 };
/**
* BT.2020: K_R = 0.2627; K_B = 0.0593
@@ -445,9 +446,9 @@
*
* This is the largest clip range.
*/
-const struct ColorConverter::Coeffs BT2020_FULL = { 256, 377, 42, 146, 482 };
-const struct ColorConverter::Coeffs BT2020_LIMITED = { 298, 430, 48, 167, 548 };
-const struct ColorConverter::Coeffs BT2020_LTD_10BIT = { 299, 431, 48, 167, 550 };
+const struct ColorConverter::Coeffs BT2020_FULL = { 256, 377, 42, 146, 482, 0 };
+const struct ColorConverter::Coeffs BT2020_LIMITED = { 298, 430, 48, 167, 548, 16 };
+const struct ColorConverter::Coeffs BT2020_LTD_10BIT = { 299, 431, 48, 167, 550, 16 };
constexpr int CLIP_RANGE_MIN_8BIT = -294;
constexpr int CLIP_RANGE_MAX_8BIT = 552;
@@ -781,7 +782,7 @@
signed _neg_g_v = -matrix->_g_v;
signed _r_v = matrix->_r_v;
signed _y = matrix->_y;
- signed _c16 = mSrcColorSpace.mRange == ColorUtils::kColorRangeLimited ? 16 : 0;
+ signed _c16 = matrix->_c16;
uint8_t *kAdjustedClip = initClip();
@@ -1257,6 +1258,7 @@
signed _neg_g_v = -matrix->_g_v;
signed _r_v = matrix->_r_v;
signed _y = matrix->_y;
+ signed _c16 = matrix->_c16;
uint8_t *dst_ptr = (uint8_t *)dst.mBits
+ dst.mCropTop * dst.mStride + dst.mCropLeft * dst.mBpp;
@@ -1275,13 +1277,12 @@
//TODO: optimize for chroma sampling, reading and writing multiple pixels
// within the same loop
- signed _c16 = 0;
+
void *kAdjustedClip = nullptr;
if (mSrcImage->getBitDepth() != ImageBitDepth8) {
ALOGE("BitDepth != 8 for MediaImage2");
return ERROR_UNSUPPORTED;
}
- _c16 = mSrcColorSpace.mRange == ColorUtils::kColorRangeLimited ? 16 : 0;
kAdjustedClip = initClip();
auto writeToDst = getWriteToDst(mDstFormat, (void *)kAdjustedClip);
@@ -1388,7 +1389,7 @@
signed _neg_g_v = -matrix->_g_v;
signed _r_v = matrix->_r_v;
signed _y = matrix->_y;
- signed _c16 = mSrcColorSpace.mRange == ColorUtils::kColorRangeLimited ? 16 : 0;
+ signed _c16 = matrix->_c16;
uint8_t *kAdjustedClip = initClip();
@@ -1463,7 +1464,7 @@
signed _neg_g_v = -matrix->_g_v;
signed _r_v = matrix->_r_v;
signed _y = matrix->_y;
- signed _c16 = mSrcColorSpace.mRange == ColorUtils::kColorRangeLimited ? 64 : 0;
+ signed _c64 = matrix->_c16 * 4;
uint16_t *kAdjustedClip10bit = initClip10Bit();
@@ -1483,8 +1484,8 @@
for (size_t y = 0; y < src.cropHeight(); ++y) {
for (size_t x = 0; x < src.cropWidth(); x += 2) {
signed y1, y2, u, v;
- y1 = (src_y[x] >> 6) - _c16;
- y2 = (src_y[x + 1] >> 6) - _c16;
+ y1 = (src_y[x] >> 6) - _c64;
+ y2 = (src_y[x + 1] >> 6) - _c64;
u = int(src_uv[x] >> 6) - 512;
v = int(src_uv[x + 1] >> 6) - 512;
diff --git a/media/libstagefright/include/ACodecBufferChannel.h b/media/libstagefright/include/ACodecBufferChannel.h
index 903280f..a464504 100644
--- a/media/libstagefright/include/ACodecBufferChannel.h
+++ b/media/libstagefright/include/ACodecBufferChannel.h
@@ -29,6 +29,7 @@
#include <media/IOMX.h>
namespace android {
+ struct ACodec;
namespace hardware {
class HidlMemory;
};
@@ -63,7 +64,8 @@
};
ACodecBufferChannel(
- const sp<AMessage> &inputBufferFilled, const sp<AMessage> &outputBufferDrained);
+ const sp<AMessage> &inputBufferFilled, const sp<AMessage> &outputBufferDrained,
+ const sp<AMessage> &pollForRenderedBuffers);
virtual ~ACodecBufferChannel();
// BufferChannelBase interface
@@ -138,6 +140,7 @@
const sp<AMessage> mInputBufferFilled;
const sp<AMessage> mOutputBufferDrained;
+ const sp<AMessage> mPollForRenderedBuffers;
sp<MemoryDealer> mDealer;
sp<IMemory> mDecryptDestination;
diff --git a/media/libstagefright/include/media/stagefright/ACodec.h b/media/libstagefright/include/media/stagefright/ACodec.h
index e535d5d..f876bc6 100644
--- a/media/libstagefright/include/media/stagefright/ACodec.h
+++ b/media/libstagefright/include/media/stagefright/ACodec.h
@@ -19,7 +19,7 @@
#include <set>
#include <stdint.h>
-#include <list>
+#include <deque>
#include <vector>
#include <android/native_window.h>
#include <media/hardware/MetadataBufferType.h>
@@ -27,9 +27,9 @@
#include <media/IOMX.h>
#include <media/stagefright/AHierarchicalStateMachine.h>
#include <media/stagefright/CodecBase.h>
-#include <media/stagefright/FrameRenderTracker.h>
#include <media/stagefright/MediaDefs.h>
#include <media/stagefright/SkipCutBuffer.h>
+#include <ui/GraphicBuffer.h>
#include <utils/NativeHandle.h>
#include <OMX_Audio.h>
#include <hardware/gralloc.h>
@@ -156,6 +156,7 @@
kWhatForceStateTransition = 'fstt',
kWhatCheckIfStuck = 'Cstk',
kWhatSubmitExtraOutputMetadataBuffer = 'sbxo',
+ kWhatPollForRenderedBuffers = 'pfrb',
};
enum {
@@ -177,6 +178,13 @@
| static_cast<uint64_t>(BufferUsage::VIDEO_DECODER),
};
+ struct TrackedFrame {
+ int64_t id;
+ int64_t mediaTimeUs;
+ int64_t desiredRenderTimeNs;
+ nsecs_t renderTimeNs;
+ };
+
struct BufferInfo {
enum Status {
OWNED_BY_US,
@@ -204,7 +212,6 @@
sp<GraphicBuffer> mGraphicBuffer;
bool mNewGraphicBuffer;
int mFenceFd;
- FrameRenderTracker::Info *mRenderInfo;
// The following field and 4 methods are used for debugging only
bool mIsReadFence;
@@ -251,6 +258,11 @@
int32_t mNodeGeneration;
sp<TAllocator> mAllocator[2];
+ std::deque<TrackedFrame> mTrackedFrames; // render information for buffers sent to a window
+ bool mAreRenderMetricsEnabled;
+ bool mIsWindowToDisplay;
+ bool mHasPresentFenceTimes;
+
bool mUsingNativeWindow;
sp<ANativeWindow> mNativeWindow;
int mNativeWindowUsageBits;
@@ -267,7 +279,6 @@
// format updates. This will equal to mOutputFormat until the first actual frame is received.
sp<AMessage> mBaseOutputFormat;
- FrameRenderTracker mRenderTracker; // render information for buffers rendered by ACodec
std::vector<BufferInfo> mBuffers[2];
bool mPortEOS[2];
status_t mInputEOSResult;
@@ -349,6 +360,10 @@
status_t freeOutputBuffersNotOwnedByComponent();
BufferInfo *dequeueBufferFromNativeWindow();
+ void initializeFrameTracking();
+ void trackReleasedFrame(int64_t frameId, int64_t mediaTimeUs, int64_t desiredRenderTimeNs);
+ void pollForRenderedFrames();
+
inline bool storingMetadataInDecodedBuffers() {
return (mPortMode[kPortIndexOutput] == IOMX::kPortModeDynamicANWBuffer) && !mIsEncoder;
}
@@ -571,21 +586,6 @@
void processDeferredMessages();
void onFrameRendered(int64_t mediaTimeUs, nsecs_t systemNano);
- // called when we have dequeued a buffer |buf| from the native window to track render info.
- // |fenceFd| is the dequeue fence, and |info| points to the buffer info where this buffer is
- // stored.
- void updateRenderInfoForDequeuedBuffer(
- ANativeWindowBuffer *buf, int fenceFd, BufferInfo *info);
-
- // Checks to see if any frames have rendered up until |until|, and to notify client
- // (MediaCodec) of rendered frames up-until the frame pointed to by |until| or the first
- // unrendered frame. These frames are removed from the render queue.
- // If |dropIncomplete| is true, unrendered frames up-until |until| will be dropped from the
- // queue, allowing all rendered framed up till then to be notified of.
- // (This will effectively clear the render queue up-until (and including) |until|.)
- // If |until| is NULL, or is not in the rendered queue, this method will check all frames.
- void notifyOfRenderedFrames(
- bool dropIncomplete = false, FrameRenderTracker::Info *until = NULL);
void onFirstTunnelFrameReady();
diff --git a/media/libstagefright/include/media/stagefright/CodecBase.h b/media/libstagefright/include/media/stagefright/CodecBase.h
index 916d41e..90347f9 100644
--- a/media/libstagefright/include/media/stagefright/CodecBase.h
+++ b/media/libstagefright/include/media/stagefright/CodecBase.h
@@ -41,7 +41,7 @@
struct BufferProducerWrapper;
class MediaCodecBuffer;
struct PersistentSurface;
-struct RenderedFrameInfo;
+class RenderedFrameInfo;
class Surface;
struct ICrypto;
class IMemory;
diff --git a/media/libstagefright/include/media/stagefright/FrameRenderTracker.h b/media/libstagefright/include/media/stagefright/FrameRenderTracker.h
index c14755a..cab7ecc 100644
--- a/media/libstagefright/include/media/stagefright/FrameRenderTracker.h
+++ b/media/libstagefright/include/media/stagefright/FrameRenderTracker.h
@@ -32,61 +32,59 @@
namespace android {
-// Tracks the render information about a frame. Frames go through several states while
-// the render information is tracked:
-//
-// 1. queued frame: mMediaTime and mGraphicBuffer are set for the frame. mFence is the
-// queue fence (read fence). mIndex is negative, and mRenderTimeNs is invalid.
-// Key characteristics: mFence is not NULL and mIndex is negative.
-//
-// 2. dequeued frame: mFence is updated with the dequeue fence (write fence). mIndex is set.
-// Key characteristics: mFence is not NULL and mIndex is non-negative. mRenderTime is still
-// invalid.
-//
-// 3. rendered frame or frame: mFence is cleared, mRenderTimeNs is set.
-// Key characteristics: mFence is NULL.
-//
-struct RenderedFrameInfo {
- // set by client during onFrameQueued or onFrameRendered
- int64_t getMediaTimeUs() const { return mMediaTimeUs; }
-
- // -1 if frame is not yet rendered
- nsecs_t getRenderTimeNs() const { return mRenderTimeNs; }
-
- // set by client during updateRenderInfoForDequeuedBuffer; -1 otherwise
- ssize_t getIndex() const { return mIndex; }
-
- // creates information for a queued frame
- RenderedFrameInfo(int64_t mediaTimeUs, const sp<GraphicBuffer> &graphicBuffer,
- const sp<Fence> &fence)
- : mMediaTimeUs(mediaTimeUs),
- mRenderTimeNs(-1),
- mIndex(-1),
- mGraphicBuffer(graphicBuffer),
- mFence(fence) {
- }
-
- // creates information for a frame rendered on a tunneled surface
- RenderedFrameInfo(int64_t mediaTimeUs, nsecs_t renderTimeNs)
- : mMediaTimeUs(mediaTimeUs),
- mRenderTimeNs(renderTimeNs),
- mIndex(-1),
- mGraphicBuffer(NULL),
- mFence(NULL) {
- }
-
-private:
- int64_t mMediaTimeUs;
- nsecs_t mRenderTimeNs;
- ssize_t mIndex; // to be used by client
- sp<GraphicBuffer> mGraphicBuffer;
- sp<Fence> mFence;
-
- friend struct FrameRenderTracker;
-};
-
struct FrameRenderTracker {
- typedef RenderedFrameInfo Info;
+ // Tracks the render information about a frame. Frames go through several states while
+ // the render information is tracked:
+ //
+ // 1. queued frame: mMediaTime and mGraphicBuffer are set for the frame. mFence is the
+ // queue fence (read fence). mIndex is negative, and mRenderTimeNs is invalid.
+ // Key characteristics: mFence is not NULL and mIndex is negative.
+ //
+ // 2. dequeued frame: mFence is updated with the dequeue fence (write fence). mIndex is set.
+ // Key characteristics: mFence is not NULL and mIndex is non-negative. mRenderTime is still
+ // invalid.
+ //
+ // 3. rendered frame or frame: mFence is cleared, mRenderTimeNs is set.
+ // Key characteristics: mFence is NULL.
+ //
+ struct Info {
+ // set by client during onFrameQueued or onFrameRendered
+ int64_t getMediaTimeUs() const { return mMediaTimeUs; }
+
+ // -1 if frame is not yet rendered
+ nsecs_t getRenderTimeNs() const { return mRenderTimeNs; }
+
+ // set by client during updateRenderInfoForDequeuedBuffer; -1 otherwise
+ ssize_t getIndex() const { return mIndex; }
+
+ // creates information for a queued frame
+ Info(int64_t mediaTimeUs, const sp<GraphicBuffer> &graphicBuffer,
+ const sp<Fence> &fence)
+ : mMediaTimeUs(mediaTimeUs),
+ mRenderTimeNs(-1),
+ mIndex(-1),
+ mGraphicBuffer(graphicBuffer),
+ mFence(fence) {
+ }
+
+ // creates information for a frame rendered on a tunneled surface
+ Info(int64_t mediaTimeUs, nsecs_t renderTimeNs)
+ : mMediaTimeUs(mediaTimeUs),
+ mRenderTimeNs(renderTimeNs),
+ mIndex(-1),
+ mGraphicBuffer(NULL),
+ mFence(NULL) {
+ }
+
+ private:
+ int64_t mMediaTimeUs;
+ nsecs_t mRenderTimeNs;
+ ssize_t mIndex; // to be used by client
+ sp<GraphicBuffer> mGraphicBuffer;
+ sp<Fence> mFence;
+
+ friend struct FrameRenderTracker;
+ };
FrameRenderTracker();
diff --git a/media/libstagefright/include/media/stagefright/MediaCodec.h b/media/libstagefright/include/media/stagefright/MediaCodec.h
index bc0f6c5..ceba7d7 100644
--- a/media/libstagefright/include/media/stagefright/MediaCodec.h
+++ b/media/libstagefright/include/media/stagefright/MediaCodec.h
@@ -64,6 +64,7 @@
class MediaCodecBuffer;
class IMemory;
struct PersistentSurface;
+class RenderedFrameInfo;
class SoftwareRenderer;
class Surface;
namespace hardware {
@@ -281,6 +282,8 @@
// by adding rendered frame information to a base notification message. Returns the number
// of frames that were rendered.
static size_t CreateFramesRenderedMessage(
+ const std::list<RenderedFrameInfo> &done, sp<AMessage> &msg);
+ static size_t CreateFramesRenderedMessage(
const std::list<FrameRenderTracker::Info> &done, sp<AMessage> &msg);
static status_t CanFetchLinearBlock(
diff --git a/media/libstagefright/include/media/stagefright/RenderedFrameInfo.h b/media/libstagefright/include/media/stagefright/RenderedFrameInfo.h
new file mode 100644
index 0000000..4b8a58d
--- /dev/null
+++ b/media/libstagefright/include/media/stagefright/RenderedFrameInfo.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2015 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 RENDERED_FRAME_INFO_H
+#define RENDERED_FRAME_INFO_H
+
+namespace android {
+
+class RenderedFrameInfo {
+public:
+ RenderedFrameInfo(int64_t mediaTimeUs, int64_t renderTimeNs)
+ : mMediaTimeUs(mediaTimeUs), mRenderTimeNs(renderTimeNs) {}
+
+ int64_t getMediaTimeUs() const { return mMediaTimeUs; }
+ nsecs_t getRenderTimeNs() const { return mRenderTimeNs;}
+
+private:
+ int64_t mMediaTimeUs;
+ nsecs_t mRenderTimeNs;
+};
+
+} // android
+
+#endif // RENDERED_FRAME_INFO_H
\ No newline at end of file
diff --git a/media/libstagefright/include/media/stagefright/VideoRenderQualityTracker.h b/media/libstagefright/include/media/stagefright/VideoRenderQualityTracker.h
index 82ba81c..a656e6e 100644
--- a/media/libstagefright/include/media/stagefright/VideoRenderQualityTracker.h
+++ b/media/libstagefright/include/media/stagefright/VideoRenderQualityTracker.h
@@ -38,6 +38,9 @@
// The render time of the first video frame.
int64_t firstRenderTimeUs;
+ // The render time of the last video frame.
+ int64_t lastRenderTimeUs;
+
// The number of frames released to be rendered.
int64_t frameReleasedCount;
diff --git a/media/utils/BatteryNotifier.cpp b/media/utils/BatteryNotifier.cpp
index 09bc042..7762c24 100644
--- a/media/utils/BatteryNotifier.cpp
+++ b/media/utils/BatteryNotifier.cpp
@@ -85,8 +85,8 @@
void BatteryNotifier::noteStopAudio(uid_t uid) {
Mutex::Autolock _l(mLock);
- if (mAudioRefCounts.find(uid) == mAudioRefCounts.end()) {
- ALOGW("%s: audio refcount is broken for uid(%d).", __FUNCTION__, (int)uid);
+ if (mAudioRefCounts.find(uid) == mAudioRefCounts.end() || (mAudioRefCounts[uid] == 0)) {
+ ALOGE("%s: audio refcount is broken for uid(%d).", __FUNCTION__, (int)uid);
return;
}
diff --git a/media/utils/include/mediautils/BatteryNotifier.h b/media/utils/include/mediautils/BatteryNotifier.h
index 3812d7a..73bed4a 100644
--- a/media/utils/include/mediautils/BatteryNotifier.h
+++ b/media/utils/include/mediautils/BatteryNotifier.h
@@ -68,6 +68,38 @@
sp<IBatteryStats> getBatteryService_l();
};
+namespace mediautils {
+class BatteryStatsAudioHandle {
+ public:
+ static constexpr uid_t INVALID_UID = static_cast<uid_t>(-1);
+
+ explicit BatteryStatsAudioHandle(uid_t uid) : mUid(uid) {
+ if (uid != INVALID_UID) {
+ BatteryNotifier::getInstance().noteStartAudio(mUid);
+ }
+ }
+
+ BatteryStatsAudioHandle(BatteryStatsAudioHandle&& other) : mUid(other.mUid) {
+ other.mUid = INVALID_UID;
+ }
+
+ BatteryStatsAudioHandle(const BatteryStatsAudioHandle& other) = delete;
+
+ BatteryStatsAudioHandle& operator=(const BatteryStatsAudioHandle& other) = delete;
+
+ BatteryStatsAudioHandle& operator=(BatteryStatsAudioHandle&& other) = delete;
+
+ ~BatteryStatsAudioHandle() {
+ if (mUid != INVALID_UID) {
+ BatteryNotifier::getInstance().noteStopAudio(mUid);
+ }
+ }
+
+ private:
+ // Logically const
+ uid_t mUid = INVALID_UID;
+};
+} // namespace mediautils
} // namespace android
#endif // MEDIA_BATTERY_NOTIFIER_H
diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp
index fe4aec9..a98011d 100644
--- a/services/audioflinger/AudioFlinger.cpp
+++ b/services/audioflinger/AudioFlinger.cpp
@@ -318,7 +318,7 @@
size_t i = 0;
for (; i < mPlaybackThreads.size(); ++i) {
IAfPlaybackThread* thread = mPlaybackThreads.valueAt(i).get();
- Mutex::Autolock _tl(thread->mutex());
+ audio_utils::lock_guard _tl(thread->mutex());
sp<IAfTrack> track = thread->getTrackById_l(trackId);
if (track != nullptr) {
ALOGD("%s trackId: %u", __func__, trackId);
@@ -560,6 +560,9 @@
return ret;
}
+ // use unique_lock as we may selectively unlock.
+ audio_utils::unique_lock l(mutex());
+
// at this stage, a MmapThread was created when openOutput() or openInput() was called by
// audio policy manager and we can retrieve it
const sp<IAfMmapThread> thread = mMmapThreads.valueFor(io);
@@ -572,12 +575,14 @@
config->channel_mask = thread->channelMask();
config->format = thread->format();
} else {
+ l.unlock();
if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
AudioSystem::releaseOutput(portId);
} else {
AudioSystem::releaseInput(portId);
}
ret = NO_INIT;
+ // we don't reacquire the lock here as nothing left to do.
}
ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
@@ -621,7 +626,7 @@
if (module == 0) {
ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
- loadHwModule_l(audio_interfaces[i]);
+ loadHwModule_ll(audio_interfaces[i]);
}
// then try to find a module supporting the requested device.
for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
@@ -644,7 +649,7 @@
return NULL;
}
-void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
+void AudioFlinger::dumpClients_ll(int fd, const Vector<String16>& args __unused)
{
String8 result;
@@ -678,7 +683,7 @@
}
-void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
+void AudioFlinger::dumpInternals_l(int fd, const Vector<String16>& args __unused)
{
const size_t SIZE = 256;
char buffer[SIZE];
@@ -746,12 +751,12 @@
write(fd, result.c_str(), result.size());
}
- dumpClients(fd, args);
+ dumpClients_ll(fd, args);
if (clientLocked) {
clientMutex().unlock();
}
- dumpInternals(fd, args);
+ dumpInternals_l(fd, args);
// dump playback threads
for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
@@ -1089,7 +1094,7 @@
if (lStatus == NO_ERROR) {
// no risk of deadlock because AudioFlinger::mutex() is held
- Mutex::Autolock _dl(thread->mutex());
+ audio_utils::lock_guard _dl(thread->mutex());
// Connect secondary outputs. Failure on a secondary output must not imped the primary
// Any secondary output setup failure will lead to a desync between the AP and AF until
// the track is destroyed.
@@ -1097,8 +1102,9 @@
// move effect chain to this output thread if an effect on same session was waiting
// for a track to be created
if (effectThread != nullptr) {
- Mutex::Autolock _sl(effectThread->mutex());
- if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
+ // No thread safety analysis: double lock on a thread capability.
+ audio_utils::lock_guard_no_thread_safety_analysis _sl(effectThread->mutex());
+ if (moveEffectChain_ll(sessionId, effectThread, thread) == NO_ERROR) {
effectThreadId = thread->id();
effectIds = thread->getEffectIds_l(sessionId);
}
@@ -1474,7 +1480,8 @@
return mMasterMute;
}
-status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
+/* static */
+status_t AudioFlinger::checkStreamType(audio_stream_type_t stream)
{
if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
ALOGW("checkStreamType() invalid stream %d", stream);
@@ -1570,7 +1577,7 @@
if (support == nullptr) {
return BAD_VALUE;
}
- audio_utils::lock_guard _l(mutex());
+ audio_utils::lock_guard _l(hardwareMutex());
*support = false;
for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
if (mAudioHwDevs.valueAt(i)->supportsBluetoothVariableLatency()) {
@@ -1831,6 +1838,7 @@
}
if (thread != 0) {
status_t result = thread->setParameters(filteredKeyValuePairs);
+ audio_utils::lock_guard _l(mutex());
forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
return result;
}
@@ -2364,7 +2372,7 @@
// session and move it to this thread.
sp<IAfEffectChain> chain = getOrphanEffectChain_l(sessionId);
if (chain != 0) {
- Mutex::Autolock _l2(thread->mutex());
+ audio_utils::lock_guard _l2(thread->mutex());
thread->addEffectChain_l(chain);
}
break;
@@ -2417,7 +2425,7 @@
RETURN_STATUS_IF_ERROR(mDevicesFactoryHal->getDeviceNames(&hwModuleNames));
std::set<AudioMode> allSupportedModes;
for (const auto& name : hwModuleNames) {
- AudioHwDevice* module = loadHwModule_l(name.c_str());
+ AudioHwDevice* module = loadHwModule_ll(name.c_str());
if (module == nullptr) continue;
media::AudioHwModule aidlModule;
if (module->hwDevice()->getAudioPorts(&aidlModule.ports) == OK &&
@@ -2454,13 +2462,13 @@
}
audio_utils::lock_guard _l(mutex());
audio_utils::lock_guard lock(hardwareMutex());
- AudioHwDevice* module = loadHwModule_l(name);
+ AudioHwDevice* module = loadHwModule_ll(name);
return module != nullptr ? module->handle() : AUDIO_MODULE_HANDLE_NONE;
}
// loadHwModule_l() must be called with AudioFlinger::mutex()
// and AudioFlinger::hardwareMutex() held
-AudioHwDevice* AudioFlinger::loadHwModule_l(const char *name)
+AudioHwDevice* AudioFlinger::loadHwModule_ll(const char *name)
{
for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
@@ -3023,11 +3031,11 @@
checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
if (dstThread != NULL) {
// audioflinger lock is held so order of thread lock acquisition doesn't matter
- Mutex::Autolock _dl(dstThread->mutex());
- Mutex::Autolock _sl(playbackThread->mutex());
+ // Use scoped_lock to avoid deadlock order issues with duplicating threads.
+ audio_utils::scoped_lock sl(dstThread->mutex(), playbackThread->mutex());
Vector<sp<IAfEffectChain>> effectChains = playbackThread->getEffectChains_l();
for (size_t i = 0; i < effectChains.size(); i ++) {
- moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
+ moveEffectChain_ll(effectChains[i]->sessionId(), playbackThread.get(),
dstThread);
}
}
@@ -3064,6 +3072,7 @@
return NO_ERROR;
}
+/* static */
void AudioFlinger::closeOutputFinish(const sp<IAfPlaybackThread>& thread)
{
AudioStreamOut *out = thread->clearOutput();
@@ -3263,7 +3272,7 @@
// new capture on the same session
sp<IAfEffectChain> chain;
{
- Mutex::Autolock _sl(recordThread->mutex());
+ audio_utils::lock_guard _sl(recordThread->mutex());
const Vector<sp<IAfEffectChain>> effectChains = recordThread->getEffectChains_l();
// Note: maximum one chain per record thread
if (effectChains.size() != 0) {
@@ -3281,7 +3290,7 @@
continue;
}
if (t->hasAudioSession(chain->sessionId()) != 0) {
- Mutex::Autolock _l2(t->mutex());
+ audio_utils::lock_guard _l2(t->mutex());
ALOGV("closeInput() found thread %d for effect session %d",
t->id(), chain->sessionId());
t->addEffectChain_l(chain);
@@ -3465,7 +3474,7 @@
for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
sp<IAfPlaybackThread> t = mPlaybackThreads.valueAt(i);
- Mutex::Autolock _l(t->mutex());
+ audio_utils::lock_guard _l(t->mutex());
const Vector<sp<IAfEffectChain>> threadChains = t->getEffectChains_l();
for (size_t j = 0; j < threadChains.size(); j++) {
sp<IAfEffectChain> ec = threadChains[j];
@@ -3477,7 +3486,7 @@
for (size_t i = 0; i < mRecordThreads.size(); i++) {
sp<IAfRecordThread> t = mRecordThreads.valueAt(i);
- Mutex::Autolock _l(t->mutex());
+ audio_utils::lock_guard _l(t->mutex());
const Vector<sp<IAfEffectChain>> threadChains = t->getEffectChains_l();
for (size_t j = 0; j < threadChains.size(); j++) {
sp<IAfEffectChain> ec = threadChains[j];
@@ -3487,7 +3496,7 @@
for (size_t i = 0; i < mMmapThreads.size(); i++) {
const sp<IAfMmapThread> t = mMmapThreads.valueAt(i);
- Mutex::Autolock _l(t->mutex());
+ audio_utils::lock_guard _l(t->mutex());
const Vector<sp<IAfEffectChain>> threadChains = t->getEffectChains_l();
for (size_t j = 0; j < threadChains.size(); j++) {
sp<IAfEffectChain> ec = threadChains[j];
@@ -3515,7 +3524,7 @@
}
}
if (!found) {
- Mutex::Autolock _l(t->mutex());
+ audio_utils::lock_guard _l(t->mutex());
// remove all effects from the chain
while (ec->numberOfEffects()) {
sp<IAfEffectModule> effect = ec->getEffectModule(0);
@@ -3747,7 +3756,7 @@
// The frameCount should also not be smaller than the secondary thread min frame
// count
size_t minFrameCount = AudioSystem::calculateMinFrameCount(
- [&] { Mutex::Autolock _l(secondaryThread->mutex());
+ [&] { audio_utils::lock_guard _l(secondaryThread->mutex());
return secondaryThread->latency_l(); }(),
secondaryThread->frameCount(), // normal frame count
secondaryThread->sampleRate(),
@@ -3806,7 +3815,7 @@
patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
}
- track->setTeePatchesToUpdate(std::move(teePatches));
+ track->setTeePatchesToUpdate_l(std::move(teePatches));
}
sp<audioflinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
@@ -3999,7 +4008,11 @@
lStatus = BAD_VALUE;
goto Exit;
}
- IAfPlaybackThread* const thread = checkPlaybackThread_l(io);
+ IAfPlaybackThread* thread;
+ {
+ audio_utils::lock_guard l(mutex());
+ thread = checkPlaybackThread_l(io);
+ }
if (thread == nullptr) {
ALOGE("%s: invalid output %d specified for AUDIO_SESSION_OUTPUT_STAGE", __func__, io);
lStatus = BAD_VALUE;
@@ -4193,7 +4206,7 @@
// session and used it instead of creating a new one.
sp<IAfEffectChain> chain = getOrphanEffectChain_l(sessionId);
if (chain != 0) {
- Mutex::Autolock _l2(thread->mutex());
+ audio_utils::lock_guard _l2(thread->mutex());
thread->addEffectChain_l(chain);
}
}
@@ -4285,9 +4298,8 @@
return BAD_VALUE;
}
- Mutex::Autolock _dl(dstThread->mutex());
- Mutex::Autolock _sl(srcThread->mutex());
- return moveEffectChain_l(sessionId, srcThread, dstThread);
+ audio_utils::scoped_lock _ll(dstThread->mutex(), srcThread->mutex());
+ return moveEffectChain_ll(sessionId, srcThread, dstThread);
}
@@ -4301,31 +4313,32 @@
if (thread == nullptr) {
return;
}
- Mutex::Autolock _sl(thread->mutex());
+ audio_utils::lock_guard _sl(thread->mutex());
sp<IAfEffectModule> effect = thread->getEffect_l(sessionId, effectId);
thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
}
-// moveEffectChain_l must be called with both srcThread and dstThread mutex()s held
-status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
+// moveEffectChain_ll must be called with the AudioFlinger::mutex()
+// and both srcThread and dstThread mutex()s held
+status_t AudioFlinger::moveEffectChain_ll(audio_session_t sessionId,
IAfPlaybackThread* srcThread, IAfPlaybackThread* dstThread)
{
- ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
- sessionId, srcThread, dstThread);
+ ALOGV("%s: session %d from thread %p to thread %p",
+ __func__, sessionId, srcThread, dstThread);
sp<IAfEffectChain> chain = srcThread->getEffectChain_l(sessionId);
if (chain == 0) {
- ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
- sessionId, srcThread);
+ ALOGW("%s: effect chain for session %d not on source thread %p",
+ __func__, sessionId, srcThread);
return INVALID_OPERATION;
}
// Check whether the destination thread and all effects in the chain are compatible
if (!chain->isCompatibleWithThread_l(dstThread)) {
- ALOGW("moveEffectChain_l() effect chain failed because"
+ ALOGW("%s: effect chain failed because"
" destination thread %p is not compatible with effects in the chain",
- dstThread);
+ __func__, dstThread);
return INVALID_OPERATION;
}
@@ -4347,7 +4360,7 @@
effect = chain->getEffectFromId_l(0)) {
srcThread->removeEffect_l(effect);
removed.add(effect);
- status = dstThread->addEffect_l(effect);
+ status = dstThread->addEffect_ll(effect);
if (status != NO_ERROR) {
errorString = StringPrintf(
"cannot add effect %p to destination thread", effect.get());
@@ -4373,7 +4386,7 @@
for (const auto& effect : removed) {
dstThread->removeEffect_l(effect); // Note: Depending on error location, the last
// effect may not have been placed on dstThread.
- if (srcThread->addEffect_l(effect) == NO_ERROR) {
+ if (srcThread->addEffect_ll(effect) == NO_ERROR) {
++restored;
if (dstChain == nullptr) {
dstChain = effect->getCallback()->chain().promote();
@@ -4389,7 +4402,7 @@
// If we do not take the dstChain lock, it is possible that processing is ongoing
// while we are starting the effect. This can cause glitches with volume,
// see b/202360137.
- dstChain->lock();
+ dstChain->mutex().lock();
for (const auto& effect : removed) {
if (effect->state() == IAfEffectModule::ACTIVE ||
effect->state() == IAfEffectModule::STOPPING) {
@@ -4397,7 +4410,7 @@
effect->start();
}
}
- dstChain->unlock();
+ dstChain->mutex().unlock();
}
if (status != NO_ERROR) {
@@ -4426,8 +4439,7 @@
const sp<IAfPlaybackThread> thread = threadBase ? threadBase->asIAfPlaybackThread() : nullptr;
if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
- Mutex::Autolock _dl(dstThread->mutex());
- Mutex::Autolock _sl(thread->mutex());
+ audio_utils::scoped_lock _ll(dstThread->mutex(), thread->mutex());
sp<IAfEffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
sp<IAfEffectChain> dstChain;
if (srcChain == 0) {
@@ -4439,16 +4451,16 @@
return INVALID_OPERATION;
}
thread->removeEffect_l(effect);
- status = dstThread->addEffect_l(effect);
+ status = dstThread->addEffect_ll(effect);
if (status != NO_ERROR) {
- thread->addEffect_l(effect);
+ thread->addEffect_ll(effect);
status = INVALID_OPERATION;
goto Exit;
}
dstChain = effect->getCallback()->chain().promote();
if (dstChain == 0) {
- thread->addEffect_l(effect);
+ thread->addEffect_ll(effect);
status = INVALID_OPERATION;
}
@@ -4553,7 +4565,7 @@
struct audio_port* ports) const
{
audio_utils::lock_guard _l(mutex());
- return mPatchPanel->listAudioPorts(num_ports, ports);
+ return mPatchPanel->listAudioPorts_l(num_ports, ports);
}
/* Get supported attributes for a given audio port */
@@ -4564,7 +4576,7 @@
}
audio_utils::lock_guard _l(mutex());
- return mPatchPanel->getAudioPort(port);
+ return mPatchPanel->getAudioPort_l(port);
}
/* Connect a patch between several source and sink ports */
@@ -4577,14 +4589,14 @@
}
audio_utils::lock_guard _l(mutex());
- return mPatchPanel->createAudioPatch(patch, handle);
+ return mPatchPanel->createAudioPatch_l(patch, handle);
}
/* Disconnect a patch */
status_t AudioFlinger::releaseAudioPatch(audio_patch_handle_t handle)
{
audio_utils::lock_guard _l(mutex());
- return mPatchPanel->releaseAudioPatch(handle);
+ return mPatchPanel->releaseAudioPatch_l(handle);
}
/* List connected audio ports and they attributes */
@@ -4592,7 +4604,7 @@
unsigned int* num_patches, struct audio_patch* patches) const
{
audio_utils::lock_guard _l(mutex());
- return mPatchPanel->listAudioPatches(num_patches, patches);
+ return mPatchPanel->listAudioPatches_l(num_patches, patches);
}
// ----------------------------------------------------------------------------
diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h
index 729638a..2c34144 100644
--- a/services/audioflinger/AudioFlinger.h
+++ b/services/audioflinger/AudioFlinger.h
@@ -65,187 +65,213 @@
// ---- begin IAudioFlinger interface
- status_t dump(int fd, const Vector<String16>& args) final;
+ status_t dump(int fd, const Vector<String16>& args) final EXCLUDES_AudioFlinger_Mutex;
status_t createTrack(const media::CreateTrackRequest& input,
- media::CreateTrackResponse& output) final;
+ media::CreateTrackResponse& output) final EXCLUDES_AudioFlinger_Mutex;
status_t createRecord(const media::CreateRecordRequest& input,
- media::CreateRecordResponse& output) final;
+ media::CreateRecordResponse& output) final EXCLUDES_AudioFlinger_Mutex;
- uint32_t sampleRate(audio_io_handle_t ioHandle) const final;
- audio_format_t format(audio_io_handle_t output) const final;
- size_t frameCount(audio_io_handle_t ioHandle) const final;
- size_t frameCountHAL(audio_io_handle_t ioHandle) const final;
- uint32_t latency(audio_io_handle_t output) const final;
+ uint32_t sampleRate(audio_io_handle_t ioHandle) const final EXCLUDES_AudioFlinger_Mutex;
+ audio_format_t format(audio_io_handle_t output) const final EXCLUDES_AudioFlinger_Mutex;
+ size_t frameCount(audio_io_handle_t ioHandle) const final EXCLUDES_AudioFlinger_Mutex;
+ size_t frameCountHAL(audio_io_handle_t ioHandle) const final EXCLUDES_AudioFlinger_Mutex;
+ uint32_t latency(audio_io_handle_t output) const final EXCLUDES_AudioFlinger_Mutex;
- status_t setMasterVolume(float value) final;
- status_t setMasterMute(bool muted) final;
- float masterVolume() const final;
- bool masterMute() const final;
+ status_t setMasterVolume(float value) final EXCLUDES_AudioFlinger_Mutex;
+ status_t setMasterMute(bool muted) final EXCLUDES_AudioFlinger_Mutex;
+ float masterVolume() const final EXCLUDES_AudioFlinger_Mutex;
+ bool masterMute() const final EXCLUDES_AudioFlinger_Mutex;
// Balance value must be within -1.f (left only) to 1.f (right only) inclusive.
- status_t setMasterBalance(float balance) final;
- status_t getMasterBalance(float* balance) const final;
+ status_t setMasterBalance(float balance) final EXCLUDES_AudioFlinger_Mutex;
+ status_t getMasterBalance(float* balance) const final EXCLUDES_AudioFlinger_Mutex;
status_t setStreamVolume(audio_stream_type_t stream, float value,
- audio_io_handle_t output) final;
- status_t setStreamMute(audio_stream_type_t stream, bool muted) final;
+ audio_io_handle_t output) final EXCLUDES_AudioFlinger_Mutex;
+ status_t setStreamMute(audio_stream_type_t stream, bool muted) final
+ EXCLUDES_AudioFlinger_Mutex;
float streamVolume(audio_stream_type_t stream,
- audio_io_handle_t output) const final;
- bool streamMute(audio_stream_type_t stream) const final;
+ audio_io_handle_t output) const final EXCLUDES_AudioFlinger_Mutex;
+ bool streamMute(audio_stream_type_t stream) const final EXCLUDES_AudioFlinger_Mutex;
- status_t setMode(audio_mode_t mode) final;
+ status_t setMode(audio_mode_t mode) final EXCLUDES_AudioFlinger_Mutex;
- status_t setMicMute(bool state) final;
- bool getMicMute() const final;
+ status_t setMicMute(bool state) final EXCLUDES_AudioFlinger_Mutex;
+ bool getMicMute() const final EXCLUDES_AudioFlinger_Mutex;
- void setRecordSilenced(audio_port_handle_t portId, bool silenced) final;
+ void setRecordSilenced(audio_port_handle_t portId, bool silenced) final
+ EXCLUDES_AudioFlinger_Mutex;
- status_t setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs) final;
- String8 getParameters(audio_io_handle_t ioHandle, const String8& keys) const final;
+ status_t setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs) final
+ EXCLUDES_AudioFlinger_Mutex;
+ String8 getParameters(audio_io_handle_t ioHandle, const String8& keys) const final
+ EXCLUDES_AudioFlinger_Mutex;
- void registerClient(const sp<media::IAudioFlingerClient>& client) final;
+ void registerClient(const sp<media::IAudioFlingerClient>& client) final
+ EXCLUDES_AudioFlinger_Mutex;
size_t getInputBufferSize(uint32_t sampleRate, audio_format_t format,
- audio_channel_mask_t channelMask) const final;
+ audio_channel_mask_t channelMask) const final EXCLUDES_AudioFlinger_Mutex;
status_t openOutput(const media::OpenOutputRequest& request,
- media::OpenOutputResponse* response) final;
+ media::OpenOutputResponse* response) final EXCLUDES_AudioFlinger_Mutex;
audio_io_handle_t openDuplicateOutput(audio_io_handle_t output1,
- audio_io_handle_t output2) final;
+ audio_io_handle_t output2) final EXCLUDES_AudioFlinger_Mutex;
- status_t closeOutput(audio_io_handle_t output) final;
+ status_t closeOutput(audio_io_handle_t output) final EXCLUDES_AudioFlinger_Mutex;
- status_t suspendOutput(audio_io_handle_t output) final;
+ status_t suspendOutput(audio_io_handle_t output) final EXCLUDES_AudioFlinger_Mutex;
- status_t restoreOutput(audio_io_handle_t output) final;
+ status_t restoreOutput(audio_io_handle_t output) final EXCLUDES_AudioFlinger_Mutex;
status_t openInput(const media::OpenInputRequest& request,
- media::OpenInputResponse* response) final;
+ media::OpenInputResponse* response) final EXCLUDES_AudioFlinger_Mutex;
- status_t closeInput(audio_io_handle_t input) final;
+ status_t closeInput(audio_io_handle_t input) final EXCLUDES_AudioFlinger_Mutex;
- status_t setVoiceVolume(float volume) final;
+ status_t setVoiceVolume(float volume) final EXCLUDES_AudioFlinger_Mutex;
status_t getRenderPosition(uint32_t* halFrames, uint32_t* dspFrames,
- audio_io_handle_t output) const final;
+ audio_io_handle_t output) const final EXCLUDES_AudioFlinger_Mutex;
- uint32_t getInputFramesLost(audio_io_handle_t ioHandle) const final;
+ uint32_t getInputFramesLost(audio_io_handle_t ioHandle) const final
+ EXCLUDES_AudioFlinger_Mutex;
// This is the binder API. For the internal API see nextUniqueId().
- audio_unique_id_t newAudioUniqueId(audio_unique_id_use_t use) final;
+ audio_unique_id_t newAudioUniqueId(audio_unique_id_use_t use) final
+ EXCLUDES_AudioFlinger_Mutex;
- void acquireAudioSessionId(audio_session_t audioSession, pid_t pid, uid_t uid) final;
+ void acquireAudioSessionId(audio_session_t audioSession, pid_t pid, uid_t uid) final
+ EXCLUDES_AudioFlinger_Mutex;
- void releaseAudioSessionId(audio_session_t audioSession, pid_t pid) final;
+ void releaseAudioSessionId(audio_session_t audioSession, pid_t pid) final
+ EXCLUDES_AudioFlinger_Mutex;
- status_t queryNumberEffects(uint32_t* numEffects) const final;
+ status_t queryNumberEffects(uint32_t* numEffects) const final EXCLUDES_AudioFlinger_Mutex;
- status_t queryEffect(uint32_t index, effect_descriptor_t* descriptor) const final;
+ status_t queryEffect(uint32_t index, effect_descriptor_t* descriptor) const final
+ EXCLUDES_AudioFlinger_Mutex;
status_t getEffectDescriptor(const effect_uuid_t* pUuid,
const effect_uuid_t* pTypeUuid,
uint32_t preferredTypeFlag,
- effect_descriptor_t* descriptor) const final;
+ effect_descriptor_t* descriptor) const final EXCLUDES_AudioFlinger_Mutex;
status_t createEffect(const media::CreateEffectRequest& request,
- media::CreateEffectResponse* response) final;
+ media::CreateEffectResponse* response) final EXCLUDES_AudioFlinger_Mutex;
status_t moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
- audio_io_handle_t dstOutput) final;
+ audio_io_handle_t dstOutput) final EXCLUDES_AudioFlinger_Mutex;
void setEffectSuspended(int effectId,
audio_session_t sessionId,
- bool suspended) final;
+ bool suspended) final EXCLUDES_AudioFlinger_Mutex;
- audio_module_handle_t loadHwModule(const char* name) final;
+ audio_module_handle_t loadHwModule(const char* name) final EXCLUDES_AudioFlinger_Mutex;
- uint32_t getPrimaryOutputSamplingRate() const final;
- size_t getPrimaryOutputFrameCount() const final;
+ uint32_t getPrimaryOutputSamplingRate() const final EXCLUDES_AudioFlinger_Mutex;
+ size_t getPrimaryOutputFrameCount() const final EXCLUDES_AudioFlinger_Mutex;
- status_t setLowRamDevice(bool isLowRamDevice, int64_t totalMemory) final;
+ status_t setLowRamDevice(bool isLowRamDevice, int64_t totalMemory) final
+ EXCLUDES_AudioFlinger_Mutex;
/* Get attributes for a given audio port */
- status_t getAudioPort(struct audio_port_v7* port) const final;
+ status_t getAudioPort(struct audio_port_v7* port) const final EXCLUDES_AudioFlinger_Mutex;
/* Create an audio patch between several source and sink ports */
status_t createAudioPatch(const struct audio_patch *patch,
- audio_patch_handle_t* handle) final;
+ audio_patch_handle_t* handle) final EXCLUDES_AudioFlinger_Mutex;
/* Release an audio patch */
- status_t releaseAudioPatch(audio_patch_handle_t handle) final;
+ status_t releaseAudioPatch(audio_patch_handle_t handle) final EXCLUDES_AudioFlinger_Mutex;
/* List existing audio patches */
status_t listAudioPatches(unsigned int* num_patches,
- struct audio_patch* patches) const final;
+ struct audio_patch* patches) const final EXCLUDES_AudioFlinger_Mutex;
/* Set audio port configuration */
- status_t setAudioPortConfig(const struct audio_port_config* config) final;
+ status_t setAudioPortConfig(const struct audio_port_config* config) final
+ EXCLUDES_AudioFlinger_Mutex;
/* Get the HW synchronization source used for an audio session */
- audio_hw_sync_t getAudioHwSyncForSession(audio_session_t sessionId) final;
+ audio_hw_sync_t getAudioHwSyncForSession(audio_session_t sessionId) final
+ EXCLUDES_AudioFlinger_Mutex;
/* Indicate JAVA services are ready (scheduling, power management ...) */
- status_t systemReady() final;
+ status_t systemReady() final EXCLUDES_AudioFlinger_Mutex;
status_t audioPolicyReady() final { mAudioPolicyReady.store(true); return NO_ERROR; }
- status_t getMicrophones(std::vector<media::MicrophoneInfoFw>* microphones) const final;
+ status_t getMicrophones(std::vector<media::MicrophoneInfoFw>* microphones) const final
+ EXCLUDES_AudioFlinger_Mutex;
- status_t setAudioHalPids(const std::vector<pid_t>& pids) final;
+ status_t setAudioHalPids(const std::vector<pid_t>& pids) final
+ EXCLUDES_AudioFlinger_Mutex;
- status_t setVibratorInfos(const std::vector<media::AudioVibratorInfo>& vibratorInfos) final;
+ status_t setVibratorInfos(const std::vector<media::AudioVibratorInfo>& vibratorInfos) final
+ EXCLUDES_AudioFlinger_Mutex;
status_t updateSecondaryOutputs(
- const TrackSecondaryOutputsMap& trackSecondaryOutputs) final;
+ const TrackSecondaryOutputsMap& trackSecondaryOutputs) final
+ EXCLUDES_AudioFlinger_Mutex;
status_t getMmapPolicyInfos(
media::audio::common::AudioMMapPolicyType policyType,
- std::vector<media::audio::common::AudioMMapPolicyInfo>* policyInfos) final;
+ std::vector<media::audio::common::AudioMMapPolicyInfo>* policyInfos) final
+ EXCLUDES_AudioFlinger_Mutex;
- int32_t getAAudioMixerBurstCount() const final;
+ int32_t getAAudioMixerBurstCount() const final EXCLUDES_AudioFlinger_Mutex;
- int32_t getAAudioHardwareBurstMinUsec() const final;
+ int32_t getAAudioHardwareBurstMinUsec() const final EXCLUDES_AudioFlinger_Mutex;
status_t setDeviceConnectedState(const struct audio_port_v7* port,
- media::DeviceConnectedState state) final;
+ media::DeviceConnectedState state) final EXCLUDES_AudioFlinger_Mutex;
- status_t setSimulateDeviceConnections(bool enabled) final;
+ status_t setSimulateDeviceConnections(bool enabled) final EXCLUDES_AudioFlinger_Mutex;
status_t setRequestedLatencyMode(
- audio_io_handle_t output, audio_latency_mode_t mode) final;
+ audio_io_handle_t output, audio_latency_mode_t mode) final
+ EXCLUDES_AudioFlinger_Mutex;
status_t getSupportedLatencyModes(audio_io_handle_t output,
- std::vector<audio_latency_mode_t>* modes) const final;
+ std::vector<audio_latency_mode_t>* modes) const final EXCLUDES_AudioFlinger_Mutex;
- status_t setBluetoothVariableLatencyEnabled(bool enabled) final;
+ status_t setBluetoothVariableLatencyEnabled(bool enabled) final EXCLUDES_AudioFlinger_Mutex;
- status_t isBluetoothVariableLatencyEnabled(bool* enabled) const final;
+ status_t isBluetoothVariableLatencyEnabled(bool* enabled) const final
+ EXCLUDES_AudioFlinger_Mutex;
- status_t supportsBluetoothVariableLatency(bool* support) const final;
+ status_t supportsBluetoothVariableLatency(bool* support) const final
+ EXCLUDES_AudioFlinger_Mutex;
status_t getSoundDoseInterface(const sp<media::ISoundDoseCallback>& callback,
- sp<media::ISoundDose>* soundDose) const final;
+ sp<media::ISoundDose>* soundDose) const final EXCLUDES_AudioFlinger_Mutex;
- status_t invalidateTracks(const std::vector<audio_port_handle_t>& portIds) final;
+ status_t invalidateTracks(const std::vector<audio_port_handle_t>& portIds) final
+ EXCLUDES_AudioFlinger_Mutex;
- status_t getAudioPolicyConfig(media::AudioPolicyConfig* config) final;
+ status_t getAudioPolicyConfig(media::AudioPolicyConfig* config) final
+ EXCLUDES_AudioFlinger_Mutex;
status_t onTransactWrapper(TransactionCode code, const Parcel& data, uint32_t flags,
- const std::function<status_t()>& delegate) final;
+ const std::function<status_t()>& delegate) final EXCLUDES_AudioFlinger_Mutex;
// ---- end of IAudioFlinger interface
// ---- begin IAfClientCallback interface
- audio_utils::mutex& clientMutex() const final { return mClientMutex; }
- void removeClient_l(pid_t pid) final;
- void removeNotificationClient(pid_t pid) final;
+ audio_utils::mutex& clientMutex() const final
+ RETURN_CAPABILITY(audio_utils::AudioFlinger_ClientMutex) {
+ return mClientMutex;
+ }
+ void removeClient_l(pid_t pid) REQUIRES(clientMutex()) final;
+ void removeNotificationClient(pid_t pid) final EXCLUDES_AudioFlinger_Mutex;
status_t moveAuxEffectToIo(
int effectId,
const sp<IAfPlaybackThread>& dstThread,
- sp<IAfPlaybackThread>* srcThread) final;
+ sp<IAfPlaybackThread>* srcThread) final EXCLUDES_AudioFlinger_Mutex;
// ---- end of IAfClientCallback interface
@@ -256,16 +282,20 @@
// below also used by IAfMelReporterCallback, IAfPatchPanelCallback
const sp<PatchCommandThread>& getPatchCommandThread() final { return mPatchCommandThread; }
status_t addEffectToHal(
- const struct audio_port_config* device, const sp<EffectHalInterface>& effect) final;
+ const struct audio_port_config* device, const sp<EffectHalInterface>& effect) final
+ EXCLUDES_AudioFlinger_HardwareMutex;
status_t removeEffectFromHal(
- const struct audio_port_config* device, const sp<EffectHalInterface>& effect) final;
+ const struct audio_port_config* device, const sp<EffectHalInterface>& effect) final
+ EXCLUDES_AudioFlinger_HardwareMutex;
// ---- end of IAfDeviceEffectManagerCallback interface
// ---- begin IAfMelReporterCallback interface
// below also used by IAfThreadCallback
- audio_utils::mutex& mutex() const final { return mMutex; }
+ audio_utils::mutex& mutex() const final
+ RETURN_CAPABILITY(audio_utils::AudioFlinger_Mutex)
+ EXCLUDES_BELOW_AudioFlinger_Mutex { return mMutex; }
sp<IAfThreadBase> checkOutputThread_l(audio_io_handle_t ioHandle) const final
REQUIRES(mutex());
@@ -273,13 +303,14 @@
// ---- begin IAfPatchPanelCallback interface
- void closeThreadInternal_l(const sp<IAfPlaybackThread>& thread) final;
- void closeThreadInternal_l(const sp<IAfRecordThread>& thread) final;
+ void closeThreadInternal_l(const sp<IAfPlaybackThread>& thread) final REQUIRES(mutex());
+ void closeThreadInternal_l(const sp<IAfRecordThread>& thread) final REQUIRES(mutex());
// return thread associated with primary hardware device, or NULL
- IAfPlaybackThread* primaryPlaybackThread_l() const final;
- IAfPlaybackThread* checkPlaybackThread_l(audio_io_handle_t output) const final;
- IAfRecordThread* checkRecordThread_l(audio_io_handle_t input) const final;
- IAfMmapThread* checkMmapThread_l(audio_io_handle_t io) const final;
+ IAfPlaybackThread* primaryPlaybackThread_l() const final REQUIRES(mutex());
+ IAfPlaybackThread* checkPlaybackThread_l(audio_io_handle_t output) const final
+ REQUIRES(mutex());
+ IAfRecordThread* checkRecordThread_l(audio_io_handle_t input) const final REQUIRES(mutex());
+ IAfMmapThread* checkMmapThread_l(audio_io_handle_t io) const final REQUIRES(mutex());
sp<IAfThreadBase> openInput_l(audio_module_handle_t module,
audio_io_handle_t* input,
audio_config_t* config,
@@ -288,36 +319,40 @@
audio_source_t source,
audio_input_flags_t flags,
audio_devices_t outputDevice,
- const String8& outputDeviceAddress) final;
+ const String8& outputDeviceAddress) final REQUIRES(mutex());
sp<IAfThreadBase> openOutput_l(audio_module_handle_t module,
audio_io_handle_t* output,
audio_config_t* halConfig,
audio_config_base_t* mixerConfig,
audio_devices_t deviceType,
const String8& address,
- audio_output_flags_t flags) final;
+ audio_output_flags_t flags) final REQUIRES(mutex());
const DefaultKeyedVector<audio_module_handle_t, AudioHwDevice*>&
- getAudioHwDevs_l() const final { return mAudioHwDevs; }
+ getAudioHwDevs_l() const final REQUIRES(mutex()) { return mAudioHwDevs; }
void updateDownStreamPatches_l(const struct audio_patch* patch,
- const std::set<audio_io_handle_t>& streams) final;
- void updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices) final;
+ const std::set<audio_io_handle_t>& streams) final REQUIRES(mutex());
+ void updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices) final
+ REQUIRES(mutex());
// ---- end of IAfPatchPanelCallback interface
// ----- begin IAfThreadCallback interface
- bool isNonOffloadableGlobalEffectEnabled_l() const final;
+ bool isNonOffloadableGlobalEffectEnabled_l() const final REQUIRES(mutex());
bool btNrecIsOff() const final { return mBtNrecIsOff.load(); }
- float masterVolume_l() const final;
- bool masterMute_l() const final;
- float getMasterBalance_l() const;
+ float masterVolume_l() const final REQUIRES(mutex());
+ bool masterMute_l() const final REQUIRES(mutex());
+ float getMasterBalance_l() const REQUIRES(mutex());
// no range check, AudioFlinger::mutex() held
- bool streamMute_l(audio_stream_type_t stream) const final { return mStreamTypes[stream].mute; }
+ bool streamMute_l(audio_stream_type_t stream) const final REQUIRES(mutex()) {
+ return mStreamTypes[stream].mute;
+ }
audio_mode_t getMode() const final { return mMode; }
bool isLowRamDevice() const final { return mIsLowRamDevice; }
uint32_t getScreenState() const final { return mScreenState; }
- std::optional<media::AudioVibratorInfo> getDefaultVibratorInfo_l() const final;
+ std::optional<media::AudioVibratorInfo> getDefaultVibratorInfo_l() const final
+ REQUIRES(mutex());
const sp<IAfPatchPanel>& getPatchPanel() const final { return mPatchPanel; }
const sp<MelReporter>& getMelReporter() const final { return mMelReporter; }
const sp<EffectsFactoryHalInterface>& getEffectsFactoryHal() const final {
@@ -329,34 +364,38 @@
// effect belongs to an effect chain in mOrphanEffectChains, the chain is updated
// and removed from mOrphanEffectChains if it does not contain any effect.
// Return true if the effect was found in mOrphanEffectChains, false otherwise.
- bool updateOrphanEffectChains(const sp<IAfEffectModule>& effect) final;
+ bool updateOrphanEffectChains(const sp<IAfEffectModule>& effect) final
+ EXCLUDES_AudioFlinger_Mutex;
- status_t moveEffectChain_l(audio_session_t sessionId,
- IAfPlaybackThread* srcThread, IAfPlaybackThread* dstThread) final;
+ status_t moveEffectChain_ll(audio_session_t sessionId,
+ IAfPlaybackThread* srcThread, IAfPlaybackThread* dstThread) final
+ REQUIRES(mutex(), audio_utils::ThreadBase_Mutex);
// This is a helper that is called during incoming binder calls.
// Requests media.log to start merging log buffers
void requestLogMerge() final;
- sp<NBLog::Writer> newWriter_l(size_t size, const char *name) final;
+ sp<NBLog::Writer> newWriter_l(size_t size, const char *name) final REQUIRES(mutex());
void unregisterWriter(const sp<NBLog::Writer>& writer) final;
sp<audioflinger::SyncEvent> createSyncEvent(AudioSystem::sync_event_t type,
audio_session_t triggerSession,
audio_session_t listenerSession,
const audioflinger::SyncEventCallback& callBack,
- const wp<IAfTrackBase>& cookie) final;
+ const wp<IAfTrackBase>& cookie) final EXCLUDES_AudioFlinger_Mutex;
void ioConfigChanged(audio_io_config_event_t event,
const sp<AudioIoDescriptor>& ioDesc,
- pid_t pid = 0) final;
- void onNonOffloadableGlobalEffectEnable() final;
+ pid_t pid = 0) final EXCLUDES_AudioFlinger_ClientMutex;
+ void onNonOffloadableGlobalEffectEnable() final EXCLUDES_AudioFlinger_Mutex;
void onSupportedLatencyModesChanged(
- audio_io_handle_t output, const std::vector<audio_latency_mode_t>& modes) final;
+ audio_io_handle_t output, const std::vector<audio_latency_mode_t>& modes) final
+ EXCLUDES_AudioFlinger_ClientMutex;
// ---- end of IAfThreadCallback interface
/* List available audio ports and their attributes */
- status_t listAudioPorts(unsigned int* num_ports, struct audio_port* ports) const;
+ status_t listAudioPorts(unsigned int* num_ports, struct audio_port* ports) const
+ EXCLUDES_AudioFlinger_Mutex;
sp<EffectsFactoryHalInterface> getEffectsFactory();
@@ -373,7 +412,7 @@
audio_session_t *sessionId,
const sp<MmapStreamCallback>& callback,
sp<MmapStreamInterface>& interface,
- audio_port_handle_t *handle);
+ audio_port_handle_t *handle) EXCLUDES_AudioFlinger_Mutex;
private:
// FIXME The 400 is temporarily too high until a leak of writers in media.log is fixed.
static const size_t kLogMemorySize = 400 * 1024;
@@ -388,26 +427,26 @@
~AudioFlinger() override;
// call in any IAudioFlinger method that accesses mPrimaryHardwareDev
- status_t initCheck() const { return mPrimaryHardwareDev == NULL ?
+ status_t initCheck() const { return mPrimaryHardwareDev == NULL ?
NO_INIT : NO_ERROR; }
// RefBase
void onFirstRef() override;
AudioHwDevice* findSuitableHwDev_l(audio_module_handle_t module,
- audio_devices_t deviceType);
+ audio_devices_t deviceType) REQUIRES(mutex());
// incremented by 2 when screen state changes, bit 0 == 1 means "off"
// AudioFlinger::setParameters() updates with mutex().
std::atomic_uint32_t mScreenState{};
void dumpPermissionDenial(int fd, const Vector<String16>& args);
- void dumpClients(int fd, const Vector<String16>& args);
- void dumpInternals(int fd, const Vector<String16>& args);
+ void dumpClients_ll(int fd, const Vector<String16>& args) REQUIRES(mutex(), clientMutex());
+ void dumpInternals_l(int fd, const Vector<String16>& args) REQUIRES(mutex());
SimpleLog mThreadLog{16}; // 16 Thread history limit
- void dumpToThreadLog_l(const sp<IAfThreadBase>& thread);
+ void dumpToThreadLog_l(const sp<IAfThreadBase>& thread) REQUIRES(mutex());
// --- Notification Client ---
class NotificationClient : public IBinder::DeathRecipient {
@@ -468,7 +507,8 @@
// If none found, AUDIO_IO_HANDLE_NONE is returned.
template <typename T>
static audio_io_handle_t findIoHandleBySessionId_l(
- audio_session_t sessionId, const T& threads) {
+ audio_session_t sessionId, const T& threads)
+ REQUIRES(audio_utils::AudioFlinger_Mutex) {
audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
for (size_t i = 0; i < threads.size(); i++) {
@@ -483,14 +523,14 @@
return io;
}
- IAfThreadBase* checkThread_l(audio_io_handle_t ioHandle) const;
- IAfPlaybackThread* checkMixerThread_l(audio_io_handle_t output) const;
+ IAfThreadBase* checkThread_l(audio_io_handle_t ioHandle) const REQUIRES(mutex());
+ IAfPlaybackThread* checkMixerThread_l(audio_io_handle_t output) const REQUIRES(mutex());
- sp<VolumeInterface> getVolumeInterface_l(audio_io_handle_t output) const;
- std::vector<sp<VolumeInterface>> getAllVolumeInterfaces_l() const;
+ sp<VolumeInterface> getVolumeInterface_l(audio_io_handle_t output) const REQUIRES(mutex());
+ std::vector<sp<VolumeInterface>> getAllVolumeInterfaces_l() const REQUIRES(mutex());
- void closeOutputFinish(const sp<IAfPlaybackThread>& thread);
+ static void closeOutputFinish(const sp<IAfPlaybackThread>& thread);
void closeInputFinish(const sp<IAfRecordThread>& thread);
// Allocate an audio_unique_id_t.
@@ -508,21 +548,22 @@
audio_unique_id_t nextUniqueId(audio_unique_id_use_t use) final;
// return thread associated with primary hardware device, or NULL
- DeviceTypeSet primaryOutputDevice_l() const;
+ DeviceTypeSet primaryOutputDevice_l() const REQUIRES(mutex());
// return the playback thread with smallest HAL buffer size, and prefer fast
- IAfPlaybackThread* fastPlaybackThread_l() const;
+ IAfPlaybackThread* fastPlaybackThread_l() const REQUIRES(mutex());
- sp<IAfThreadBase> getEffectThread_l(audio_session_t sessionId, int effectId);
+ sp<IAfThreadBase> getEffectThread_l(audio_session_t sessionId, int effectId)
+ REQUIRES(mutex());
- IAfThreadBase* hapticPlaybackThread_l() const;
+ IAfThreadBase* hapticPlaybackThread_l() const REQUIRES(mutex());
void updateSecondaryOutputsForTrack_l(
IAfTrack* track,
IAfPlaybackThread* thread,
- const std::vector<audio_io_handle_t>& secondaryOutputs) const;
+ const std::vector<audio_io_handle_t>& secondaryOutputs) const REQUIRES(mutex());
- bool isSessionAcquired_l(audio_session_t audioSession);
+ bool isSessionAcquired_l(audio_session_t audioSession) REQUIRES(mutex());
// Store an effect chain to mOrphanEffectChains keyed vector.
// Called when a thread exits and effects are still attached to it.
@@ -531,17 +572,18 @@
// return ALREADY_EXISTS if a chain with the same session already exists in
// mOrphanEffectChains. Note that this should never happen as there is only one
// chain for a given session and it is attached to only one thread at a time.
- status_t putOrphanEffectChain_l(const sp<IAfEffectChain>& chain);
+ status_t putOrphanEffectChain_l(const sp<IAfEffectChain>& chain) REQUIRES(mutex());
// Get an effect chain for the specified session in mOrphanEffectChains and remove
// it if found. Returns 0 if not found (this is the most common case).
- sp<IAfEffectChain> getOrphanEffectChain_l(audio_session_t session);
+ sp<IAfEffectChain> getOrphanEffectChain_l(audio_session_t session) REQUIRES(mutex());
- std::vector< sp<IAfEffectModule> > purgeStaleEffects_l();
+ std::vector< sp<IAfEffectModule> > purgeStaleEffects_l() REQUIRES(mutex());
- void broadcastParametersToRecordThreads_l(const String8& keyValuePairs);
- void forwardParametersToDownstreamPatches_l(
+ void broadcastParametersToRecordThreads_l(const String8& keyValuePairs) REQUIRES(mutex());
+ void forwardParametersToDownstreamPatches_l(
audio_io_handle_t upStream, const String8& keyValuePairs,
- const std::function<bool(const sp<IAfPlaybackThread>&)>& useThread = nullptr);
+ const std::function<bool(const sp<IAfPlaybackThread>&)>& useThread = nullptr)
+ REQUIRES(mutex());
// for mAudioSessionRefs only
struct AudioSessionRef {
@@ -560,8 +602,7 @@
mutable audio_utils::mutex mClientMutex;
- // protected by mClientMutex
- DefaultKeyedVector< pid_t, wp<Client> > mClients; // see ~Client()
+ DefaultKeyedVector<pid_t, wp<Client>> mClients GUARDED_BY(clientMutex()); // see ~Client()
audio_utils::mutex& hardwareMutex() const { return mHardwareMutex; }
@@ -570,7 +611,8 @@
// always take mMutex before mHardwareMutex
std::atomic<AudioHwDevice*> mPrimaryHardwareDev = nullptr;
- DefaultKeyedVector<audio_module_handle_t, AudioHwDevice*> mAudioHwDevs{nullptr /* defValue */};
+ DefaultKeyedVector<audio_module_handle_t, AudioHwDevice*> mAudioHwDevs
+ GUARDED_BY(hardwareMutex()) {nullptr /* defValue */};
const sp<DevicesFactoryHalInterface> mDevicesFactoryHal =
DevicesFactoryHalInterface::create();
@@ -605,20 +647,18 @@
};
mutable hardware_call_state mHardwareStatus = AUDIO_HW_IDLE; // for dump only
+ DefaultKeyedVector<audio_io_handle_t, sp<IAfPlaybackThread>> mPlaybackThreads
+ GUARDED_BY(mutex());
+ stream_type_t mStreamTypes[AUDIO_STREAM_CNT] GUARDED_BY(mutex());
- DefaultKeyedVector<audio_io_handle_t, sp<IAfPlaybackThread>> mPlaybackThreads;
- stream_type_t mStreamTypes[AUDIO_STREAM_CNT];
+ float mMasterVolume GUARDED_BY(mutex()) = 1.f;
+ bool mMasterMute GUARDED_BY(mutex()) = false;
+ float mMasterBalance GUARDED_BY(mutex()) = 0.f;
- // member variables below are protected by mutex()
- float mMasterVolume = 1.f;
- bool mMasterMute = false;
- float mMasterBalance = 0.f;
- // end of variables protected by mutex()
+ DefaultKeyedVector<audio_io_handle_t, sp<IAfRecordThread>> mRecordThreads GUARDED_BY(mutex());
- DefaultKeyedVector<audio_io_handle_t, sp<IAfRecordThread>> mRecordThreads;
-
- // protected by clientMutex()
- DefaultKeyedVector< pid_t, sp<NotificationClient> > mNotificationClients;
+ DefaultKeyedVector<pid_t, sp<NotificationClient>> mNotificationClients
+ GUARDED_BY(clientMutex());
// updated by atomic_fetch_add_explicit
volatile atomic_uint_fast32_t mNextUniqueIds[AUDIO_UNIQUE_ID_USE_MAX]; // ctor init
@@ -626,34 +666,36 @@
std::atomic<audio_mode_t> mMode = AUDIO_MODE_INVALID;
std::atomic<bool> mBtNrecIsOff = false;
- // protected by mutex()
- Vector<AudioSessionRef*> mAudioSessionRefs;
+ Vector<AudioSessionRef*> mAudioSessionRefs GUARDED_BY(mutex());
- AudioHwDevice* loadHwModule_l(const char *name);
+ AudioHwDevice* loadHwModule_ll(const char *name) REQUIRES(mutex(), hardwareMutex());
// sync events awaiting for a session to be created.
- std::list<sp<audioflinger::SyncEvent>> mPendingSyncEvents;
+ std::list<sp<audioflinger::SyncEvent>> mPendingSyncEvents GUARDED_BY(mutex());
// Effect chains without a valid thread
- DefaultKeyedVector<audio_session_t, sp<IAfEffectChain>> mOrphanEffectChains;
+ DefaultKeyedVector<audio_session_t, sp<IAfEffectChain>> mOrphanEffectChains
+ GUARDED_BY(mutex());
// list of sessions for which a valid HW A/V sync ID was retrieved from the HAL
- DefaultKeyedVector< audio_session_t , audio_hw_sync_t >mHwAvSyncIds;
+ DefaultKeyedVector<audio_session_t, audio_hw_sync_t> mHwAvSyncIds GUARDED_BY(mutex());
// list of MMAP stream control threads. Those threads allow for wake lock, routing
// and volume control for activity on the associated MMAP stream at the HAL.
// Audio data transfer is directly handled by the client creating the MMAP stream
- DefaultKeyedVector<audio_io_handle_t, sp<IAfMmapThread>> mMmapThreads;
+ DefaultKeyedVector<audio_io_handle_t, sp<IAfMmapThread>> mMmapThreads GUARDED_BY(mutex());
- sp<Client> registerPid(pid_t pid); // always returns non-0
+ sp<Client> registerPid(pid_t pid) EXCLUDES_AudioFlinger_ClientMutex; // always returns non-0
// for use from destructor
- status_t closeOutput_nonvirtual(audio_io_handle_t output);
- status_t closeInput_nonvirtual(audio_io_handle_t input);
- void setAudioHwSyncForSession_l(IAfPlaybackThread* thread, audio_session_t sessionId);
+ status_t closeOutput_nonvirtual(audio_io_handle_t output) EXCLUDES_AudioFlinger_Mutex;
+ status_t closeInput_nonvirtual(audio_io_handle_t input) EXCLUDES_AudioFlinger_Mutex;
+ void setAudioHwSyncForSession_l(IAfPlaybackThread* thread, audio_session_t sessionId)
+ REQUIRES(mutex());
- status_t checkStreamType(audio_stream_type_t stream) const;
+ static status_t checkStreamType(audio_stream_type_t stream);
+ // no mutex needed.
void filterReservedParameters(String8& keyValuePairs, uid_t callingUid);
void logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
size_t rejectedKVPSize, const String8& rejectedKVPs,
@@ -664,12 +706,13 @@
size_t getClientSharedHeapSize() const;
std::atomic<bool> mIsLowRamDevice = true;
- bool mIsDeviceTypeKnown = false;
- int64_t mTotalMemory = 0;
+ bool mIsDeviceTypeKnown GUARDED_BY(mutex()) = false;
+ int64_t mTotalMemory GUARDED_BY(mutex()) = 0;
std::atomic<size_t> mClientSharedHeapSize = kMinimumClientSharedHeapSizeBytes;
static constexpr size_t kMinimumClientSharedHeapSizeBytes = 1024 * 1024; // 1MB
- nsecs_t mGlobalEffectEnableTime = 0; // when a global effect was last enabled
+ // when a global effect was last enabled
+ nsecs_t mGlobalEffectEnableTime GUARDED_BY(mutex()) = 0;
/* const */ sp<IAfPatchPanel> mPatchPanel;
@@ -680,26 +723,28 @@
/* const */ sp<DeviceEffectManager> mDeviceEffectManager; // set onFirstRef
/* const */ sp<MelReporter> mMelReporter; // set onFirstRef
- bool mSystemReady = false;
+ bool mSystemReady GUARDED_BY(mutex()) = false;
std::atomic<bool> mAudioPolicyReady = false;
- mediautils::UidInfo mUidInfo;
+ mediautils::UidInfo mUidInfo GUARDED_BY(mutex());
+ // no mutex needed.
SimpleLog mRejectedSetParameterLog;
SimpleLog mAppSetParameterLog;
SimpleLog mSystemSetParameterLog;
- std::vector<media::AudioVibratorInfo> mAudioVibratorInfos;
+ std::vector<media::AudioVibratorInfo> mAudioVibratorInfos GUARDED_BY(mutex());
static inline constexpr const char *mMetricsId = AMEDIAMETRICS_KEY_AUDIO_FLINGER;
std::map<media::audio::common::AudioMMapPolicyType,
- std::vector<media::audio::common::AudioMMapPolicyInfo>> mPolicyInfos;
- int32_t mAAudioBurstsPerBuffer = 0;
- int32_t mAAudioHwBurstMinMicros = 0;
+ std::vector<media::audio::common::AudioMMapPolicyInfo>> mPolicyInfos
+ GUARDED_BY(mutex());
+ int32_t mAAudioBurstsPerBuffer GUARDED_BY(mutex()) = 0;
+ int32_t mAAudioHwBurstMinMicros GUARDED_BY(mutex()) = 0;
/** Interface for interacting with the AudioService. */
- mediautils::atomic_sp<IAudioManager> mAudioManager;
+ mediautils::atomic_sp<IAudioManager> mAudioManager;
// Bluetooth Variable latency control logic is enabled or disabled
std::atomic<bool> mBluetoothLatencyModesEnabled = true;
diff --git a/services/audioflinger/Client.h b/services/audioflinger/Client.h
index b2ee18e..ff0d751 100644
--- a/services/audioflinger/Client.h
+++ b/services/audioflinger/Client.h
@@ -28,13 +28,16 @@
class IAfClientCallback : public virtual RefBase {
public:
- virtual audio_utils::mutex& clientMutex() const = 0;
- virtual void removeClient_l(pid_t pid) = 0;
- virtual void removeNotificationClient(pid_t pid) = 0;
+ virtual audio_utils::mutex& clientMutex() const
+ RETURN_CAPABILITY(audio_utils::AudioFlinger_ClientMutex) = 0;
+ virtual void removeClient_l(pid_t pid) REQUIRES(clientMutex()) = 0;
+ virtual void removeNotificationClient(pid_t pid) EXCLUDES_AudioFlinger_Mutex = 0;
+
+ // used indirectly by clients.
virtual status_t moveAuxEffectToIo(
int effectId,
const sp<IAfPlaybackThread>& dstThread,
- sp<IAfPlaybackThread>* srcThread) = 0; // used by indirectly by clients.
+ sp<IAfPlaybackThread>* srcThread) EXCLUDES_AudioFlinger_Mutex = 0;
};
class Client : public RefBase {
diff --git a/services/audioflinger/DeviceEffectManager.cpp b/services/audioflinger/DeviceEffectManager.cpp
index 6636717..5dfe8ce 100644
--- a/services/audioflinger/DeviceEffectManager.cpp
+++ b/services/audioflinger/DeviceEffectManager.cpp
@@ -59,7 +59,7 @@
ALOGV("%s handle %d mHalHandle %d device sink %08x",
__func__, handle, patch.mHalHandle,
patch.mAudioPatch.num_sinks > 0 ? patch.mAudioPatch.sinks[0].ext.device.type : 0);
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (auto& effect : mDeviceEffects) {
status_t status = effect.second->onCreatePatch(handle, patch);
ALOGV("%s Effect onCreatePatch status %d", __func__, status);
@@ -69,13 +69,13 @@
void DeviceEffectManager::onReleaseAudioPatch(audio_patch_handle_t handle) {
ALOGV("%s", __func__);
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (auto& effect : mDeviceEffects) {
effect.second->onReleasePatch(handle);
}
}
-// DeviceEffectManager::createEffect_l() must be called with AudioFlinger::mLock held
+// DeviceEffectManager::createEffect_l() must be called with AudioFlinger::mutex() held
sp<IAfEffectHandle> DeviceEffectManager::createEffect_l(
effect_descriptor_t *descriptor,
const AudioDeviceTypeAddr& device,
@@ -97,7 +97,7 @@
}
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
auto iter = mDeviceEffects.find(device);
if (iter != mDeviceEffects.end()) {
effect = iter->second;
@@ -173,7 +173,7 @@
void DeviceEffectManager::dump(int fd)
NO_THREAD_SAFETY_ANALYSIS // conditional try lock
{
- const bool locked = afutils::dumpTryLock(mLock);
+ const bool locked = afutils::dumpTryLock(mutex());
if (!locked) {
String8 result("DeviceEffectManager may be deadlocked\n");
write(fd, result.c_str(), result.size());
@@ -190,13 +190,13 @@
}
if (locked) {
- mLock.unlock();
+ mutex().unlock();
}
}
size_t DeviceEffectManager::removeEffect(const sp<IAfDeviceEffectProxy>& effect)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
mDeviceEffects.erase(effect->device());
return mDeviceEffects.size();
}
diff --git a/services/audioflinger/DeviceEffectManager.h b/services/audioflinger/DeviceEffectManager.h
index 6111030..14ecdcb 100644
--- a/services/audioflinger/DeviceEffectManager.h
+++ b/services/audioflinger/DeviceEffectManager.h
@@ -20,8 +20,6 @@
#include "IAfEffect.h"
#include "PatchCommandThread.h"
-#include <utils/Mutex.h> // avoid transitive dependency
-
namespace android {
class IAfDeviceEffectManagerCallback : public virtual RefBase {
@@ -30,9 +28,11 @@
virtual audio_unique_id_t nextUniqueId(audio_unique_id_use_t use) = 0;
virtual const sp<PatchCommandThread>& getPatchCommandThread() = 0;
virtual status_t addEffectToHal(
- const struct audio_port_config* device, const sp<EffectHalInterface>& effect) = 0;
+ const struct audio_port_config* device, const sp<EffectHalInterface>& effect)
+ EXCLUDES_AudioFlinger_HardwareMutex = 0;
virtual status_t removeEffectFromHal(
- const struct audio_port_config* device, const sp<EffectHalInterface>& effect) = 0;
+ const struct audio_port_config* device, const sp<EffectHalInterface>& effect)
+ EXCLUDES_AudioFlinger_HardwareMutex= 0;
};
class DeviceEffectManagerCallback;
@@ -77,7 +77,8 @@
private:
status_t checkEffectCompatibility(const effect_descriptor_t *desc);
- Mutex mLock;
+ audio_utils::mutex& mutex() const { return mMutex; }
+ mutable audio_utils::mutex mMutex;
const sp<IAfDeviceEffectManagerCallback> mAfDeviceEffectManagerCallback;
const sp<DeviceEffectManagerCallback> mMyCallback;
std::map<AudioDeviceTypeAddr, sp<IAfDeviceEffectProxy>> mDeviceEffects;
diff --git a/services/audioflinger/Effects.cpp b/services/audioflinger/Effects.cpp
index 871377c..0f3e130 100644
--- a/services/audioflinger/Effects.cpp
+++ b/services/audioflinger/Effects.cpp
@@ -109,7 +109,7 @@
{
}
-// must be called with EffectModule::mLock held
+// must be called with EffectModule::mutex() held
status_t EffectBase::setEnabled_l(bool enabled)
{
@@ -155,7 +155,7 @@
{
status_t status;
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
status = setEnabled_l(enabled);
}
if (fromHandle) {
@@ -190,13 +190,13 @@
void EffectBase::setSuspended(bool suspended)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
mSuspended = suspended;
}
bool EffectBase::suspended() const
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
return mSuspended;
}
@@ -204,7 +204,7 @@
{
status_t status;
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
int priority = handle->priority();
size_t size = mHandles.size();
IAfEffectHandle *controlHandle = nullptr;
@@ -250,7 +250,7 @@
product_strategy_t strategy = PRODUCT_STRATEGY_NONE;
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if ((isInternal_l() && !mPolicyRegistered)
|| !getCallback()->isAudioPolicyReady()) {
@@ -284,7 +284,7 @@
return NO_ERROR;
}
}
- mPolicyLock.lock();
+ policyMutex().lock();
ALOGV("%s name %s id %d session %d doRegister %d registered %d doEnable %d enabled %d",
__func__, mDescriptor.name, mId, mSessionId, doRegister, registered, doEnable, enabled);
if (doRegister) {
@@ -302,7 +302,7 @@
if (registered && doEnable) {
status = AudioSystem::setEffectEnabled(mId, enabled);
}
- mPolicyLock.unlock();
+ policyMutex().unlock();
return status;
}
@@ -310,7 +310,7 @@
ssize_t EffectBase::removeHandle(IAfEffectHandle *handle)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
return removeHandle_l(handle);
}
@@ -348,7 +348,7 @@
return mHandles.size();
}
-// must be called with EffectModule::mLock held
+// must be called with EffectModule::mutex() held
IAfEffectHandle *EffectBase::controlHandle_l()
{
// the first valid handle in the list has control over the module
@@ -371,12 +371,12 @@
return mHandles.size();
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
ssize_t numHandles = removeHandle_l(handle);
if ((numHandles == 0) && (!mPinned || unpinIfLast)) {
- mLock.unlock();
+ mutex().unlock();
callback->updateOrphanEffectChains(this);
- mLock.lock();
+ mutex().lock();
}
return numHandles;
}
@@ -384,7 +384,7 @@
bool EffectBase::purgeHandles()
{
bool enabled = false;
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
IAfEffectHandle *handle = controlHandle_l();
if (handle != NULL) {
enabled = handle->enabled();
@@ -509,7 +509,7 @@
result.appendFormat("\tEffect ID %d:\n", mId);
- const bool locked = afutils::dumpTryLock(mLock);
+ const bool locked = afutils::dumpTryLock(mutex());
// failed to lock - AudioFlinger is probably deadlocked
if (!locked) {
result.append("\t\tCould not lock Fx mutex:\n");
@@ -547,7 +547,7 @@
}
}
if (locked) {
- mLock.unlock();
+ mutex().unlock();
}
write(fd, result.c_str(), result.length());
@@ -616,7 +616,7 @@
}
bool EffectModule::updateState() {
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
bool started = false;
switch (mState) {
@@ -672,7 +672,7 @@
void EffectModule::process()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (mState == DESTROYED || mEffectInterface == 0 || mInBuffer == 0 || mOutBuffer == 0) {
return;
@@ -1016,7 +1016,7 @@
status_t EffectModule::init()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (mEffectInterface == 0) {
return NO_INIT;
}
@@ -1046,12 +1046,12 @@
}
}
-// start() must be called with PlaybackThread::mLock or EffectChain::mLock held
+// start() must be called with PlaybackThread::mutex() or EffectChain::mutex() held
status_t EffectModule::start()
{
status_t status;
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
status = start_l();
}
if (status == NO_ERROR) {
@@ -1086,7 +1086,7 @@
status_t EffectModule::stop()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
return stop_l();
}
@@ -1123,7 +1123,7 @@
return status;
}
-// must be called with EffectChain::mLock held
+// must be called with EffectChain::mutex() held
void EffectModule::release_l()
{
if (mEffectInterface != 0) {
@@ -1159,7 +1159,7 @@
int32_t maxReplySize,
std::vector<uint8_t>* reply)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface.get());
if (mState == DESTROYED || mEffectInterface == 0) {
@@ -1356,7 +1356,7 @@
status_t EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
{
- AutoLockReentrant _l(mLock, mSetVolumeReentrantTid);
+ AutoLockReentrant _l(mutex(), mSetVolumeReentrantTid);
if (mStatus != NO_ERROR) {
return mStatus;
}
@@ -1410,7 +1410,7 @@
return NO_ERROR;
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (mStatus != NO_ERROR) {
return mStatus;
}
@@ -1440,7 +1440,7 @@
status_t EffectModule::setMode(audio_mode_t mode)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (mStatus != NO_ERROR) {
return mStatus;
}
@@ -1462,7 +1462,7 @@
status_t EffectModule::setAudioSource(audio_source_t source)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (mStatus != NO_ERROR) {
return mStatus;
}
@@ -1480,7 +1480,7 @@
status_t EffectModule::setOffloaded(bool offloaded, audio_io_handle_t io)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (mStatus != NO_ERROR) {
return mStatus;
}
@@ -1513,7 +1513,7 @@
bool EffectModule::isOffloaded() const
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
return mOffloaded;
}
@@ -1584,7 +1584,7 @@
status_t EffectModule::getConfigs(
audio_config_base_t* inputCfg, audio_config_base_t* outputCfg, bool* isOutput) const {
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (mConfig.inputCfg.mask == 0 || mConfig.outputCfg.mask == 0) {
return NO_INIT;
}
@@ -1619,7 +1619,7 @@
EffectBase::dump(fd, args);
String8 result;
- const bool locked = afutils::dumpTryLock(mLock);
+ const bool locked = afutils::dumpTryLock(mutex());
result.append("\t\tStatus Engine:\n");
result.appendFormat("\t\t%03d %p\n",
@@ -1662,7 +1662,7 @@
}
if (locked) {
- mLock.unlock();
+ mutex().unlock();
}
}
@@ -1785,7 +1785,7 @@
Status EffectHandle::enable(int32_t* _aidl_return)
{
- AutoMutex _l(mLock);
+ audio_utils::lock_guard _l(mutex());
ALOGV("enable %p", this);
sp<IAfEffectBase> effect = mEffect.promote();
if (effect == 0 || mDisconnected) {
@@ -1824,7 +1824,7 @@
Status EffectHandle::disable(int32_t* _aidl_return)
{
ALOGV("disable %p", this);
- AutoMutex _l(mLock);
+ audio_utils::lock_guard _l(mutex());
sp<IAfEffectBase> effect = mEffect.promote();
if (effect == 0 || mDisconnected) {
RETURN(DEAD_OBJECT);
@@ -1857,7 +1857,7 @@
void EffectHandle::disconnect(bool unpinIfLast)
{
- AutoMutex _l(mLock);
+ audio_utils::lock_guard _l(mutex());
ALOGV("disconnect(%s) %p", unpinIfLast ? "true" : "false", this);
if (mDisconnected) {
if (unpinIfLast) {
@@ -1896,7 +1896,7 @@
Status EffectHandle::getConfig(
media::EffectConfig* _config, int32_t* _aidl_return) {
- AutoMutex _l(mLock);
+ audio_utils::lock_guard _l(mutex());
sp<IAfEffectBase> effect = mEffect.promote();
if (effect == nullptr || mDisconnected) {
RETURN(DEAD_OBJECT);
@@ -1963,7 +1963,7 @@
return disable(_aidl_return);
}
- AutoMutex _l(mLock);
+ audio_utils::lock_guard _l(mutex());
sp<IAfEffectBase> effect = mEffect.promote();
if (effect == 0 || mDisconnected) {
RETURN(DEAD_OBJECT);
@@ -2177,7 +2177,7 @@
std::vector<int> EffectChain::getEffectIds() const
{
std::vector<int> ids;
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (size_t i = 0; i < mEffects.size(); i++) {
ids.push_back(mEffects[i]->id());
}
@@ -2186,11 +2186,11 @@
void EffectChain::clearInputBuffer()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
clearInputBuffer_l();
}
-// Must be called with EffectChain::mLock locked
+// Must be called with EffectChain::mutex() locked
void EffectChain::clearInputBuffer_l()
{
if (mInBuffer == NULL) {
@@ -2203,7 +2203,7 @@
mInBuffer->commit();
}
-// Must be called with EffectChain::mLock locked
+// Must be called with EffectChain::mutex() locked
void EffectChain::process_l()
{
// never process effects when:
@@ -2262,7 +2262,7 @@
audio_session_t sessionId,
bool pinned)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
effect = new EffectModule(mEffectCallback, desc, id, sessionId, pinned, AUDIO_PORT_HANDLE_NONE);
status_t lStatus = effect->status();
if (lStatus == NO_ERROR) {
@@ -2277,10 +2277,10 @@
// addEffect_l() must be called with IAfThreadBase::mutex() held
status_t EffectChain::addEffect_l(const sp<IAfEffectModule>& effect)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
return addEffect_ll(effect);
}
-// addEffect_l() must be called with IAfThreadBase::mLock and EffectChain::mutex() held
+// addEffect_l() must be called with IAfThreadBase::mutex() and EffectChain::mutex() held
status_t EffectChain::addEffect_ll(const sp<IAfEffectModule>& effect)
{
effect->setCallback(mEffectCallback);
@@ -2447,7 +2447,7 @@
size_t EffectChain::removeEffect_l(const sp<IAfEffectModule>& effect,
bool release)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
size_t size = mEffects.size();
uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
@@ -2534,7 +2534,7 @@
return false;
}
-// setVolume_l() must be called with IAfThreadBase::mLock or EffectChain::mLock held
+// setVolume_l() must be called with IAfThreadBase::mutex() or EffectChain::mutex() held
bool EffectChain::setVolume_l(uint32_t *left, uint32_t *right, bool force)
{
uint32_t newLeft = *left;
@@ -2610,7 +2610,7 @@
return volumeControlIndex.has_value();
}
-// resetVolume_l() must be called with IAfThreadBase::mutex() or EffectChain::mLock held
+// resetVolume_l() must be called with IAfThreadBase::mutex() or EffectChain::mutex() held
void EffectChain::resetVolume_l()
{
if ((mLeftVolume != UINT_MAX) && (mRightVolume != UINT_MAX)) {
@@ -2621,7 +2621,7 @@
}
// containsHapticGeneratingEffect_l must be called with
-// IAfThreadBase::mutex() or EffectChain::mLock held
+// IAfThreadBase::mutex() or EffectChain::mutex() held
bool EffectChain::containsHapticGeneratingEffect_l()
{
for (size_t i = 0; i < mEffects.size(); ++i) {
@@ -2634,7 +2634,7 @@
void EffectChain::setHapticIntensity_l(int id, os::HapticScale intensity)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (size_t i = 0; i < mEffects.size(); ++i) {
mEffects[i]->setHapticIntensity(id, intensity);
}
@@ -2642,7 +2642,7 @@
void EffectChain::syncHalEffectsState()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (size_t i = 0; i < mEffects.size(); i++) {
if (mEffects[i]->state() == EffectModule::ACTIVE ||
mEffects[i]->state() == EffectModule::STOPPING) {
@@ -2660,7 +2660,7 @@
result.appendFormat(" %zu effects for session %d\n", numEffects, mSessionId);
if (numEffects) {
- const bool locked = afutils::dumpTryLock(mLock);
+ const bool locked = afutils::dumpTryLock(mutex());
// failed to lock - AudioFlinger is probably deadlocked
if (!locked) {
result.append("\tCould not lock mutex:\n");
@@ -2683,7 +2683,7 @@
}
if (locked) {
- mLock.unlock();
+ mutex().unlock();
}
} else {
write(fd, result.c_str(), result.size());
@@ -2732,12 +2732,12 @@
sp<IAfEffectModule> effect = desc->mEffect.promote();
if (effect != 0) {
effect->setSuspended(false);
- effect->lock();
+ effect->mutex().lock();
IAfEffectHandle *handle = effect->controlHandle_l();
if (handle != NULL && !handle->disconnected()) {
effect->setEnabled_l(handle->enabled());
}
- effect->unlock();
+ effect->mutex().unlock();
}
desc->mEffect.clear();
}
@@ -2887,7 +2887,7 @@
bool EffectChain::isNonOffloadableEnabled() const
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
return isNonOffloadableEnabled_l();
}
@@ -2904,7 +2904,7 @@
void EffectChain::setThread(const sp<IAfThreadBase>& thread)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
mEffectCallback->setThread(thread);
}
@@ -2933,7 +2933,7 @@
bool EffectChain::isRawCompatible() const
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (const auto &effect : mEffects) {
if (effect->isProcessImplemented()) {
return false;
@@ -2945,7 +2945,7 @@
bool EffectChain::isFastCompatible() const
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (const auto &effect : mEffects) {
if (effect->isProcessImplemented()
&& effect->isImplementationSoftware()) {
@@ -2957,7 +2957,7 @@
}
bool EffectChain::isBitPerfectCompatible() const {
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (const auto &effect : mEffects) {
if (effect->isProcessImplemented()
&& effect->isImplementationSoftware()) {
@@ -2968,10 +2968,10 @@
return true;
}
-// isCompatibleWithThread_l() must be called with thread->mLock held
+// isCompatibleWithThread_l() must be called with thread->mutex() held
bool EffectChain::isCompatibleWithThread_l(const sp<IAfThreadBase>& thread) const
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (size_t i = 0; i < mEffects.size(); i++) {
if (thread->checkEffectCompatibility_l(&(mEffects[i]->desc()), mSessionId) != NO_ERROR) {
return false;
@@ -3275,7 +3275,7 @@
status_t DeviceEffectProxy::setEnabled(bool enabled, bool fromHandle)
{
status_t status = EffectBase::setEnabled(enabled, fromHandle);
- Mutex::Autolock _l(mProxyLock);
+ audio_utils::lock_guard _l(proxyMutex());
if (status == NO_ERROR) {
for (auto& handle : mEffectHandles) {
Status bs;
@@ -3328,7 +3328,7 @@
ALOGV("%s sink %d checkPort status %d", __func__, i, status);
}
if (status == NO_ERROR || status == ALREADY_EXISTS) {
- Mutex::Autolock _l(mProxyLock);
+ audio_utils::lock_guard _l(proxyMutex());
mEffectHandles.emplace(patchHandle, handle);
}
ALOGW_IF(status == BAD_VALUE,
@@ -3338,7 +3338,10 @@
}
status_t DeviceEffectProxy::checkPort(const IAfPatchPanel::Patch& patch,
- const struct audio_port_config *port, sp<IAfEffectHandle> *handle) {
+ const struct audio_port_config *port, sp<IAfEffectHandle> *handle)
+NO_THREAD_SAFETY_ANALYSIS
+// calling function 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
+{
ALOGV("%s type %d device type %d address %s device ID %d patch.isSoftware() %d",
__func__, port->type, port->ext.device.type,
@@ -3360,7 +3363,7 @@
status_t status = NAME_NOT_FOUND;
if (mDescriptor.flags & EFFECT_FLAG_HW_ACC_TUNNEL) {
- Mutex::Autolock _l(mProxyLock);
+ audio_utils::lock_guard _l(proxyMutex());
mDevicePort = *port;
mHalEffect = new EffectModule(mMyCallback,
const_cast<effect_descriptor_t *>(&mDescriptor),
@@ -3424,7 +3427,7 @@
void DeviceEffectProxy::onReleasePatch(audio_patch_handle_t patchHandle) {
sp<IAfEffectHandle> effect;
{
- Mutex::Autolock _l(mProxyLock);
+ audio_utils::lock_guard _l(proxyMutex());
if (mEffectHandles.find(patchHandle) != mEffectHandles.end()) {
effect = mEffectHandles.at(patchHandle);
mEffectHandles.erase(patchHandle);
@@ -3435,7 +3438,7 @@
size_t DeviceEffectProxy::removeEffect(const sp<IAfEffectModule>& effect)
{
- Mutex::Autolock _l(mProxyLock);
+ audio_utils::lock_guard _l(proxyMutex());
if (effect == mHalEffect) {
mHalEffect->release_l();
mHalEffect.clear();
@@ -3496,7 +3499,7 @@
const Vector<String16> args;
EffectBase::dump(fd, args);
- const bool locked = afutils::dumpTryLock(mProxyLock);
+ const bool locked = afutils::dumpTryLock(proxyMutex());
if (!locked) {
String8 result("DeviceEffectProxy may be deadlocked\n");
write(fd, result.c_str(), result.size());
@@ -3526,7 +3529,7 @@
}
if (locked) {
- mLock.unlock();
+ proxyMutex().unlock();
}
}
diff --git a/services/audioflinger/Effects.h b/services/audioflinger/Effects.h
index e0f5cd7..6b1d9cf 100644
--- a/services/audioflinger/Effects.h
+++ b/services/audioflinger/Effects.h
@@ -111,8 +111,7 @@
bool isPinned() const final { return mPinned; }
void unPin() final { mPinned = false; }
- void lock() ACQUIRE(mLock) final { mLock.lock(); }
- void unlock() RELEASE(mLock) final { mLock.unlock(); }
+ audio_utils::mutex& mutex() const final { return mMutex; }
status_t updatePolicyState() final;
@@ -135,7 +134,8 @@
DISALLOW_COPY_AND_ASSIGN(EffectBase);
- mutable Mutex mLock; // mutex for process, commands and handles list protection
+ // mutex for process, commands and handles list protection
+ mutable audio_utils::mutex mMutex;
mediautils::atomic_sp<EffectCallbackInterface> mCallback; // parent effect chain
const int mId; // this instance unique ID
const audio_session_t mSessionId; // audio session ID
@@ -148,9 +148,10 @@
// First handle in mHandles has highest priority and controls the effect module
// Audio policy effect state management
- // Mutex protecting transactions with audio policy manager as mLock cannot
+ // Mutex protecting transactions with audio policy manager as mutex() cannot
// be held to avoid cross deadlocks with audio policy mutex
- Mutex mPolicyLock;
+ audio_utils::mutex& policyMutex() const { return mPolicyMutex; }
+ mutable audio_utils::mutex mPolicyMutex;
// Effect is registered in APM or not
bool mPolicyRegistered = false;
// Effect enabled state communicated to APM. Enabled state corresponds to
@@ -272,9 +273,10 @@
uint32_t mInChannelCountRequested;
uint32_t mOutChannelCountRequested;
+ template <typename MUTEX>
class AutoLockReentrant {
public:
- AutoLockReentrant(Mutex& mutex, pid_t allowedTid)
+ AutoLockReentrant(MUTEX& mutex, pid_t allowedTid)
: mMutex(gettid() == allowedTid ? nullptr : &mutex)
{
if (mMutex != nullptr) mMutex->lock();
@@ -283,7 +285,7 @@
if (mMutex != nullptr) mMutex->unlock();
}
private:
- Mutex * const mMutex;
+ MUTEX * const mMutex;
};
static constexpr pid_t INVALID_PID = (pid_t)-1;
@@ -364,7 +366,8 @@
private:
DISALLOW_COPY_AND_ASSIGN(EffectHandle);
- Mutex mLock; // protects IEffect method calls
+ audio_utils::mutex& mutex() const { return mMutex; }
+ mutable audio_utils::mutex mMutex; // protects IEffect method calls
const wp<IAfEffectBase> mEffect; // pointer to controlled EffectModule
const sp<media::IEffectClient> mEffectClient; // callback interface for client notifications
/*const*/ sp<Client> mClient; // client for shared memory allocation, see
@@ -397,12 +400,8 @@
void process_l() final;
- void lock() ACQUIRE(mLock) final {
- mLock.lock();
- }
- void unlock() RELEASE(mLock) final {
- mLock.unlock();
- }
+ audio_utils::mutex& mutex() const final { return mMutex; }
+
status_t createEffect_l(sp<IAfEffectModule>& effect,
effect_descriptor_t *desc,
int id,
@@ -488,7 +487,7 @@
// Is this EffectChain compatible with the bit-perfect audio flag.
bool isBitPerfectCompatible() const final;
- // isCompatibleWithThread_l() must be called with thread->mLock held
+ // isCompatibleWithThread_l() must be called with thread->mutex() held
bool isCompatibleWithThread_l(const sp<IAfThreadBase>& thread) const final;
bool containsHapticGeneratingEffect_l() final;
@@ -624,7 +623,7 @@
std::optional<size_t> findVolumeControl_l(size_t from, size_t to) const;
- mutable Mutex mLock; // mutex protecting effect list
+ mutable audio_utils::mutex mMutex; // mutex protecting effect list
Vector<sp<IAfEffectModule>> mEffects; // list of effect modules
audio_session_t mSessionId; // audio session ID
sp<EffectBufferHalInterface> mInBuffer; // chain input buffer
@@ -754,9 +753,10 @@
const sp<DeviceEffectManagerCallback> mManagerCallback;
const sp<ProxyCallback> mMyCallback;
- mutable Mutex mProxyLock;
- std::map<audio_patch_handle_t, sp<IAfEffectHandle>> mEffectHandles; // protected by mProxyLock
- sp<IAfEffectModule> mHalEffect; // protected by mProxyLock
+ audio_utils::mutex& proxyMutex() const { return mProxyMutex; }
+ mutable audio_utils::mutex mProxyMutex;
+ std::map<audio_patch_handle_t, sp<IAfEffectHandle>> mEffectHandles; // protected by mProxyMutex
+ sp<IAfEffectModule> mHalEffect; // protected by mProxyMutex
struct audio_port_config mDevicePort = { .id = AUDIO_PORT_HANDLE_NONE };
const bool mNotifyFramesProcessed;
};
diff --git a/services/audioflinger/IAfEffect.h b/services/audioflinger/IAfEffect.h
index 7393448..ea0c6d9 100644
--- a/services/audioflinger/IAfEffect.h
+++ b/services/audioflinger/IAfEffect.h
@@ -21,6 +21,7 @@
#include <android/media/AudioVibratorInfo.h>
#include <android/media/BnEffect.h>
#include <android/media/BnEffectClient.h>
+#include <audio_utils/mutex.h>
#include <media/AudioCommonTypes.h> // product_strategy_t
#include <media/AudioDeviceTypeAddr.h>
#include <media/audiohal/EffectHalInterface.h>
@@ -141,8 +142,7 @@
virtual ssize_t removeHandle_l(IAfEffectHandle *handle) = 0;
virtual IAfEffectHandle* controlHandle_l() = 0;
- virtual void lock() = 0;
- virtual void unlock() = 0;
+ virtual audio_utils::mutex& mutex() const = 0;
};
class IAfEffectModule : public virtual IAfEffectBase {
@@ -218,8 +218,7 @@
virtual void process_l() = 0;
- virtual void lock() = 0;
- virtual void unlock() = 0;
+ virtual audio_utils::mutex& mutex() const = 0;
virtual status_t createEffect_l(sp<IAfEffectModule>& effect,
effect_descriptor_t *desc,
diff --git a/services/audioflinger/IAfPatchPanel.h b/services/audioflinger/IAfPatchPanel.h
index 9302e25..5a6621e 100644
--- a/services/audioflinger/IAfPatchPanel.h
+++ b/services/audioflinger/IAfPatchPanel.h
@@ -45,8 +45,7 @@
mRecordThreadHandle(recordThreadHandle) {}
SoftwarePatch(const SoftwarePatch&) = default;
- // Must be called under AudioFlinger::mLock
- status_t getLatencyMs_l(double* latencyMs) const;
+ status_t getLatencyMs_l(double* latencyMs) const REQUIRES(audio_utils::AudioFlinger_Mutex);
audio_patch_handle_t getPatchHandle() const { return mPatchHandle; };
audio_io_handle_t getPlaybackThreadHandle() const { return mPlaybackThreadHandle; };
audio_io_handle_t getRecordThreadHandle() const { return mRecordThreadHandle; };
@@ -60,12 +59,14 @@
class IAfPatchPanelCallback : public virtual RefBase {
public:
- virtual void closeThreadInternal_l(const sp<IAfPlaybackThread>& thread) = 0;
- virtual void closeThreadInternal_l(const sp<IAfRecordThread>& thread) = 0;
- virtual IAfPlaybackThread* primaryPlaybackThread_l() const = 0;
- virtual IAfPlaybackThread* checkPlaybackThread_l(audio_io_handle_t output) const = 0;
- virtual IAfRecordThread* checkRecordThread_l(audio_io_handle_t input) const = 0;
- virtual IAfMmapThread* checkMmapThread_l(audio_io_handle_t io) const = 0;
+ virtual void closeThreadInternal_l(const sp<IAfPlaybackThread>& thread) REQUIRES(mutex()) = 0;
+ virtual void closeThreadInternal_l(const sp<IAfRecordThread>& thread) REQUIRES(mutex()) = 0;
+ virtual IAfPlaybackThread* primaryPlaybackThread_l() const REQUIRES(mutex()) = 0;
+ virtual IAfPlaybackThread* checkPlaybackThread_l(audio_io_handle_t output) const
+ REQUIRES(mutex()) = 0;
+ virtual IAfRecordThread* checkRecordThread_l(audio_io_handle_t input) const
+ REQUIRES(mutex()) = 0;
+ virtual IAfMmapThread* checkMmapThread_l(audio_io_handle_t io) const REQUIRES(mutex()) = 0;
virtual sp<IAfThreadBase> openInput_l(audio_module_handle_t module,
audio_io_handle_t* input,
audio_config_t* config,
@@ -74,22 +75,25 @@
audio_source_t source,
audio_input_flags_t flags,
audio_devices_t outputDevice,
- const String8& outputDeviceAddress) = 0;
+ const String8& outputDeviceAddress) REQUIRES(mutex()) = 0;
virtual sp<IAfThreadBase> openOutput_l(audio_module_handle_t module,
audio_io_handle_t* output,
audio_config_t* halConfig,
audio_config_base_t* mixerConfig,
audio_devices_t deviceType,
const String8& address,
- audio_output_flags_t flags) = 0;
- virtual audio_utils::mutex& mutex() const = 0;
+ audio_output_flags_t flags) REQUIRES(mutex()) = 0;
+ virtual audio_utils::mutex& mutex() const
+ RETURN_CAPABILITY(audio_utils::AudioFlinger_Mutex) = 0;
virtual const DefaultKeyedVector<audio_module_handle_t, AudioHwDevice*>&
- getAudioHwDevs_l() const = 0;
+ getAudioHwDevs_l() const REQUIRES(mutex()) = 0;
virtual audio_unique_id_t nextUniqueId(audio_unique_id_use_t use) = 0;
virtual const sp<PatchCommandThread>& getPatchCommandThread() = 0;
virtual void updateDownStreamPatches_l(
- const struct audio_patch* patch, const std::set<audio_io_handle_t>& streams) = 0;
- virtual void updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices) = 0;
+ const struct audio_patch* patch, const std::set<audio_io_handle_t>& streams)
+ REQUIRES(mutex()) = 0;
+ virtual void updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
+ REQUIRES(mutex()) = 0;
};
class IAfPatchPanel : public virtual RefBase {
@@ -133,9 +137,12 @@
sp<const ThreadType> const_thread() const { return mThread; }
sp<const TrackType> const_track() const { return mTrack; }
- void closeConnections(const sp<IAfPatchPanel>& panel) {
+ void closeConnections_l(const sp<IAfPatchPanel>& panel)
+ REQUIRES(audio_utils::AudioFlinger_Mutex)
+ NO_THREAD_SAFETY_ANALYSIS // this is broken in clang
+ {
if (mHandle != AUDIO_PATCH_HANDLE_NONE) {
- panel->releaseAudioPatch(mHandle);
+ panel->releaseAudioPatch_l(mHandle);
mHandle = AUDIO_PATCH_HANDLE_NONE;
}
if (mThread != nullptr) {
@@ -217,8 +224,10 @@
friend void swap(Patch& a, Patch& b) noexcept { a.swap(b); }
- status_t createConnections(const sp<IAfPatchPanel>& panel);
- void clearConnections(const sp<IAfPatchPanel>& panel);
+ status_t createConnections_l(const sp<IAfPatchPanel>& panel)
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
+ void clearConnections_l(const sp<IAfPatchPanel>& panel)
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
bool isSoftware() const {
return mRecord.handle() != AUDIO_PATCH_HANDLE_NONE ||
mPlayback.handle() != AUDIO_PATCH_HANDLE_NONE;
@@ -250,22 +259,27 @@
};
/* List connected audio ports and their attributes */
- virtual status_t listAudioPorts(unsigned int* num_ports, struct audio_port* ports) = 0;
+ virtual status_t listAudioPorts_l(unsigned int* num_ports, struct audio_port* ports)
+ REQUIRES(audio_utils::AudioFlinger_Mutex) = 0;
/* Get supported attributes for a given audio port */
- virtual status_t getAudioPort(struct audio_port_v7* port) = 0;
+ virtual status_t getAudioPort_l(struct audio_port_v7* port)
+ REQUIRES(audio_utils::AudioFlinger_Mutex) = 0;
/* Create a patch between several source and sink ports */
- virtual status_t createAudioPatch(
+ virtual status_t createAudioPatch_l(
const struct audio_patch* patch,
audio_patch_handle_t* handle,
- bool endpointPatch = false) = 0;
+ bool endpointPatch = false)
+ REQUIRES(audio_utils::AudioFlinger_Mutex) = 0;
/* Release a patch */
- virtual status_t releaseAudioPatch(audio_patch_handle_t handle) = 0;
+ virtual status_t releaseAudioPatch_l(audio_patch_handle_t handle)
+ REQUIRES(audio_utils::AudioFlinger_Mutex) = 0;
/* List connected audio devices and they attributes */
- virtual status_t listAudioPatches(unsigned int* num_patches, struct audio_patch* patches) = 0;
+ virtual status_t listAudioPatches_l(unsigned int* num_patches, struct audio_patch* patches)
+ REQUIRES(audio_utils::AudioFlinger_Mutex) = 0;
// Retrieves all currently estrablished software patches for a stream
// opened on an intermediate module.
@@ -280,13 +294,14 @@
virtual void dump(int fd) const = 0;
- // Must be called under AudioFlinger::mLock
+ virtual const std::map<audio_patch_handle_t, Patch>& patches_l() const
+ REQUIRES(audio_utils::AudioFlinger_Mutex) = 0;
- virtual const std::map<audio_patch_handle_t, Patch>& patches_l() const = 0;
+ virtual status_t getLatencyMs_l(audio_patch_handle_t patchHandle, double* latencyMs) const
+ REQUIRES(audio_utils::AudioFlinger_Mutex) = 0;
- virtual status_t getLatencyMs_l(audio_patch_handle_t patchHandle, double* latencyMs) const = 0;
-
- virtual void closeThreadInternal_l(const sp<IAfThreadBase>& thread) const = 0;
+ virtual void closeThreadInternal_l(const sp<IAfThreadBase>& thread) const
+ REQUIRES(audio_utils::AudioFlinger_Mutex) = 0;
};
} // namespace android
diff --git a/services/audioflinger/IAfThread.h b/services/audioflinger/IAfThread.h
index fec8cd7..fc2f805 100644
--- a/services/audioflinger/IAfThread.h
+++ b/services/audioflinger/IAfThread.h
@@ -31,7 +31,6 @@
#include <media/audiohal/StreamHalInterface.h>
#include <media/nblog/NBLog.h>
#include <timing/SyncEvent.h>
-#include <utils/Mutex.h>
#include <utils/RefBase.h>
#include <vibrator/ExternalVibration.h>
@@ -68,44 +67,56 @@
// and hence may be used by the Effect / Track framework.
class IAfThreadCallback : public virtual RefBase {
public:
- virtual audio_utils::mutex& mutex() const = 0;
- virtual bool isNonOffloadableGlobalEffectEnabled_l() const = 0; // Tracks
+ virtual audio_utils::mutex& mutex() const
+ RETURN_CAPABILITY(audio_utils::AudioFlinger_Mutex) = 0;
+ virtual bool isNonOffloadableGlobalEffectEnabled_l() const
+ REQUIRES(mutex()) = 0; // Tracks
virtual audio_unique_id_t nextUniqueId(audio_unique_id_use_t use) = 0;
virtual bool btNrecIsOff() const = 0;
- virtual float masterVolume_l() const = 0;
- virtual bool masterMute_l() const = 0;
- virtual float getMasterBalance_l() const = 0;
- virtual bool streamMute_l(audio_stream_type_t stream) const = 0;
+ virtual float masterVolume_l() const
+ REQUIRES(mutex()) = 0;
+ virtual bool masterMute_l() const
+ REQUIRES(mutex()) = 0;
+ virtual float getMasterBalance_l() const
+ REQUIRES(mutex()) = 0;
+ virtual bool streamMute_l(audio_stream_type_t stream) const
+ REQUIRES(mutex()) = 0;
virtual audio_mode_t getMode() const = 0;
virtual bool isLowRamDevice() const = 0;
virtual bool isAudioPolicyReady() const = 0; // Effects
virtual uint32_t getScreenState() const = 0;
- virtual std::optional<media::AudioVibratorInfo> getDefaultVibratorInfo_l() const = 0;
+ virtual std::optional<media::AudioVibratorInfo> getDefaultVibratorInfo_l() const
+ REQUIRES(mutex()) = 0;
virtual const sp<IAfPatchPanel>& getPatchPanel() const = 0;
virtual const sp<MelReporter>& getMelReporter() const = 0;
virtual const sp<EffectsFactoryHalInterface>& getEffectsFactoryHal() const = 0;
virtual sp<IAudioManager> getOrCreateAudioManager() = 0; // Tracks
- virtual bool updateOrphanEffectChains(const sp<IAfEffectModule>& effect) = 0;
- virtual status_t moveEffectChain_l(audio_session_t sessionId,
- IAfPlaybackThread* srcThread, IAfPlaybackThread* dstThread) = 0;
+ virtual bool updateOrphanEffectChains(const sp<IAfEffectModule>& effect)
+ EXCLUDES_AudioFlinger_Mutex = 0;
+ virtual status_t moveEffectChain_ll(audio_session_t sessionId,
+ IAfPlaybackThread* srcThread, IAfPlaybackThread* dstThread)
+ REQUIRES(mutex(), audio_utils::ThreadBase_Mutex) = 0;
virtual void requestLogMerge() = 0;
- virtual sp<NBLog::Writer> newWriter_l(size_t size, const char *name) = 0;
+ virtual sp<NBLog::Writer> newWriter_l(size_t size, const char *name)
+ REQUIRES(mutex()) = 0;
virtual void unregisterWriter(const sp<NBLog::Writer>& writer) = 0;
virtual sp<audioflinger::SyncEvent> createSyncEvent(AudioSystem::sync_event_t type,
audio_session_t triggerSession,
audio_session_t listenerSession,
const audioflinger::SyncEventCallback& callBack,
- const wp<IAfTrackBase>& cookie) = 0;
+ const wp<IAfTrackBase>& cookie)
+ EXCLUDES_AudioFlinger_Mutex = 0;
virtual void ioConfigChanged(audio_io_config_event_t event,
const sp<AudioIoDescriptor>& ioDesc,
- pid_t pid = 0) = 0;
- virtual void onNonOffloadableGlobalEffectEnable() = 0;
+ pid_t pid = 0) EXCLUDES_AudioFlinger_ClientMutex = 0;
+ virtual void onNonOffloadableGlobalEffectEnable() EXCLUDES_AudioFlinger_Mutex = 0;
virtual void onSupportedLatencyModesChanged(
- audio_io_handle_t output, const std::vector<audio_latency_mode_t>& modes) = 0;
+ audio_io_handle_t output, const std::vector<audio_latency_mode_t>& modes)
+ EXCLUDES_AudioFlinger_ClientMutex = 0;
};
class IAfThreadBase : public virtual RefBase {
@@ -214,7 +225,8 @@
status_t* status /*non-NULL*/,
bool pinned,
bool probe,
- bool notifyFramesProcessed) = 0;
+ bool notifyFramesProcessed)
+ REQUIRES(audio_utils::AudioFlinger_Mutex) = 0;
// return values for hasAudioSession (bit field)
enum effect_state {
@@ -256,7 +268,8 @@
// add and effect module. Also creates the effect chain is none exists for
// the effects audio session. Only called in a context of moving an effect
// from one thread to another
- virtual status_t addEffect_l(const sp<IAfEffectModule>& effect) = 0;
+ virtual status_t addEffect_ll(const sp<IAfEffectModule>& effect)
+ REQUIRES(audio_utils::AudioFlinger_Mutex, mutex()) = 0;
// remove and effect module. Also removes the effect chain is this was the last
// effect
virtual void removeEffect_l(const sp<IAfEffectModule>& effect, bool release = false) = 0;
@@ -311,7 +324,8 @@
// deliver stats to mediametrics.
virtual void sendStatistics(bool force) = 0;
- virtual Mutex& mutex() const = 0;
+ virtual audio_utils::mutex& mutex() const
+ RETURN_CAPABILITY(audio_utils::ThreadBase_Mutex) = 0;
virtual void onEffectEnable(const sp<IAfEffectModule>& effect) = 0;
virtual void onEffectDisable() = 0;
@@ -322,8 +336,10 @@
virtual void invalidateTracksForAudioSession(audio_session_t sessionId) const = 0;
virtual bool isStreamInitialized() const = 0;
- virtual void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) = 0;
- virtual void stopMelComputation_l() = 0;
+ virtual void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor)
+ REQUIRES(audio_utils::AudioFlinger_Mutex) = 0;
+ virtual void stopMelComputation_l()
+ REQUIRES(audio_utils::AudioFlinger_Mutex) = 0;
virtual product_strategy_t getStrategyForStream(audio_stream_type_t stream) const = 0;
@@ -399,7 +415,8 @@
audio_port_handle_t portId,
const sp<media::IAudioTrackCallback>& callback,
bool isSpatialized,
- bool isBitPerfect) = 0;
+ bool isBitPerfect)
+ REQUIRES(audio_utils::AudioFlinger_Mutex) = 0;
virtual status_t addTrack_l(const sp<IAfTrack>& track) = 0;
virtual bool destroyTrack_l(const sp<IAfTrack>& track) = 0;
@@ -503,7 +520,8 @@
pid_t tid,
status_t* status /*non-NULL*/,
audio_port_handle_t portId,
- int32_t maxSharedAudioHistoryMs) = 0;
+ int32_t maxSharedAudioHistoryMs)
+ REQUIRES(audio_utils::AudioFlinger_Mutex) = 0;
virtual void destroyTrack_l(const sp<IAfRecordTrack>& track) = 0;
virtual void removeTrack_l(const sp<IAfRecordTrack>& track) = 0;
diff --git a/services/audioflinger/IAfTrack.h b/services/audioflinger/IAfTrack.h
index cf30ded..2302e13 100644
--- a/services/audioflinger/IAfTrack.h
+++ b/services/audioflinger/IAfTrack.h
@@ -227,6 +227,18 @@
virtual void setMetadataHasChanged() = 0;
/**
+ * Called when a track moves to active state to record its contribution to battery usage.
+ * Track state transitions should eventually be handled within the track class.
+ */
+ virtual void beginBatteryAttribution() = 0;
+
+ /**
+ * Called when a track moves out of the active state to record its contribution
+ * to battery usage.
+ */
+ virtual void endBatteryAttribution() = 0;
+
+ /**
* For RecordTrack
* TODO(b/291317964) either use this or add asRecordTrack or asTrack etc.
*/
@@ -339,10 +351,10 @@
virtual sp<os::ExternalVibration> getExternalVibration() const = 0;
// This function should be called with holding thread lock.
- virtual void updateTeePatches() = 0;
+ virtual void updateTeePatches_l() = 0;
// Argument teePatchesToUpdate is by value, use std::move to optimize.
- virtual void setTeePatchesToUpdate(TeePatches teePatchesToUpdate) = 0;
+ virtual void setTeePatchesToUpdate_l(TeePatches teePatchesToUpdate) = 0;
static bool checkServerLatencySupported(audio_format_t format, audio_output_flags_t flags) {
return audio_is_linear_pcm(format) && (flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) == 0;
diff --git a/services/audioflinger/MelReporter.cpp b/services/audioflinger/MelReporter.cpp
index bcc6536..3a2608e 100644
--- a/services/audioflinger/MelReporter.cpp
+++ b/services/audioflinger/MelReporter.cpp
@@ -38,24 +38,21 @@
ndk::SpAIBinder soundDoseBinder;
if (device->getSoundDoseInterface(module, &soundDoseBinder) != OK) {
- ALOGW("%s: HAL cannot provide sound dose interface for module %s, use internal MEL",
+ ALOGW("%s: HAL cannot provide sound dose interface for module %s",
__func__, module.c_str());
- activateInternalSoundDoseComputation();
return false;
}
if (soundDoseBinder == nullptr) {
- ALOGW("%s: HAL doesn't implement a sound dose interface for module %s, use internal MEL",
+ ALOGW("%s: HAL doesn't implement a sound dose interface for module %s",
__func__, module.c_str());
- activateInternalSoundDoseComputation();
return false;
}
std::shared_ptr<ISoundDose> soundDoseInterface = ISoundDose::fromBinder(soundDoseBinder);
- if (!mSoundDoseManager->setHalSoundDoseInterface(soundDoseInterface)) {
+ if (!mSoundDoseManager->setHalSoundDoseInterface(module, soundDoseInterface)) {
ALOGW("%s: cannot activate HAL MEL reporting for module %s", __func__, module.c_str());
- activateInternalSoundDoseComputation();
return false;
}
@@ -65,7 +62,7 @@
void MelReporter::activateInternalSoundDoseComputation() {
{
- std::lock_guard _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (!mUseHalSoundDoseInterface) {
// no need to start internal MEL on active patches
return;
@@ -73,35 +70,14 @@
mUseHalSoundDoseInterface = false;
}
- mSoundDoseManager->setHalSoundDoseInterface(nullptr);
+ // reset the HAL interfaces and use internal MELs
+ mSoundDoseManager->resetHalSoundDoseInterfaces();
}
void MelReporter::onFirstRef() {
mAfMelReporterCallback->getPatchCommandThread()->addListener(this);
-}
-bool MelReporter::shouldComputeMelForDeviceType(audio_devices_t device) {
- if (!mSoundDoseManager->isCsdEnabled()) {
- ALOGV("%s csd is disabled", __func__);
- return false;
- }
- if (mSoundDoseManager->forceComputeCsdOnAllDevices()) {
- return true;
- }
-
- switch (device) {
- case AUDIO_DEVICE_OUT_WIRED_HEADSET:
- case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
- // TODO(b/278265907): enable A2DP when we can distinguish A2DP headsets
- // case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
- case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
- case AUDIO_DEVICE_OUT_USB_HEADSET:
- case AUDIO_DEVICE_OUT_BLE_HEADSET:
- case AUDIO_DEVICE_OUT_BLE_BROADCAST:
- return true;
- default:
- return false;
- }
+ mSoundDoseManager = sp<SoundDoseManager>::make(sp<IMelReporterCallback>::fromExisting(this));
}
void MelReporter::updateMetadataForCsd(audio_io_handle_t streamHandle,
@@ -111,8 +87,8 @@
return;
}
- std::lock_guard _laf(mAfMelReporterCallback->mutex());
- std::lock_guard _l(mLock);
+ audio_utils::lock_guard _laf(mAfMelReporterCallback->mutex());
+ audio_utils::lock_guard _l(mutex());
auto activeMelPatchId = activePatchStreamHandle_l(streamHandle);
if (!activeMelPatchId) {
ALOGV("%s stream handle %d does not have an active patch", __func__, streamHandle);
@@ -127,16 +103,17 @@
}
auto activeMelPatchIt = mActiveMelPatches.find(activeMelPatchId.value());
- if (activeMelPatchIt != mActiveMelPatches.end()
- && shouldActivateCsd != activeMelPatchIt->second.csdActive) {
- if (activeMelPatchIt->second.csdActive) {
- ALOGV("%s should not compute CSD for stream handle %d", __func__, streamHandle);
- stopMelComputationForPatch_l(activeMelPatchIt->second);
- } else {
- ALOGV("%s should compute CSD for stream handle %d", __func__, streamHandle);
- startMelComputationForActivePatch_l(activeMelPatchIt->second);
+ if (activeMelPatchIt != mActiveMelPatches.end()) {
+ if (shouldActivateCsd != activeMelPatchIt->second.csdActive) {
+ if (activeMelPatchIt->second.csdActive) {
+ ALOGV("%s should not compute CSD for stream handle %d", __func__, streamHandle);
+ stopMelComputationForPatch_l(activeMelPatchIt->second);
+ } else {
+ ALOGV("%s should compute CSD for stream handle %d", __func__, streamHandle);
+ startMelComputationForActivePatch_l(activeMelPatchIt->second);
+ }
+ activeMelPatchIt->second.csdActive = shouldActivateCsd;
}
- activeMelPatchIt->second.csdActive = shouldActivateCsd;
}
}
@@ -159,23 +136,28 @@
audio_io_handle_t streamHandle = patch.mAudioPatch.sources[0].ext.mix.handle;
ActiveMelPatch newPatch;
newPatch.streamHandle = streamHandle;
+ newPatch.csdActive = false;
for (size_t i = 0; i < patch.mAudioPatch.num_sinks; ++i) {
- if (patch.mAudioPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE
- && shouldComputeMelForDeviceType(patch.mAudioPatch.sinks[i].ext.device.type)) {
+ if (patch.mAudioPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE &&
+ mSoundDoseManager->shouldComputeCsdForDeviceType(
+ patch.mAudioPatch.sinks[i].ext.device.type)) {
audio_port_handle_t deviceId = patch.mAudioPatch.sinks[i].id;
- newPatch.deviceHandles.push_back(deviceId);
+ bool shouldComputeCsd = mSoundDoseManager->shouldComputeCsdForDeviceWithAddress(
+ patch.mAudioPatch.sinks[i].ext.device.type,
+ patch.mAudioPatch.sinks[i].ext.device.address);
+ newPatch.deviceStates.push_back({deviceId, shouldComputeCsd});
+ newPatch.csdActive |= shouldComputeCsd;
AudioDeviceTypeAddr adt{patch.mAudioPatch.sinks[i].ext.device.type,
patch.mAudioPatch.sinks[i].ext.device.address};
mSoundDoseManager->mapAddressToDeviceId(adt, deviceId);
}
}
- if (!newPatch.deviceHandles.empty()) {
- std::lock_guard _afl(mAfMelReporterCallback->mutex());
- std::lock_guard _l(mLock);
+ if (!newPatch.deviceStates.empty() && newPatch.csdActive) {
+ audio_utils::lock_guard _afl(mAfMelReporterCallback->mutex());
+ audio_utils::lock_guard _l(mutex());
ALOGV("%s add patch handle %d to active devices", __func__, handle);
startMelComputationForActivePatch_l(newPatch);
- newPatch.csdActive = true;
mActiveMelPatches[handle] = newPatch;
}
}
@@ -189,18 +171,41 @@
return;
}
- for (const auto& deviceHandle : patch.deviceHandles) {
- ++mActiveDevices[deviceHandle];
- ALOGI("%s add stream %d that uses device %d for CSD, nr of streams: %d", __func__,
- patch.streamHandle, deviceHandle, mActiveDevices[deviceHandle]);
+ for (const auto& device : patch.deviceStates) {
+ if (device.second) {
+ ++mActiveDevices[device.first];
+ ALOGI("%s add stream %d that uses device %d for CSD, nr of streams: %d", __func__,
+ patch.streamHandle, device.first, mActiveDevices[device.first]);
- if (outputThread != nullptr && !useHalSoundDoseInterface_l()) {
- outputThread->startMelComputation_l(mSoundDoseManager->getOrCreateProcessorForDevice(
- deviceHandle,
- patch.streamHandle,
- outputThread->sampleRate(),
- outputThread->channelCount(),
- outputThread->format()));
+ if (outputThread != nullptr && !useHalSoundDoseInterface_l()) {
+ outputThread->startMelComputation_l(
+ mSoundDoseManager->getOrCreateProcessorForDevice(
+ device.first,
+ patch.streamHandle,
+ outputThread->sampleRate(),
+ outputThread->channelCount(),
+ outputThread->format()));
+ }
+ }
+ }
+}
+
+void MelReporter::startMelComputationForDeviceId(audio_port_handle_t deviceId) {
+ ALOGV("%s(%d)", __func__, deviceId);
+ audio_utils::lock_guard _laf(mAfMelReporterCallback->mutex());
+ audio_utils::lock_guard _l(mutex());
+
+ for (auto& activeMelPatch : mActiveMelPatches) {
+ bool csdActive = false;
+ for (auto& device: activeMelPatch.second.deviceStates) {
+ if (device.first == deviceId && !device.second) {
+ device.second = true;
+ }
+ csdActive |= device.second;
+ }
+ if (csdActive && !activeMelPatch.second.csdActive) {
+ activeMelPatch.second.csdActive = csdActive;
+ startMelComputationForActivePatch_l(activeMelPatch.second);
}
}
}
@@ -213,7 +218,7 @@
ActiveMelPatch melPatch;
{
- std::lock_guard _l(mLock);
+ audio_utils::lock_guard _l(mutex());
auto patchIt = mActiveMelPatches.find(handle);
if (patchIt == mActiveMelPatches.end()) {
@@ -226,8 +231,8 @@
mActiveMelPatches.erase(patchIt);
}
- std::lock_guard _afl(mAfMelReporterCallback->mutex());
- std::lock_guard _l(mLock);
+ audio_utils::lock_guard _afl(mAfMelReporterCallback->mutex());
+ audio_utils::lock_guard _l(mutex());
stopMelComputationForPatch_l(melPatch);
}
@@ -239,7 +244,10 @@
void MelReporter::stopInternalMelComputation() {
ALOGV("%s", __func__);
- std::lock_guard _l(mLock);
+ audio_utils::lock_guard _l(mutex());
+ if (mUseHalSoundDoseInterface) {
+ return;
+ }
mActiveMelPatches.clear();
mUseHalSoundDoseInterface = true;
}
@@ -247,30 +255,48 @@
void MelReporter::stopMelComputationForPatch_l(const ActiveMelPatch& patch)
NO_THREAD_SAFETY_ANALYSIS // access of AudioFlinger::checkOutputThread_l
{
- if (!patch.csdActive) {
- // no need to stop CSD inactive patches
- return;
- }
-
auto outputThread = mAfMelReporterCallback->checkOutputThread_l(patch.streamHandle);
ALOGV("%s: stop MEL for stream id: %d", __func__, patch.streamHandle);
- for (const auto& deviceId : patch.deviceHandles) {
- if (mActiveDevices[deviceId] > 0) {
- --mActiveDevices[deviceId];
- if (mActiveDevices[deviceId] == 0) {
+ for (const auto& device : patch.deviceStates) {
+ if (mActiveDevices[device.first] > 0) {
+ --mActiveDevices[device.first];
+ if (mActiveDevices[device.first] == 0) {
// no stream is using deviceId anymore
- ALOGI("%s removing device %d from active CSD devices", __func__, deviceId);
- mSoundDoseManager->clearMapDeviceIdEntries(deviceId);
+ ALOGI("%s removing device %d from active CSD devices", __func__, device.first);
+ mSoundDoseManager->clearMapDeviceIdEntries(device.first);
}
}
}
+ mSoundDoseManager->removeStreamProcessor(patch.streamHandle);
if (outputThread != nullptr && !useHalSoundDoseInterface_l()) {
outputThread->stopMelComputation_l();
}
}
+void MelReporter::stopMelComputationForDeviceId(audio_port_handle_t deviceId) {
+ ALOGV("%s(%d)", __func__, deviceId);
+ audio_utils::lock_guard _laf(mAfMelReporterCallback->mutex());
+ audio_utils::lock_guard _l(mutex());
+
+ for (auto& activeMelPatch : mActiveMelPatches) {
+ bool csdActive = false;
+ for (auto& device: activeMelPatch.second.deviceStates) {
+ if (device.first == deviceId && device.second) {
+ device.second = false;
+ }
+ csdActive |= device.second;
+ }
+
+ if (!csdActive && activeMelPatch.second.csdActive) {
+ activeMelPatch.second.csdActive = csdActive;
+ stopMelComputationForPatch_l(activeMelPatch.second);
+ }
+ }
+
+}
+
std::optional<audio_patch_handle_t> MelReporter::activePatchStreamHandle_l(
audio_io_handle_t streamHandle) {
for(const auto& patchIt : mActiveMelPatches) {
@@ -286,7 +312,7 @@
}
std::string MelReporter::dump() {
- std::lock_guard _l(mLock);
+ audio_utils::lock_guard _l(mutex());
std::string output("\nSound Dose:\n");
output.append(mSoundDoseManager->dump());
return output;
diff --git a/services/audioflinger/MelReporter.h b/services/audioflinger/MelReporter.h
index 3511bea..3779776 100644
--- a/services/audioflinger/MelReporter.h
+++ b/services/audioflinger/MelReporter.h
@@ -23,7 +23,6 @@
#include <audio_utils/mutex.h>
#include <sounddose/SoundDoseManager.h>
-#include <mutex>
#include <unordered_map>
namespace android {
@@ -32,20 +31,22 @@
class IAfMelReporterCallback : public virtual RefBase {
public:
- virtual audio_utils::mutex& mutex() const = 0;
+ virtual audio_utils::mutex& mutex() const
+ RETURN_CAPABILITY(audio_utils::AudioFlinger_Mutex) = 0;
virtual const sp<PatchCommandThread>& getPatchCommandThread() = 0;
- virtual sp<IAfThreadBase> checkOutputThread_l(audio_io_handle_t ioHandle) const = 0;
+ virtual sp<IAfThreadBase> checkOutputThread_l(audio_io_handle_t ioHandle) const
+ REQUIRES(mutex()) = 0;
};
/**
* Class for listening to new patches and starting the MEL computation. MelReporter is
* concealed within AudioFlinger, their lifetimes are the same.
*/
-class MelReporter : public PatchCommandThread::PatchCommandListener {
+class MelReporter : public PatchCommandThread::PatchCommandListener,
+ public IMelReporterCallback {
public:
explicit MelReporter(const sp<IAfMelReporterCallback>& afMelReporterCallback)
- : mAfMelReporterCallback(afMelReporterCallback),
- mSoundDoseManager(sp<SoundDoseManager>::make()) {}
+ : mAfMelReporterCallback(afMelReporterCallback) {}
void onFirstRef() override;
@@ -77,6 +78,10 @@
std::string dump();
+ // IMelReporterCallback methods
+ void stopMelComputationForDeviceId(audio_port_handle_t deviceId) override;
+ void startMelComputationForDeviceId(audio_port_handle_t deviceId) override;
+
// PatchCommandListener methods
void onCreateAudioPatch(audio_patch_handle_t handle,
const IAfPatchPanel::Patch& patch) final;
@@ -92,38 +97,42 @@
private:
struct ActiveMelPatch {
audio_io_handle_t streamHandle{AUDIO_IO_HANDLE_NONE};
- std::vector<audio_port_handle_t> deviceHandles;
+ /**
+ * Stores device ids and whether they are compatible for CSD calculation.
+ * The boolean value can change since BT audio device types are user-configurable
+ * to headphones/headsets or other device types.
+ */
+ std::vector<std::pair<audio_port_handle_t,bool>> deviceStates;
bool csdActive;
};
- /** Returns true if we should compute MEL for the given device. */
- bool shouldComputeMelForDeviceType(audio_devices_t device);
-
void stopInternalMelComputation();
+ audio_utils::mutex& mutex() const { return mMutex; }
- /** Should be called with the following order of locks: mAudioFlinger.mLock -> mLock. */
- void stopMelComputationForPatch_l(const ActiveMelPatch& patch) REQUIRES(mLock);
+ /** Should be called with the following order of locks: mAudioFlinger.mutex() -> mutex(). */
+ void stopMelComputationForPatch_l(const ActiveMelPatch& patch) REQUIRES(mutex());
- /** Should be called with the following order of locks: mAudioFlinger.mLock -> mLock. */
- void startMelComputationForActivePatch_l(const ActiveMelPatch& patch) REQUIRES(mLock);
+ /** Should be called with the following order of locks: mAudioFlinger.mutex() -> mutex(). */
+ void startMelComputationForActivePatch_l(const ActiveMelPatch& patch) REQUIRES(mutex());
std::optional<audio_patch_handle_t>
- activePatchStreamHandle_l(audio_io_handle_t streamHandle) REQUIRES(mLock);
+ activePatchStreamHandle_l(audio_io_handle_t streamHandle) REQUIRES(mutex());
- bool useHalSoundDoseInterface_l() REQUIRES(mLock);
+ bool useHalSoundDoseInterface_l() REQUIRES(mutex());
const sp<IAfMelReporterCallback> mAfMelReporterCallback;
- sp<SoundDoseManager> mSoundDoseManager;
+ /* const */ sp<SoundDoseManager> mSoundDoseManager; // set onFirstRef
/**
* Lock for protecting the active mel patches. Do not mix with the AudioFlinger lock.
- * Locking order AudioFlinger::mLock -> PatchCommandThread::mLock -> MelReporter::mLock.
+ * Locking order AudioFlinger::mutex() -> PatchCommandThread::mutex() -> MelReporter::mutex().
*/
- std::mutex mLock;
- std::unordered_map<audio_patch_handle_t, ActiveMelPatch> mActiveMelPatches GUARDED_BY(mLock);
- std::unordered_map<audio_port_handle_t, int> mActiveDevices GUARDED_BY(mLock);
- bool mUseHalSoundDoseInterface GUARDED_BY(mLock) = false;
+ mutable audio_utils::mutex mMutex;
+ std::unordered_map<audio_patch_handle_t, ActiveMelPatch> mActiveMelPatches
+ GUARDED_BY(mutex());
+ std::unordered_map<audio_port_handle_t, int> mActiveDevices GUARDED_BY(mutex());
+ bool mUseHalSoundDoseInterface GUARDED_BY(mutex()) = false;
};
} // namespace android
diff --git a/services/audioflinger/PatchCommandThread.cpp b/services/audioflinger/PatchCommandThread.cpp
index c3259f1..f4c76d6 100644
--- a/services/audioflinger/PatchCommandThread.cpp
+++ b/services/audioflinger/PatchCommandThread.cpp
@@ -29,7 +29,7 @@
PatchCommandThread::~PatchCommandThread() {
exit();
- std::lock_guard _l(mLock);
+ audio_utils::lock_guard _l(mutex());
mCommands.clear();
}
@@ -39,7 +39,7 @@
void PatchCommandThread::addListener(const sp<PatchCommandListener>& listener) {
ALOGV("%s add listener %p", __func__, static_cast<void*>(listener.get()));
- std::lock_guard _l(mListenerLock);
+ audio_utils::lock_guard _l(listenerMutex());
mListeners.emplace_back(listener);
}
@@ -59,9 +59,8 @@
}
bool PatchCommandThread::threadLoop()
-NO_THREAD_SAFETY_ANALYSIS // bug in clang compiler.
{
- std::unique_lock _l(mLock);
+ audio_utils::unique_lock _l(mutex());
while (!exitPending()) {
while (!mCommands.empty() && !exitPending()) {
@@ -71,7 +70,7 @@
std::vector<wp<PatchCommandListener>> listenersCopy;
{
- std::lock_guard _ll(mListenerLock);
+ audio_utils::lock_guard _ll(listenerMutex());
listenersCopy = mListeners;
}
@@ -122,7 +121,7 @@
}
void PatchCommandThread::sendCommand(const sp<Command>& command) {
- std::lock_guard _l(mLock);
+ audio_utils::lock_guard _l(mutex());
mCommands.emplace_back(command);
mWaitWorkCV.notify_one();
}
@@ -148,7 +147,7 @@
void PatchCommandThread::exit() {
ALOGV("%s", __func__);
{
- std::lock_guard _l(mLock);
+ audio_utils::lock_guard _l(mutex());
requestExit();
mWaitWorkCV.notify_one();
}
diff --git a/services/audioflinger/PatchCommandThread.h b/services/audioflinger/PatchCommandThread.h
index a312fb7..092c0bc 100644
--- a/services/audioflinger/PatchCommandThread.h
+++ b/services/audioflinger/PatchCommandThread.h
@@ -100,13 +100,16 @@
void sendCommand(const sp<Command>& command);
- std::string mThreadName;
- std::mutex mLock;
- std::condition_variable mWaitWorkCV;
- std::deque<sp<Command>> mCommands GUARDED_BY(mLock); // list of pending commands
+ audio_utils::mutex& mutex() const { return mMutex; }
+ audio_utils::mutex& listenerMutex() const { return mListenerMutex; }
- std::mutex mListenerLock;
- std::vector<wp<PatchCommandListener>> mListeners GUARDED_BY(mListenerLock);
+ std::string mThreadName;
+ mutable audio_utils::mutex mMutex;
+ audio_utils::condition_variable mWaitWorkCV;
+ std::deque<sp<Command>> mCommands GUARDED_BY(mutex()); // list of pending commands
+
+ mutable audio_utils::mutex mListenerMutex;
+ std::vector<wp<PatchCommandListener>> mListeners GUARDED_BY(listenerMutex());
};
} // namespace android
diff --git a/services/audioflinger/PatchPanel.cpp b/services/audioflinger/PatchPanel.cpp
index 77ca013..7d3900b 100644
--- a/services/audioflinger/PatchPanel.cpp
+++ b/services/audioflinger/PatchPanel.cpp
@@ -83,7 +83,7 @@
}
/* List connected audio ports and their attributes */
-status_t PatchPanel::listAudioPorts(unsigned int* /* num_ports */,
+status_t PatchPanel::listAudioPorts_l(unsigned int* /* num_ports */,
struct audio_port *ports __unused)
{
ALOGV(__func__);
@@ -91,14 +91,14 @@
}
/* Get supported attributes for a given audio port */
-status_t PatchPanel::getAudioPort(struct audio_port_v7* port)
+status_t PatchPanel::getAudioPort_l(struct audio_port_v7* port)
{
if (port->type != AUDIO_PORT_TYPE_DEVICE) {
// Only query the HAL when the port is a device.
// TODO: implement getAudioPort for mix.
return INVALID_OPERATION;
}
- AudioHwDevice* hwDevice = findAudioHwDeviceByModule(port->ext.device.hw_module);
+ AudioHwDevice* hwDevice = findAudioHwDeviceByModule_l(port->ext.device.hw_module);
if (hwDevice == nullptr) {
ALOGW("%s cannot find hw module %d", __func__, port->ext.device.hw_module);
return BAD_VALUE;
@@ -110,7 +110,7 @@
}
/* Connect a patch between several source and sink ports */
-status_t PatchPanel::createAudioPatch(const struct audio_patch* patch,
+status_t PatchPanel::createAudioPatch_l(const struct audio_patch* patch,
audio_patch_handle_t *handle,
bool endpointPatch)
//unlocks AudioFlinger::mLock when calling IAfThreadBase::sendCreateAudioPatchConfigEvent
@@ -144,7 +144,7 @@
// 1) if a software patch is present, release the playback and capture threads and
// tracks created. This will also release the corresponding audio HAL patches
if (removedPatch.isSoftware()) {
- removedPatch.clearConnections(this);
+ removedPatch.clearConnections_l(this);
}
// 2) if the new patch and old patch source or sink are devices from different
// hw modules, clear the audio HAL patches now because they will not be updated
@@ -169,7 +169,7 @@
// removedPatch.mHalHandle would be AUDIO_PATCH_HANDLE_NONE in this case.
hwModule = oldPatch.sinks[0].ext.device.hw_module;
}
- sp<DeviceHalInterface> hwDevice = findHwDeviceByModule(hwModule);
+ sp<DeviceHalInterface> hwDevice = findHwDeviceByModule_l(hwModule);
if (hwDevice != 0) {
hwDevice->releaseAudioPatch(removedPatch.mHalHandle);
}
@@ -185,7 +185,7 @@
switch (patch->sources[0].type) {
case AUDIO_PORT_TYPE_DEVICE: {
audio_module_handle_t srcModule = patch->sources[0].ext.device.hw_module;
- AudioHwDevice *audioHwDevice = findAudioHwDeviceByModule(srcModule);
+ AudioHwDevice *audioHwDevice = findAudioHwDeviceByModule_l(srcModule);
if (!audioHwDevice) {
status = BAD_VALUE;
goto exit;
@@ -317,7 +317,7 @@
goto exit;
}
newPatch.mRecord.setThread(thread->asIAfRecordThread().get());
- status = newPatch.createConnections(this);
+ status = newPatch.createConnections_l(this);
if (status != NO_ERROR) {
goto exit;
}
@@ -438,11 +438,11 @@
newPatch.mHalHandle = halHandle;
mAfPatchPanelCallback->getPatchCommandThread()->createAudioPatch(*handle, newPatch);
if (insertedModule != AUDIO_MODULE_HANDLE_NONE) {
- addSoftwarePatchToInsertedModules(insertedModule, *handle, &newPatch.mAudioPatch);
+ addSoftwarePatchToInsertedModules_l(insertedModule, *handle, &newPatch.mAudioPatch);
}
mPatches.insert(std::make_pair(*handle, std::move(newPatch)));
} else {
- newPatch.clearConnections(this);
+ newPatch.clearConnections_l(this);
}
return status;
}
@@ -453,10 +453,10 @@
mRecord.handle(), mPlayback.handle());
}
-status_t PatchPanel::Patch::createConnections(const sp<IAfPatchPanel>& panel)
+status_t PatchPanel::Patch::createConnections_l(const sp<IAfPatchPanel>& panel)
{
// create patch from source device to record thread input
- status_t status = panel->createAudioPatch(
+ status_t status = panel->createAudioPatch_l(
PatchBuilder().addSource(mAudioPatch.sources[0]).
addSink(mRecord.thread(), { .source = AUDIO_SOURCE_MIC }).patch(),
mRecord.handlePtr(),
@@ -468,7 +468,7 @@
// create patch from playback thread output to sink device
if (mAudioPatch.num_sinks != 0) {
- status = panel->createAudioPatch(
+ status = panel->createAudioPatch_l(
PatchBuilder().addSource(mPlayback.thread()).addSink(mAudioPatch.sinks[0]).patch(),
mPlayback.handlePtr(),
true /*endpointPatch*/);
@@ -617,15 +617,15 @@
return status;
}
-void PatchPanel::Patch::clearConnections(const sp<IAfPatchPanel>& panel)
+void PatchPanel::Patch::clearConnections_l(const sp<IAfPatchPanel>& panel)
{
ALOGV("%s() mRecord.handle %d mPlayback.handle %d",
__func__, mRecord.handle(), mPlayback.handle());
mRecord.stopTrack();
mPlayback.stopTrack();
mRecord.clearTrackPeer(); // mRecord stop is synchronous. Break PeerProxy sp<> cycle.
- mRecord.closeConnections(panel);
- mPlayback.closeConnections(panel);
+ mRecord.closeConnections_l(panel);
+ mPlayback.closeConnections_l(panel);
}
status_t PatchPanel::Patch::getLatencyMs(double* latencyMs) const
@@ -715,7 +715,7 @@
}
/* Disconnect a patch */
-status_t PatchPanel::releaseAudioPatch(audio_patch_handle_t handle)
+status_t PatchPanel::releaseAudioPatch_l(audio_patch_handle_t handle)
//unlocks AudioFlinger::mLock when calling IAfThreadBase::sendReleaseAudioPatchConfigEvent
//to avoid deadlocks if the thread loop needs to acquire AudioFlinger::mLock
//before processing the release patch request.
@@ -734,7 +734,7 @@
const struct audio_port_config &src = patch.sources[0];
switch (src.type) {
case AUDIO_PORT_TYPE_DEVICE: {
- sp<DeviceHalInterface> hwDevice = findHwDeviceByModule(src.ext.device.hw_module);
+ sp<DeviceHalInterface> hwDevice = findHwDeviceByModule_l(src.ext.device.hw_module);
if (hwDevice == 0) {
ALOGW("%s() bad src hw module %d", __func__, src.ext.device.hw_module);
status = BAD_VALUE;
@@ -742,7 +742,7 @@
}
if (removedPatch.isSoftware()) {
- removedPatch.clearConnections(this);
+ removedPatch.clearConnections_l(this);
break;
}
@@ -765,7 +765,7 @@
}
} break;
case AUDIO_PORT_TYPE_MIX: {
- if (findHwDeviceByModule(src.ext.mix.hw_module) == 0) {
+ if (findHwDeviceByModule_l(src.ext.mix.hw_module) == 0) {
ALOGW("%s() bad src hw module %d", __func__, src.ext.mix.hw_module);
status = BAD_VALUE;
break;
@@ -799,7 +799,7 @@
}
/* List connected audio ports and they attributes */
-status_t PatchPanel::listAudioPatches(unsigned int* /* num_patches */,
+status_t PatchPanel::listAudioPatches_l(unsigned int* /* num_patches */,
struct audio_patch *patches __unused)
{
ALOGV(__func__);
@@ -856,7 +856,7 @@
}
}
-AudioHwDevice* PatchPanel::findAudioHwDeviceByModule(audio_module_handle_t module)
+AudioHwDevice* PatchPanel::findAudioHwDeviceByModule_l(audio_module_handle_t module)
{
if (module == AUDIO_MODULE_HANDLE_NONE) return nullptr;
ssize_t index = mAfPatchPanelCallback->getAudioHwDevs_l().indexOfKey(module);
@@ -867,13 +867,13 @@
return mAfPatchPanelCallback->getAudioHwDevs_l().valueAt(index);
}
-sp<DeviceHalInterface> PatchPanel::findHwDeviceByModule(audio_module_handle_t module)
+sp<DeviceHalInterface> PatchPanel::findHwDeviceByModule_l(audio_module_handle_t module)
{
- AudioHwDevice *audioHwDevice = findAudioHwDeviceByModule(module);
+ AudioHwDevice *audioHwDevice = findAudioHwDeviceByModule_l(module);
return audioHwDevice ? audioHwDevice->hwDevice() : nullptr;
}
-void PatchPanel::addSoftwarePatchToInsertedModules(
+void PatchPanel::addSoftwarePatchToInsertedModules_l(
audio_module_handle_t module, audio_patch_handle_t handle,
const struct audio_patch *patch)
{
diff --git a/services/audioflinger/PatchPanel.h b/services/audioflinger/PatchPanel.h
index b8b7b79..1ff8fff 100644
--- a/services/audioflinger/PatchPanel.h
+++ b/services/audioflinger/PatchPanel.h
@@ -30,25 +30,29 @@
: mAfPatchPanelCallback(afPatchPanelCallback) {}
/* List connected audio ports and their attributes */
- status_t listAudioPorts(unsigned int *num_ports,
- struct audio_port* ports) final;
+ status_t listAudioPorts_l(unsigned int *num_ports,
+ struct audio_port* ports) final REQUIRES(audio_utils::AudioFlinger_Mutex);
/* Get supported attributes for a given audio port */
- status_t getAudioPort(struct audio_port_v7* port) final;
+ status_t getAudioPort_l(struct audio_port_v7* port) final
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
/* Create a patch between several source and sink ports */
- status_t createAudioPatch(const struct audio_patch *patch,
+ status_t createAudioPatch_l(const struct audio_patch *patch,
audio_patch_handle_t *handle,
- bool endpointPatch = false) final;
+ bool endpointPatch = false) final
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
/* Release a patch */
- status_t releaseAudioPatch(audio_patch_handle_t handle) final;
+ status_t releaseAudioPatch_l(audio_patch_handle_t handle) final
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
/* List connected audio devices and they attributes */
- status_t listAudioPatches(unsigned int *num_patches,
- struct audio_patch* patches) final;
+ status_t listAudioPatches_l(unsigned int *num_patches,
+ struct audio_patch* patches) final
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
- // Retrieves all currently estrablished software patches for a stream
+ // Retrieves all currently established software patches for a stream
// opened on an intermediate module.
status_t getDownstreamSoftwarePatches(audio_io_handle_t stream,
std::vector<SoftwarePatch>* patches) const final;
@@ -60,20 +64,24 @@
void dump(int fd) const final;
- // Call with AudioFlinger mLock held
- const std::map<audio_patch_handle_t, Patch>& patches_l() const final { return mPatches; }
+ const std::map<audio_patch_handle_t, Patch>& patches_l() const final
+ REQUIRES(audio_utils::AudioFlinger_Mutex) { return mPatches; }
- // Must be called under AudioFlinger::mLock
- status_t getLatencyMs_l(audio_patch_handle_t patchHandle, double* latencyMs) const final;
+ status_t getLatencyMs_l(audio_patch_handle_t patchHandle, double* latencyMs) const final
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
- void closeThreadInternal_l(const sp<IAfThreadBase>& thread) const final;
+ void closeThreadInternal_l(const sp<IAfThreadBase>& thread) const final
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
private:
- AudioHwDevice* findAudioHwDeviceByModule(audio_module_handle_t module);
- sp<DeviceHalInterface> findHwDeviceByModule(audio_module_handle_t module);
- void addSoftwarePatchToInsertedModules(
+ AudioHwDevice* findAudioHwDeviceByModule_l(audio_module_handle_t module)
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
+ sp<DeviceHalInterface> findHwDeviceByModule_l(audio_module_handle_t module)
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
+ void addSoftwarePatchToInsertedModules_l(
audio_module_handle_t module, audio_patch_handle_t handle,
- const struct audio_patch *patch);
+ const struct audio_patch *patch)
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
void removeSoftwarePatchFromInsertedModules(audio_patch_handle_t handle);
void erasePatch(audio_patch_handle_t handle);
diff --git a/services/audioflinger/PlaybackTracks.h b/services/audioflinger/PlaybackTracks.h
index beb3e1c..ae60ed0 100644
--- a/services/audioflinger/PlaybackTracks.h
+++ b/services/audioflinger/PlaybackTracks.h
@@ -20,6 +20,7 @@
#include "TrackBase.h"
#include <android/os/BnExternalVibrationController.h>
+#include <audio_utils/mutex.h>
#include <audio_utils/LinearMap.h>
#include <binder/AppOpsManager.h>
@@ -192,8 +193,8 @@
sp<os::ExternalVibration> getExternalVibration() const final { return mExternalVibration; }
// This function should be called with holding thread lock.
- void updateTeePatches() final;
- void setTeePatchesToUpdate(TeePatches teePatchesToUpdate) final;
+ void updateTeePatches_l() final;
+ void setTeePatchesToUpdate_l(TeePatches teePatchesToUpdate) final;
void tallyUnderrunFrames(size_t frames) final {
if (isOut()) { // we expect this from output tracks only
@@ -348,8 +349,9 @@
private:
void interceptBuffer(const AudioBufferProvider::Buffer& buffer);
+ // Must hold thread lock to access tee patches
template <class F>
- void forEachTeePatchTrack(F f) {
+ void forEachTeePatchTrack_l(F f) {
for (auto& tp : mTeePatches) { f(tp.patchTrack); }
};
@@ -467,7 +469,8 @@
*/
SourceMetadatas mTrackMetadatas;
/** Protects mTrackMetadatas against concurrent access. */
- mutable std::mutex mTrackMetadatasMutex;
+ audio_utils::mutex& trackMetadataMutex() const { return mTrackMetadataMutex; }
+ mutable audio_utils::mutex mTrackMetadataMutex;
}; // end of OutputTrack
// playback track, used by PatchPanel
diff --git a/services/audioflinger/RecordTracks.h b/services/audioflinger/RecordTracks.h
index 021add4..8d3de38 100644
--- a/services/audioflinger/RecordTracks.h
+++ b/services/audioflinger/RecordTracks.h
@@ -20,6 +20,7 @@
#include "TrackBase.h"
#include <android/content/AttributionSourceState.h>
+#include <audio_utils/mutex.h>
#include <datapath/AudioStreamIn.h> // struct Source
namespace android {
@@ -214,15 +215,16 @@
};
sp<StreamInHalInterface> obtainStream(sp<IAfThreadBase>* thread);
+ audio_utils::mutex& readMutex() const { return mReadMutex; }
PatchRecordAudioBufferProvider mPatchRecordAudioBufferProvider;
std::unique_ptr<void, decltype(free)*> mSinkBuffer; // frame size aligned continuous buffer
std::unique_ptr<void, decltype(free)*> mStubBuffer; // buffer used for AudioBufferProvider
size_t mUnconsumedFrames = 0;
- std::mutex mReadLock;
- std::condition_variable mReadCV;
- size_t mReadBytes = 0; // GUARDED_BY(mReadLock)
- status_t mReadError = NO_ERROR; // GUARDED_BY(mReadLock)
+ mutable audio_utils::mutex mReadMutex;
+ audio_utils::condition_variable mReadCV;
+ size_t mReadBytes = 0; // GUARDED_BY(readMutex())
+ status_t mReadError = NO_ERROR; // GUARDED_BY(readMutex())
int64_t mLastReadFrames = 0; // accessed on RecordThread only
};
diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp
index cdae2ff..914b60d 100644
--- a/services/audioflinger/Threads.cpp
+++ b/services/audioflinger/Threads.cpp
@@ -685,9 +685,9 @@
// mWaitWorkCV.wait(...);
// // now thread is hung
// }
- AutoMutex lock(mLock);
+ audio_utils::lock_guard lock(mutex());
requestExit();
- mWaitWorkCV.broadcast();
+ mWaitWorkCV.notify_all();
}
// When Thread::requestExitAndWait is made virtual and this method is renamed to
// "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
@@ -697,7 +697,7 @@
status_t ThreadBase::setParameters(const String8& keyValuePairs)
{
ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
return sendSetParameterConfigEvent_l(keyValuePairs);
}
@@ -716,30 +716,31 @@
}
mConfigEvents.add(event);
ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
- mWaitWorkCV.signal();
- mLock.unlock();
+ mWaitWorkCV.notify_one();
+ mutex().unlock();
{
- Mutex::Autolock _l(event->mLock);
+ audio_utils::unique_lock _l(event->mutex());
while (event->mWaitStatus) {
- if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
+ if (event->mCondition.wait_for(_l, std::chrono::nanoseconds(kConfigEventTimeoutNs))
+ == std::cv_status::timeout) {
event->mStatus = TIMED_OUT;
event->mWaitStatus = false;
}
}
status = event->mStatus;
}
- mLock.lock();
+ mutex().lock();
return status;
}
void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
audio_port_handle_t portId)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
sendIoConfigEvent_l(event, pid, portId);
}
-// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
+// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
audio_port_handle_t portId)
{
@@ -759,11 +760,11 @@
void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
sendPrioConfigEvent_l(pid, tid, prio, forApp);
}
-// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
+// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
void ThreadBase::sendPrioConfigEvent_l(
pid_t pid, pid_t tid, int32_t prio, bool forApp)
{
@@ -771,7 +772,7 @@
sendConfigEvent_l(configEvent);
}
-// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
+// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
{
sp<ConfigEvent> configEvent;
@@ -794,7 +795,7 @@
const struct audio_patch *patch,
audio_patch_handle_t *handle)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
status_t status = sendConfigEvent_l(configEvent);
if (status == NO_ERROR) {
@@ -808,7 +809,7 @@
status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
const audio_patch_handle_t handle)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
return sendConfigEvent_l(configEvent);
}
@@ -820,7 +821,7 @@
// The update out device operation is only for record thread.
return INVALID_OPERATION;
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
return sendConfigEvent_l(configEvent);
}
@@ -835,7 +836,7 @@
void ThreadBase::sendCheckOutputStageEffectsEvent()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
sendCheckOutputStageEffectsEvent_l();
}
@@ -930,10 +931,10 @@
break;
}
{
- Mutex::Autolock _l(event->mLock);
+ audio_utils::lock_guard _l(event->mutex());
if (event->mWaitStatus) {
event->mWaitStatus = false;
- event->mCond.signal();
+ event->mCondition.notify_one();
}
}
ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
@@ -1026,7 +1027,7 @@
dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
this, mThreadName, getTid(), type(), threadTypeToString(type()));
- const bool locked = afutils::dumpTryLock(mLock);
+ const bool locked = afutils::dumpTryLock(mutex());
if (!locked) {
dprintf(fd, " Thread may be deadlocked\n");
}
@@ -1037,7 +1038,7 @@
dumpEffectChains_l(fd, args);
if (locked) {
- mLock.unlock();
+ mutex().unlock();
}
dprintf(fd, " Local log:\n");
@@ -1152,7 +1153,7 @@
void ThreadBase::acquireWakeLock()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
acquireWakeLock_l();
}
@@ -1206,7 +1207,7 @@
void ThreadBase::releaseWakeLock()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
releaseWakeLock_l();
}
@@ -1265,7 +1266,7 @@
void ThreadBase::clearPowerManager()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
releaseWakeLock_l();
mPowerManager.clear();
}
@@ -1396,7 +1397,7 @@
NO_THREAD_SAFETY_ANALYSIS // manual locking
{
if (!threadLocked) {
- mLock.lock();
+ mutex().lock();
}
if (mType != RECORD) {
@@ -1411,11 +1412,11 @@
}
if (!threadLocked) {
- mLock.unlock();
+ mutex().unlock();
}
}
-// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
+// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
status_t RecordThread::checkEffectCompatibility_l(
const effect_descriptor_t *desc, audio_session_t sessionId)
{
@@ -1459,7 +1460,7 @@
return NO_ERROR;
}
-// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
+// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
status_t PlaybackThread::checkEffectCompatibility_l(
const effect_descriptor_t *desc, audio_session_t sessionId)
{
@@ -1614,7 +1615,7 @@
return NO_ERROR;
}
-// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
+// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
sp<IAfEffectHandle> ThreadBase::createEffect_l(
const sp<Client>& client,
const sp<IEffectClient>& effectClient,
@@ -1643,8 +1644,8 @@
ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
- { // scope for mLock
- Mutex::Autolock _l(mLock);
+ { // scope for mutex()
+ audio_utils::lock_guard _l(mutex());
lStatus = checkEffectCompatibility_l(desc, sessionId);
if (probe || lStatus != NO_ERROR) {
@@ -1706,7 +1707,7 @@
Exit:
if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (effectCreated) {
chain->removeEffect_l(effect);
}
@@ -1726,7 +1727,7 @@
bool remove = false;
sp<IAfEffectModule> effect;
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
sp<IAfEffectBase> effectBase = handle->effect().promote();
if (effectBase == nullptr) {
return;
@@ -1752,7 +1753,7 @@
void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
if (isOffloadOrMmap()) {
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
broadcast_l();
}
if (!effect->isOffloadable()) {
@@ -1768,7 +1769,7 @@
void ThreadBase::onEffectDisable() {
if (isOffloadOrMmap()) {
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
broadcast_l();
}
}
@@ -1776,7 +1777,7 @@
sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
int effectId) const
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
return getEffect_l(sessionId, effectId);
}
@@ -1793,9 +1794,9 @@
return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
}
-// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
-// PlaybackThread::mLock held
-status_t ThreadBase::addEffect_l(const sp<IAfEffectModule>& effect)
+// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
+// ThreadBase::mutex() held
+status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
{
// check for existing effect chain with the requested audio session
audio_session_t sessionId = effect->sessionId();
@@ -1803,22 +1804,22 @@
bool chainCreated = false;
ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
- "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
- this, effect->desc().name, effect->desc().flags);
+ "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
+ __func__, this, effect->desc().name, effect->desc().flags);
if (chain == 0) {
// create a new chain for this session
- ALOGV("addEffect_l() new effect chain for session %d", sessionId);
+ ALOGV("%s: new effect chain for session %d", __func__, sessionId);
chain = IAfEffectChain::create(this, sessionId);
addEffectChain_l(chain);
chain->setStrategy(getStrategyForSession_l(sessionId));
chainCreated = true;
}
- ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
+ ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
if (chain->getEffectFromId_l(effect->id()) != 0) {
- ALOGW("addEffect_l() %p effect %s already present in chain %p",
- this, effect->desc().name, chain.get());
+ ALOGW("%s: %p effect %s already present in chain %p",
+ __func__, this, effect->desc().name, chain.get());
return BAD_VALUE;
}
@@ -1865,7 +1866,7 @@
{
effectChains = mEffectChains;
for (size_t i = 0; i < mEffectChains.size(); i++) {
- mEffectChains[i]->lock();
+ mEffectChains[i]->mutex().lock();
}
}
@@ -1874,13 +1875,13 @@
NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
{
for (size_t i = 0; i < effectChains.size(); i++) {
- effectChains[i]->unlock();
+ effectChains[i]->mutex().unlock();
}
}
sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
return getEffectChain_l(sessionId);
}
@@ -1898,7 +1899,7 @@
void ThreadBase::setMode(audio_mode_t mode)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
size_t size = mEffectChains.size();
for (size_t i = 0; i < size; i++) {
mEffectChains[i]->setMode_l(mode);
@@ -1918,7 +1919,7 @@
void ThreadBase::systemReady()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (mSystemReady) {
return;
}
@@ -1940,7 +1941,7 @@
logTrack("add", track);
mActiveTracksGeneration++;
mLatestActiveTrack = track;
- ++mBatteryCounter[track->uid()].second;
+ track->beginBatteryAttribution();
mHasChanged = true;
return mActiveTracks.add(track);
}
@@ -1954,7 +1955,7 @@
}
logTrack("remove", track);
mActiveTracksGeneration++;
- --mBatteryCounter[track->uid()].second;
+ track->endBatteryAttribution();
// mLatestActiveTrack is not cleared even if is the same as track.
mHasChanged = true;
#ifdef TEE_SINK
@@ -1967,14 +1968,13 @@
template <typename T>
void ThreadBase::ActiveTracks<T>::clear() {
for (const sp<T> &track : mActiveTracks) {
- BatteryNotifier::getInstance().noteStopAudio(track->uid());
+ track->endBatteryAttribution();
logTrack("clear", track);
}
mLastActiveTracksGeneration = mActiveTracksGeneration;
if (!mActiveTracks.empty()) { mHasChanged = true; }
mActiveTracks.clear();
mLatestActiveTrack.clear();
- mBatteryCounter.clear();
}
template <typename T>
@@ -1985,27 +1985,6 @@
thread->updateWakeLockUids_l(getWakeLockUids());
mLastActiveTracksGeneration = mActiveTracksGeneration;
}
-
- // Updates BatteryNotifier uids
- for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
- const uid_t uid = it->first;
- ssize_t &previous = it->second.first;
- ssize_t ¤t = it->second.second;
- if (current > 0) {
- if (previous == 0) {
- BatteryNotifier::getInstance().noteStartAudio(uid);
- }
- previous = current;
- ++it;
- } else if (current == 0) {
- if (previous > 0) {
- BatteryNotifier::getInstance().noteStopAudio(uid);
- }
- it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
- } else /* (current < 0) */ {
- LOG_ALWAYS_FATAL("negative battery count %zd", current);
- }
- }
}
template <typename T>
@@ -2038,7 +2017,7 @@
// If threadLoop is currently unlocked a signal of mWaitWorkCV will
// be lost so we also flag to prevent it blocking on mWaitWorkCV
mSignalPending = true;
- mWaitWorkCV.broadcast();
+ mWaitWorkCV.notify_all();
}
// Call only from threadLoop() or when it is idle.
@@ -2114,7 +2093,7 @@
return AudioSystem::getStrategyForStream(stream);
}
-// startMelComputation_l() must be called with AudioFlinger::mLock held
+// startMelComputation_l() must be called with AudioFlinger::mutex() held
void ThreadBase::startMelComputation_l(
const sp<audio_utils::MelProcessor>& /*processor*/)
{
@@ -2122,7 +2101,7 @@
ALOGW("%s: ThreadBase does not support CSD", __func__);
}
-// stopMelComputation_l() must be called with AudioFlinger::mLock held
+// stopMelComputation_l() must be called with AudioFlinger::mutex() held
void ThreadBase::stopMelComputation_l()
{
// Do nothing
@@ -2178,7 +2157,7 @@
snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
- // Assumes constructor is called by AudioFlinger with it's mLock held, but
+ // Assumes constructor is called by AudioFlinger with its mutex() held, but
// it would be safer to explicitly pass initial masterVolume/masterMute as
// parameter.
//
@@ -2378,7 +2357,7 @@
}
}
-// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
+// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
sp<IAfTrack> PlaybackThread::createTrack_l(
const sp<Client>& client,
audio_stream_type_t streamType,
@@ -2482,8 +2461,8 @@
}
// check compatibility with audio effects.
- { // scope for mLock
- Mutex::Autolock _l(mLock);
+ { // scope for mutex()
+ audio_utils::lock_guard _l(mutex());
for (audio_session_t session : {
AUDIO_SESSION_DEVICE,
AUDIO_SESSION_OUTPUT_STAGE,
@@ -2689,8 +2668,8 @@
goto Exit;
}
- { // scope for mLock
- Mutex::Autolock _l(mLock);
+ { // scope for mutex()
+ audio_utils::lock_guard _l(mutex());
// all tracks in same audio session must share the same routing strategy otherwise
// conflicts will happen when tracks are moved from one output to another by audio policy
@@ -2734,7 +2713,7 @@
}
mTracks.add(track);
{
- Mutex::Autolock _atCbL(mAudioTrackCbLock);
+ audio_utils::lock_guard _atCbL(audioTrackCbMutex());
if (callback.get() != nullptr) {
mAudioTrackCallbacks.emplace(track, callback);
}
@@ -2786,7 +2765,7 @@
uint32_t PlaybackThread::latency() const
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
return latency_l();
}
uint32_t PlaybackThread::latency_l() const
@@ -2800,7 +2779,7 @@
void PlaybackThread::setMasterVolume(float value)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
// Don't apply master volume in SW if our HAL can do it for us.
if (mOutput && mOutput->audioHwDev &&
mOutput->audioHwDev->canSetMasterVolume()) {
@@ -2820,7 +2799,7 @@
if (isDuplicating()) {
return;
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
// Don't apply master mute in SW if our HAL can do it for us.
if (mOutput && mOutput->audioHwDev &&
mOutput->audioHwDev->canSetMasterMute()) {
@@ -2832,21 +2811,21 @@
void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
mStreamTypes[stream].volume = value;
broadcast_l();
}
void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
mStreamTypes[stream].mute = muted;
broadcast_l();
}
float PlaybackThread::streamVolume(audio_stream_type_t stream) const
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
return mStreamTypes[stream].volume;
}
@@ -2855,9 +2834,9 @@
mOutput->stream->setVolume(left, right);
}
-// addTrack_l() must be called with ThreadBase::mLock held
+// addTrack_l() must be called with ThreadBase::mutex() held
status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
-NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
+NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
{
status_t status = ALREADY_EXISTS;
@@ -2867,15 +2846,15 @@
// effectively get the latency it requested.
if (track->isExternalTrack()) {
IAfTrackBase::track_state state = track->state();
- mLock.unlock();
+ mutex().unlock();
status = AudioSystem::startOutput(track->portId());
- mLock.lock();
+ mutex().lock();
// abort track was stopped/paused while we released the lock
if (state != track->state()) {
if (status == NO_ERROR) {
- mLock.unlock();
+ mutex().unlock();
AudioSystem::stopOutput(track->portId());
- mLock.lock();
+ mutex().lock();
}
return INVALID_OPERATION;
}
@@ -2914,17 +2893,17 @@
|| (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
// Unlock due to VibratorService will lock for this call and will
// call Tracks.mute/unmute which also require thread's lock.
- mLock.unlock();
+ mutex().unlock();
const os::HapticScale intensity = afutils::onExternalVibrationStart(
track->getExternalVibration());
std::optional<media::AudioVibratorInfo> vibratorInfo;
{
// TODO(b/184194780): Use the vibrator information from the vibrator that will be
// used to play this track.
- audio_utils::lock_guard _l(mAfThreadCallback->mutex());
+ audio_utils::lock_guard _l(mAfThreadCallback->mutex());
vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
}
- mLock.lock();
+ mutex().lock();
track->setHapticIntensity(intensity);
if (vibratorInfo) {
track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
@@ -2990,7 +2969,7 @@
mTracks.remove(track);
{
- Mutex::Autolock _atCbL(mAudioTrackCbLock);
+ audio_utils::lock_guard _atCbL(audioTrackCbMutex());
mAudioTrackCallbacks.erase(track);
}
if (track->isFastTrack()) {
@@ -3009,7 +2988,7 @@
String8 PlaybackThread::getParameters(const String8& keys)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
String8 out_s8;
if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
return out_s8;
@@ -3018,7 +2997,7 @@
}
status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (!isStreamInitialized()) {
return NO_INIT;
}
@@ -3088,7 +3067,7 @@
audio_utils::metadata::ByteString metaDataStr =
audio_utils::metadata::byteStringFromData(metadata);
std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
- Mutex::Autolock _l(mAudioTrackCbLock);
+ audio_utils::lock_guard _l(audioTrackCbMutex());
for (const auto& callbackPair : mAudioTrackCallbacks) {
callbackPair.second->onCodecFormatChanged(metadataVec);
}
@@ -3097,17 +3076,17 @@
void PlaybackThread::resetWriteBlocked(uint32_t sequence)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
// reject out of sequence requests
if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
mWriteAckSequence &= ~1;
- mWaitWorkCV.signal();
+ mWaitWorkCV.notify_one();
}
}
void PlaybackThread::resetDraining(uint32_t sequence)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
// reject out of sequence requests
if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
// Register discontinuity when HW drain is completed because that can cause
@@ -3116,11 +3095,13 @@
// elsewhere, e.g. in flush).
mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
mDrainSequence &= ~1;
- mWaitWorkCV.signal();
+ mWaitWorkCV.notify_one();
}
}
void PlaybackThread::readOutputParameters_l()
+NO_THREAD_SAFETY_ANALYSIS
+// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
{
// unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
const audio_config_base_t audioConfig = mOutput->getAudioProperties();
@@ -3285,13 +3266,14 @@
// 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_l() is called from the constructor
+ // Note that mutex() is not held when readOutputParameters_l() 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
+ // create a copy of mEffectChains as calling moveEffectChain_ll()
+ // can reorder some effect chains
Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
for (size_t i = 0; i < effectChains.size(); i ++) {
- mAfThreadCallback->moveEffectChain_l(effectChains[i]->sessionId(),
+ mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
this/* srcThread */, this/* dstThread */);
}
@@ -3349,7 +3331,7 @@
if (halFrames == NULL || dspFrames == NULL) {
return BAD_VALUE;
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (initCheck() != NO_ERROR) {
return INVALID_OPERATION;
}
@@ -3390,13 +3372,13 @@
AudioStreamOut* PlaybackThread::getOutput() const
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
return mOutput;
}
AudioStreamOut* PlaybackThread::clearOutput()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
AudioStreamOut *output = mOutput;
mOutput = NULL;
// FIXME FastMixer might also have a raw ptr to mOutputSink;
@@ -3407,7 +3389,7 @@
return output;
}
-// this method must always be called either with ThreadBase mLock held or inside the thread loop
+// this method must always be called either with ThreadBase mutex() held or inside the thread loop
sp<StreamHalInterface> PlaybackThread::stream() const
{
if (mOutput == NULL) {
@@ -3427,7 +3409,7 @@
return BAD_VALUE;
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (size_t i = 0; i < mTracks.size(); ++i) {
sp<IAfTrack> track = mTracks[i];
@@ -3557,7 +3539,7 @@
return bytesWritten;
}
-// startMelComputation_l() must be called with AudioFlinger::mLock held
+// startMelComputation_l() must be called with AudioFlinger::mutex() held
void PlaybackThread::startMelComputation_l(
const sp<audio_utils::MelProcessor>& processor)
{
@@ -3567,7 +3549,7 @@
}
}
-// stopMelComputation_l() must be called with AudioFlinger::mLock held
+// stopMelComputation_l() must be called with AudioFlinger::mutex() held
void PlaybackThread::stopMelComputation_l()
{
auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
@@ -3595,7 +3577,7 @@
void PlaybackThread::threadLoop_exit()
{
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (size_t i = 0; i < mTracks.size(); i++) {
sp<IAfTrack> track = mTracks[i];
track->invalidate();
@@ -3663,12 +3645,12 @@
void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
invalidateTracks_l(streamType);
}
void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
invalidateTracks_l(portIds);
}
@@ -3872,7 +3854,7 @@
status_t PlaybackThread::attachAuxEffect(
const sp<IAfTrack>& track, int EffectId)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
return attachAuxEffect_l(track, EffectId);
}
@@ -3973,7 +3955,7 @@
// If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
//
- // Note: we access outDeviceTypes() outside of mLock.
+ // Note: we access outDeviceTypes() outside of mutex().
if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
// Here, we try for the AF lock, but do not block on it as the latency
// is more informational.
@@ -4019,16 +4001,16 @@
}
MetadataUpdate metadataUpdate;
- { // scope for mLock
+ { // scope for mutex()
- Mutex::Autolock _l(mLock);
+ audio_utils::unique_lock _l(mutex());
processConfigEvents_l();
if (mCheckOutputStageEffects.load()) {
continue;
}
- // See comment at declaration of logString for why this is done under mLock
+ // See comment at declaration of logString for why this is done under mutex()
if (logString != NULL) {
mNBLogWriter->logTimestamp();
mNBLogWriter->log(logString);
@@ -4053,8 +4035,9 @@
const int64_t waitNs = computeWaitTimeNs_l();
ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
- status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
- if (status == TIMED_OUT) {
+ std::cv_status cvstatus =
+ mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
+ if (cvstatus == std::cv_status::timeout) {
mSignalPending = true; // if timeout recheck everything
}
ALOGV("async completion/wake");
@@ -4096,7 +4079,7 @@
releaseWakeLock_l();
// wait until we have something to do...
ALOGV("%s going to sleep", myName.c_str());
- mWaitWorkCV.wait(mLock);
+ mWaitWorkCV.wait(_l);
ALOGV("%s waking up", myName.c_str());
acquireWakeLock_l();
@@ -4160,7 +4143,7 @@
setHalLatencyMode_l();
for (const auto &track : mActiveTracks ) {
- track->updateTeePatches();
+ track->updateTeePatches_l();
}
// signal actual start of output stream when the render position reported by the kernel
@@ -4169,9 +4152,9 @@
&& (mKernelPositionOnStandby
!= mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
mHalStarted = true;
- mWaitHalStartCV.broadcast();
+ mWaitHalStartCV.notify_all();
}
- } // mLock scope ends
+ } // mutex() scope ends
if (mBytesRemaining == 0) {
mCurrentWriteLength = 0;
@@ -4402,7 +4385,7 @@
const double processMs =
(lastIoBeginNs - mLastIoEndNs) * 1e-6;
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
mIoJitterMs.add(jitterMs);
mProcessTimeMs.add(processMs);
@@ -4503,7 +4486,7 @@
} else {
ATRACE_BEGIN("sleep");
- Mutex::Autolock _l(mLock);
+ audio_utils::unique_lock _l(mutex());
// suspended requires accurate metering of sleep time.
if (isSuspended()) {
// advance by expected sleepTime
@@ -4528,7 +4511,7 @@
mSleepTimeUs = deltaNs / 1000;
}
if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
- mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
+ mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
}
ATRACE_END();
}
@@ -4701,9 +4684,9 @@
#endif
}
-// removeTracks_l() must be called with ThreadBase::mLock held
+// removeTracks_l() must be called with ThreadBase::mutex() held
void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
-NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
+NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
{
for (const auto& track : tracksToRemove) {
mActiveTracks.remove(track);
@@ -4729,11 +4712,11 @@
if (mHapticChannelCount > 0 &&
((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
|| (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
- mLock.unlock();
+ mutex().unlock();
// Unlock due to VibratorService will lock for this call and will
// call Tracks.mute/unmute which also require thread's lock.
afutils::onExternalVibrationStop(track->getExternalVibration());
- mLock.lock();
+ mutex().lock();
// When the track is stop, set the haptic intensity as MUTE
// for the HapticGenerator effect.
@@ -4931,13 +4914,13 @@
void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
mTracks.add(track);
}
void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
destroyTrack_l(track);
}
@@ -5187,7 +5170,7 @@
void MixerThread::onFirstRef() {
PlaybackThread::onFirstRef();
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (mOutput != nullptr && mOutput->stream != nullptr) {
status_t status = mOutput->stream->setLatencyModeCallback(this);
if (status != INVALID_OPERATION) {
@@ -5302,7 +5285,7 @@
bool PlaybackThread::waitingAsyncCallback()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
return waitingAsyncCallback_l();
}
@@ -5407,7 +5390,7 @@
// TODO add standby time extension fct of effect tail
}
-// prepareTracks_l() must be called with ThreadBase::mLock held
+// prepareTracks_l() must be called with ThreadBase::mutex() held
PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Vector<sp<IAfTrack>>* tracksToRemove)
{
@@ -6203,7 +6186,7 @@
return mixerStatus;
}
-// trackCountForUid_l() must be called with ThreadBase::mLock held
+// trackCountForUid_l() must be called with ThreadBase::mutex() held
uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
{
uint32_t trackCount = 0;
@@ -6246,7 +6229,7 @@
mPreviousNs = 0;
}
-// isTrackAllowed_l() must be called with ThreadBase::mLock held
+// isTrackAllowed_l() must be called with ThreadBase::mutex() held
bool MixerThread::isTrackAllowed_l(
audio_channel_mask_t channelMask, audio_format_t format,
audio_session_t sessionId, uid_t uid) const
@@ -6266,7 +6249,7 @@
return true;
}
-// checkForNewParameter_l() must be called with ThreadBase::mLock held
+// checkForNewParameter_l() must be called with ThreadBase::mutex() held
bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
status_t& status)
{
@@ -6484,14 +6467,14 @@
if (modes == nullptr) {
return BAD_VALUE;
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
*modes = mSupportedLatencyModes;
return NO_ERROR;
}
void MixerThread::onRecommendedLatencyModeChanged(
std::vector<audio_latency_mode_t> modes) {
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (modes != mSupportedLatencyModes) {
ALOGD("%s: thread(%d) supported latency modes: %s",
__func__, mId, toString(modes).c_str());
@@ -6542,7 +6525,7 @@
void DirectOutputThread::setMasterBalance(float balance)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (mMasterBalance != balance) {
mMasterBalance.store(balance);
mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
@@ -6922,7 +6905,7 @@
void DirectOutputThread::threadLoop_exit()
{
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (size_t i = 0; i < mTracks.size(); i++) {
if (mTracks[i]->isFlushPending()) {
mTracks[i]->flushAck();
@@ -6953,7 +6936,7 @@
return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
}
-// checkForNewParameter_l() must be called with ThreadBase::mLock held
+// checkForNewParameter_l() must be called with ThreadBase::mutex() held
bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
status_t& status)
{
@@ -7088,12 +7071,12 @@
bool asyncError;
{
- Mutex::Autolock _l(mLock);
+ audio_utils::unique_lock _l(mutex());
while (!((mWriteAckSequence & 1) ||
(mDrainSequence & 1) ||
mAsyncError ||
exitPending())) {
- mWaitWorkCV.wait(mLock);
+ mWaitWorkCV.wait(_l);
}
if (exitPending()) {
@@ -7129,50 +7112,50 @@
void AsyncCallbackThread::exit()
{
ALOGV("AsyncCallbackThread::exit");
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
requestExit();
- mWaitWorkCV.broadcast();
+ mWaitWorkCV.notify_all();
}
void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
// bit 0 is cleared
mWriteAckSequence = sequence << 1;
}
void AsyncCallbackThread::resetWriteBlocked()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
// ignore unexpected callbacks
if (mWriteAckSequence & 2) {
mWriteAckSequence |= 1;
- mWaitWorkCV.signal();
+ mWaitWorkCV.notify_one();
}
}
void AsyncCallbackThread::setDraining(uint32_t sequence)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
// bit 0 is cleared
mDrainSequence = sequence << 1;
}
void AsyncCallbackThread::resetDraining()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
// ignore unexpected callbacks
if (mDrainSequence & 2) {
mDrainSequence |= 1;
- mWaitWorkCV.signal();
+ mWaitWorkCV.notify_one();
}
}
void AsyncCallbackThread::setAsyncError()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
mAsyncError = true;
- mWaitWorkCV.signal();
+ mWaitWorkCV.notify_one();
}
@@ -7468,7 +7451,7 @@
bool OffloadThread::waitingAsyncCallback()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
return waitingAsyncCallback_l();
}
@@ -7495,14 +7478,14 @@
void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (PlaybackThread::invalidateTracks_l(streamType)) {
mFlushPending = true;
}
}
void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (PlaybackThread::invalidateTracks_l(portIds)) {
mFlushPending = true;
}
@@ -7644,7 +7627,7 @@
void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
// The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
// Adjust for thread->sampleRate() to determine minimum buffer frame count.
// Then triple buffer because Threads do not run synchronously and may not be clock locked.
@@ -7681,7 +7664,7 @@
void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (size_t i = 0; i < mOutputTracks.size(); i++) {
if (mOutputTracks[i]->thread() == thread) {
mOutputTracks[i]->destroy();
@@ -7696,7 +7679,7 @@
ALOGV("removeOutputTrack(): unknown thread: %p", thread);
}
-// caller must hold mLock
+// caller must hold mutex()
void DuplicatingThread::updateWaitTime_l()
{
mWaitTimeMs = UINT_MAX;
@@ -7830,18 +7813,20 @@
if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
return BAD_VALUE;
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
mRequestedLatencyMode = mode;
return NO_ERROR;
}
void SpatializerThread::checkOutputStageEffects()
+NO_THREAD_SAFETY_ANALYSIS
+// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
{
bool hasVirtualizer = false;
bool hasDownMixer = false;
sp<IAfEffectHandle> finalDownMixer;
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
if (chain != 0) {
hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
@@ -7882,7 +7867,7 @@
}
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
mFinalDownMixer = finalDownMixer;
}
}
@@ -8088,13 +8073,13 @@
void RecordThread::preExit()
{
ALOGV(" preExit()");
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (size_t i = 0; i < mTracks.size(); i++) {
sp<IAfRecordTrack> track = mTracks[i];
track->invalidate();
}
mActiveTracks.clear();
- mStartStopCond.broadcast();
+ mStartStopCV.notify_all();
}
bool RecordThread::threadLoop()
@@ -8106,7 +8091,7 @@
reacquire_wakelock:
sp<IAfRecordTrack> activeTrack;
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
acquireWakeLock_l();
}
@@ -8130,13 +8115,13 @@
bool silenceFastCapture = false;
- { // scope for mLock
- Mutex::Autolock _l(mLock);
+ { // scope for mutex()
+ audio_utils::unique_lock _l(mutex());
processConfigEvents_l();
// check exitPending here because checkForNewParameters_l() and
- // checkForNewParameters_l() can temporarily release mLock
+ // checkForNewParameters_l() can temporarily release mutex()
if (exitPending()) {
break;
}
@@ -8144,7 +8129,7 @@
// sleep with mutex unlocked
if (sleepUs > 0) {
ATRACE_BEGIN("sleepC");
- mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
+ (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
ATRACE_END();
sleepUs = 0;
continue;
@@ -8158,7 +8143,7 @@
releaseWakeLock_l();
ALOGV("RecordThread: loop stopping");
// go to sleep
- mWaitWorkCV.wait(mLock);
+ mWaitWorkCV.wait(_l);
ALOGV("RecordThread: loop starting");
goto reacquire_wakelock;
}
@@ -8265,7 +8250,7 @@
standbyIfNotAlreadyInStandby();
}
if (doBroadcast) {
- mStartStopCond.broadcast();
+ mStartStopCV.notify_all();
}
// sleep if there are no active tracks to process
@@ -8634,7 +8619,7 @@
{0, 0} /* lastTimestamp */, mSampleRate);
const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
mIoJitterMs.add(jitterMs);
mProcessTimeMs.add(processMs);
}
@@ -8647,13 +8632,13 @@
standbyIfNotAlreadyInStandby();
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (size_t i = 0; i < mTracks.size(); i++) {
sp<IAfRecordTrack> track = mTracks[i];
track->invalidate();
}
mActiveTracks.clear();
- mStartStopCond.broadcast();
+ mStartStopCV.notify_all();
}
releaseWakeLock();
@@ -8712,7 +8697,7 @@
}
}
-// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
+// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
const sp<Client>& client,
const audio_attributes_t& attr,
@@ -8804,7 +8789,7 @@
mFastTrackAvail
) {
// check compatibility with audio effects.
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
// Do not accept FAST flag if the session has software effects
sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
if (chain != 0) {
@@ -8868,8 +8853,8 @@
*pFrameCount = frameCount;
*pNotificationFrameCount = notificationFrameCount;
- { // scope for mLock
- Mutex::Autolock _l(mLock);
+ { // scope for mutex()
+ audio_utils::lock_guard _l(mutex());
int32_t startFrames = -1;
if (!mSharedAudioPackageName.empty()
&& mSharedAudioPackageName == attributionSource.packageName
@@ -8930,7 +8915,7 @@
{
// This section is a rendezvous between binder thread executing start() and RecordThread
- AutoMutex lock(mLock);
+ audio_utils::lock_guard lock(mutex());
if (recordTrack->isInvalid()) {
recordTrack->clearSyncStartEvent();
ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
@@ -8954,9 +8939,9 @@
recordTrack->setState(IAfTrackBase::STARTING_1);
mActiveTracks.add(recordTrack);
if (recordTrack->isExternalTrack()) {
- mLock.unlock();
+ mutex().unlock();
status = AudioSystem::startInput(recordTrack->portId());
- mLock.lock();
+ mutex().lock();
if (recordTrack->isInvalid()) {
recordTrack->clearSyncStartEvent();
if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
@@ -9002,7 +8987,7 @@
}
recordTrack->setState(IAfTrackBase::STARTING_2);
// signal thread to start
- mWaitWorkCV.broadcast();
+ mWaitWorkCV.notify_all();
return status;
}
}
@@ -9023,7 +9008,7 @@
bool RecordThread::stop(IAfRecordTrack* recordTrack) {
ALOGV("RecordThread::stop");
- AutoMutex _l(mLock);
+ audio_utils::unique_lock _l(mutex());
// if we're invalid, we can't be on the ActiveTracks.
if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
return false;
@@ -9034,8 +9019,8 @@
// NOTE: Waiting here is important to keep stop synchronous.
// This is needed for proper patchRecord peer release.
while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
- mWaitWorkCV.broadcast(); // signal thread to stop
- mStartStopCond.wait(mLock);
+ mWaitWorkCV.notify_all(); // signal thread to stop
+ mStartStopCV.wait(_l);
}
if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
@@ -9064,7 +9049,7 @@
audio_session_t eventSession = event->triggerSession();
status_t ret = NAME_NOT_FOUND;
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (size_t i = 0; i < mTracks.size(); i++) {
sp<IAfRecordTrack> track = mTracks[i];
@@ -9083,7 +9068,7 @@
std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
{
ALOGV("RecordThread::getActiveMicrophones");
- AutoMutex _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (!isStreamInitialized()) {
return NO_INIT;
}
@@ -9095,7 +9080,7 @@
audio_microphone_direction_t direction)
{
ALOGV("setPreferredMicrophoneDirection(%d)", direction);
- AutoMutex _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (!isStreamInitialized()) {
return NO_INIT;
}
@@ -9105,7 +9090,7 @@
status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
{
ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
- AutoMutex _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (!isStreamInitialized()) {
return NO_INIT;
}
@@ -9115,7 +9100,7 @@
status_t RecordThread::shareAudioHistory(
const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
int64_t sharedAudioStartMs) {
- AutoMutex _l(mLock);
+ audio_utils::lock_guard _l(mutex());
return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
}
@@ -9181,7 +9166,7 @@
return change;
}
-// destroyTrack_l() must be called with ThreadBase::mLock held
+// destroyTrack_l() must be called with ThreadBase::mutex() held
void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
{
track->terminate();
@@ -9281,7 +9266,7 @@
void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (size_t i = 0; i < mTracks.size() ; i++) {
sp<IAfRecordTrack> track = mTracks[i];
if (track != 0 && track->portId() == portId) {
@@ -9406,7 +9391,7 @@
void RecordThread::checkBtNrec()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
checkBtNrec_l();
}
@@ -9515,7 +9500,7 @@
String8 RecordThread::getParameters(const String8& keys)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (initCheck() == NO_ERROR) {
String8 out_s8;
if (mInput->stream->getParameters(keys, &out_s8) == OK) {
@@ -9591,7 +9576,7 @@
uint32_t RecordThread::getInputFramesLost() const
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
uint32_t result;
if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
return result;
@@ -9602,7 +9587,7 @@
KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
{
KeyedVector<audio_session_t, bool> ids;
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (size_t j = 0; j < mTracks.size(); ++j) {
sp<IAfRecordTrack> track = mTracks[j];
audio_session_t sessionId = track->sessionId();
@@ -9615,14 +9600,14 @@
AudioStreamIn* RecordThread::clearInput()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
AudioStreamIn *input = mInput;
mInput = NULL;
mInputSource.clear();
return input;
}
-// this method must always be called either with ThreadBase mLock held or inside the thread loop
+// this method must always be called either with ThreadBase mutex() held or inside the thread loop
sp<StreamHalInterface> RecordThread::stream() const
{
if (mInput == NULL) {
@@ -9740,7 +9725,7 @@
void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
mOutDevices = outDevices;
mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
for (size_t i = 0; i < mEffectChains.size(); i++) {
@@ -9877,7 +9862,7 @@
void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
mTracks.add(record);
if (record->getSource()) {
mSource = record->getSource();
@@ -9886,7 +9871,7 @@
void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (mSource == record->getSource()) {
mSource = mInput;
}
@@ -10011,7 +9996,7 @@
{
ActiveTracks<IAfMmapTrack> activeTracks;
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (const sp<IAfMmapTrack>& t : mActiveTracks) {
activeTracks.add(t);
}
@@ -10155,24 +10140,24 @@
{
// Add the track record before starting input so that the silent status for the
// client can be cached.
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
setClientSilencedState_l(portId, false /*silenced*/);
}
ret = AudioSystem::startInput(portId);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
// abort if start is rejected by audio policy manager
if (ret != NO_ERROR) {
ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
if (!mActiveTracks.isEmpty()) {
- mLock.unlock();
+ mutex().unlock();
if (isOutput()) {
AudioSystem::releaseOutput(portId);
} else {
AudioSystem::releaseInput(portId);
}
- mLock.lock();
+ mutex().lock();
} else {
mHalStream->stop();
}
@@ -10237,7 +10222,7 @@
return NO_ERROR;
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
sp<IAfMmapTrack> track;
for (const sp<IAfMmapTrack>& t : mActiveTracks) {
@@ -10253,7 +10238,7 @@
mActiveTracks.remove(track);
eraseClientSilencedState_l(track->portId());
- mLock.unlock();
+ mutex().unlock();
if (isOutput()) {
AudioSystem::stopOutput(track->portId());
AudioSystem::releaseOutput(track->portId());
@@ -10261,7 +10246,7 @@
AudioSystem::stopInput(track->portId());
AudioSystem::releaseInput(track->portId());
}
- mLock.lock();
+ mutex().lock();
sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
if (chain != 0) {
@@ -10350,7 +10335,7 @@
Vector<sp<IAfEffectChain>> effectChains;
{ // under Thread lock
- Mutex::Autolock _l(mLock);
+ audio_utils::unique_lock _l(mutex());
if (mSignalPending) {
// A signal was raised while we were unlocked
@@ -10366,7 +10351,7 @@
// wait until we have something to do...
ALOGV("%s going to sleep", myName.c_str());
- mWaitWorkCV.wait(mLock);
+ mWaitWorkCV.wait(_l);
ALOGV("%s waking up", myName.c_str());
checkSilentMode_l();
@@ -10409,7 +10394,7 @@
return false;
}
-// checkForNewParameter_l() must be called with ThreadBase::mLock held
+// checkForNewParameter_l() must be called with ThreadBase::mutex() held
bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
status_t& status)
{
@@ -10430,7 +10415,7 @@
String8 MmapThread::getParameters(const String8& keys)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
String8 out_s8;
if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
return out_s8;
@@ -10465,7 +10450,7 @@
status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
audio_patch_handle_t *handle)
-NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mLock
+NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
{
status_t status = NO_ERROR;
@@ -10541,9 +10526,9 @@
}
sp<MmapStreamCallback> callback = mCallback.promote();
if (mDeviceId != deviceId && callback != 0) {
- mLock.unlock();
+ mutex().unlock();
callback->onRoutingChanged(deviceId);
- mLock.lock();
+ mutex().lock();
}
mPatch = *patch;
mDeviceId = deviceId;
@@ -10694,7 +10679,7 @@
}
void MmapThread::checkInvalidTracks_l()
-NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
+NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
{
sp<MmapStreamCallback> callback;
for (const sp<IAfMmapTrack>& track : mActiveTracks) {
@@ -10708,9 +10693,9 @@
}
}
if (callback != 0) {
- mLock.unlock();
+ mutex().unlock();
callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
- mLock.lock();
+ mutex().lock();
}
}
@@ -10788,7 +10773,7 @@
AudioStreamOut* MmapPlaybackThread::clearOutput()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
AudioStreamOut *output = mOutput;
mOutput = NULL;
return output;
@@ -10796,7 +10781,7 @@
void MmapPlaybackThread::setMasterVolume(float value)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
// Don't apply master volume in SW if our HAL can do it for us.
if (mAudioHwDev &&
mAudioHwDev->canSetMasterVolume()) {
@@ -10808,7 +10793,7 @@
void MmapPlaybackThread::setMasterMute(bool muted)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
// Don't apply master mute in SW if our HAL can do it for us.
if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
mMasterMute = false;
@@ -10819,7 +10804,7 @@
void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (stream == mStreamType) {
mStreamVolume = value;
broadcast_l();
@@ -10828,7 +10813,7 @@
float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (stream == mStreamType) {
return mStreamVolume;
}
@@ -10837,7 +10822,7 @@
void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (stream == mStreamType) {
mStreamMute= muted;
broadcast_l();
@@ -10846,7 +10831,7 @@
void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
if (streamType == mStreamType) {
for (const sp<IAfMmapTrack>& track : mActiveTracks) {
track->invalidate();
@@ -10857,7 +10842,7 @@
void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
bool trackMatch = false;
for (const sp<IAfMmapTrack>& track : mActiveTracks) {
if (portIds.find(track->portId()) != portIds.end()) {
@@ -10906,9 +10891,9 @@
if (callback != 0) {
mHalVolFloat = volume; // SW volume control worked, so update value.
mNoCallbackWarningCount = 0;
- mLock.unlock();
+ mutex().unlock();
callback->onVolumeChanged(volume);
- mLock.lock();
+ mutex().lock();
} else {
if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
ALOGW("Could not set MMAP stream volume: no volume callback!");
@@ -11005,7 +10990,7 @@
return NO_ERROR;
}
-// startMelComputation_l() must be called with AudioFlinger::mLock held
+// startMelComputation_l() must be called with AudioFlinger::mutex() held
void MmapPlaybackThread::startMelComputation_l(
const sp<audio_utils::MelProcessor>& processor)
{
@@ -11019,7 +11004,7 @@
// assigned constant for each thread
}
-// stopMelComputation_l() must be called with AudioFlinger::mLock held
+// stopMelComputation_l() must be called with AudioFlinger::mutex() held
void MmapPlaybackThread::stopMelComputation_l()
{
ALOGV("%s: pausing mel processor for thread %d", __func__, id());
@@ -11068,7 +11053,7 @@
AudioStreamIn* MmapCaptureThread::clearInput()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
AudioStreamIn *input = mInput;
mInput = NULL;
return input;
@@ -11126,7 +11111,7 @@
void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mutex());
for (size_t i = 0; i < mActiveTracks.size() ; i++) {
if (mActiveTracks[i]->portId() == portId) {
mActiveTracks[i]->setSilenced_l(silenced);
diff --git a/services/audioflinger/Threads.h b/services/audioflinger/Threads.h
index 3098892..01a8a22 100644
--- a/services/audioflinger/Threads.h
+++ b/services/audioflinger/Threads.h
@@ -77,20 +77,20 @@
// Config event sequence by client if status needed (e.g binder thread calling setParameters()):
// 1. create SetParameterConfigEvent. This sets mWaitStatus in config event
- // 2. Lock mLock
+ // 2. Lock mutex()
// 3. Call sendConfigEvent_l(): Append to mConfigEvents and mWaitWorkCV.signal
// 4. sendConfigEvent_l() reads status from event->mStatus;
// 5. sendConfigEvent_l() returns status
// 6. Unlock
//
// Parameter sequence by server: threadLoop calling processConfigEvents_l():
- // 1. Lock mLock
+ // 1. Lock mutex()
// 2. If there is an entry in mConfigEvents proceed ...
// 3. Read first entry in mConfigEvents
// 4. Remove first entry from mConfigEvents
// 5. Process
// 6. Set event->mStatus
- // 7. event->mCond.signal
+ // 7. event->mCondition.notify_one()
// 8. Unlock
class ConfigEvent: public RefBase {
@@ -103,9 +103,10 @@
}
}
+ audio_utils::mutex& mutex() const { return mMutex; }
const int mType; // event type e.g. CFG_EVENT_IO
- Mutex mLock; // mutex associated with mCond
- Condition mCond; // condition for status return
+ mutable audio_utils::mutex mMutex; // mutex associated with mCondition
+ audio_utils::condition_variable mCondition; // condition for status return
status_t mStatus; // status communicated to sender
bool mWaitStatus; // true if sender is waiting for status
bool mRequiresSystemReady; // true if must wait for system ready to enter event queue
@@ -322,7 +323,7 @@
void exit() final;
status_t setParameters(const String8& keyValuePairs) final;
- // sendConfigEvent_l() must be called with ThreadBase::mLock held
+ // sendConfigEvent_l() must be called with ThreadBase::mutex() held
// Can temporarily release the lock if waiting for a reply from
// processConfigEvents_l().
status_t sendConfigEvent_l(sp<ConfigEvent>& event);
@@ -389,7 +390,8 @@
status_t *status /*non-NULL*/,
bool pinned,
bool probe,
- bool notifyFramesProcessed) final;
+ bool notifyFramesProcessed) final
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
// return values for hasAudioSession (bit field)
enum effect_state {
@@ -428,7 +430,8 @@
// add and effect module. Also creates the effect chain is none exists for
// the effects audio session. Only called in a context of moving an effect
// from one thread to another
- status_t addEffect_l(const sp<IAfEffectModule>& effect) final;
+ status_t addEffect_ll(const sp<IAfEffectModule>& effect) final
+ REQUIRES(audio_utils::AudioFlinger_Mutex, mutex());
// remove and effect module. Also removes the effect chain is this was the last
// effect
void removeEffect_l(const sp<IAfEffectModule>& effect, bool release = false) final;
@@ -439,7 +442,7 @@
// TODO(b/291317898) - remove hasAudioSession_l below.
uint32_t hasAudioSession_l(audio_session_t sessionId) const override = 0;
uint32_t hasAudioSession(audio_session_t sessionId) const final {
- Mutex::Autolock _l(mLock);
+ std::lock_guard _l(mutex());
return hasAudioSession_l(sessionId);
}
@@ -507,19 +510,19 @@
// deliver stats to mediametrics.
void sendStatistics(bool force) final;
- Mutex& mutex() const final {
- return mLock;
+ audio_utils::mutex& mutex() const final RETURN_CAPABILITY(audio_utils::ThreadBase_Mutex) {
+ return mMutex;
}
- mutable Mutex mLock;
+ mutable audio_utils::mutex mMutex;
void onEffectEnable(const sp<IAfEffectModule>& effect) final;
void onEffectDisable() final;
- // invalidateTracksForAudioSession_l must be called with holding mLock.
+ // invalidateTracksForAudioSession_l must be called with holding mutex().
void invalidateTracksForAudioSession_l(audio_session_t /* sessionId */) const override {}
// Invalidate all the tracks with the given audio session.
void invalidateTracksForAudioSession(audio_session_t sessionId) const final {
- Mutex::Autolock _l(mLock);
+ std::lock_guard _l(mutex());
invalidateTracksForAudioSession_l(sessionId);
}
@@ -534,8 +537,10 @@
}
}
- void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override;
- void stopMelComputation_l() override;
+ void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
+ void stopMelComputation_l() override
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
protected:
@@ -599,7 +604,7 @@
const type_t mType;
// Used by parameters, config events, addTrack_l, exit
- Condition mWaitWorkCV;
+ audio_utils::condition_variable mWaitWorkCV;
const sp<IAfThreadCallback> mAfThreadCallback;
ThreadMetrics mThreadMetrics;
@@ -783,8 +788,6 @@
return wakeLockUids; // moved by underlying SharedBuffer
}
- std::map<uid_t, std::pair<ssize_t /* previous */, ssize_t /* current */>>
- mBatteryCounter;
SortedVector<sp<T>> mActiveTracks;
int mActiveTracksGeneration;
int mLastActiveTracksGeneration;
@@ -937,7 +940,8 @@
audio_port_handle_t portId,
const sp<media::IAudioTrackCallback>& callback,
bool isSpatialized,
- bool isBitPerfect) final;
+ bool isBitPerfect) final
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
bool isTrackActive(const sp<IAfTrack>& track) const final {
return mActiveTracks.indexOf(track) >= 0;
@@ -1041,7 +1045,7 @@
}
void setDownStreamPatch(const struct audio_patch* patch) final {
- Mutex::Autolock _l(mLock);
+ std::lock_guard _l(mutex());
mDownStreamPatch = *patch;
}
@@ -1063,11 +1067,13 @@
return INVALID_OPERATION;
}
- void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override;
- void stopMelComputation_l() override;
+ void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
+ void stopMelComputation_l() override
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
void setStandby() final {
- Mutex::Autolock _l(mLock);
+ std::lock_guard _l(mutex());
setStandby_l();
}
@@ -1079,7 +1085,7 @@
}
bool waitForHalStart() final {
- Mutex::Autolock _l(mLock);
+ audio_utils::unique_lock _l(mutex());
static const nsecs_t kWaitHalTimeoutNs = seconds(2);
nsecs_t endWaitTimetNs = systemTime() + kWaitHalTimeoutNs;
while (!mHalStarted) {
@@ -1088,7 +1094,7 @@
break;
}
nsecs_t waitTimeLeftNs = endWaitTimetNs - timeNs;
- mWaitHalStartCV.waitRelative(mLock, waitTimeLeftNs);
+ mWaitHalStartCV.wait_for(_l, std::chrono::nanoseconds(waitTimeLeftNs));
}
return mHalStarted;
}
@@ -1369,7 +1375,8 @@
sp<AsyncCallbackThread> mCallbackThread;
- Mutex mAudioTrackCbLock;
+ audio_utils::mutex& audioTrackCbMutex() const { return mAudioTrackCbMutex; }
+ mutable audio_utils::mutex mAudioTrackCbMutex;
// Record of IAudioTrackCallback
std::map<sp<IAfTrack>, sp<media::IAudioTrackCallback>> mAudioTrackCallbacks;
@@ -1390,7 +1397,7 @@
// output stream start detection based on render position returned by the kernel
// condition signalled when the output stream has started
- Condition mWaitHalStartCV;
+ audio_utils::condition_variable mWaitHalStartCV;
// true when the output stream render position has moved, reset to false in standby
bool mHalStarted = false;
// last kernel render position saved when entering standby
@@ -1717,9 +1724,11 @@
// setDraining(). The sequence is shifted one bit to the left and the lsb is used
// to indicate that the callback has been received via resetDraining()
uint32_t mDrainSequence;
- Condition mWaitWorkCV;
- Mutex mLock;
+ audio_utils::condition_variable mWaitWorkCV;
+ mutable audio_utils::mutex mMutex;
bool mAsyncError;
+
+ audio_utils::mutex& mutex() const { return mMutex; }
};
class DuplicatingThread : public MixerThread, public IAfDuplicatingThread {
@@ -1859,7 +1868,8 @@
pid_t tid,
status_t *status /*non-NULL*/,
audio_port_handle_t portId,
- int32_t maxSharedAudioHistoryMs) final;
+ int32_t maxSharedAudioHistoryMs) final
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
status_t start(IAfRecordTrack* recordTrack,
AudioSystem::sync_event_t event,
@@ -1976,10 +1986,10 @@
Source *mSource;
SortedVector <sp<IAfRecordTrack>> mTracks;
// mActiveTracks has dual roles: it indicates the current active track(s), and
- // is used together with mStartStopCond to indicate start()/stop() progress
+ // is used together with mStartStopCV to indicate start()/stop() progress
ActiveTracks<IAfRecordTrack> mActiveTracks;
- Condition mStartStopCond;
+ audio_utils::condition_variable mStartStopCV;
// resampler converts input at HAL Hz to output at AudioRecord client Hz
void *mRsmpInBuffer; // size = mRsmpInFramesOA
@@ -2081,7 +2091,7 @@
virtual void threadLoop_exit() final;
virtual void threadLoop_standby() final;
virtual bool shouldStandby_l() final { return false; }
- virtual status_t exitStandby_l() REQUIRES(mLock);
+ virtual status_t exitStandby_l() REQUIRES(mutex());
status_t initCheck() const final { return mHalStream == nullptr ? NO_INIT : NO_ERROR; }
size_t frameCount() const final { return mFrameCount; }
@@ -2217,8 +2227,10 @@
status_t reportData(const void* buffer, size_t frameCount) final;
- void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) final;
- void stopMelComputation_l() final;
+ void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) final
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
+ void stopMelComputation_l() final
+ REQUIRES(audio_utils::AudioFlinger_Mutex);
protected:
void dumpInternals_l(int fd, const Vector<String16>& args) final;
@@ -2245,7 +2257,7 @@
AudioStreamIn* clearInput() final;
- status_t exitStandby_l() REQUIRES(mLock) final;
+ status_t exitStandby_l() REQUIRES(mutex()) final;
MetadataUpdate updateMetadata_l() final;
void processVolume_l() final;
diff --git a/services/audioflinger/TrackBase.h b/services/audioflinger/TrackBase.h
index 4e37953..5708c61 100644
--- a/services/audioflinger/TrackBase.h
+++ b/services/audioflinger/TrackBase.h
@@ -236,6 +236,22 @@
/** Set that a metadata has changed and needs to be notified to backend. Thread safe. */
void setMetadataHasChanged() final { mChangeNotified.clear(); }
+ /**
+ * Called when a track moves to active state to record its contribution to battery usage.
+ * Track state transitions should eventually be handled within the track class.
+ */
+ void beginBatteryAttribution() final {
+ mBatteryStatsHolder.emplace(uid());
+ }
+
+ /**
+ * Called when a track moves out of the active state to record its contribution
+ * to battery usage.
+ */
+ void endBatteryAttribution() final {
+ mBatteryStatsHolder.reset();
+ }
+
protected:
DISALLOW_COPY_AND_ASSIGN(TrackBase);
@@ -379,6 +395,8 @@
// If the last track change was notified to the client with readAndClearHasChanged
std::atomic_flag mChangeNotified = ATOMIC_FLAG_INIT;
+ // RAII object for battery stats book-keeping
+ std::optional<mediautils::BatteryStatsAudioHandle> mBatteryStatsHolder;
};
class PatchTrackBase : public PatchProxyBufferProvider, public virtual IAfPatchTrackBase
diff --git a/services/audioflinger/Tracks.cpp b/services/audioflinger/Tracks.cpp
index 3c93083..47f95ac 100644
--- a/services/audioflinger/Tracks.cpp
+++ b/services/audioflinger/Tracks.cpp
@@ -642,7 +642,7 @@
auto thread = mThread.promote();
if (thread != nullptr && thread->type() == IAfThreadBase::OFFLOAD) {
// Wake up Thread if offloaded, otherwise it may be several seconds for update.
- Mutex::Autolock _l(thread->mutex());
+ audio_utils::lock_guard _l(thread->mutex());
thread->broadcast_l();
}
}
@@ -889,15 +889,15 @@
bool wasActive = false;
const sp<IAfThreadBase> thread = mThread.promote();
if (thread != 0) {
- Mutex::Autolock _l(thread->mutex());
+ audio_utils::lock_guard _l(thread->mutex());
auto* const playbackThread = thread->asIAfPlaybackThread().get();
wasActive = playbackThread->destroyTrack_l(this);
+ forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->destroy(); });
}
if (isExternalTrack() && !wasActive) {
AudioSystem::releaseOutput(mPortId);
}
}
- forEachTeePatchTrack([](auto patchTrack) { patchTrack->destroy(); });
}
void Track::appendDumpHeader(String8& result) const
@@ -1170,7 +1170,7 @@
if (thread != 0) {
if (isOffloaded()) {
audio_utils::lock_guard _laf(thread->afThreadCallback()->mutex());
- Mutex::Autolock _lth(thread->mutex());
+ audio_utils::lock_guard _lth(thread->mutex());
sp<IAfEffectChain> ec = thread->getEffectChain_l(mSessionId);
if (thread->afThreadCallback()->isNonOffloadableGlobalEffectEnabled_l() ||
(ec != 0 && ec->isNonOffloadableEnabled())) {
@@ -1178,7 +1178,7 @@
return PERMISSION_DENIED;
}
}
- Mutex::Autolock _lth(thread->mutex());
+ audio_utils::lock_guard _lth(thread->mutex());
track_state state = mState;
// here the track could be either new, or restarted
// in both cases "unstop" the track
@@ -1270,12 +1270,13 @@
buffer.mFrameCount = 1;
(void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
}
+ if (status == NO_ERROR) {
+ forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->start(); });
+ }
} else {
status = BAD_VALUE;
}
if (status == NO_ERROR) {
- forEachTeePatchTrack([](auto patchTrack) { patchTrack->start(); });
-
// send format to AudioManager for playback activity monitoring
const sp<IAudioManager> audioManager =
thread->afThreadCallback()->getOrCreateAudioManager();
@@ -1302,7 +1303,7 @@
ALOGV("%s(%d): calling pid %d", __func__, mId, IPCThreadState::self()->getCallingPid());
const sp<IAfThreadBase> thread = mThread.promote();
if (thread != 0) {
- Mutex::Autolock _l(thread->mutex());
+ audio_utils::lock_guard _l(thread->mutex());
track_state state = mState;
if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
// If the track is not active (PAUSED and buffers full), flush buffers
@@ -1326,8 +1327,8 @@
ALOGV("%s(%d): not stopping/stopped => stopping/stopped on thread %d",
__func__, mId, (int)mThreadIoHandle);
}
+ forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->stop(); });
}
- forEachTeePatchTrack([](auto patchTrack) { patchTrack->stop(); });
}
void Track::pause()
@@ -1335,7 +1336,7 @@
ALOGV("%s(%d): calling pid %d", __func__, mId, IPCThreadState::self()->getCallingPid());
const sp<IAfThreadBase> thread = mThread.promote();
if (thread != 0) {
- Mutex::Autolock _l(thread->mutex());
+ audio_utils::lock_guard _l(thread->mutex());
auto* const playbackThread = thread->asIAfPlaybackThread().get();
switch (mState) {
case STOPPING_1:
@@ -1362,9 +1363,9 @@
default:
break;
}
+ // Pausing the TeePatch to avoid a glitch on underrun, at the cost of buffered audio loss.
+ forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->pause(); });
}
- // Pausing the TeePatch to avoid a glitch on underrun, at the cost of buffered audio loss.
- forEachTeePatchTrack([](auto patchTrack) { patchTrack->pause(); });
}
void Track::flush()
@@ -1372,7 +1373,7 @@
ALOGV("%s(%d)", __func__, mId);
const sp<IAfThreadBase> thread = mThread.promote();
if (thread != 0) {
- Mutex::Autolock _l(thread->mutex());
+ audio_utils::lock_guard _l(thread->mutex());
auto* const playbackThread = thread->asIAfPlaybackThread().get();
// Flush the ring buffer now if the track is not active in the PlaybackThread.
@@ -1425,9 +1426,10 @@
// before mixer thread can run. This is important when offloading
// because the hardware buffer could hold a large amount of audio
playbackThread->broadcast_l();
+ // Flush the Tee to avoid on resume playing old data and glitching on the transition to
+ // new data
+ forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->flush(); });
}
- // Flush the Tee to avoid on resume playing old data and glitching on the transition to new data
- forEachTeePatchTrack([](auto patchTrack) { patchTrack->flush(); });
}
// must be called with thread lock held
@@ -1503,7 +1505,7 @@
// Signal thread to fetch new volume.
const sp<IAfThreadBase> thread = mThread.promote();
if (thread != 0) {
- Mutex::Autolock _l(thread->mutex());
+ audio_utils::lock_guard _l(thread->mutex());
thread->broadcast_l();
}
}
@@ -1606,19 +1608,19 @@
*backInserter++ = metadata;
}
-void Track::updateTeePatches() {
+void Track::updateTeePatches_l() {
if (mTeePatchesToUpdate.has_value()) {
- forEachTeePatchTrack([](auto patchTrack) { patchTrack->destroy(); });
+ forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->destroy(); });
mTeePatches = mTeePatchesToUpdate.value();
if (mState == TrackBase::ACTIVE || mState == TrackBase::RESUMING ||
mState == TrackBase::STOPPING_1) {
- forEachTeePatchTrack([](auto patchTrack) { patchTrack->start(); });
+ forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->start(); });
}
mTeePatchesToUpdate.reset();
}
}
-void Track::setTeePatchesToUpdate(TeePatches teePatchesToUpdate) {
+void Track::setTeePatchesToUpdate_l(TeePatches teePatchesToUpdate) {
ALOGW_IF(mTeePatchesToUpdate.has_value(),
"%s, existing tee patches to update will be ignored", __func__);
mTeePatchesToUpdate = std::move(teePatchesToUpdate);
@@ -1667,7 +1669,7 @@
return INVALID_OPERATION;
}
- Mutex::Autolock _l(thread->mutex());
+ audio_utils::lock_guard _l(thread->mutex());
auto* const playbackThread = thread->asIAfPlaybackThread().get();
return playbackThread->getTimestamp_l(timestamp);
}
@@ -1870,7 +1872,7 @@
const sp<IAfThreadBase> thread = mThread.promote();
if (thread != 0) {
auto* const t = thread->asIAfPlaybackThread().get();
- Mutex::Autolock _l(t->mutex());
+ audio_utils::lock_guard _l(t->mutex());
t->broadcast_l();
}
}
@@ -1882,7 +1884,7 @@
const sp<IAfThreadBase> thread = mThread.promote();
if (thread != nullptr) {
auto* const t = thread->asIAfPlaybackThread().get();
- Mutex::Autolock _l(t->mutex());
+ audio_utils::lock_guard _l(t->mutex());
status = t->getOutput_l()->stream->getDualMonoMode(mode);
ALOGD_IF((status == NO_ERROR) && (mDualMonoMode != *mode),
"%s: mode %d inconsistent", __func__, mDualMonoMode);
@@ -1898,7 +1900,7 @@
const sp<IAfThreadBase> thread = mThread.promote();
if (thread != nullptr) {
auto* const t = thread->asIAfPlaybackThread().get();
- Mutex::Autolock lock(t->mutex());
+ audio_utils::lock_guard lock(t->mutex());
status = t->getOutput_l()->stream->setDualMonoMode(mode);
if (status == NO_ERROR) {
mDualMonoMode = mode;
@@ -1915,7 +1917,7 @@
sp<IAfThreadBase> thread = mThread.promote();
if (thread != nullptr) {
auto* const t = thread->asIAfPlaybackThread().get();
- Mutex::Autolock lock(t->mutex());
+ audio_utils::lock_guard lock(t->mutex());
status = t->getOutput_l()->stream->getAudioDescriptionMixLevel(leveldB);
ALOGD_IF((status == NO_ERROR) && (mAudioDescriptionMixLevel != *leveldB),
"%s: level %.3f inconsistent", __func__, mAudioDescriptionMixLevel);
@@ -1931,7 +1933,7 @@
const sp<IAfThreadBase> thread = mThread.promote();
if (thread != nullptr) {
auto* const t = thread->asIAfPlaybackThread().get();
- Mutex::Autolock lock(t->mutex());
+ audio_utils::lock_guard lock(t->mutex());
status = t->getOutput_l()->stream->setAudioDescriptionMixLevel(leveldB);
if (status == NO_ERROR) {
mAudioDescriptionMixLevel = leveldB;
@@ -1949,7 +1951,7 @@
const sp<IAfThreadBase> thread = mThread.promote();
if (thread != nullptr) {
auto* const t = thread->asIAfPlaybackThread().get();
- Mutex::Autolock lock(t->mutex());
+ audio_utils::lock_guard lock(t->mutex());
status = t->getOutput_l()->stream->getPlaybackRateParameters(playbackRate);
ALOGD_IF((status == NO_ERROR) &&
!isAudioPlaybackRateEqual(mPlaybackRateParameters, *playbackRate),
@@ -1967,7 +1969,7 @@
const sp<IAfThreadBase> thread = mThread.promote();
if (thread != nullptr) {
auto* const t = thread->asIAfPlaybackThread().get();
- Mutex::Autolock lock(t->mutex());
+ audio_utils::lock_guard lock(t->mutex());
status = t->getOutput_l()->stream->setPlaybackRateParameters(playbackRate);
if (status == NO_ERROR) {
mPlaybackRateParameters = playbackRate;
@@ -2090,7 +2092,7 @@
const sp<IAfThreadBase> thread = mTrack->mThread.promote();
if (thread != 0) {
// Lock for updating mHapticPlaybackEnabled.
- Mutex::Autolock _l(thread->mutex());
+ audio_utils::lock_guard _l(thread->mutex());
auto* const playbackThread = thread->asIAfPlaybackThread().get();
if ((mTrack->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
&& playbackThread->hapticChannelCount() > 0) {
@@ -2353,13 +2355,13 @@
void OutputTrack::copyMetadataTo(MetadataInserter& backInserter) const
{
- std::lock_guard<std::mutex> lock(mTrackMetadatasMutex);
+ audio_utils::lock_guard lock(trackMetadataMutex());
backInserter = std::copy(mTrackMetadatas.begin(), mTrackMetadatas.end(), backInserter);
}
void OutputTrack::setMetadatas(const SourceMetadatas& metadatas) {
{
- std::lock_guard<std::mutex> lock(mTrackMetadatasMutex);
+ audio_utils::lock_guard lock(trackMetadataMutex());
mTrackMetadatas = metadatas;
}
// No need to adjust metadata track volumes as OutputTrack volumes are always 0dBFS.
@@ -2846,7 +2848,7 @@
track_state priorState = mState;
const sp<IAfThreadBase> thread = mThread.promote();
if (thread != 0) {
- Mutex::Autolock _l(thread->mutex());
+ audio_utils::lock_guard _l(thread->mutex());
auto* const recordThread = thread->asIAfRecordThread().get();
priorState = mState;
if (!mSharedAudioPackageName.empty()) {
@@ -3270,7 +3272,7 @@
*thread = mThread.promote();
if (!*thread) return nullptr;
auto* const recordThread = (*thread)->asIAfRecordThread().get();
- Mutex::Autolock _l(recordThread->mutex());
+ audio_utils::lock_guard _l(recordThread->mutex());
return recordThread->getInput() ? recordThread->getInput()->stream : nullptr;
}
@@ -3307,7 +3309,7 @@
}
{
- std::lock_guard<std::mutex> lock(mReadLock);
+ audio_utils::lock_guard lock(readMutex());
mReadBytes += bytesRead;
mReadError = NO_ERROR;
}
@@ -3334,7 +3336,7 @@
stream_error:
stream->standby();
{
- std::lock_guard<std::mutex> lock(mReadLock);
+ audio_utils::lock_guard lock(readMutex());
mReadError = result;
}
mReadCV.notify_one();
@@ -3363,7 +3365,7 @@
{
bytes = std::min(bytes, mFrameCount * mFrameSize);
{
- std::unique_lock<std::mutex> lock(mReadLock);
+ audio_utils::unique_lock lock(readMutex());
mReadCV.wait(lock, [&]{ return mReadError != NO_ERROR || mReadBytes != 0; });
if (mReadError != NO_ERROR) {
mLastReadFrames = 0;
diff --git a/services/audioflinger/sounddose/SoundDoseManager.cpp b/services/audioflinger/sounddose/SoundDoseManager.cpp
index 21f346e..39c80d8 100644
--- a/services/audioflinger/sounddose/SoundDoseManager.cpp
+++ b/services/audioflinger/sounddose/SoundDoseManager.cpp
@@ -49,7 +49,7 @@
size_t channelCount, audio_format_t format) {
const std::lock_guard _l(mLock);
- if (mHalSoundDose != nullptr && mEnabledCsd) {
+ if (mHalSoundDose.size() > 0 && mEnabledCsd) {
ALOGD("%s: using HAL MEL computation, no MelProcessor needed.", __func__);
return nullptr;
}
@@ -82,20 +82,27 @@
return melProcessor;
}
-bool SoundDoseManager::setHalSoundDoseInterface(const std::shared_ptr<ISoundDose>& halSoundDose) {
+bool SoundDoseManager::setHalSoundDoseInterface(const std::string &module,
+ const std::shared_ptr<ISoundDose> &halSoundDose) {
ALOGV("%s", __func__);
+ if (halSoundDose == nullptr) {
+ ALOGI("%s: passed ISoundDose object is null", __func__);
+ return false;
+ }
+
std::shared_ptr<HalSoundDoseCallback> halSoundDoseCallback;
{
const std::lock_guard _l(mLock);
- mHalSoundDose = halSoundDose;
- if (halSoundDose == nullptr) {
- ALOGI("%s: passed ISoundDose object is null, switching to internal CSD", __func__);
+ if (mHalSoundDose.find(module) != mHalSoundDose.end()) {
+ ALOGW("%s: Module %s already has a sound dose HAL assigned, skipping", __func__,
+ module.c_str());
return false;
}
+ mHalSoundDose[module] = halSoundDose;
- if (!mHalSoundDose->setOutputRs2UpperBound(mRs2UpperBound).isOk()) {
+ if (!halSoundDose->setOutputRs2UpperBound(mRs2UpperBound).isOk()) {
ALOGW("%s: Cannot set RS2 value for momentary exposure %f",
__func__,
mRs2UpperBound);
@@ -121,16 +128,26 @@
return true;
}
+void SoundDoseManager::resetHalSoundDoseInterfaces() {
+ ALOGV("%s", __func__);
+
+ const std::lock_guard _l(mLock);
+ mHalSoundDose.clear();
+}
+
void SoundDoseManager::setOutputRs2UpperBound(float rs2Value) {
ALOGV("%s", __func__);
const std::lock_guard _l(mLock);
- if (mHalSoundDose != nullptr) {
- // using the HAL sound dose interface
- if (!mHalSoundDose->setOutputRs2UpperBound(rs2Value).isOk()) {
- ALOGE("%s: Cannot set RS2 value for momentary exposure %f", __func__, rs2Value);
- return;
+ if (mHalSoundDose.size() > 0) {
+ for (auto& halSoundDose : mHalSoundDose) {
+ // using the HAL sound dose interface
+ if (!halSoundDose.second->setOutputRs2UpperBound(rs2Value).isOk()) {
+ ALOGE("%s: Cannot set RS2 value for momentary exposure %f", __func__, rs2Value);
+ continue;
+ }
}
+
mRs2UpperBound = rs2Value;
return;
}
@@ -202,14 +219,16 @@
ndk::ScopedAStatus SoundDoseManager::HalSoundDoseCallback::onMomentaryExposureWarning(
float in_currentDbA, const AudioDevice& in_audioDevice) {
- auto soundDoseManager = mSoundDoseManager.promote();
- if (soundDoseManager == nullptr) {
- return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ sp<SoundDoseManager> soundDoseManager;
+ {
+ const std::lock_guard _l(mCbLock);
+ soundDoseManager = mSoundDoseManager.promote();
+ if (soundDoseManager == nullptr) {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
}
- std::shared_ptr<ISoundDose> halSoundDose;
- soundDoseManager->getHalSoundDose(&halSoundDose);
- if(halSoundDose == nullptr) {
+ if (!soundDoseManager->useHalSoundDose()) {
ALOGW("%s: HAL sound dose interface deactivated. Ignoring", __func__);
return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
}
@@ -229,14 +248,16 @@
ndk::ScopedAStatus SoundDoseManager::HalSoundDoseCallback::onNewMelValues(
const ISoundDose::IHalSoundDoseCallback::MelRecord& in_melRecord,
const AudioDevice& in_audioDevice) {
- auto soundDoseManager = mSoundDoseManager.promote();
- if (soundDoseManager == nullptr) {
- return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ sp<SoundDoseManager> soundDoseManager;
+ {
+ const std::lock_guard _l(mCbLock);
+ soundDoseManager = mSoundDoseManager.promote();
+ if (soundDoseManager == nullptr) {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
}
- std::shared_ptr<ISoundDose> halSoundDose;
- soundDoseManager->getHalSoundDose(&halSoundDose);
- if(halSoundDose == nullptr) {
+ if (!soundDoseManager->useHalSoundDose()) {
ALOGW("%s: HAL sound dose interface deactivated. Ignoring", __func__);
return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
}
@@ -301,6 +322,25 @@
return binder::Status::ok();
}
+binder::Status SoundDoseManager::SoundDose::initCachedAudioDeviceCategories(
+ const std::vector<media::ISoundDose::AudioDeviceCategory>& btDeviceCategories) {
+ ALOGV("%s", __func__);
+ auto soundDoseManager = mSoundDoseManager.promote();
+ if (soundDoseManager != nullptr) {
+ soundDoseManager->initCachedAudioDeviceCategories(btDeviceCategories);
+ }
+ return binder::Status::ok();
+}
+binder::Status SoundDoseManager::SoundDose::setAudioDeviceCategory(
+ const media::ISoundDose::AudioDeviceCategory& btAudioDevice) {
+ ALOGV("%s", __func__);
+ auto soundDoseManager = mSoundDoseManager.promote();
+ if (soundDoseManager != nullptr) {
+ soundDoseManager->setAudioDeviceCategory(btAudioDevice);
+ }
+ return binder::Status::ok();
+}
+
binder::Status SoundDoseManager::SoundDose::getOutputRs2UpperBound(float* value) {
ALOGV("%s", __func__);
auto soundDoseManager = mSoundDoseManager.promote();
@@ -358,7 +398,9 @@
auto melProcessor = mp.second.promote();
if (melProcessor != nullptr) {
auto deviceId = melProcessor->getDeviceId();
- if (mActiveDeviceTypes[deviceId] == deviceType) {
+ const auto deviceTypeIt = mActiveDeviceTypes.find(deviceId);
+ if (deviceTypeIt != mActiveDeviceTypes.end() &&
+ deviceTypeIt->second == deviceType) {
ALOGV("%s: set attenuation for deviceId %d to %f",
__func__, deviceId, attenuationDB);
melProcessor->setAttenuation(attenuationDB);
@@ -390,9 +432,105 @@
return mEnabledCsd;
}
+void SoundDoseManager::initCachedAudioDeviceCategories(
+ const std::vector<media::ISoundDose::AudioDeviceCategory>& deviceCategories) {
+ ALOGV("%s", __func__);
+ {
+ const std::lock_guard _l(mLock);
+ mBluetoothDevicesWithCsd.clear();
+ }
+ for (const auto& btDeviceCategory : deviceCategories) {
+ setAudioDeviceCategory(btDeviceCategory);
+ }
+}
+
+void SoundDoseManager::setAudioDeviceCategory(
+ const media::ISoundDose::AudioDeviceCategory& audioDevice) {
+ ALOGV("%s: set BT audio device type with address %s to headphone %d", __func__,
+ audioDevice.address.c_str(), audioDevice.csdCompatible);
+
+ std::vector<audio_port_handle_t> devicesToStart;
+ std::vector<audio_port_handle_t> devicesToStop;
+ {
+ const std::lock_guard _l(mLock);
+ const auto deviceIt = mBluetoothDevicesWithCsd.find(
+ std::make_pair(audioDevice.address,
+ static_cast<audio_devices_t>(audioDevice.internalAudioType)));
+ if (deviceIt != mBluetoothDevicesWithCsd.end()) {
+ deviceIt->second = audioDevice.csdCompatible;
+ } else {
+ mBluetoothDevicesWithCsd.emplace(
+ std::make_pair(audioDevice.address,
+ static_cast<audio_devices_t>(audioDevice.internalAudioType)),
+ audioDevice.csdCompatible);
+ }
+
+ for (const auto &activeDevice: mActiveDevices) {
+ if (activeDevice.first.address() == audioDevice.address &&
+ activeDevice.first.mType ==
+ static_cast<audio_devices_t>(audioDevice.internalAudioType)) {
+ if (audioDevice.csdCompatible) {
+ devicesToStart.push_back(activeDevice.second);
+ } else {
+ devicesToStop.push_back(activeDevice.second);
+ }
+ }
+ }
+ }
+
+ for (const auto& deviceToStart : devicesToStart) {
+ mMelReporterCallback->startMelComputationForDeviceId(deviceToStart);
+ }
+ for (const auto& deviceToStop : devicesToStop) {
+ mMelReporterCallback->stopMelComputationForDeviceId(deviceToStop);
+ }
+}
+
+bool SoundDoseManager::shouldComputeCsdForDeviceType(audio_devices_t device) {
+ if (!isCsdEnabled()) {
+ ALOGV("%s csd is disabled", __func__);
+ return false;
+ }
+ if (forceComputeCsdOnAllDevices()) {
+ return true;
+ }
+
+ switch (device) {
+ case AUDIO_DEVICE_OUT_WIRED_HEADSET:
+ case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
+ case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
+ case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
+ case AUDIO_DEVICE_OUT_USB_HEADSET:
+ case AUDIO_DEVICE_OUT_BLE_HEADSET:
+ case AUDIO_DEVICE_OUT_BLE_BROADCAST:
+ return true;
+ default:
+ return false;
+ }
+}
+
+bool SoundDoseManager::shouldComputeCsdForDeviceWithAddress(const audio_devices_t type,
+ const std::string& deviceAddress) {
+ if (!isCsdEnabled()) {
+ ALOGV("%s csd is disabled", __func__);
+ return false;
+ }
+ if (forceComputeCsdOnAllDevices()) {
+ return true;
+ }
+
+ if (!audio_is_ble_out_device(type) && !audio_is_a2dp_device(type)) {
+ return shouldComputeCsdForDeviceType(type);
+ }
+
+ const std::lock_guard _l(mLock);
+ const auto deviceIt = mBluetoothDevicesWithCsd.find(std::make_pair(deviceAddress, type));
+ return deviceIt != mBluetoothDevicesWithCsd.end() && deviceIt->second;
+}
+
void SoundDoseManager::setUseFrameworkMel(bool useFrameworkMel) {
// invalidate any HAL sound dose interface used
- setHalSoundDoseInterface(nullptr);
+ resetHalSoundDoseInterfaces();
const std::lock_guard _l(mLock);
mUseFrameworkMel = useFrameworkMel;
@@ -419,14 +557,12 @@
if (!mEnabledCsd) return false;
}
- std::shared_ptr<ISoundDose> halSoundDose;
- getHalSoundDose(&halSoundDose);
- return halSoundDose != nullptr;
+ return useHalSoundDose();
}
-void SoundDoseManager::getHalSoundDose(std::shared_ptr<ISoundDose>* halSoundDose) const {
+bool SoundDoseManager::useHalSoundDose() const {
const std::lock_guard _l(mLock);
- *halSoundDose = mHalSoundDose;
+ return mHalSoundDose.size() > 0;
}
void SoundDoseManager::resetSoundDose() {
diff --git a/services/audioflinger/sounddose/SoundDoseManager.h b/services/audioflinger/sounddose/SoundDoseManager.h
index 9ed0661..6e0bc34 100644
--- a/services/audioflinger/sounddose/SoundDoseManager.h
+++ b/services/audioflinger/sounddose/SoundDoseManager.h
@@ -32,6 +32,15 @@
using aidl::android::hardware::audio::core::sounddose::ISoundDose;
+class IMelReporterCallback : public virtual RefBase {
+public:
+ IMelReporterCallback() {};
+ virtual ~IMelReporterCallback() {};
+
+ virtual void stopMelComputationForDeviceId(audio_port_handle_t deviceId) = 0;
+ virtual void startMelComputationForDeviceId(audio_port_handle_t deviceId) = 0;
+};
+
class SoundDoseManager : public audio_utils::MelProcessor::MelCallback {
public:
/** CSD is computed with a rolling window of 7 days. */
@@ -39,8 +48,9 @@
/** Default RS2 upper bound in dBA as defined in IEC 62368-1 3rd edition. */
static constexpr float kDefaultRs2UpperBound = 100.f;
- SoundDoseManager()
- : mMelAggregator(sp<audio_utils::MelAggregator>::make(kCsdWindowSeconds)),
+ explicit SoundDoseManager(const sp<IMelReporterCallback>& melReporterCallback)
+ : mMelReporterCallback(melReporterCallback),
+ mMelAggregator(sp<audio_utils::MelAggregator>::make(kCsdWindowSeconds)),
mRs2UpperBound(kDefaultRs2UpperBound) {};
/**
@@ -84,12 +94,15 @@
sp<media::ISoundDose> getSoundDoseInterface(const sp<media::ISoundDoseCallback>& callback);
/**
- * Sets the HAL sound dose interface to use for the MEL computation. Use nullptr
- * for using the internal MEL computation.
+ * Sets the HAL sound dose interface for a specific module to use for the MEL computation.
*
* @return true if setting the HAL sound dose value was successful, false otherwise.
*/
- bool setHalSoundDoseInterface(const std::shared_ptr<ISoundDose>& halSoundDose);
+ bool setHalSoundDoseInterface(const std::string &module,
+ const std::shared_ptr<ISoundDose> &halSoundDose);
+
+ /** Reset all the stored HAL sound dose interface. */
+ void resetHalSoundDoseInterfaces();
/** Returns the cached audio port id from the active devices. */
audio_port_handle_t getIdForAudioDevice(
@@ -104,6 +117,21 @@
/** Returns true if CSD is enabled. */
bool isCsdEnabled();
+ void initCachedAudioDeviceCategories(
+ const std::vector<media::ISoundDose::AudioDeviceCategory>& deviceCategories);
+
+ void setAudioDeviceCategory(
+ const media::ISoundDose::AudioDeviceCategory& audioDevice);
+
+ /**
+ * Returns true if the type can compute CSD. For bluetooth devices we rely on whether we
+ * categorized the address as headphones/headsets, only in this case we return true.
+ */
+ bool shouldComputeCsdForDeviceWithAddress(const audio_devices_t type,
+ const std::string& deviceAddress);
+ /** Returns true for all device types which could support CSD computation. */
+ bool shouldComputeCsdForDeviceType(audio_devices_t device);
+
std::string dump() const;
// used for testing only
@@ -139,6 +167,13 @@
binder::Status getOutputRs2UpperBound(float* value) override;
binder::Status setCsdEnabled(bool enabled) override;
+ binder::Status initCachedAudioDeviceCategories(
+ const std::vector<media::ISoundDose::AudioDeviceCategory> &btDeviceCategories)
+ override;
+
+ binder::Status setAudioDeviceCategory(
+ const media::ISoundDose::AudioDeviceCategory& btAudioDevice) override;
+
binder::Status getCsd(float* value) override;
binder::Status forceUseFrameworkMel(bool useFrameworkMel) override;
binder::Status forceComputeCsdOnAllDevices(bool computeCsdOnAllDevices) override;
@@ -161,6 +196,7 @@
const aidl::android::media::audio::common::AudioDevice& in_audioDevice) override;
wp<SoundDoseManager> mSoundDoseManager;
+ std::mutex mCbLock;
};
void resetSoundDose();
@@ -174,11 +210,16 @@
void setUseFrameworkMel(bool useFrameworkMel);
void setComputeCsdOnAllDevices(bool computeCsdOnAllDevices);
bool isSoundDoseHalSupported() const;
- /** Returns the HAL sound dose interface or null if internal MEL computation is used. */
- void getHalSoundDose(std::shared_ptr<ISoundDose>* halSoundDose) const;
+ /**
+ * Returns true if there is one active HAL sound dose interface or null if internal MEL
+ * computation is used.
+ **/
+ bool useHalSoundDose() const;
mutable std::mutex mLock;
+ const sp<IMelReporterCallback> mMelReporterCallback;
+
// no need for lock since MelAggregator is thread-safe
const sp<audio_utils::MelAggregator> mMelAggregator;
@@ -191,15 +232,26 @@
std::map<AudioDeviceTypeAddr, audio_port_handle_t> mActiveDevices GUARDED_BY(mLock);
std::unordered_map<audio_port_handle_t, audio_devices_t> mActiveDeviceTypes GUARDED_BY(mLock);
+ struct bt_device_type_hash {
+ std::size_t operator() (const std::pair<std::string, audio_devices_t> &deviceType) const {
+ return std::hash<std::string>()(deviceType.first) ^
+ std::hash<audio_devices_t>()(deviceType.second);
+ }
+ };
+ // storing the BT cached information as received from the java side
+ // see SoundDoseManager::setCachedAudioDeviceCategories
+ std::unordered_map<std::pair<std::string, audio_devices_t>, bool, bt_device_type_hash>
+ mBluetoothDevicesWithCsd GUARDED_BY(mLock);
+
float mRs2UpperBound GUARDED_BY(mLock);
std::unordered_map<audio_devices_t, float> mMelAttenuationDB GUARDED_BY(mLock);
sp<SoundDose> mSoundDose GUARDED_BY(mLock);
- std::shared_ptr<ISoundDose> mHalSoundDose GUARDED_BY(mLock);
+ std::unordered_map<std::string, std::shared_ptr<ISoundDose>> mHalSoundDose GUARDED_BY(mLock);
std::shared_ptr<HalSoundDoseCallback> mHalSoundDoseCallback GUARDED_BY(mLock);
- bool mUseFrameworkMel GUARDED_BY(mLock) = true;
+ bool mUseFrameworkMel GUARDED_BY(mLock) = false;
bool mComputeCsdOnAllDevices GUARDED_BY(mLock) = false;
bool mEnabledCsd GUARDED_BY(mLock) = true;
diff --git a/services/audioflinger/sounddose/tests/sounddosemanager_tests.cpp b/services/audioflinger/sounddose/tests/sounddosemanager_tests.cpp
index 9fab77d..5f6dcb9 100644
--- a/services/audioflinger/sounddose/tests/sounddosemanager_tests.cpp
+++ b/services/audioflinger/sounddose/tests/sounddosemanager_tests.cpp
@@ -39,21 +39,39 @@
(const std::shared_ptr<ISoundDose::IHalSoundDoseCallback>&), (override));
};
+class MelReporterCallback : public IMelReporterCallback {
+public:
+ MOCK_METHOD(void, startMelComputationForDeviceId, (audio_port_handle_t), (override));
+ MOCK_METHOD(void, stopMelComputationForDeviceId, (audio_port_handle_t), (override));
+};
+
+constexpr char kPrimaryModule[] = "primary";
+constexpr char kSecondaryModule[] = "secondary";
+
class SoundDoseManagerTest : public ::testing::Test {
protected:
void SetUp() override {
- mSoundDoseManager = sp<SoundDoseManager>::make();
+ mMelReporterCallback = sp<MelReporterCallback>::make();
+ mSoundDoseManager = sp<SoundDoseManager>::make(mMelReporterCallback);
mHalSoundDose = ndk::SharedRefBase::make<HalSoundDoseMock>();
+ mSecondaryHalSoundDose = ndk::SharedRefBase::make<HalSoundDoseMock>();
ON_CALL(*mHalSoundDose.get(), setOutputRs2UpperBound)
.WillByDefault([] (float rs2) {
EXPECT_EQ(rs2, ISoundDose::DEFAULT_MAX_RS2);
return ndk::ScopedAStatus::ok();
});
+ ON_CALL(*mSecondaryHalSoundDose.get(), setOutputRs2UpperBound)
+ .WillByDefault([] (float rs2) {
+ EXPECT_EQ(rs2, ISoundDose::DEFAULT_MAX_RS2);
+ return ndk::ScopedAStatus::ok();
+ });
}
+ sp<MelReporterCallback> mMelReporterCallback;
sp<SoundDoseManager> mSoundDoseManager;
std::shared_ptr<HalSoundDoseMock> mHalSoundDose;
+ std::shared_ptr<HalSoundDoseMock> mSecondaryHalSoundDose;
};
TEST_F(SoundDoseManagerTest, GetProcessorForExistingStream) {
@@ -101,7 +119,7 @@
}
TEST_F(SoundDoseManagerTest, InvalidHalInterfaceIsNotSet) {
- EXPECT_FALSE(mSoundDoseManager->setHalSoundDoseInterface(nullptr));
+ EXPECT_FALSE(mSoundDoseManager->setHalSoundDoseInterface(kPrimaryModule, nullptr));
}
TEST_F(SoundDoseManagerTest, SetHalSoundDoseDisablesNewMelProcessorCallbacks) {
@@ -113,7 +131,7 @@
return ndk::ScopedAStatus::ok();
});
- EXPECT_TRUE(mSoundDoseManager->setHalSoundDoseInterface(mHalSoundDose));
+ EXPECT_TRUE(mSoundDoseManager->setHalSoundDoseInterface(kPrimaryModule, mHalSoundDose));
EXPECT_EQ(nullptr, mSoundDoseManager->getOrCreateProcessorForDevice(/*deviceId=*/2,
/*streamHandle=*/1,
@@ -130,8 +148,17 @@
EXPECT_NE(nullptr, callback);
return ndk::ScopedAStatus::ok();
});
+ EXPECT_CALL(*mSecondaryHalSoundDose.get(), setOutputRs2UpperBound).Times(1);
+ EXPECT_CALL(*mSecondaryHalSoundDose.get(), registerSoundDoseCallback)
+ .Times(1)
+ .WillOnce([&] (const std::shared_ptr<ISoundDose::IHalSoundDoseCallback>& callback) {
+ EXPECT_NE(nullptr, callback);
+ return ndk::ScopedAStatus::ok();
+ });
- EXPECT_TRUE(mSoundDoseManager->setHalSoundDoseInterface(mHalSoundDose));
+ EXPECT_TRUE(mSoundDoseManager->setHalSoundDoseInterface(kPrimaryModule, mHalSoundDose));
+ EXPECT_TRUE(mSoundDoseManager->setHalSoundDoseInterface(kSecondaryModule,
+ mSecondaryHalSoundDose));
}
TEST_F(SoundDoseManagerTest, MomentaryExposureFromHalWithNoAddressIllegalArgument) {
@@ -145,7 +172,7 @@
return ndk::ScopedAStatus::ok();
});
- EXPECT_TRUE(mSoundDoseManager->setHalSoundDoseInterface(mHalSoundDose));
+ EXPECT_TRUE(mSoundDoseManager->setHalSoundDoseInterface(kPrimaryModule, mHalSoundDose));
EXPECT_NE(nullptr, halCallback);
AudioDevice audioDevice = {};
@@ -166,9 +193,9 @@
return ndk::ScopedAStatus::ok();
});
- EXPECT_TRUE(mSoundDoseManager->setHalSoundDoseInterface(mHalSoundDose));
+ EXPECT_TRUE(mSoundDoseManager->setHalSoundDoseInterface(kPrimaryModule, mHalSoundDose));
EXPECT_NE(nullptr, halCallback);
- EXPECT_FALSE(mSoundDoseManager->setHalSoundDoseInterface(nullptr));
+ mSoundDoseManager->resetHalSoundDoseInterfaces();
AudioDevice audioDevice = {};
audioDevice.address.set<AudioDeviceAddress::id>("test");
@@ -188,7 +215,7 @@
return ndk::ScopedAStatus::ok();
});
- EXPECT_TRUE(mSoundDoseManager->setHalSoundDoseInterface(mHalSoundDose));
+ EXPECT_TRUE(mSoundDoseManager->setHalSoundDoseInterface(kPrimaryModule, mHalSoundDose));
EXPECT_NE(nullptr, halCallback);
AudioDevice audioDevice = {};
@@ -239,9 +266,56 @@
}
TEST_F(SoundDoseManagerTest, GetDefaultForceUseFrameworkMel) {
- // TODO: for now dogfooding with internal MEL. Revert to false when using the HAL MELs
- EXPECT_TRUE(mSoundDoseManager->forceUseFrameworkMel());
+ EXPECT_FALSE(mSoundDoseManager->forceUseFrameworkMel());
}
+TEST_F(SoundDoseManagerTest, SetAudioDeviceCategoryStopsNonHeadphone) {
+ media::ISoundDose::AudioDeviceCategory device1;
+ device1.address = "dev1";
+ device1.csdCompatible = false;
+ device1.internalAudioType = AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
+ const AudioDeviceTypeAddr dev1Adt{AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, device1.address};
+
+ // this will mark the device as active
+ mSoundDoseManager->mapAddressToDeviceId(dev1Adt, /*deviceId=*/1);
+ EXPECT_CALL(*mMelReporterCallback.get(), stopMelComputationForDeviceId).Times(1);
+
+ mSoundDoseManager->setAudioDeviceCategory(device1);
+}
+
+TEST_F(SoundDoseManagerTest, SetAudioDeviceCategoryStartsHeadphone) {
+ media::ISoundDose::AudioDeviceCategory device1;
+ device1.address = "dev1";
+ device1.csdCompatible = true;
+ device1.internalAudioType = AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
+ const AudioDeviceTypeAddr dev1Adt{AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, device1.address};
+
+ // this will mark the device as active
+ mSoundDoseManager->mapAddressToDeviceId(dev1Adt, /*deviceId=*/1);
+ EXPECT_CALL(*mMelReporterCallback.get(), startMelComputationForDeviceId).Times(1);
+
+ mSoundDoseManager->setAudioDeviceCategory(device1);
+}
+
+TEST_F(SoundDoseManagerTest, InitCachedAudioDevicesStartsOnlyActiveDevices) {
+ media::ISoundDose::AudioDeviceCategory device1;
+ media::ISoundDose::AudioDeviceCategory device2;
+ device1.address = "dev1";
+ device1.csdCompatible = true;
+ device1.internalAudioType = AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
+ device2.address = "dev2";
+ device2.csdCompatible = true;
+ device2.internalAudioType = AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
+ const AudioDeviceTypeAddr dev1Adt{AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, device1.address};
+ std::vector<media::ISoundDose::AudioDeviceCategory> btDevices = {device1, device2};
+
+ // this will mark the device as active
+ mSoundDoseManager->mapAddressToDeviceId(dev1Adt, /*deviceId=*/1);
+ EXPECT_CALL(*mMelReporterCallback.get(), startMelComputationForDeviceId).Times(1);
+
+ mSoundDoseManager->initCachedAudioDeviceCategories(btDevices);
+}
+
+
} // namespace
} // namespace android
diff --git a/services/audiopolicy/common/managerdefinitions/include/AudioOutputDescriptor.h b/services/audiopolicy/common/managerdefinitions/include/AudioOutputDescriptor.h
index 876911d..1e57edd 100644
--- a/services/audiopolicy/common/managerdefinitions/include/AudioOutputDescriptor.h
+++ b/services/audiopolicy/common/managerdefinitions/include/AudioOutputDescriptor.h
@@ -102,9 +102,13 @@
void setVolume(float volumeDb) { mCurVolumeDb = volumeDb; }
float getVolume() const { return mCurVolumeDb; }
+ void setIsVoice(bool isVoice) { mIsVoice = isVoice; }
+ bool isVoice() const { return mIsVoice; }
+
private:
int mMuteCount = 0; /**< mute request counter */
float mCurVolumeDb = NAN; /**< current volume in dB. */
+ bool mIsVoice = false; /** true if this volume source is used for voice call volume */
};
/**
* Note: volume activities shall be indexed by CurvesId if we want to allow multiple
@@ -162,7 +166,8 @@
VolumeSource volumeSource, const StreamTypeVector &streams,
const DeviceTypeSet& deviceTypes,
uint32_t delayMs,
- bool force);
+ bool force,
+ bool isVoiceVolSrc = false);
/**
* @brief setStopTime set the stop time due to the client stoppage or a re routing of this
@@ -222,17 +227,25 @@
{
return mVolumeActivities[vs].decMuteCount();
}
- void setCurVolume(VolumeSource vs, float volumeDb)
+ void setCurVolume(VolumeSource vs, float volumeDb, bool isVoiceVolSrc)
{
// Even if not activity for this source registered, need to create anyway
mVolumeActivities[vs].setVolume(volumeDb);
+ mVolumeActivities[vs].setIsVoice(isVoiceVolSrc);
}
float getCurVolume(VolumeSource vs) const
{
return mVolumeActivities.find(vs) != std::end(mVolumeActivities) ?
mVolumeActivities.at(vs).getVolume() : NAN;
}
-
+ VolumeSource getVoiceSource() {
+ for (const auto &iter : mVolumeActivities) {
+ if (iter.second.isVoice()) {
+ return iter.first;
+ }
+ }
+ return VOLUME_SOURCE_NONE;
+ }
bool isStrategyActive(product_strategy_t ps, uint32_t inPastMs = 0, nsecs_t sysTime = 0) const
{
return mRoutingActivities.find(ps) != std::end(mRoutingActivities)?
@@ -381,7 +394,8 @@
VolumeSource volumeSource, const StreamTypeVector &streams,
const DeviceTypeSet& device,
uint32_t delayMs,
- bool force);
+ bool force,
+ bool isVoiceVolSrc = false);
virtual void toAudioPortConfig(struct audio_port_config *dstConfig,
const struct audio_port_config *srcConfig = NULL) const;
@@ -424,6 +438,15 @@
bool supportsAllDevices(const DeviceVector &devices) const;
/**
+ * @brief supportsAtLeastOne checks if any device in devices is currently supported
+ * @param devices to be checked against
+ * @return true if the device is weakly supported by type (e.g. for non bus / rsubmix devices),
+ * true if the device is supported (both type and address) for bus / remote submix
+ * false otherwise
+ */
+ bool supportsAtLeastOne(const DeviceVector &devices) const;
+
+ /**
* @brief supportsDevicesForPlayback
* @param devices to be checked against
* @return true if the devices is a supported combo for playback
@@ -475,7 +498,8 @@
VolumeSource volumeSource, const StreamTypeVector &streams,
const DeviceTypeSet& deviceTypes,
uint32_t delayMs,
- bool force);
+ bool force,
+ bool isVoiceVolSrc = false);
virtual void toAudioPortConfig(struct audio_port_config *dstConfig,
const struct audio_port_config *srcConfig = NULL) const;
diff --git a/services/audiopolicy/common/managerdefinitions/include/AudioPolicyMix.h b/services/audiopolicy/common/managerdefinitions/include/AudioPolicyMix.h
index 92292e1..7e29e10 100644
--- a/services/audiopolicy/common/managerdefinitions/include/AudioPolicyMix.h
+++ b/services/audiopolicy/common/managerdefinitions/include/AudioPolicyMix.h
@@ -138,7 +138,7 @@
*/
status_t setUserIdDeviceAffinities(int userId, const AudioDeviceTypeAddrVector& devices);
status_t removeUserIdDeviceAffinities(int userId);
- status_t getDevicesForUserId(int userId, Vector<AudioDeviceTypeAddr>& devices) const;
+ status_t getDevicesForUserId(int userId, AudioDeviceTypeAddrVector& devices) const;
void dump(String8 *dst) const;
diff --git a/services/audiopolicy/common/managerdefinitions/include/IOProfile.h b/services/audiopolicy/common/managerdefinitions/include/IOProfile.h
index c489eed..a2cacd2 100644
--- a/services/audiopolicy/common/managerdefinitions/include/IOProfile.h
+++ b/services/audiopolicy/common/managerdefinitions/include/IOProfile.h
@@ -63,13 +63,7 @@
if (getRole() == AUDIO_PORT_ROLE_SINK && (flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
maxActiveCount = 0;
}
- if (getRole() == AUDIO_PORT_ROLE_SOURCE) {
- mMixerBehaviors.clear();
- mMixerBehaviors.insert(AUDIO_MIXER_BEHAVIOR_DEFAULT);
- if (mFlags.output & AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
- mMixerBehaviors.insert(AUDIO_MIXER_BEHAVIOR_BIT_PERFECT);
- }
- }
+ refreshMixerBehaviors();
}
const MixerBehaviorSet& getMixerBehaviors() const {
@@ -222,6 +216,8 @@
void toSupportedMixerAttributes(std::vector<audio_mixer_attributes_t>* mixerAttributes) const;
+ status_t readFromParcelable(const media::AudioPortFw& parcelable);
+
// Number of streams currently opened for this profile.
uint32_t curOpenCount;
// Number of streams currently active for this profile. This is not the number of active clients
@@ -229,6 +225,8 @@
uint32_t curActiveCount;
private:
+ void refreshMixerBehaviors();
+
DeviceVector mSupportedDevices; // supported devices: this input/output can be routed from/to
MixerBehaviorSet mMixerBehaviors;
diff --git a/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp b/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp
index 4877166..2f424b8 100644
--- a/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp
@@ -163,7 +163,8 @@
const StreamTypeVector &/*streams*/,
const DeviceTypeSet& deviceTypes,
uint32_t delayMs,
- bool force)
+ bool force,
+ bool isVoiceVolSrc)
{
if (!supportedDevices().containsDeviceAmongTypes(deviceTypes)) {
@@ -176,7 +177,7 @@
// - the force flag is set
if (volumeDb != getCurVolume(volumeSource) || force) {
ALOGV("%s for volumeSrc %d, volume %f, delay %d", __func__, volumeSource, volumeDb, delayMs);
- setCurVolume(volumeSource, volumeDb);
+ setCurVolume(volumeSource, volumeDb, isVoiceVolSrc);
return true;
}
return false;
@@ -389,6 +390,11 @@
return supportedDevices().containsAllDevices(devices);
}
+bool SwAudioOutputDescriptor::supportsAtLeastOne(const DeviceVector &devices) const
+{
+ return filterSupportedDevices(devices).size() > 0;
+}
+
bool SwAudioOutputDescriptor::supportsDevicesForPlayback(const DeviceVector &devices) const
{
// No considering duplicated output
@@ -505,11 +511,12 @@
VolumeSource vs, const StreamTypeVector &streamTypes,
const DeviceTypeSet& deviceTypes,
uint32_t delayMs,
- bool force)
+ bool force,
+ bool isVoiceVolSrc)
{
StreamTypeVector streams = streamTypes;
if (!AudioOutputDescriptor::setVolume(
- volumeDb, muted, vs, streamTypes, deviceTypes, delayMs, force)) {
+ volumeDb, muted, vs, streamTypes, deviceTypes, delayMs, force, isVoiceVolSrc)) {
return false;
}
if (streams.empty()) {
@@ -555,6 +562,10 @@
float volumeAmpl = Volume::DbToAmpl(getCurVolume(vs));
if (hasStream(streams, AUDIO_STREAM_BLUETOOTH_SCO)) {
mClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volumeAmpl, mIoHandle, delayMs);
+ VolumeSource callVolSrc = getVoiceSource();
+ if (callVolSrc != VOLUME_SOURCE_NONE) {
+ setCurVolume(callVolSrc, getCurVolume(vs), true);
+ }
}
for (const auto &stream : streams) {
ALOGV("%s output %d for volumeSource %d, volume %f, delay %d stream=%s", __func__,
@@ -783,10 +794,11 @@
VolumeSource volumeSource, const StreamTypeVector &streams,
const DeviceTypeSet& deviceTypes,
uint32_t delayMs,
- bool force)
+ bool force,
+ bool isVoiceVolSrc)
{
bool changed = AudioOutputDescriptor::setVolume(
- volumeDb, muted, volumeSource, streams, deviceTypes, delayMs, force);
+ volumeDb, muted, volumeSource, streams, deviceTypes, delayMs, force, isVoiceVolSrc);
if (changed) {
// TODO: use gain controller on source device if any to adjust volume
diff --git a/services/audiopolicy/common/managerdefinitions/src/AudioPolicyMix.cpp b/services/audiopolicy/common/managerdefinitions/src/AudioPolicyMix.cpp
index b41f86d..f870b4f 100644
--- a/services/audiopolicy/common/managerdefinitions/src/AudioPolicyMix.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/AudioPolicyMix.cpp
@@ -642,7 +642,7 @@
}
status_t AudioPolicyMixCollection::getDevicesForUserId(int userId,
- Vector<AudioDeviceTypeAddr>& devices) const {
+ AudioDeviceTypeAddrVector& devices) const {
// for each player mix:
// find rules that don't exclude this userId, and add the device to the list
for (size_t i = 0; i < size(); i++) {
@@ -660,7 +660,7 @@
}
}
if (ruleAllowsUserId) {
- devices.add(AudioDeviceTypeAddr(mix->mDeviceType, mix->mDeviceAddress.c_str()));
+ devices.push_back(AudioDeviceTypeAddr(mix->mDeviceType, mix->mDeviceAddress.c_str()));
}
}
return NO_ERROR;
diff --git a/services/audiopolicy/common/managerdefinitions/src/AudioProfileVectorHelper.cpp b/services/audiopolicy/common/managerdefinitions/src/AudioProfileVectorHelper.cpp
index 8ccb8b9..82f51ad 100644
--- a/services/audiopolicy/common/managerdefinitions/src/AudioProfileVectorHelper.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/AudioProfileVectorHelper.cpp
@@ -115,12 +115,22 @@
profile->setDynamicFormat(true);
profile->setDynamicChannels(dynamicFormatProfile->isDynamicChannels());
profile->setDynamicRate(dynamicFormatProfile->isDynamicRate());
- addAudioProfileAndSort(audioProfileVector, profile);
+ size_t profileIndex = 0;
+ for (; profileIndex < audioProfileVector.size(); profileIndex++) {
+ if (profile->equals(audioProfileVector.at(profileIndex))) {
+ // The dynamic profile is already there
+ break;
+ }
+ }
+ if (profileIndex >= audioProfileVector.size()) {
+ // Only add when the dynamic profile is not there
+ addAudioProfileAndSort(audioProfileVector, profile);
+ }
}
}
void addDynamicAudioProfileAndSort(AudioProfileVector &audioProfileVector,
- const sp<AudioProfile> &profileToAdd)
+ const sp<AudioProfile> &profileToAdd)
{
// Check valid profile to add:
if (!profileToAdd->hasValidFormat()) {
@@ -143,11 +153,15 @@
audioProfileVector, profileToAdd->getChannels(), profileToAdd->getFormat());
return;
}
+ const bool originalIsDynamicFormat = profileToAdd->isDynamicFormat();
+ profileToAdd->setDynamicFormat(true); // set the format as dynamic to allow removal
// Go through the list of profile to avoid duplicates
for (size_t profileIndex = 0; profileIndex < audioProfileVector.size(); profileIndex++) {
const sp<AudioProfile> &profile = audioProfileVector.at(profileIndex);
- if (profile->isValid() && profile == profileToAdd) {
- // Nothing to do
+ if (profile->isValid() && profile->equals(profileToAdd)) {
+ // The same profile is already there, no need to add.
+ // Reset `isDynamicProfile` as original value.
+ profileToAdd->setDynamicFormat(originalIsDynamicFormat);
return;
}
}
diff --git a/services/audiopolicy/common/managerdefinitions/src/IOProfile.cpp b/services/audiopolicy/common/managerdefinitions/src/IOProfile.cpp
index 03ab3f8..25b1c5c 100644
--- a/services/audiopolicy/common/managerdefinitions/src/IOProfile.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/IOProfile.cpp
@@ -171,6 +171,24 @@
}
}
+void IOProfile::refreshMixerBehaviors() {
+ if (getRole() == AUDIO_PORT_ROLE_SOURCE) {
+ mMixerBehaviors.clear();
+ mMixerBehaviors.insert(AUDIO_MIXER_BEHAVIOR_DEFAULT);
+ if (mFlags.output & AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
+ mMixerBehaviors.insert(AUDIO_MIXER_BEHAVIOR_BIT_PERFECT);
+ }
+ }
+}
+
+status_t IOProfile::readFromParcelable(const media::AudioPortFw &parcelable) {
+ status_t status = AudioPort::readFromParcelable(parcelable);
+ if (status == OK) {
+ refreshMixerBehaviors();
+ }
+ return status;
+}
+
void IOProfile::dump(String8 *dst, int spaces) const
{
String8 extraInfo;
@@ -195,6 +213,10 @@
spaces - 2, "", maxActiveCount, curActiveCount);
dst->appendFormat("%*s- recommendedMuteDurationMs: %u ms\n",
spaces - 2, "", recommendedMuteDurationMs);
+ if (hasDynamicAudioProfile() && !mMixerBehaviors.empty()) {
+ dst->appendFormat("%*s- mixerBehaviors: %s\n",
+ spaces - 2, "", dumpMixerBehaviors(mMixerBehaviors).c_str());
+ }
}
void IOProfile::log()
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
index cc32aec..878c0cd 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
@@ -1298,7 +1298,8 @@
if (outputDevices.size() == 1) {
info = getPreferredMixerAttributesInfo(
outputDevices.itemAt(0)->getId(),
- mEngine->getProductStrategyForAttributes(*resultAttr));
+ mEngine->getProductStrategyForAttributes(*resultAttr),
+ true /*activeBitPerfectPreferred*/);
// Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
// and it is currently active.
if (info != nullptr && info->getUid() != uid &&
@@ -2152,6 +2153,26 @@
return DEAD_OBJECT;
}
info->increaseActiveClient();
+ if (info->getActiveClientCount() == 1 &&
+ (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
+ // If it is first bit-perfect client, reroute all clients that will be routed to
+ // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
+ PortHandleVector clientsToInvalidate;
+ for (size_t i = 0; i < mOutputs.size(); i++) {
+ if (mOutputs[i] == outputDesc ||
+ mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
+ continue;
+ }
+ for (const auto& c : mOutputs[i]->getClientIterable()) {
+ clientsToInvalidate.push_back(c->portId());
+ }
+ }
+ if (!clientsToInvalidate.empty()) {
+ ALOGD("%s Invalidate clients due to first bit-perfect client started",
+ __func__);
+ mpClientInterface->invalidateTracks(clientsToInvalidate);
+ }
+ }
}
}
@@ -3787,6 +3808,44 @@
return true;
}
+void AudioPolicyManager::changeOutputDevicesMuteState(
+ const AudioDeviceTypeAddrVector& devices) {
+ ALOGVV("%s() num devices %zu", __func__, devices.size());
+
+ std::vector<sp<SwAudioOutputDescriptor>> outputs =
+ getSoftwareOutputsForDevices(devices);
+
+ for (size_t i = 0; i < outputs.size(); i++) {
+ sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
+ DeviceVector prevDevices = outputDesc->devices();
+ checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
+ }
+}
+
+std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
+ const AudioDeviceTypeAddrVector& devices) const
+{
+ std::vector<sp<SwAudioOutputDescriptor>> outputs;
+ DeviceVector deviceDescriptors;
+ for (size_t j = 0; j < devices.size(); j++) {
+ sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
+ devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
+ if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
+ ALOGE("%s: device type %#x address %s not supported or not an output device",
+ __func__, devices[j].mType, devices[j].getAddress());
+ continue;
+ }
+ deviceDescriptors.add(desc);
+ }
+ for (size_t i = 0; i < mOutputs.size(); i++) {
+ if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
+ continue;
+ }
+ outputs.push_back(mOutputs.valueAt(i));
+ }
+ return outputs;
+}
+
status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
const AudioDeviceTypeAddrVector& devices) {
ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
@@ -3853,7 +3912,8 @@
return NO_ERROR;
}
-void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
+void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
+ bool skipDelays)
{
uint32_t waitMs = 0;
bool wasLeUnicastActive = isLeUnicastActive();
@@ -3879,8 +3939,8 @@
continue;
}
waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
- true /*requiresMuteCheck*/,
- !forceRouting /*requiresVolumeCheck*/);
+ !skipDelays /*requiresMuteCheck*/,
+ !forceRouting /*requiresVolumeCheck*/, skipDelays);
// Only apply special touch sound delay once
delayMs = 0;
}
@@ -4065,13 +4125,18 @@
// reevaluate outputs for all devices
checkForDeviceAndOutputChanges();
- updateCallAndOutputRouting();
+ changeOutputDevicesMuteState(devices);
+ updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
+ true /* skipDelays */);
+ changeOutputDevicesMuteState(devices);
return NO_ERROR;
}
status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
ALOGV("%s() userId=%d", __FUNCTION__, userId);
+ AudioDeviceTypeAddrVector devices;
+ mPolicyMixes.getDevicesForUserId(userId, devices);
status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
if (status != NO_ERROR) {
ALOGE("%s() Could not remove all device affinities fo userId = %d",
@@ -4081,7 +4146,10 @@
// reevaluate outputs for all devices
checkForDeviceAndOutputChanges();
- updateCallAndOutputRouting();
+ changeOutputDevicesMuteState(devices);
+ updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
+ true /* skipDelays */);
+ changeOutputDevicesMuteState(devices);
return NO_ERROR;
}
@@ -4490,16 +4558,24 @@
}
sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
- audio_port_handle_t devicePortId, product_strategy_t strategy) {
+ audio_port_handle_t devicePortId,
+ product_strategy_t strategy,
+ bool activeBitPerfectPreferred) {
auto it = mPreferredMixerAttrInfos.find(devicePortId);
if (it == mPreferredMixerAttrInfos.end()) {
return nullptr;
}
- auto mixerAttrInfoIt = it->second.find(strategy);
- if (mixerAttrInfoIt == it->second.end()) {
- return nullptr;
+ if (activeBitPerfectPreferred) {
+ for (auto [strategy, info] : it->second) {
+ if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
+ && info->getActiveClientCount() != 0) {
+ return info;
+ }
+ }
}
- return mixerAttrInfoIt->second;
+ auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
+ return strategyMatchedMixerAttrInfoIt == it->second.end()
+ ? nullptr : strategyMatchedMixerAttrInfoIt->second;
}
status_t AudioPolicyManager::getPreferredMixerAttributes(
@@ -5841,22 +5917,26 @@
}
}
+ // The caller can have the audio config criteria ignored by either passing a null ptr or
+ // the AUDIO_CONFIG_INITIALIZER value.
+ // If an audio config is specified, current policy is to only allow spatialization for
+ // some positional channel masks and PCM format
+
+ if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
+ if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
+ return false;
+ }
+ if (!audio_is_linear_pcm(config->format)) {
+ return false;
+ }
+ }
+
sp<IOProfile> profile =
getSpatializerOutputProfile(config, devices);
if (profile == nullptr) {
return false;
}
- // The caller can have the audio config criteria ignored by either passing a null ptr or
- // the AUDIO_CONFIG_INITIALIZER value.
- // If an audio config is specified, current policy is to only allow spatialization for
- // some positional channel masks.
-
- if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
- if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
- return false;
- }
- }
return true;
}
@@ -7320,7 +7400,8 @@
bool force,
int delayMs,
audio_patch_handle_t *patchHandle,
- bool requiresMuteCheck, bool requiresVolumeCheck)
+ bool requiresMuteCheck, bool requiresVolumeCheck,
+ bool skipMuteDelay)
{
// TODO(b/262404095): Consider if the output need to be reopened.
ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
@@ -7328,9 +7409,9 @@
if (outputDesc->isDuplicated()) {
muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
- nullptr /* patchHandle */, requiresMuteCheck);
+ nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
- nullptr /* patchHandle */, requiresMuteCheck);
+ nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
return muteWaitMs;
}
@@ -7396,12 +7477,16 @@
// Add half reported latency to delayMs when muteWaitMs is null in order
// to avoid disordered sequence of muting volume and changing devices.
- installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
- muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
+ int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
+ ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
+ installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
}
- // update stream volumes according to new device
- applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
+ // Since the mute is skip, also skip the apply stream volume as that will be applied externally
+ if (!skipMuteDelay) {
+ // update stream volumes according to new device
+ applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
+ }
return muteWaitMs;
}
@@ -7576,8 +7661,10 @@
const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
-
- if (volumeSource == a11yVolumeSrc
+ // Verify that the current volume source is not the ringer volume to prevent recursively
+ // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
+ // to the same volume group.
+ if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
&& (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
mOutputs.isActive(ringVolumeSrc, 0)) {
auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
@@ -7640,8 +7727,12 @@
// 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
- if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
- mLimitRingtoneVolume) {
+ // Verify that the current volume source is not the music volume to prevent recursively
+ // calling to compute volume. This could happen in cases where music and
+ // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
+ if (volumeSource != musicVolumeSrc &&
+ (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
+ || mLimitRingtoneVolume)) {
volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
DeviceTypeSet musicDevice =
mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
@@ -7759,8 +7850,8 @@
volumeDb = 0.0f;
}
const bool muted = (index == 0) && (volumeDb != 0.0f);
- outputDesc->setVolume(
- volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
+ outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
+ deviceTypes, delayMs, force, isVoiceVolSrc);
if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
float voiceVolume;
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.h b/services/audiopolicy/managerdefault/AudioPolicyManager.h
index 88bafef..863c785 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.h
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.h
@@ -535,8 +535,9 @@
* and currently active, allow to have proper drain and avoid pops
* @param requiresVolumeCheck true if called requires to reapply volume if the routing did
* not change (but the output is still routed).
+ * @param skipMuteDelay if true will skip mute delay when installing audio patch
* @return the number of ms we have slept to allow new routing to take effect in certain
- * cases.
+ * cases.
*/
uint32_t setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
const DeviceVector &device,
@@ -544,7 +545,8 @@
int delayMs = 0,
audio_patch_handle_t *patchHandle = NULL,
bool requiresMuteCheck = true,
- bool requiresVolumeCheck = false);
+ bool requiresVolumeCheck = false,
+ bool skipMuteDelay = false);
status_t resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
int delayMs = 0,
audio_patch_handle_t *patchHandle = NULL);
@@ -647,8 +649,10 @@
/**
* @brief updates routing for all outputs (including call if call in progress).
* @param delayMs delay for unmuting if required
+ * @param skipDelays if true all the delays will be skip while updating routing
*/
- void updateCallAndOutputRouting(bool forceVolumeReeval = true, uint32_t delayMs = 0);
+ void updateCallAndOutputRouting(bool forceVolumeReeval = true, uint32_t delayMs = 0,
+ bool skipDelays = false);
bool isCallRxAudioSource(const sp<SourceClientDescriptor> &source) {
return mCallRxSourceClient != nullptr && source == mCallRxSourceClient;
@@ -1241,6 +1245,21 @@
const char* context,
bool matchAddress = true);
+ /**
+ * @brief changeOutputDevicesMuteState mute/unmute devices using checkDeviceMuteStrategies
+ * @param devices devices to mute/unmute
+ */
+ void changeOutputDevicesMuteState(const AudioDeviceTypeAddrVector& devices);
+
+ /**
+ * @brief Returns a vector of software output descriptor that support the queried devices
+ * @param devices devices to query
+ * @param openOutputs open outputs where the devices are supported as determined by
+ * SwAudioOutputDescriptor::supportsAtLeastOne
+ */
+ std::vector<sp<SwAudioOutputDescriptor>> getSoftwareOutputsForDevices(
+ const AudioDeviceTypeAddrVector& devices) const;
+
bool isScoRequestedForComm() const;
bool isHearingAidUsedForComm() const;
@@ -1298,8 +1317,15 @@
uint32_t flags,
bool isInput);
+ /**
+ * Returns the preferred mixer attributes info for the given device port id and strategy.
+ * Bit-perfect mixer attributes will be returned if it is active and
+ * `activeBitPerfectPreferred` is true.
+ */
sp<PreferredMixerAttributesInfo> getPreferredMixerAttributesInfo(
- audio_port_handle_t devicePortId, product_strategy_t strategy);
+ audio_port_handle_t devicePortId,
+ product_strategy_t strategy,
+ bool activeBitPerfectPreferred = false);
sp<SwAudioOutputDescriptor> reopenOutput(
sp<SwAudioOutputDescriptor> outputDesc,
diff --git a/services/audiopolicy/service/AudioPolicyService.cpp b/services/audiopolicy/service/AudioPolicyService.cpp
index d7aa5c9..041aa1c 100644
--- a/services/audiopolicy/service/AudioPolicyService.cpp
+++ b/services/audiopolicy/service/AudioPolicyService.cpp
@@ -25,6 +25,7 @@
#include <sys/time.h>
#include <dlfcn.h>
+#include <android/content/pm/IPackageManagerNative.h>
#include <audio_utils/clock.h>
#include <binder/IServiceManager.h>
#include <utils/Log.h>
@@ -215,6 +216,27 @@
{
delete interface;
}
+
+namespace {
+int getTargetSdkForPackageName(std::string_view packageName) {
+ const auto binder = defaultServiceManager()->checkService(String16{"package_native"});
+ int targetSdk = -1;
+ if (binder != nullptr) {
+ const auto pm = interface_cast<content::pm::IPackageManagerNative>(binder);
+ if (pm != nullptr) {
+ const auto status = pm->getTargetSdkVersionForPackage(
+ String16{packageName.data(), packageName.size()}, &targetSdk);
+ ALOGI("Capy check package %s, sdk %d", packageName.data(), targetSdk);
+ return status.isOk() ? targetSdk : -1;
+ }
+ }
+ return targetSdk;
+}
+
+bool doesPackageTargetAtLeastU(std::string_view packageName) {
+ return getTargetSdkForPackageName(packageName) >= __ANDROID_API_U__;
+}
+} // anonymous
// ----------------------------------------------------------------------------
AudioPolicyService::AudioPolicyService()
@@ -1926,10 +1948,14 @@
checkOp();
mOpCallback = new RecordAudioOpCallback(this);
ALOGV("start watching op %d for %s", mAppOp, mAttributionSource.toString().c_str());
+ int flags = doesPackageTargetAtLeastU(
+ mAttributionSource.packageName.value_or("")) ?
+ AppOpsManager::WATCH_FOREGROUND_CHANGES : 0;
// TODO: We need to always watch AppOpsManager::OP_RECORD_AUDIO too
// since it controls the mic permission for legacy apps.
mAppOpsManager.startWatchingMode(mAppOp, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
mAttributionSource.packageName.value_or(""))),
+ flags,
mOpCallback);
}
diff --git a/services/audiopolicy/tests/audiopolicymanager_tests.cpp b/services/audiopolicy/tests/audiopolicymanager_tests.cpp
index 5e58dbb..15eae14 100644
--- a/services/audiopolicy/tests/audiopolicymanager_tests.cpp
+++ b/services/audiopolicy/tests/audiopolicymanager_tests.cpp
@@ -1232,6 +1232,19 @@
EXPECT_FALSE(isBitPerfect);
EXPECT_EQ(bitPerfectOutput, output);
+ const audio_attributes_t dtmfAttr = {
+ .content_type = AUDIO_CONTENT_TYPE_UNKNOWN,
+ .usage = AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING,
+ };
+ audio_io_handle_t dtmfOutput = AUDIO_IO_HANDLE_NONE;
+ selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
+ portId = AUDIO_PORT_HANDLE_NONE;
+ getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
+ 48000, AUDIO_OUTPUT_FLAG_NONE, &dtmfOutput, &portId, dtmfAttr,
+ AUDIO_SESSION_NONE, anotherUid, &isBitPerfect);
+ EXPECT_FALSE(isBitPerfect);
+ EXPECT_EQ(bitPerfectOutput, dtmfOutput);
+
// When configuration matches preferred mixer attributes, which is bit-perfect, but the client
// is not the owner of preferred mixer attributes, the playback will not be bit-perfect.
getOutputForAttr(&selectedDeviceId, bitPerfectFormat, bitPerfectChannelMask,
diff --git a/services/camera/libcameraservice/CameraService.cpp b/services/camera/libcameraservice/CameraService.cpp
index 3e7af3d..dd2e2d8 100644
--- a/services/camera/libcameraservice/CameraService.cpp
+++ b/services/camera/libcameraservice/CameraService.cpp
@@ -305,14 +305,23 @@
for (auto& i : mListenerList) {
if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
i->getListenerUid())) {
- ALOGV("Skipping torch callback for system-only camera device %s",
- cameraId.c_str());
+ ALOGV("%s: Skipping torch callback for system-only camera device %s",
+ __FUNCTION__, cameraId.c_str());
continue;
}
auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
cameraId);
i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
__FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
+ // Also trigger the torch callbacks for cameras that were remapped to the current cameraId
+ // for the specific package that this listener belongs to.
+ std::vector<std::string> remappedCameraIds =
+ findOriginalIdsForRemappedCameraId(cameraId, i->getListenerUid());
+ for (auto& remappedCameraId : remappedCameraIds) {
+ ret = i->getListener()->onTorchStatusChanged(mapToInterface(status), remappedCameraId);
+ i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
+ __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
+ }
}
}
@@ -729,11 +738,178 @@
return Status::ok();
}
+Status CameraService::remapCameraIds(const hardware::CameraIdRemapping&
+ cameraIdRemapping) {
+ if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
+ const int pid = CameraThreadState::getCallingPid();
+ const int uid = CameraThreadState::getCallingUid();
+ ALOGE("%s: Permission Denial: can't configure camera ID mapping pid=%d, uid=%d",
+ __FUNCTION__, pid, uid);
+ return STATUS_ERROR(ERROR_PERMISSION_DENIED,
+ "Permission Denial: no permission to configure camera id mapping");
+ }
+ TCameraIdRemapping cameraIdRemappingMap{};
+ binder::Status parseStatus = parseCameraIdRemapping(cameraIdRemapping, &cameraIdRemappingMap);
+ if (!parseStatus.isOk()) {
+ return parseStatus;
+ }
+ remapCameraIds(cameraIdRemappingMap);
+ return Status::ok();
+}
+
+Status CameraService::parseCameraIdRemapping(
+ const hardware::CameraIdRemapping& cameraIdRemapping,
+ /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
+ std::string packageName;
+ std::string cameraIdToReplace, updatedCameraId;
+ for(const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
+ packageName = packageIdRemapping.packageName;
+ if (packageName == "") {
+ return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
+ "CameraIdRemapping: Package name cannot be empty");
+ }
+
+ if (packageIdRemapping.cameraIdsToReplace.size()
+ != packageIdRemapping.updatedCameraIds.size()) {
+ return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
+ "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
+ packageName.c_str());
+ }
+ for(size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
+ cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
+ updatedCameraId = packageIdRemapping.updatedCameraIds[i];
+ if (cameraIdToReplace == "" || updatedCameraId == "") {
+ return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
+ "CameraIdRemapping: Camera Id cannot be empty for package %s",
+ packageName.c_str());
+ }
+ if (cameraIdToReplace == updatedCameraId) {
+ return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
+ "CameraIdRemapping: CameraIdToReplace cannot be the same"
+ " as updatedCameraId for %s",
+ packageName.c_str());
+ }
+ (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
+ }
+ }
+ return Status::ok();
+}
+
+void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
+ // Acquire mServiceLock and prevent other clients from connecting
+ std::unique_ptr<AutoConditionLock> serviceLockWrapper =
+ AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
+
+ // Collect all existing clients for camera Ids that are being
+ // remapped in the new cameraIdRemapping, but only if they were being used by a
+ // targeted packageName.
+ std::vector<sp<BasicClient>> clientsToDisconnect;
+ std::vector<std::string> cameraIdsToUpdate;
+ for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
+ for (auto& [id0, id1] : injectionMap) {
+ ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
+ id0.c_str(), id1.c_str());
+ auto clientDescriptor = mActiveClientManager.get(id0);
+ if (clientDescriptor != nullptr) {
+ sp<BasicClient> clientSp = clientDescriptor->getValue();
+ if (clientSp->getPackageName() == packageName) {
+ // This camera is being used by a targeted packageName and
+ // being remapped to a new camera Id. We should disconnect it.
+ clientsToDisconnect.push_back(clientSp);
+ cameraIdsToUpdate.push_back(id0);
+ }
+ }
+ }
+ }
+
+ for (auto& clientSp : clientsToDisconnect) {
+ // We send up ERROR_CAMERA_DEVICE so that the app attempts to reconnect
+ // automatically. Note that this itself can cause clientSp->disconnect() based on the
+ // app's response.
+ clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
+ CaptureResultExtras{});
+ }
+
+ // Do not hold mServiceLock while disconnecting clients, but retain the condition
+ // blocking other clients from connecting in mServiceLockWrapper if held.
+ mServiceLock.unlock();
+
+ // Clear calling identity for disconnect() PID checks.
+ int64_t token = CameraThreadState::clearCallingIdentity();
+
+ // Disconnect clients.
+ for (auto& clientSp : clientsToDisconnect) {
+ // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
+ // and requires mCameraIdRemappingLock.
+ clientSp->disconnect();
+ }
+
+ // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
+ clientsToDisconnect.clear();
+
+ CameraThreadState::restoreCallingIdentity(token);
+ mServiceLock.lock();
+
+ {
+ Mutex::Autolock lock(mCameraIdRemappingLock);
+ // Update mCameraIdRemapping.
+ mCameraIdRemapping.clear();
+ mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
+ }
+}
+
+std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
+ const std::string& inputCameraId, int clientUid) {
+ std::string packageName = getPackageNameFromUid(clientUid);
+ std::vector<std::string> cameraIds;
+ Mutex::Autolock lock(mCameraIdRemappingLock);
+ if (auto packageMapIter = mCameraIdRemapping.find(packageName);
+ packageMapIter != mCameraIdRemapping.end()) {
+ for (auto& [id0, id1]: packageMapIter->second) {
+ if (id1 == inputCameraId) {
+ cameraIds.push_back(id0);
+ }
+ }
+ }
+ return cameraIds;
+}
+
+std::string CameraService::resolveCameraId(
+ const std::string& inputCameraId,
+ int clientUid,
+ const std::string& packageName) {
+ std::string packageNameVal = packageName;
+ if (packageName.empty()) {
+ packageNameVal = getPackageNameFromUid(clientUid);
+ }
+ if (clientUid < AID_APP_START || packageNameVal.empty()) {
+ // We shouldn't remap cameras for processes with system/vendor UIDs.
+ return inputCameraId;
+ }
+ Mutex::Autolock lock(mCameraIdRemappingLock);
+ if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
+ packageMapIter != mCameraIdRemapping.end()) {
+ auto packageMap = packageMapIter->second;
+ if (auto replacementIdIter = packageMap.find(inputCameraId);
+ replacementIdIter != packageMap.end()) {
+ ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
+ __FUNCTION__, inputCameraId.c_str(),
+ packageNameVal.c_str(),
+ replacementIdIter->second.c_str());
+ return replacementIdIter->second;
+ }
+ }
+ return inputCameraId;
+}
+
Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait,
CameraInfo* cameraInfo) {
ATRACE_CALL();
Mutex::Autolock l(mServiceLock);
- std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
+ std::string unresolvedCameraId = cameraIdIntToStrLocked(cameraId);
+ std::string cameraIdStr = resolveCameraId(
+ unresolvedCameraId, CameraThreadState::getCallingUid());
+
if (shouldRejectSystemCameraConnection(cameraIdStr)) {
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
"characteristics for system only device %s: ", cameraIdStr.c_str());
@@ -799,9 +975,13 @@
return cameraIdIntToStrLocked(cameraIdInt);
}
-Status CameraService::getCameraCharacteristics(const std::string& cameraId,
+Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) {
ATRACE_CALL();
+
+ const std::string cameraId = resolveCameraId(unresolvedCameraId,
+ CameraThreadState::getCallingUid());
+
if (!cameraInfo) {
ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
@@ -886,10 +1066,12 @@
return ret;
}
-Status CameraService::getTorchStrengthLevel(const std::string& cameraId,
+Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
int32_t* torchStrength) {
ATRACE_CALL();
Mutex::Autolock l(mServiceLock);
+ const std::string cameraId = resolveCameraId(
+ unresolvedCameraId, CameraThreadState::getCallingUid());
if (!mInitialized) {
ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
@@ -1008,7 +1190,7 @@
int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
- bool forceSlowJpegMode, /*out*/sp<BasicClient>* client) {
+ bool forceSlowJpegMode, const std::string& originalCameraId, /*out*/sp<BasicClient>* client) {
// For HIDL devices
if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
// Create CameraClient based on device version reported by the HAL.
@@ -1052,7 +1234,7 @@
*client = new CameraDeviceClient(cameraService, tmp,
cameraService->mCameraServiceProxyWrapper, packageName, systemNativeClient,
featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
- overrideForPerfClass, overrideToPortrait);
+ overrideForPerfClass, overrideToPortrait, originalCameraId);
ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
}
return Status::ok();
@@ -1143,7 +1325,7 @@
kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
/*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
- /*forceSlowJpegMode*/false, /*out*/ tmp)
+ /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
).isOk()) {
ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
}
@@ -1163,7 +1345,9 @@
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
}
- std::string cameraIdStr = std::to_string(cameraId);
+ std::string unresolvedCameraId = std::to_string(cameraId);
+ std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
+ CameraThreadState::getCallingUid());
// Check if we already have parameters
{
@@ -1348,8 +1532,8 @@
attributionSource.uid = clientUid;
attributionSource.packageName = clientName;
bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
- toString16(sCameraPermission), attributionSource, String16(),
- AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
+ toString16(sCameraPermission), attributionSource, String16(), AppOpsManager::OP_NONE)
+ != permission::PermissionChecker::PERMISSION_HARD_DENIED;
if (callingPid != getpid() &&
(deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
@@ -1676,12 +1860,15 @@
ATRACE_CALL();
Status ret = Status::ok();
- std::string cameraIdStr = cameraIdIntToStr(api1CameraId);
+ std::string unresolvedCameraId = cameraIdIntToStr(api1CameraId);
+ std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
+ CameraThreadState::getCallingUid());
+
sp<Client> client = nullptr;
ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
/*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
- overrideToPortrait, forceSlowJpegMode, /*out*/client);
+ overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
if(!ret.isOk()) {
logRejected(cameraIdStr, CameraThreadState::getCallingPid(), clientPackageName,
@@ -1761,7 +1948,7 @@
Status CameraService::connectDevice(
const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
- const std::string& cameraId,
+ const std::string& unresolvedCameraId,
const std::string& clientPackageName,
const std::optional<std::string>& clientFeatureId,
int clientUid, int oomScoreOffset, int targetSdkVersion,
@@ -1781,6 +1968,10 @@
clientPackageNameAdj = systemClient;
systemNativeClient = true;
}
+ const std::string cameraId = resolveCameraId(
+ unresolvedCameraId,
+ CameraThreadState::getCallingUid(),
+ clientPackageNameAdj);
if (oomScoreOffset < 0) {
std::string msg =
@@ -1818,9 +2009,9 @@
cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false,
- /*out*/client);
+ unresolvedCameraId, /*out*/client);
- if(!ret.isOk()) {
+ if (!ret.isOk()) {
logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
return ret;
}
@@ -1887,7 +2078,7 @@
int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
- bool overrideToPortrait, bool forceSlowJpegMode,
+ bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
/*out*/sp<CLIENT>& device) {
binder::Status ret = binder::Status::ok();
@@ -2002,7 +2193,7 @@
clientFeatureId, cameraId, api1CameraId, facing,
orientation, clientPid, clientUid, getpid(),
deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
- overrideToPortrait, forceSlowJpegMode,
+ overrideToPortrait, forceSlowJpegMode, originalCameraId,
/*out*/&tmp)).isOk()) {
return ret;
}
@@ -2016,6 +2207,9 @@
if (err != OK) {
ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
// Errors could be from the HAL module open call or from AppOpsManager
+ mServiceLock.unlock();
+ client->disconnect();
+ mServiceLock.lock();
switch(err) {
case BAD_VALUE:
return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
@@ -2256,8 +2450,9 @@
return OK;
}
-Status CameraService::turnOnTorchWithStrengthLevel(const std::string& cameraId,
- int32_t torchStrength, const sp<IBinder>& clientBinder) {
+Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
+ int32_t torchStrength,
+ const sp<IBinder>& clientBinder) {
Mutex::Autolock lock(mServiceLock);
ATRACE_CALL();
@@ -2268,7 +2463,7 @@
}
int uid = CameraThreadState::getCallingUid();
-
+ const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
if (shouldRejectSystemCameraConnection(cameraId)) {
return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
"for system only device %s: ", cameraId.c_str());
@@ -2384,7 +2579,8 @@
return Status::ok();
}
-Status CameraService::setTorchMode(const std::string& cameraId, bool enabled,
+Status CameraService::setTorchMode(const std::string& unresolvedCameraId,
+ bool enabled,
const sp<IBinder>& clientBinder) {
Mutex::Autolock lock(mServiceLock);
@@ -2396,6 +2592,7 @@
}
int uid = CameraThreadState::getCallingUid();
+ const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
if (shouldRejectSystemCameraConnection(cameraId)) {
return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
@@ -2922,10 +3119,13 @@
return ret;
}
-Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
+Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
/*out*/ bool *isSupported) {
ATRACE_CALL();
+ const std::string cameraId = resolveCameraId(
+ unresolvedCameraId, CameraThreadState::getCallingUid());
+
ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
switch (apiVersion) {
@@ -2984,10 +3184,13 @@
return Status::ok();
}
-Status CameraService::isHiddenPhysicalCamera(const std::string& cameraId,
+Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
/*out*/ bool *isSupported) {
ATRACE_CALL();
+ const std::string cameraId = resolveCameraId(unresolvedCameraId,
+ CameraThreadState::getCallingUid());
+
ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
*isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
@@ -4918,7 +5121,6 @@
state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
&logicalCameraIds]
(const std::string& cameraId, StatusInternal status) {
-
if (status != StatusInternal::ENUMERATING) {
// Update torch status if it has a flash unit.
Mutex::Autolock al(mTorchStatusMutex);
@@ -4951,9 +5153,21 @@
auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
cameraId);
listener->handleBinderStatus(ret,
- "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
+ "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
__FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
ret.exceptionCode());
+ // Also trigger the callbacks for cameras that were remapped to the current
+ // cameraId for the specific package that this listener belongs to.
+ std::vector<std::string> remappedCameraIds =
+ findOriginalIdsForRemappedCameraId(cameraId, listener->getListenerUid());
+ for (auto& remappedCameraId : remappedCameraIds) {
+ ret = listener->getListener()->onStatusChanged(
+ mapToInterface(status), remappedCameraId);
+ listener->handleBinderStatus(ret,
+ "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
+ __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
+ ret.exceptionCode());
+ }
}
});
}
@@ -5163,6 +5377,8 @@
return handleWatchCommand(args, in, out);
} else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
return handleSetCameraServiceWatchdog(args);
+ } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
+ return handleCameraIdRemapping(args, err);
} else if (args.size() == 1 && args[0] == toString16("help")) {
printHelp(out);
return OK;
@@ -5171,6 +5387,23 @@
return BAD_VALUE;
}
+status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
+ uid_t uid = IPCThreadState::self()->getCallingUid();
+ if (uid != AID_ROOT) {
+ dprintf(err, "Must be adb root\n");
+ return PERMISSION_DENIED;
+ }
+ if (args.size() != 4) {
+ dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
+ return BAD_VALUE;
+ }
+ std::string packageName = toStdString(args[1]);
+ std::string cameraIdToReplace = toStdString(args[2]);
+ std::string cameraIdNew = toStdString(args[3]);
+ remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
+ return OK;
+}
+
status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
std::string packageName = toStdString(args[1]);
@@ -5784,6 +6017,7 @@
" clear-stream-use-case-override clear the stream use case override\n"
" set-zoom-override <-1/0/1> enable or disable zoom override\n"
" Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
+ " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
" watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
" help print this message\n");
}
diff --git a/services/camera/libcameraservice/CameraService.h b/services/camera/libcameraservice/CameraService.h
index bc65293..68f7f73 100644
--- a/services/camera/libcameraservice/CameraService.h
+++ b/services/camera/libcameraservice/CameraService.h
@@ -20,6 +20,7 @@
#include <android/hardware/BnCameraService.h>
#include <android/hardware/BnSensorPrivacyListener.h>
#include <android/hardware/ICameraServiceListener.h>
+#include <android/hardware/CameraIdRemapping.h>
#include <android/hardware/camera2/BnCameraInjectionSession.h>
#include <android/hardware/camera2/ICameraInjectionCallback.h>
@@ -61,6 +62,7 @@
#include <utility>
#include <unordered_map>
#include <unordered_set>
+#include <vector>
namespace android {
@@ -138,6 +140,9 @@
/////////////////////////////////////////////////////////////////////
// ICameraService
+ // IMPORTANT: All binder calls that deal with logicalCameraId should use
+ // resolveCameraId(logicalCameraId) to arrive at the correct cameraId to
+ // perform the operation on (in case of Id Remapping).
virtual binder::Status getNumberOfCameras(int32_t type, int32_t* numCameras);
virtual binder::Status getCameraInfo(int cameraId, bool overrideToPortrait,
@@ -222,6 +227,9 @@
virtual binder::Status reportExtensionSessionStats(
const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/);
+ virtual binder::Status remapCameraIds(const hardware::CameraIdRemapping&
+ cameraIdRemapping);
+
// Extra permissions checks
virtual status_t onTransact(uint32_t code, const Parcel& data,
Parcel* reply, uint32_t flags);
@@ -355,7 +363,7 @@
static bool isValidAudioRestriction(int32_t mode);
// Override rotate-and-crop AUTO behavior
- virtual status_t setRotateAndCropOverride(uint8_t rotateAndCrop) = 0;
+ virtual status_t setRotateAndCropOverride(uint8_t rotateAndCrop, bool fromHal = false) = 0;
// Override autoframing AUTO behaviour
virtual status_t setAutoframingOverride(uint8_t autoframingValue) = 0;
@@ -915,7 +923,7 @@
int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
apiLevel effectiveApiLevel, bool shimUpdateOnly, int scoreOffset, int targetSdkVersion,
- bool overrideToPortrait, bool forceSlowJpegMode,
+ bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
/*out*/sp<CLIENT>& device);
// Lock guarding camera service state
@@ -943,6 +951,46 @@
// Mutex guarding mCameraStates map
mutable Mutex mCameraStatesLock;
+ /**
+ * Mapping from packageName -> {cameraIdToReplace -> newCameraIdtoUse}.
+ *
+ * This specifies that for packageName, for every binder operation targeting
+ * cameraIdToReplace, use newCameraIdToUse instead.
+ */
+ typedef std::map<std::string, std::map<std::string, std::string>> TCameraIdRemapping;
+ TCameraIdRemapping mCameraIdRemapping{};
+ /** Mutex guarding mCameraIdRemapping. */
+ Mutex mCameraIdRemappingLock;
+
+ /** Parses cameraIdRemapping parcelable into the native cameraIdRemappingMap. */
+ binder::Status parseCameraIdRemapping(
+ const hardware::CameraIdRemapping& cameraIdRemapping,
+ /* out */ TCameraIdRemapping* cameraIdRemappingMap);
+
+ /**
+ * Resolve the (potentially remapped) camera Id to use for packageName.
+ *
+ * This returns the Camera Id to use in case inputCameraId was remapped to a
+ * different Id for the given packageName. Otherwise, it returns the inputCameraId.
+ *
+ * If the packageName is not provided, it will be inferred from the clientUid.
+ */
+ std::string resolveCameraId(
+ const std::string& inputCameraId,
+ int clientUid,
+ const std::string& packageName = "");
+
+ /**
+ * Updates the state of mCameraIdRemapping, while disconnecting active clients as necessary.
+ */
+ void remapCameraIds(const TCameraIdRemapping& cameraIdRemapping);
+
+ /**
+ * Finds the Camera Ids that were remapped to the inputCameraId for the given client.
+ */
+ std::vector<std::string> findOriginalIdsForRemappedCameraId(
+ const std::string& inputCameraId, int clientUid);
+
// Circular buffer for storing event logging for dumps
RingBuffer<std::string> mEventLog;
Mutex mLogLock;
@@ -1325,6 +1373,9 @@
// Set or clear the zoom override flag
status_t handleSetZoomOverride(const Vector<String16>& args);
+ // Set Camera Id remapping using 'cmd'
+ status_t handleCameraIdRemapping(const Vector<String16>& args, int errFd);
+
// Handle 'watch' command as passed through 'cmd'
status_t handleWatchCommand(const Vector<String16> &args, int inFd, int outFd);
@@ -1370,14 +1421,15 @@
*/
static std::string getFormattedCurrentTime();
- static binder::Status makeClient(const sp<CameraService>& cameraService,
- const sp<IInterface>& cameraCb, const std::string& packageName,
- bool systemNativeClient, const std::optional<std::string>& featureId,
- const std::string& cameraId, int api1CameraId, int facing, int sensorOrientation,
- int clientPid, uid_t clientUid, int servicePid,
+ static binder::Status makeClient(
+ const sp<CameraService>& cameraService, const sp<IInterface>& cameraCb,
+ const std::string& packageName, bool systemNativeClient,
+ const std::optional<std::string>& featureId, const std::string& cameraId, int api1CameraId,
+ int facing, int sensorOrientation, int clientPid, uid_t clientUid, int servicePid,
std::pair<int, IPCTransport> deviceVersionAndIPCTransport, apiLevel effectiveApiLevel,
bool overrideForPerfClass, bool overrideToPortrait, bool forceSlowJpegMode,
- /*out*/sp<BasicClient>* client);
+ const std::string& originalCameraId,
+ /*out*/ sp<BasicClient>* client);
static std::string toString(std::set<userid_t> intSet);
static int32_t mapToInterface(TorchModeStatus status);
diff --git a/services/camera/libcameraservice/api1/Camera2Client.cpp b/services/camera/libcameraservice/api1/Camera2Client.cpp
index b388e5a..caa6424 100644
--- a/services/camera/libcameraservice/api1/Camera2Client.cpp
+++ b/services/camera/libcameraservice/api1/Camera2Client.cpp
@@ -73,7 +73,9 @@
cameraDeviceId, api1CameraId, cameraFacing, sensorOrientation, clientPid,
clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
/*legacyClient*/ true),
- mParameters(api1CameraId, cameraFacing)
+ mParameters(api1CameraId, cameraFacing),
+ mLatestRequestIds(kMaxRequestIds),
+ mLatestFailedRequestIds(kMaxRequestIds)
{
ATRACE_CALL();
@@ -1835,7 +1837,7 @@
(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode)) {
Mutex::Autolock al(mLatestRequestMutex);
- mLatestFailedRequestId = resultExtras.requestId;
+ mLatestFailedRequestIds.add(resultExtras.requestId);
mLatestRequestSignal.signal();
}
mCaptureSequencer->notifyError(errorCode, resultExtras);
@@ -2340,7 +2342,7 @@
return mDevice->setCameraServiceWatchdog(enabled);
}
-status_t Camera2Client::setRotateAndCropOverride(uint8_t rotateAndCrop) {
+status_t Camera2Client::setRotateAndCropOverride(uint8_t rotateAndCrop, bool fromHal) {
if (rotateAndCrop > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
{
@@ -2354,7 +2356,7 @@
}
return mDevice->setRotateAndCropAutoBehavior(
- static_cast<camera_metadata_enum_android_scaler_rotate_and_crop_t>(rotateAndCrop));
+ static_cast<camera_metadata_enum_android_scaler_rotate_and_crop_t>(rotateAndCrop), fromHal);
}
status_t Camera2Client::setAutoframingOverride(uint8_t autoframingValue) {
@@ -2410,7 +2412,10 @@
status_t Camera2Client::waitUntilRequestIdApplied(int32_t requestId, nsecs_t timeout) {
Mutex::Autolock l(mLatestRequestMutex);
- while ((mLatestRequestId != requestId) && (mLatestFailedRequestId != requestId)) {
+ while ((std::find(mLatestRequestIds.begin(), mLatestRequestIds.end(), requestId) ==
+ mLatestRequestIds.end()) &&
+ (std::find(mLatestFailedRequestIds.begin(), mLatestFailedRequestIds.end(), requestId) ==
+ mLatestFailedRequestIds.end())) {
nsecs_t startTime = systemTime();
auto res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
@@ -2419,13 +2424,14 @@
timeout -= (systemTime() - startTime);
}
- return (mLatestRequestId == requestId) ? OK : DEAD_OBJECT;
+ return (std::find(mLatestRequestIds.begin(), mLatestRequestIds.end(), requestId) !=
+ mLatestRequestIds.end()) ? OK : DEAD_OBJECT;
}
void Camera2Client::notifyRequestId(int32_t requestId) {
Mutex::Autolock al(mLatestRequestMutex);
- mLatestRequestId = requestId;
+ mLatestRequestIds.add(requestId);
mLatestRequestSignal.signal();
}
diff --git a/services/camera/libcameraservice/api1/Camera2Client.h b/services/camera/libcameraservice/api1/Camera2Client.h
index fe12690..2cb7af0 100644
--- a/services/camera/libcameraservice/api1/Camera2Client.h
+++ b/services/camera/libcameraservice/api1/Camera2Client.h
@@ -22,11 +22,7 @@
#include "common/Camera2ClientBase.h"
#include "api1/client2/Parameters.h"
#include "api1/client2/FrameProcessor.h"
-//#include "api1/client2/StreamingProcessor.h"
-//#include "api1/client2/JpegProcessor.h"
-//#include "api1/client2/ZslProcessor.h"
-//#include "api1/client2/CaptureSequencer.h"
-//#include "api1/client2/CallbackProcessor.h"
+#include <media/RingBuffer.h>
namespace android {
@@ -85,7 +81,7 @@
virtual status_t setVideoTarget(const sp<IGraphicBufferProducer>& bufferProducer);
virtual status_t setAudioRestriction(int mode);
virtual int32_t getGlobalAudioRestriction();
- virtual status_t setRotateAndCropOverride(uint8_t rotateAndCrop);
+ virtual status_t setRotateAndCropOverride(uint8_t rotateAndCrop, bool fromHal = false);
virtual status_t setAutoframingOverride(uint8_t autoframingMode);
virtual bool supportsCameraMute();
@@ -263,8 +259,8 @@
mutable Mutex mLatestRequestMutex;
Condition mLatestRequestSignal;
- int32_t mLatestRequestId = -1;
- int32_t mLatestFailedRequestId = -1;
+ static constexpr size_t kMaxRequestIds = BufferQueueDefs::NUM_BUFFER_SLOTS;
+ RingBuffer<int32_t> mLatestRequestIds, mLatestFailedRequestIds;
status_t waitUntilRequestIdApplied(int32_t requestId, nsecs_t timeout);
status_t waitUntilCurrentRequestIdLocked();
};
diff --git a/services/camera/libcameraservice/api2/CameraDeviceClient.cpp b/services/camera/libcameraservice/api2/CameraDeviceClient.cpp
index c60f327..c27fc90 100644
--- a/services/camera/libcameraservice/api2/CameraDeviceClient.cpp
+++ b/services/camera/libcameraservice/api2/CameraDeviceClient.cpp
@@ -99,7 +99,8 @@
uid_t clientUid,
int servicePid,
bool overrideForPerfClass,
- bool overrideToPortrait) :
+ bool overrideToPortrait,
+ const std::string& originalCameraId) :
Camera2ClientBase(cameraService, remoteCallback, cameraServiceProxyWrapper, clientPackageName,
systemNativeClient, clientFeatureId, cameraId, /*API1 camera ID*/ -1, cameraFacing,
sensorOrientation, clientPid, clientUid, servicePid, overrideForPerfClass,
@@ -107,8 +108,8 @@
mInputStream(),
mStreamingRequestId(REQUEST_ID_NONE),
mRequestIdCounter(0),
- mOverrideForPerfClass(overrideForPerfClass) {
-
+ mOverrideForPerfClass(overrideForPerfClass),
+ mOriginalCameraId(originalCameraId) {
ATRACE_CALL();
ALOGI("CameraDeviceClient %s: Opened", cameraId.c_str());
}
@@ -323,7 +324,7 @@
//The first capture settings should always match the logical camera id
const std::string &logicalId = request.mPhysicalCameraSettings.begin()->id;
- if (mDevice->getId() != logicalId) {
+ if (mDevice->getId() != logicalId && mOriginalCameraId != logicalId) {
ALOGE("%s: Camera %s: Invalid camera request settings.", __FUNCTION__,
mCameraIdStr.c_str());
return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT,
@@ -438,6 +439,7 @@
CameraDeviceBase::PhysicalCameraSettingsList physicalSettingsList;
for (const auto& it : request.mPhysicalCameraSettings) {
+ std::string resolvedId = (mOriginalCameraId == it.id) ? mDevice->getId() : it.id;
if (it.settings.isEmpty()) {
ALOGE("%s: Camera %s: Sent empty metadata packet. Rejecting request.",
__FUNCTION__, mCameraIdStr.c_str());
@@ -448,7 +450,7 @@
// Check whether the physical / logical stream has settings
// consistent with the sensor pixel mode(s) it was configured with.
// mCameraIdToStreamSet will only have ids that are high resolution
- const auto streamIdSetIt = mHighResolutionCameraIdToStreamIdSet.find(it.id);
+ const auto streamIdSetIt = mHighResolutionCameraIdToStreamIdSet.find(resolvedId);
if (streamIdSetIt != mHighResolutionCameraIdToStreamIdSet.end()) {
std::list<int> streamIdsUsedInRequest = getIntersection(streamIdSetIt->second,
outputStreamIds);
@@ -456,26 +458,25 @@
!isSensorPixelModeConsistent(streamIdsUsedInRequest, it.settings)) {
ALOGE("%s: Camera %s: Request settings CONTROL_SENSOR_PIXEL_MODE not "
"consistent with configured streams. Rejecting request.",
- __FUNCTION__, it.id.c_str());
+ __FUNCTION__, resolvedId.c_str());
return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT,
"Request settings CONTROL_SENSOR_PIXEL_MODE are not consistent with "
"streams configured");
}
}
- const std::string &physicalId = it.id;
bool hasTestPatternModePhysicalKey = std::find(mSupportedPhysicalRequestKeys.begin(),
mSupportedPhysicalRequestKeys.end(), ANDROID_SENSOR_TEST_PATTERN_MODE) !=
mSupportedPhysicalRequestKeys.end();
bool hasTestPatternDataPhysicalKey = std::find(mSupportedPhysicalRequestKeys.begin(),
mSupportedPhysicalRequestKeys.end(), ANDROID_SENSOR_TEST_PATTERN_DATA) !=
mSupportedPhysicalRequestKeys.end();
- if (physicalId != mDevice->getId()) {
+ if (resolvedId != mDevice->getId()) {
auto found = std::find(requestedPhysicalIds.begin(), requestedPhysicalIds.end(),
- it.id);
+ resolvedId);
if (found == requestedPhysicalIds.end()) {
ALOGE("%s: Camera %s: Physical camera id: %s not part of attached outputs.",
- __FUNCTION__, mCameraIdStr.c_str(), physicalId.c_str());
+ __FUNCTION__, mCameraIdStr.c_str(), resolvedId.c_str());
return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT,
"Invalid physical camera id");
}
@@ -495,11 +496,11 @@
}
}
- physicalSettingsList.push_back({it.id, filteredParams,
+ physicalSettingsList.push_back({resolvedId, filteredParams,
hasTestPatternModePhysicalKey, hasTestPatternDataPhysicalKey});
}
} else {
- physicalSettingsList.push_back({it.id, it.settings});
+ physicalSettingsList.push_back({resolvedId, it.settings});
}
}
@@ -1760,11 +1761,11 @@
return mDevice->setCameraServiceWatchdog(enabled);
}
-status_t CameraDeviceClient::setRotateAndCropOverride(uint8_t rotateAndCrop) {
+status_t CameraDeviceClient::setRotateAndCropOverride(uint8_t rotateAndCrop, bool fromHal) {
if (rotateAndCrop > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
return mDevice->setRotateAndCropAutoBehavior(
- static_cast<camera_metadata_enum_android_scaler_rotate_and_crop_t>(rotateAndCrop));
+ static_cast<camera_metadata_enum_android_scaler_rotate_and_crop_t>(rotateAndCrop), fromHal);
}
status_t CameraDeviceClient::setAutoframingOverride(uint8_t autoframingValue) {
diff --git a/services/camera/libcameraservice/api2/CameraDeviceClient.h b/services/camera/libcameraservice/api2/CameraDeviceClient.h
index 45c904a..1c19dbd 100644
--- a/services/camera/libcameraservice/api2/CameraDeviceClient.h
+++ b/services/camera/libcameraservice/api2/CameraDeviceClient.h
@@ -191,13 +191,15 @@
uid_t clientUid,
int servicePid,
bool overrideForPerfClass,
- bool overrideToPortrait);
+ bool overrideToPortrait,
+ const std::string& originalCameraId);
virtual ~CameraDeviceClient();
virtual status_t initialize(sp<CameraProviderManager> manager,
const std::string& monitorTags) override;
- virtual status_t setRotateAndCropOverride(uint8_t rotateAndCrop) override;
+ virtual status_t setRotateAndCropOverride(uint8_t rotateAndCrop,
+ bool fromHal = false) override;
virtual status_t setAutoframingOverride(uint8_t autoframingValue) override;
@@ -368,6 +370,9 @@
std::string mUserTag;
// The last set video stabilization mode
int mVideoStabilizationMode = -1;
+
+ // This only exists in case of camera ID Remapping.
+ std::string mOriginalCameraId;
};
}; // namespace android
diff --git a/services/camera/libcameraservice/api2/CameraOfflineSessionClient.cpp b/services/camera/libcameraservice/api2/CameraOfflineSessionClient.cpp
index 99bdb0e..4ed352d 100644
--- a/services/camera/libcameraservice/api2/CameraOfflineSessionClient.cpp
+++ b/services/camera/libcameraservice/api2/CameraOfflineSessionClient.cpp
@@ -80,7 +80,8 @@
return OK;
}
-status_t CameraOfflineSessionClient::setRotateAndCropOverride(uint8_t /*rotateAndCrop*/) {
+status_t CameraOfflineSessionClient::setRotateAndCropOverride(uint8_t /*rotateAndCrop*/,
+ bool /*fromHal*/) {
// Since we're not submitting more capture requests, changes to rotateAndCrop override
// make no difference.
return OK;
diff --git a/services/camera/libcameraservice/api2/CameraOfflineSessionClient.h b/services/camera/libcameraservice/api2/CameraOfflineSessionClient.h
index 70bad03..8aad4e9 100644
--- a/services/camera/libcameraservice/api2/CameraOfflineSessionClient.h
+++ b/services/camera/libcameraservice/api2/CameraOfflineSessionClient.h
@@ -80,7 +80,7 @@
status_t initialize(sp<CameraProviderManager> /*manager*/,
const std::string& /*monitorTags*/) override;
- status_t setRotateAndCropOverride(uint8_t rotateAndCrop) override;
+ status_t setRotateAndCropOverride(uint8_t rotateAndCrop, bool fromHal = false) override;
status_t setAutoframingOverride(uint8_t autoframingValue) override;
diff --git a/services/camera/libcameraservice/common/Camera2ClientBase.cpp b/services/camera/libcameraservice/common/Camera2ClientBase.cpp
index a54ba9b..43eb181 100644
--- a/services/camera/libcameraservice/common/Camera2ClientBase.cpp
+++ b/services/camera/libcameraservice/common/Camera2ClientBase.cpp
@@ -377,7 +377,8 @@
rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
}
- static_cast<TClientBase *>(this)->setRotateAndCropOverride(rotateAndCropMode);
+ static_cast<TClientBase *>(this)->setRotateAndCropOverride(rotateAndCropMode,
+ /*fromHal*/ true);
}
}
diff --git a/services/camera/libcameraservice/common/CameraDeviceBase.h b/services/camera/libcameraservice/common/CameraDeviceBase.h
index 017da0f..01199af 100644
--- a/services/camera/libcameraservice/common/CameraDeviceBase.h
+++ b/services/camera/libcameraservice/common/CameraDeviceBase.h
@@ -444,7 +444,8 @@
* and defaults to NONE.
*/
virtual status_t setRotateAndCropAutoBehavior(
- camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) = 0;
+ camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue,
+ bool fromHal = false) = 0;
/**
* Set the current behavior for the AUTOFRAMING control when in AUTO.
diff --git a/services/camera/libcameraservice/device3/Camera3Device.cpp b/services/camera/libcameraservice/device3/Camera3Device.cpp
index 7db3787..ee4d855 100644
--- a/services/camera/libcameraservice/device3/Camera3Device.cpp
+++ b/services/camera/libcameraservice/device3/Camera3Device.cpp
@@ -70,6 +70,7 @@
#include "utils/TraceHFR.h"
#include <algorithm>
+#include <optional>
#include <tuple>
using namespace android::camera3;
@@ -3038,6 +3039,7 @@
mPrevTriggers(0),
mFrameNumber(0),
mLatestRequestId(NAME_NOT_FOUND),
+ mLatestFailedRequestId(NAME_NOT_FOUND),
mCurrentAfTriggerId(0),
mCurrentPreCaptureTriggerId(0),
mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
@@ -3288,7 +3290,7 @@
ATRACE_CALL();
Mutex::Autolock l(mLatestRequestMutex);
status_t res;
- while (mLatestRequestId != requestId) {
+ while (mLatestRequestId != requestId && mLatestFailedRequestId != requestId) {
nsecs_t startTime = systemTime();
res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
@@ -4017,8 +4019,11 @@
sp<Camera3Device> parent = mParent.promote();
if (parent != nullptr) {
const std::string& streamCameraId = outputStream->getPhysicalCameraId();
+ // Consider the case where clients are sending a single logical camera request
+ // to physical output/outputs
+ bool singleRequest = captureRequest->mSettingsList.size() == 1;
for (const auto& settings : captureRequest->mSettingsList) {
- if ((streamCameraId.empty() &&
+ if (((streamCameraId.empty() || singleRequest) &&
parent->getId() == settings.cameraId) ||
streamCameraId == settings.cameraId) {
outputStream->fireBufferRequestForFrameNumber(
@@ -4362,6 +4367,12 @@
hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
captureRequest->mResultExtras);
}
+ {
+ Mutex::Autolock al(mLatestRequestMutex);
+
+ mLatestFailedRequestId = captureRequest->mResultExtras.requestId;
+ mLatestRequestSignal.signal();
+ }
}
// Remove yet-to-be submitted inflight request from inflightMap
@@ -5392,9 +5403,13 @@
}
status_t Camera3Device::setRotateAndCropAutoBehavior(
- camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
+ camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue, bool fromHal) {
ATRACE_CALL();
- Mutex::Autolock il(mInterfaceLock);
+ // We shouldn't hold mInterfaceLock when called as an effect of a HAL
+ // callback since this can lead to a deadlock : b/299348355.
+ // mLock still protects state.
+ std::optional<Mutex::Autolock> maybeMutex =
+ fromHal ? std::nullopt : std::optional<Mutex::Autolock>(mInterfaceLock);
Mutex::Autolock l(mLock);
if (mRequestThread == nullptr) {
return INVALID_OPERATION;
diff --git a/services/camera/libcameraservice/device3/Camera3Device.h b/services/camera/libcameraservice/device3/Camera3Device.h
index dfa3b19..b36a60a 100644
--- a/services/camera/libcameraservice/device3/Camera3Device.h
+++ b/services/camera/libcameraservice/device3/Camera3Device.h
@@ -275,7 +275,7 @@
* and defaults to NONE.
*/
status_t setRotateAndCropAutoBehavior(
- camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue);
+ camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue, bool fromHal);
/**
* Set the current behavior for the AUTOFRAMING control when in AUTO.
@@ -1151,6 +1151,7 @@
Condition mLatestRequestSignal;
// android.request.id for latest process_capture_request
int32_t mLatestRequestId;
+ int32_t mLatestFailedRequestId;
CameraMetadata mLatestRequest;
std::unordered_map<std::string, CameraMetadata> mLatestPhysicalRequest;