• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 << "    Connected:            " << mConnected.load() << "\n";
73     result << "    Registered Streams:" << "\n";
74     result << AAudioServiceStreamShared::dumpHeader() << "\n";
75     for (const auto& stream : mRegisteredStreams) {
76         result << stream->dump() << "\n";
77     }
78 
79     if (isLocked) {
80         mLockStreams.unlock();
81     }
82     return result.str();
83 }
84 
85 // @return true if stream found
isStreamRegistered(audio_port_handle_t portHandle)86 bool AAudioServiceEndpoint::isStreamRegistered(audio_port_handle_t portHandle) {
87     std::lock_guard<std::mutex> lock(mLockStreams);
88     for (const auto& stream : mRegisteredStreams) {
89         if (stream->getPortHandle() == portHandle) {
90             return true;
91         }
92     }
93     return false;
94 }
95 
96 std::vector<android::sp<AAudioServiceStreamBase>>
disconnectRegisteredStreams()97         AAudioServiceEndpoint::disconnectRegisteredStreams() {
98     std::vector<android::sp<AAudioServiceStreamBase>> streamsDisconnected;
99     {
100         std::lock_guard<std::mutex> lock(mLockStreams);
101         mRegisteredStreams.swap(streamsDisconnected);
102     }
103     mConnected.store(false);
104     // We need to stop all the streams before we disconnect them.
105     // Otherwise there is a race condition where the first disconnected app
106     // tries to reopen a stream as MMAP but is blocked by the second stream,
107     // which hasn't stopped yet. Then the first app ends up with a Legacy stream.
108     for (const auto &stream : streamsDisconnected) {
109         ALOGD("%s() - stop(), port = %d", __func__, stream->getPortHandle());
110         stream->stop();
111     }
112     for (const auto &stream : streamsDisconnected) {
113         ALOGD("%s() - disconnect(), port = %d", __func__, stream->getPortHandle());
114         stream->disconnect();
115     }
116     return streamsDisconnected;
117 }
118 
releaseRegisteredStreams()119 void AAudioServiceEndpoint::releaseRegisteredStreams() {
120     // List of streams to be closed after we disconnect everything.
121     std::vector<android::sp<AAudioServiceStreamBase>> streamsToClose
122             = disconnectRegisteredStreams();
123 
124     // Close outside the lock to avoid recursive locks.
125     AAudioService *aaudioService = AAudioClientTracker::getInstance().getAAudioService();
126     for (const auto& serviceStream : streamsToClose) {
127         ALOGD("%s() - close stream 0x%08X", __func__, serviceStream->getHandle());
128         aaudioService->closeStream(serviceStream);
129     }
130 }
131 
registerStream(sp<AAudioServiceStreamBase> stream)132 aaudio_result_t AAudioServiceEndpoint::registerStream(sp<AAudioServiceStreamBase>stream) {
133     std::lock_guard<std::mutex> lock(mLockStreams);
134     mRegisteredStreams.push_back(stream);
135     return AAUDIO_OK;
136 }
137 
unregisterStream(sp<AAudioServiceStreamBase> stream)138 aaudio_result_t AAudioServiceEndpoint::unregisterStream(sp<AAudioServiceStreamBase>stream) {
139     std::lock_guard<std::mutex> lock(mLockStreams);
140     mRegisteredStreams.erase(std::remove(
141             mRegisteredStreams.begin(), mRegisteredStreams.end(), stream),
142                              mRegisteredStreams.end());
143     return AAUDIO_OK;
144 }
145 
matches(const AAudioStreamConfiguration & configuration)146 bool AAudioServiceEndpoint::matches(const AAudioStreamConfiguration& configuration) {
147     if (!mConnected.load()) {
148         return false; // Only use an endpoint if it is connected to a device.
149     }
150     if (configuration.getDirection() != getDirection()) {
151         return false;
152     }
153     if (configuration.getDeviceId() != AAUDIO_UNSPECIFIED &&
154         configuration.getDeviceId() != getDeviceId()) {
155         return false;
156     }
157     if (configuration.getSessionId() != AAUDIO_SESSION_ID_ALLOCATE &&
158         configuration.getSessionId() != getSessionId()) {
159         return false;
160     }
161     if (configuration.getSampleRate() != AAUDIO_UNSPECIFIED &&
162         configuration.getSampleRate() != getSampleRate()) {
163         return false;
164     }
165     if (configuration.getSamplesPerFrame() != AAUDIO_UNSPECIFIED &&
166         configuration.getSamplesPerFrame() != getSamplesPerFrame()) {
167         return false;
168     }
169     if (configuration.getChannelMask() != AAUDIO_UNSPECIFIED &&
170         configuration.getChannelMask() != getChannelMask()) {
171         return false;
172     }
173     return true;
174 }
175 
176 // static
getAudioAttributesFrom(const AAudioStreamParameters * params)177 audio_attributes_t AAudioServiceEndpoint::getAudioAttributesFrom(
178         const AAudioStreamParameters *params) {
179     if (params == nullptr) {
180         return {};
181     }
182     const aaudio_direction_t direction = params->getDirection();
183 
184     const audio_content_type_t contentType =
185             AAudioConvert_contentTypeToInternal(params->getContentType());
186     // Usage only used for OUTPUT
187     const audio_usage_t usage = (direction == AAUDIO_DIRECTION_OUTPUT)
188             ? AAudioConvert_usageToInternal(params->getUsage())
189             : AUDIO_USAGE_UNKNOWN;
190     const audio_source_t source = (direction == AAUDIO_DIRECTION_INPUT)
191             ? AAudioConvert_inputPresetToAudioSource(params->getInputPreset())
192             : AUDIO_SOURCE_DEFAULT;
193     audio_flags_mask_t flags;
194     if (direction == AAUDIO_DIRECTION_OUTPUT) {
195         flags = static_cast<audio_flags_mask_t>(AUDIO_FLAG_LOW_LATENCY
196                 | AAudioConvert_allowCapturePolicyToAudioFlagsMask(
197                         params->getAllowedCapturePolicy(),
198                         params->getSpatializationBehavior(),
199                         params->isContentSpatialized()));
200     } else {
201         flags = static_cast<audio_flags_mask_t>(AUDIO_FLAG_LOW_LATENCY
202                 | AAudioConvert_privacySensitiveToAudioFlagsMask(params->isPrivacySensitive()));
203     }
204     return {
205             .content_type = contentType,
206             .usage = usage,
207             .source = source,
208             .flags = flags,
209             .tags = "" };
210 }
211