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
18 #define LOG_TAG "AAudioServiceEndpointShared"
19 //#define LOG_NDEBUG 0
20 #include <utils/Log.h>
21
22 #include <iomanip>
23 #include <iostream>
24 #include <sstream>
25
26 #include "binding/AAudioServiceMessage.h"
27 #include "client/AudioStreamInternal.h"
28 #include "client/AudioStreamInternalPlay.h"
29 #include "core/AudioStreamBuilder.h"
30
31 #include "AAudioServiceEndpointShared.h"
32 #include "AAudioServiceStreamShared.h"
33 #include "AAudioServiceStreamMMAP.h"
34 #include "AAudioMixer.h"
35 #include "AAudioService.h"
36
37 using namespace android;
38 using namespace aaudio;
39
40 // This is the maximum size in frames. The effective size can be tuned smaller at runtime.
41 #define DEFAULT_BUFFER_CAPACITY (48 * 8)
42
AAudioServiceEndpointShared(AudioStreamInternal * streamInternal)43 AAudioServiceEndpointShared::AAudioServiceEndpointShared(AudioStreamInternal *streamInternal)
44 : mStreamInternal(streamInternal) {}
45
dump() const46 std::string AAudioServiceEndpointShared::dump() const {
47 std::stringstream result;
48
49 result << " SHARED: sharing exclusive stream with handle = 0x"
50 << std::setfill('0') << std::setw(8)
51 << std::hex << mStreamInternal->getServiceHandle()
52 << std::dec << std::setfill(' ');
53 result << ", XRuns = " << mStreamInternal->getXRunCount();
54 result << "\n";
55 result << " Running Stream Count: " << mRunningStreamCount << "\n";
56
57 result << AAudioServiceEndpoint::dump();
58 return result.str();
59 }
60
61 // Share an AudioStreamInternal.
open(const aaudio::AAudioStreamRequest & request)62 aaudio_result_t AAudioServiceEndpointShared::open(const aaudio::AAudioStreamRequest &request) {
63 aaudio_result_t result = AAUDIO_OK;
64 const AAudioStreamConfiguration &configuration = request.getConstantConfiguration();
65
66 copyFrom(configuration);
67 mRequestedDeviceId = android::getFirstDeviceId(configuration.getDeviceIds());
68
69 AudioStreamBuilder builder;
70 builder.copyFrom(configuration);
71
72 builder.setSharingMode(AAUDIO_SHARING_MODE_EXCLUSIVE);
73 // Don't fall back to SHARED because that would cause recursion.
74 builder.setSharingModeMatchRequired(true);
75
76 builder.setBufferCapacity(DEFAULT_BUFFER_CAPACITY);
77
78 // Each shared stream will use its own SRC.
79 builder.setSampleRate(AAUDIO_UNSPECIFIED);
80
81 result = mStreamInternal->open(builder);
82
83 setSampleRate(mStreamInternal->getSampleRate());
84 setChannelMask(mStreamInternal->getChannelMask());
85 setDeviceIds(mStreamInternal->getDeviceIds());
86 setSessionId(mStreamInternal->getSessionId());
87 setFormat(AUDIO_FORMAT_PCM_FLOAT); // force for mixer
88 setHardwareSampleRate(mStreamInternal->getHardwareSampleRate());
89 setHardwareFormat(mStreamInternal->getHardwareFormat());
90 setHardwareSamplesPerFrame(mStreamInternal->getHardwareSamplesPerFrame());
91 mFramesPerBurst = mStreamInternal->getFramesPerBurst();
92
93 return result;
94 }
95
close()96 void AAudioServiceEndpointShared::close() {
97 stopSharingThread();
98 getStreamInternal()->safeReleaseClose();
99 }
100
101 // Glue between C and C++ callbacks.
aaudio_endpoint_thread_proc(void * arg)102 static void *aaudio_endpoint_thread_proc(void *arg) {
103 assert(arg != nullptr);
104 ALOGD("%s() called", __func__);
105
106 // Prevent the stream from being deleted while being used.
107 // This is just for extra safety. It is probably not needed because
108 // this callback should be joined before the stream is closed.
109 auto endpointPtr = static_cast<AAudioServiceEndpointShared *>(arg);
110 android::sp<AAudioServiceEndpointShared> endpoint(endpointPtr);
111 // Balance the incStrong() in startSharingThread_l().
112 endpoint->decStrong(nullptr);
113
114 void *result = endpoint->callbackLoop();
115 // Close now so that the HW resource is freed and we can open a new device.
116 if (!endpoint->isConnected()) {
117 ALOGD("%s() call safeReleaseCloseFromCallback()", __func__);
118 // Release and close under a lock with no check for callback collisions.
119 endpoint->getStreamInternal()->safeReleaseCloseInternal();
120 }
121
122 return result;
123 }
124
startSharingThread_l()125 aaudio_result_t aaudio::AAudioServiceEndpointShared::startSharingThread_l() {
126 // Launch the callback loop thread.
127 int64_t periodNanos = getStreamInternal()->getFramesPerBurst()
128 * AAUDIO_NANOS_PER_SECOND
129 / getSampleRate();
130 mCallbackEnabled.store(true);
131 // Prevent this object from getting deleted before the thread has a chance to create
132 // its strong pointer. Assume the thread will call decStrong().
133 this->incStrong(nullptr);
134 aaudio_result_t result = getStreamInternal()->createThread(periodNanos,
135 aaudio_endpoint_thread_proc,
136 this);
137 if (result != AAUDIO_OK) {
138 this->decStrong(nullptr); // Because the thread won't do it.
139 }
140 return result;
141 }
142
stopSharingThread()143 aaudio_result_t aaudio::AAudioServiceEndpointShared::stopSharingThread() {
144 mCallbackEnabled.store(false);
145 return getStreamInternal()->joinThread(nullptr);
146 }
147
startStream(sp<AAudioServiceStreamBase> sharedStream,audio_port_handle_t * clientHandle)148 aaudio_result_t AAudioServiceEndpointShared::startStream(
149 sp<AAudioServiceStreamBase> sharedStream,
150 audio_port_handle_t *clientHandle)
151 NO_THREAD_SAFETY_ANALYSIS {
152 aaudio_result_t result = AAUDIO_OK;
153
154 {
155 std::lock_guard<std::mutex> lock(mLockStreams);
156 if (++mRunningStreamCount == 1) { // atomic
157 result = getStreamInternal()->systemStart();
158 if (result != AAUDIO_OK) {
159 --mRunningStreamCount;
160 } else {
161 result = startSharingThread_l();
162 if (result != AAUDIO_OK) {
163 getStreamInternal()->systemStopFromApp();
164 --mRunningStreamCount;
165 }
166 }
167 }
168 }
169
170 if (result == AAUDIO_OK) {
171 const audio_attributes_t attr = getAudioAttributesFrom(sharedStream.get());
172 result = getStreamInternal()->startClient(
173 sharedStream->getAudioClient(), &attr, clientHandle);
174 if (result != AAUDIO_OK) {
175 if (--mRunningStreamCount == 0) { // atomic
176 stopSharingThread();
177 getStreamInternal()->systemStopFromApp();
178 }
179 }
180 }
181
182 return result;
183 }
184
stopStream(sp<AAudioServiceStreamBase>,audio_port_handle_t clientHandle)185 aaudio_result_t AAudioServiceEndpointShared::stopStream(
186 sp<AAudioServiceStreamBase> /*sharedStream*/, audio_port_handle_t clientHandle) {
187 // Ignore result.
188 (void) getStreamInternal()->stopClient(clientHandle);
189
190 if (--mRunningStreamCount == 0) { // atomic
191 stopSharingThread(); // the sharing thread locks mLockStreams
192 getStreamInternal()->systemStopFromApp();
193 }
194 return AAUDIO_OK;
195 }
196
197 // Get timestamp that was written by the real-time service thread, eg. mixer.
getFreeRunningPosition(int64_t * positionFrames,int64_t * timeNanos)198 aaudio_result_t AAudioServiceEndpointShared::getFreeRunningPosition(int64_t *positionFrames,
199 int64_t *timeNanos) {
200 if (mAtomicEndpointTimestamp.isValid()) {
201 Timestamp timestamp = mAtomicEndpointTimestamp.read();
202 *positionFrames = timestamp.getPosition();
203 *timeNanos = timestamp.getNanoseconds();
204 return AAUDIO_OK;
205 } else {
206 return AAUDIO_ERROR_UNAVAILABLE;
207 }
208 }
209
getTimestamp(int64_t * positionFrames,int64_t * timeNanos)210 aaudio_result_t AAudioServiceEndpointShared::getTimestamp(int64_t *positionFrames,
211 int64_t *timeNanos) {
212 aaudio_result_t result = mStreamInternal->getTimestamp(CLOCK_MONOTONIC, positionFrames, timeNanos);
213 if (result == AAUDIO_ERROR_INVALID_STATE) {
214 // getTimestamp() can return AAUDIO_ERROR_INVALID_STATE if the stream has
215 // not completely started. This can cause a race condition that kills the
216 // timestamp service thread. So we reduce the error to a less serious one
217 // that allows the timestamp thread to continue.
218 result = AAUDIO_ERROR_UNAVAILABLE;
219 }
220 return result;
221 }
222
handleDisconnectRegisteredStreamsAsync()223 void AAudioServiceEndpointShared::handleDisconnectRegisteredStreamsAsync() {
224 android::sp<AAudioServiceEndpointShared> holdEndpoint(this);
225 // When there is a routing changed, mmap stream should be disconnected. Set `mConnected`
226 // as false here so that there won't be a new stream connected to this endpoint.
227 mConnected.store(false);
228 std::thread asyncTask([holdEndpoint]() {
229 // When handling disconnection, the service side has disconnected. In that case,
230 // it should be safe to release all registered streams.
231 holdEndpoint->releaseRegisteredStreams();
232 });
233 asyncTask.detach();
234 }
235