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 "AAudioServiceStreamShared"
18 //#define LOG_NDEBUG 0
19 #include <utils/Log.h>
20
21 #include <iomanip>
22 #include <iostream>
23 #include <mutex>
24
25 #include <aaudio/AAudio.h>
26
27 #include "binding/AAudioServiceMessage.h"
28 #include "AAudioServiceStreamBase.h"
29 #include "AAudioServiceStreamShared.h"
30 #include "AAudioEndpointManager.h"
31 #include "AAudioService.h"
32 #include "AAudioServiceEndpoint.h"
33
34 using namespace android;
35 using namespace aaudio;
36
37 #define MIN_BURSTS_PER_BUFFER 2
38 #define DEFAULT_BURSTS_PER_BUFFER 16
39 // This is an arbitrary range. TODO review.
40 #define MAX_FRAMES_PER_BUFFER (32 * 1024)
41
AAudioServiceStreamShared(AAudioService & audioService)42 AAudioServiceStreamShared::AAudioServiceStreamShared(AAudioService &audioService)
43 : AAudioServiceStreamBase(audioService)
44 , mTimestampPositionOffset(0)
45 , mXRunCount(0) {
46 }
47
dumpHeader()48 std::string AAudioServiceStreamShared::dumpHeader() {
49 std::stringstream result;
50 result << AAudioServiceStreamBase::dumpHeader();
51 result << " Write# Read# Avail XRuns";
52 return result.str();
53 }
54
dump() const55 std::string AAudioServiceStreamShared::dump() const NO_THREAD_SAFETY_ANALYSIS {
56 std::stringstream result;
57
58 const bool isLocked = AAudio_tryUntilTrue(
59 [this]()->bool { return audioDataQueueLock.try_lock(); } /* f */,
60 50 /* times */,
61 20 /* sleepMs */);
62 if (!isLocked) {
63 result << "AAudioServiceStreamShared may be deadlocked\n";
64 }
65
66 result << AAudioServiceStreamBase::dump();
67
68 result << mAudioDataQueue->dump();
69 result << std::setw(8) << getXRunCount();
70
71 if (isLocked) {
72 audioDataQueueLock.unlock();
73 }
74
75 return result.str();
76 }
77
calculateBufferCapacity(int32_t requestedCapacityFrames,int32_t framesPerBurst)78 int32_t AAudioServiceStreamShared::calculateBufferCapacity(int32_t requestedCapacityFrames,
79 int32_t framesPerBurst) {
80
81 if (requestedCapacityFrames > MAX_FRAMES_PER_BUFFER) {
82 ALOGE("calculateBufferCapacity() requested capacity %d > max %d",
83 requestedCapacityFrames, MAX_FRAMES_PER_BUFFER);
84 return AAUDIO_ERROR_OUT_OF_RANGE;
85 }
86
87 // Determine how many bursts will fit in the buffer.
88 int32_t numBursts;
89 if (requestedCapacityFrames == AAUDIO_UNSPECIFIED) {
90 // Use fewer bursts if default is too many.
91 if ((DEFAULT_BURSTS_PER_BUFFER * framesPerBurst) > MAX_FRAMES_PER_BUFFER) {
92 numBursts = MAX_FRAMES_PER_BUFFER / framesPerBurst;
93 } else {
94 numBursts = DEFAULT_BURSTS_PER_BUFFER;
95 }
96 } else {
97 // round up to nearest burst boundary
98 numBursts = (requestedCapacityFrames + framesPerBurst - 1) / framesPerBurst;
99 }
100
101 // Clip to bare minimum.
102 if (numBursts < MIN_BURSTS_PER_BUFFER) {
103 numBursts = MIN_BURSTS_PER_BUFFER;
104 }
105 // Check for numeric overflow.
106 if (numBursts > 0x8000 || framesPerBurst > 0x8000) {
107 ALOGE("calculateBufferCapacity() overflow, capacity = %d * %d",
108 numBursts, framesPerBurst);
109 return AAUDIO_ERROR_OUT_OF_RANGE;
110 }
111 int32_t capacityInFrames = numBursts * framesPerBurst;
112
113 // Final range check.
114 if (capacityInFrames > MAX_FRAMES_PER_BUFFER) {
115 ALOGE("calculateBufferCapacity() calc capacity %d > max %d",
116 capacityInFrames, MAX_FRAMES_PER_BUFFER);
117 return AAUDIO_ERROR_OUT_OF_RANGE;
118 }
119 ALOGV("calculateBufferCapacity() requested %d frames, actual = %d",
120 requestedCapacityFrames, capacityInFrames);
121 return capacityInFrames;
122 }
123
open(const aaudio::AAudioStreamRequest & request)124 aaudio_result_t AAudioServiceStreamShared::open(const aaudio::AAudioStreamRequest &request) {
125
126 sp<AAudioServiceStreamShared> keep(this);
127
128 if (request.getConstantConfiguration().getSharingMode() != AAUDIO_SHARING_MODE_SHARED) {
129 ALOGE("%s() sharingMode mismatch %d", __func__,
130 request.getConstantConfiguration().getSharingMode());
131 return AAUDIO_ERROR_INTERNAL;
132 }
133
134 aaudio_result_t result = AAudioServiceStreamBase::open(request);
135 if (result != AAUDIO_OK) {
136 return result;
137 }
138
139 const AAudioStreamConfiguration &configurationInput = request.getConstantConfiguration();
140
141 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
142 if (endpoint == nullptr) {
143 result = AAUDIO_ERROR_INVALID_STATE;
144 goto error;
145 }
146
147 // Is the request compatible with the shared endpoint?
148 setFormat(configurationInput.getFormat());
149 if (getFormat() == AUDIO_FORMAT_DEFAULT) {
150 setFormat(AUDIO_FORMAT_PCM_FLOAT);
151 } else if (getFormat() != AUDIO_FORMAT_PCM_FLOAT) {
152 ALOGD("%s() audio_format_t mAudioFormat = %d, need FLOAT", __func__, getFormat());
153 result = AAUDIO_ERROR_INVALID_FORMAT;
154 goto error;
155 }
156
157 setSampleRate(configurationInput.getSampleRate());
158 if (getSampleRate() == AAUDIO_UNSPECIFIED) {
159 setSampleRate(endpoint->getSampleRate());
160 } else if (getSampleRate() != endpoint->getSampleRate()) {
161 ALOGD("%s() mSampleRate = %d, need %d",
162 __func__, getSampleRate(), endpoint->getSampleRate());
163 result = AAUDIO_ERROR_INVALID_RATE;
164 goto error;
165 }
166
167 setSamplesPerFrame(configurationInput.getSamplesPerFrame());
168 if (getSamplesPerFrame() == AAUDIO_UNSPECIFIED) {
169 setSamplesPerFrame(endpoint->getSamplesPerFrame());
170 } else if (getSamplesPerFrame() != endpoint->getSamplesPerFrame()) {
171 ALOGD("%s() mSamplesPerFrame = %d, need %d",
172 __func__, getSamplesPerFrame(), endpoint->getSamplesPerFrame());
173 result = AAUDIO_ERROR_OUT_OF_RANGE;
174 goto error;
175 }
176
177 setBufferCapacity(calculateBufferCapacity(configurationInput.getBufferCapacity(),
178 mFramesPerBurst));
179 if (getBufferCapacity() < 0) {
180 result = getBufferCapacity(); // negative error code
181 setBufferCapacity(0);
182 goto error;
183 }
184
185 {
186 std::lock_guard<std::mutex> lock(audioDataQueueLock);
187 // Create audio data shared memory buffer for client.
188 mAudioDataQueue = std::make_shared<SharedRingBuffer>();
189 result = mAudioDataQueue->allocate(calculateBytesPerFrame(), getBufferCapacity());
190 if (result != AAUDIO_OK) {
191 ALOGE("%s() could not allocate FIFO with %d frames",
192 __func__, getBufferCapacity());
193 result = AAUDIO_ERROR_NO_MEMORY;
194 goto error;
195 }
196 }
197
198 result = endpoint->registerStream(keep);
199 if (result != AAUDIO_OK) {
200 goto error;
201 }
202
203 setState(AAUDIO_STREAM_STATE_OPEN);
204 return AAUDIO_OK;
205
206 error:
207 close();
208 return result;
209 }
210
211 /**
212 * Get an immutable description of the data queue created by this service.
213 */
getAudioDataDescription(AudioEndpointParcelable & parcelable)214 aaudio_result_t AAudioServiceStreamShared::getAudioDataDescription(
215 AudioEndpointParcelable &parcelable)
216 {
217 std::lock_guard<std::mutex> lock(audioDataQueueLock);
218 if (mAudioDataQueue == nullptr) {
219 ALOGW("%s(): mUpMessageQueue null! - stream not open", __func__);
220 return AAUDIO_ERROR_NULL;
221 }
222 // Gather information on the data queue.
223 mAudioDataQueue->fillParcelable(parcelable,
224 parcelable.mDownDataQueueParcelable);
225 parcelable.mDownDataQueueParcelable.setFramesPerBurst(getFramesPerBurst());
226 return AAUDIO_OK;
227 }
228
markTransferTime(Timestamp & timestamp)229 void AAudioServiceStreamShared::markTransferTime(Timestamp ×tamp) {
230 mAtomicStreamTimestamp.write(timestamp);
231 }
232
233 // Get timestamp that was written by mixer or distributor.
getFreeRunningPosition(int64_t * positionFrames,int64_t * timeNanos)234 aaudio_result_t AAudioServiceStreamShared::getFreeRunningPosition(int64_t *positionFrames,
235 int64_t *timeNanos) {
236 // TODO Get presentation timestamp from the HAL
237 if (mAtomicStreamTimestamp.isValid()) {
238 Timestamp timestamp = mAtomicStreamTimestamp.read();
239 *positionFrames = timestamp.getPosition();
240 *timeNanos = timestamp.getNanoseconds();
241 return AAUDIO_OK;
242 } else {
243 return AAUDIO_ERROR_UNAVAILABLE;
244 }
245 }
246
247 // Get timestamp from lower level service.
getHardwareTimestamp(int64_t * positionFrames,int64_t * timeNanos)248 aaudio_result_t AAudioServiceStreamShared::getHardwareTimestamp(int64_t *positionFrames,
249 int64_t *timeNanos) {
250
251 int64_t position = 0;
252 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
253 if (endpoint == nullptr) {
254 ALOGW("%s() has no endpoint", __func__);
255 return AAUDIO_ERROR_INVALID_STATE;
256 }
257
258 aaudio_result_t result = endpoint->getTimestamp(&position, timeNanos);
259 if (result == AAUDIO_OK) {
260 int64_t offset = mTimestampPositionOffset.load();
261 // TODO, do not go below starting value
262 position -= offset; // Offset from shared MMAP stream
263 ALOGV("%s() %8lld = %8lld - %8lld",
264 __func__, (long long) position, (long long) (position + offset), (long long) offset);
265 }
266 *positionFrames = position;
267 return result;
268 }
269
writeDataIfRoom(int64_t mmapFramesRead,const void * buffer,int32_t numFrames)270 void AAudioServiceStreamShared::writeDataIfRoom(int64_t mmapFramesRead,
271 const void *buffer, int32_t numFrames) {
272 int64_t clientFramesWritten = 0;
273
274 // Lock the AudioFifo to protect against close.
275 std::lock_guard <std::mutex> lock(audioDataQueueLock);
276
277 if (mAudioDataQueue != nullptr) {
278 std::shared_ptr<FifoBuffer> fifo = mAudioDataQueue->getFifoBuffer();
279 // Determine offset between framePosition in client's stream
280 // vs the underlying MMAP stream.
281 clientFramesWritten = fifo->getWriteCounter();
282 // There are two indices that refer to the same frame.
283 int64_t positionOffset = mmapFramesRead - clientFramesWritten;
284 setTimestampPositionOffset(positionOffset);
285
286 // Is the buffer too full to write a burst?
287 if (fifo->getEmptyFramesAvailable() < getFramesPerBurst()) {
288 incrementXRunCount();
289 } else {
290 fifo->write(buffer, numFrames);
291 }
292 clientFramesWritten = fifo->getWriteCounter();
293 }
294
295 if (clientFramesWritten > 0) {
296 // This timestamp represents the completion of data being written into the
297 // client buffer. It is sent to the client and used in the timing model
298 // to decide when data will be available to read.
299 Timestamp timestamp(clientFramesWritten, AudioClock::getNanoseconds());
300 markTransferTime(timestamp);
301 }
302 }
303