xref: /aosp_15_r20/frameworks/av/services/oboeservice/AAudioServiceStreamShared.cpp (revision ec779b8e0859a360c3d303172224686826e6e0e1)
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     // Use the sample rate of the endpoint as each shared stream should use its own SRC.
148     setSampleRate(endpoint->getSampleRate());
149 
150     // Is the request compatible with the shared endpoint?
151     setFormat(configurationInput.getFormat());
152     if (getFormat() == AUDIO_FORMAT_DEFAULT) {
153         setFormat(AUDIO_FORMAT_PCM_FLOAT);
154     } else if (getFormat() != AUDIO_FORMAT_PCM_FLOAT) {
155         ALOGD("%s() audio_format_t mAudioFormat = %d, need FLOAT", __func__, getFormat());
156         result = AAUDIO_ERROR_INVALID_FORMAT;
157         goto error;
158     }
159 
160     setChannelMask(configurationInput.getChannelMask());
161     if (getChannelMask() == AAUDIO_UNSPECIFIED) {
162         setChannelMask(endpoint->getChannelMask());
163     } else if (getSamplesPerFrame() != endpoint->getSamplesPerFrame()) {
164         ALOGD("%s() mSamplesPerFrame = %#x, need %#x",
165               __func__, getSamplesPerFrame(), endpoint->getSamplesPerFrame());
166         result = AAUDIO_ERROR_OUT_OF_RANGE;
167         goto error;
168     }
169 
170     setBufferCapacity(calculateBufferCapacity(configurationInput.getBufferCapacity(),
171                                      mFramesPerBurst));
172     if (getBufferCapacity() < 0) {
173         result = getBufferCapacity(); // negative error code
174         setBufferCapacity(0);
175         goto error;
176     }
177 
178     {
179         std::lock_guard<std::mutex> lock(audioDataQueueLock);
180         // Create audio data shared memory buffer for client.
181         mAudioDataQueue = std::make_shared<SharedRingBuffer>();
182         result = mAudioDataQueue->allocate(calculateBytesPerFrame(), getBufferCapacity());
183         if (result != AAUDIO_OK) {
184             ALOGE("%s() could not allocate FIFO with %d frames",
185                   __func__, getBufferCapacity());
186             result = AAUDIO_ERROR_NO_MEMORY;
187             goto error;
188         }
189     }
190 
191     result = endpoint->registerStream(keep);
192     if (result != AAUDIO_OK) {
193         goto error;
194     }
195 
196     setState(AAUDIO_STREAM_STATE_OPEN);
197     return AAUDIO_OK;
198 
199 error:
200     close();
201     return result;
202 }
203 
204 /**
205  * Get an immutable description of the data queue created by this service.
206  */
getAudioDataDescription_l(AudioEndpointParcelable * parcelable)207 aaudio_result_t AAudioServiceStreamShared::getAudioDataDescription_l(
208         AudioEndpointParcelable* parcelable)
209 {
210     std::lock_guard<std::mutex> lock(audioDataQueueLock);
211     if (mAudioDataQueue == nullptr) {
212         ALOGW("%s(): mUpMessageQueue null! - stream not open", __func__);
213         return AAUDIO_ERROR_NULL;
214     }
215     // Gather information on the data queue.
216     mAudioDataQueue->fillParcelable(parcelable,
217                                     parcelable->mDownDataQueueParcelable);
218     parcelable->mDownDataQueueParcelable.setFramesPerBurst(getFramesPerBurst());
219     return AAUDIO_OK;
220 }
221 
markTransferTime(Timestamp & timestamp)222 void AAudioServiceStreamShared::markTransferTime(Timestamp &timestamp) {
223     mAtomicStreamTimestamp.write(timestamp);
224 }
225 
226 // Get timestamp that was written by mixer or distributor.
getFreeRunningPosition_l(int64_t * positionFrames,int64_t * timeNanos)227 aaudio_result_t AAudioServiceStreamShared::getFreeRunningPosition_l(int64_t *positionFrames,
228                                                                     int64_t *timeNanos) {
229     // TODO Get presentation timestamp from the HAL
230     if (mAtomicStreamTimestamp.isValid()) {
231         Timestamp timestamp = mAtomicStreamTimestamp.read();
232         *positionFrames = timestamp.getPosition();
233         *timeNanos = timestamp.getNanoseconds();
234         return AAUDIO_OK;
235     } else {
236         return AAUDIO_ERROR_UNAVAILABLE;
237     }
238 }
239 
240 // Get timestamp from lower level service.
getHardwareTimestamp_l(int64_t * positionFrames,int64_t * timeNanos)241 aaudio_result_t AAudioServiceStreamShared::getHardwareTimestamp_l(int64_t *positionFrames,
242                                                                   int64_t *timeNanos) {
243 
244     int64_t position = 0;
245     sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
246     if (endpoint == nullptr) {
247         ALOGW("%s() has no endpoint", __func__);
248         return AAUDIO_ERROR_INVALID_STATE;
249     }
250 
251     aaudio_result_t result = endpoint->getTimestamp(&position, timeNanos);
252     if (result == AAUDIO_OK) {
253         int64_t offset = mTimestampPositionOffset.load();
254         // TODO, do not go below starting value
255         position -= offset; // Offset from shared MMAP stream
256         ALOGV("%s() %8lld = %8lld - %8lld",
257               __func__, (long long) position, (long long) (position + offset), (long long) offset);
258     }
259     *positionFrames = position;
260     return result;
261 }
262 
writeDataIfRoom(int64_t mmapFramesRead,const void * buffer,int32_t numFrames)263 void AAudioServiceStreamShared::writeDataIfRoom(int64_t mmapFramesRead,
264                                                 const void *buffer, int32_t numFrames) {
265     int64_t clientFramesWritten = 0;
266 
267     // Lock the AudioFifo to protect against close.
268     std::lock_guard <std::mutex> lock(audioDataQueueLock);
269 
270     if (mAudioDataQueue != nullptr) {
271         std::shared_ptr<FifoBuffer> fifo = mAudioDataQueue->getFifoBuffer();
272         // Determine offset between framePosition in client's stream
273         // vs the underlying MMAP stream.
274         clientFramesWritten = fifo->getWriteCounter();
275         // There are two indices that refer to the same frame.
276         int64_t positionOffset = mmapFramesRead - clientFramesWritten;
277         setTimestampPositionOffset(positionOffset);
278 
279         // Is the buffer too full to write a burst?
280         if (fifo->getEmptyFramesAvailable() < getFramesPerBurst()) {
281             incrementXRunCount();
282         } else {
283             fifo->write(buffer, numFrames);
284         }
285         clientFramesWritten = fifo->getWriteCounter();
286     }
287 
288     if (clientFramesWritten > 0) {
289         // This timestamp represents the completion of data being written into the
290         // client buffer. It is sent to the client and used in the timing model
291         // to decide when data will be available to read.
292         Timestamp timestamp(clientFramesWritten, AudioClock::getNanoseconds());
293         markTransferTime(timestamp);
294     }
295 }
296