1 /*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "AAudioServiceEndpoint"
18 //#define LOG_NDEBUG 0
19 #include <utils/Log.h>
20
21 #include <algorithm>
22 #include <assert.h>
23 #include <map>
24 #include <mutex>
25 #include <sstream>
26 #include <vector>
27
28 #include <utils/Singleton.h>
29
30
31 #include "core/AudioStreamBuilder.h"
32
33 #include "AAudioEndpointManager.h"
34 #include "AAudioClientTracker.h"
35 #include "AAudioServiceEndpoint.h"
36 #include "AAudioServiceStreamShared.h"
37
38 using namespace android; // TODO just import names needed
39 using namespace aaudio; // TODO just import names needed
40
~AAudioServiceEndpoint()41 AAudioServiceEndpoint::~AAudioServiceEndpoint() {
42 ALOGD("%s() called", __func__);
43 }
44
dump() const45 std::string AAudioServiceEndpoint::dump() const NO_THREAD_SAFETY_ANALYSIS {
46 std::stringstream result;
47
48 const bool isLocked = AAudio_tryUntilTrue(
49 [this]()->bool { return mLockStreams.try_lock(); } /* f */,
50 50 /* times */,
51 20 /* sleepMs */);
52 if (!isLocked) {
53 result << "AAudioServiceEndpoint may be deadlocked\n";
54 }
55
56 result << " Direction: " << ((getDirection() == AAUDIO_DIRECTION_OUTPUT)
57 ? "OUTPUT" : "INPUT") << "\n";
58 result << " Requested Device Id: " << mRequestedDeviceId << "\n";
59 result << " Device Id: " << getDeviceId() << "\n";
60 result << " Sample Rate: " << getSampleRate() << "\n";
61 result << " Channel Count: " << getSamplesPerFrame() << "\n";
62 result << " Channel Mask: 0x" << std::hex << getChannelMask() << std::dec << "\n";
63 result << " Format: " << getFormat()
64 << " (" << audio_format_to_string(getFormat()) << ")\n";
65 result << " Frames Per Burst: " << mFramesPerBurst << "\n";
66 result << " Usage: " << getUsage() << "\n";
67 result << " ContentType: " << getContentType() << "\n";
68 result << " InputPreset: " << getInputPreset() << "\n";
69 result << " Reference Count: " << mOpenCount << "\n";
70 result << " Session Id: " << getSessionId() << "\n";
71 result << " Privacy Sensitive: " << isPrivacySensitive() << "\n";
72 result << " Hardware Channel Count:" << getHardwareSamplesPerFrame() << "\n";
73 result << " Hardware Format: " << getHardwareFormat() << " ("
74 << audio_format_to_string(getHardwareFormat()) << ")\n";
75 result << " Hardware Sample Rate: " << getHardwareSampleRate() << "\n";
76 result << " Connected: " << mConnected.load() << "\n";
77 result << " Registered Streams:" << "\n";
78 result << AAudioServiceStreamShared::dumpHeader() << "\n";
79 for (const auto& stream : mRegisteredStreams) {
80 result << stream->dump() << "\n";
81 }
82
83 if (isLocked) {
84 mLockStreams.unlock();
85 }
86 return result.str();
87 }
88
89 // @return true if stream found
isStreamRegistered(audio_port_handle_t portHandle)90 bool AAudioServiceEndpoint::isStreamRegistered(audio_port_handle_t portHandle) {
91 const std::lock_guard<std::mutex> lock(mLockStreams);
92 for (const auto& stream : mRegisteredStreams) {
93 if (stream->getPortHandle() == portHandle) {
94 return true;
95 }
96 }
97 return false;
98 }
99
100 std::vector<android::sp<AAudioServiceStreamBase>>
disconnectRegisteredStreams()101 AAudioServiceEndpoint::disconnectRegisteredStreams() {
102 std::vector<android::sp<AAudioServiceStreamBase>> streamsDisconnected;
103 {
104 const std::lock_guard<std::mutex> lock(mLockStreams);
105 mRegisteredStreams.swap(streamsDisconnected);
106 }
107 mConnected.store(false);
108 // We need to stop all the streams before we disconnect them.
109 // Otherwise there is a race condition where the first disconnected app
110 // tries to reopen a stream as MMAP but is blocked by the second stream,
111 // which hasn't stopped yet. Then the first app ends up with a Legacy stream.
112 for (const auto &stream : streamsDisconnected) {
113 ALOGD("%s() - stop(), port = %d", __func__, stream->getPortHandle());
114 stream->stop();
115 }
116 for (const auto &stream : streamsDisconnected) {
117 ALOGD("%s() - disconnect(), port = %d", __func__, stream->getPortHandle());
118 stream->disconnect();
119 }
120 return streamsDisconnected;
121 }
122
releaseRegisteredStreams()123 void AAudioServiceEndpoint::releaseRegisteredStreams() {
124 // List of streams to be closed after we disconnect everything.
125 const std::vector<android::sp<AAudioServiceStreamBase>> streamsToClose
126 = disconnectRegisteredStreams();
127
128 // Close outside the lock to avoid recursive locks.
129 AAudioService *aaudioService = AAudioClientTracker::getInstance().getAAudioService();
130 for (const auto& serviceStream : streamsToClose) {
131 ALOGD("%s() - close stream 0x%08X", __func__, serviceStream->getHandle());
132 aaudioService->closeStream(serviceStream);
133 }
134 }
135
registerStream(const sp<AAudioServiceStreamBase> & stream)136 aaudio_result_t AAudioServiceEndpoint::registerStream(const sp<AAudioServiceStreamBase>& stream) {
137 const std::lock_guard<std::mutex> lock(mLockStreams);
138 mRegisteredStreams.push_back(stream);
139 return AAUDIO_OK;
140 }
141
unregisterStream(const sp<AAudioServiceStreamBase> & stream)142 aaudio_result_t AAudioServiceEndpoint::unregisterStream(const sp<AAudioServiceStreamBase>& stream) {
143 const std::lock_guard<std::mutex> lock(mLockStreams);
144 mRegisteredStreams.erase(std::remove(
145 mRegisteredStreams.begin(), mRegisteredStreams.end(), stream),
146 mRegisteredStreams.end());
147 return AAUDIO_OK;
148 }
149
matches(const AAudioStreamConfiguration & configuration)150 bool AAudioServiceEndpoint::matches(const AAudioStreamConfiguration& configuration) {
151 if (!mConnected.load()) {
152 return false; // Only use an endpoint if it is connected to a device.
153 }
154 if (configuration.getDirection() != getDirection()) {
155 return false;
156 }
157 if (configuration.getDeviceId() != AAUDIO_UNSPECIFIED &&
158 configuration.getDeviceId() != getDeviceId()) {
159 return false;
160 }
161 if (configuration.getSessionId() != AAUDIO_SESSION_ID_ALLOCATE &&
162 configuration.getSessionId() != getSessionId()) {
163 return false;
164 }
165 if (configuration.getSampleRate() != AAUDIO_UNSPECIFIED &&
166 configuration.getSampleRate() != getSampleRate()) {
167 return false;
168 }
169 if (configuration.getSamplesPerFrame() != AAUDIO_UNSPECIFIED &&
170 configuration.getSamplesPerFrame() != getSamplesPerFrame()) {
171 return false;
172 }
173 if (configuration.getChannelMask() != AAUDIO_UNSPECIFIED &&
174 configuration.getChannelMask() != getChannelMask()) {
175 return false;
176 }
177 return true;
178 }
179
180 // static
getAudioAttributesFrom(const AAudioStreamParameters * params)181 audio_attributes_t AAudioServiceEndpoint::getAudioAttributesFrom(
182 const AAudioStreamParameters *params) {
183 if (params == nullptr) {
184 return {};
185 }
186 const aaudio_direction_t direction = params->getDirection();
187
188 const audio_content_type_t contentType =
189 AAudioConvert_contentTypeToInternal(params->getContentType());
190 // Usage only used for OUTPUT
191 const audio_usage_t usage = (direction == AAUDIO_DIRECTION_OUTPUT)
192 ? AAudioConvert_usageToInternal(params->getUsage())
193 : AUDIO_USAGE_UNKNOWN;
194 const audio_source_t source = (direction == AAUDIO_DIRECTION_INPUT)
195 ? AAudioConvert_inputPresetToAudioSource(params->getInputPreset())
196 : AUDIO_SOURCE_DEFAULT;
197 audio_flags_mask_t flags;
198 if (direction == AAUDIO_DIRECTION_OUTPUT) {
199 flags = AAudio_computeAudioFlagsMask(
200 params->getAllowedCapturePolicy(),
201 params->getSpatializationBehavior(),
202 params->isContentSpatialized(),
203 AUDIO_OUTPUT_FLAG_FAST);
204 } else {
205 flags = static_cast<audio_flags_mask_t>(AUDIO_FLAG_LOW_LATENCY
206 | AAudioConvert_privacySensitiveToAudioFlagsMask(params->isPrivacySensitive()));
207 }
208 return {
209 .content_type = contentType,
210 .usage = usage,
211 .source = source,
212 .flags = flags,
213 .tags = "" };
214 }
215