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