1 /*
2  * Copyright (C) 2016 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 "AudioStreamInternal"
18 //#define LOG_NDEBUG 0
19 #include <utils/Log.h>
20 
21 #define ATRACE_TAG ATRACE_TAG_AUDIO
22 
23 #include <stdint.h>
24 
25 #include <binder/IServiceManager.h>
26 
27 #include <aaudio/AAudio.h>
28 #include <cutils/properties.h>
29 
30 #include <media/MediaMetricsItem.h>
31 #include <utils/Trace.h>
32 
33 #include "AudioEndpointParcelable.h"
34 #include "binding/AAudioStreamRequest.h"
35 #include "binding/AAudioStreamConfiguration.h"
36 #include "binding/AAudioServiceMessage.h"
37 #include "core/AudioGlobal.h"
38 #include "core/AudioStreamBuilder.h"
39 #include "fifo/FifoBuffer.h"
40 #include "utility/AudioClock.h"
41 #include <media/AidlConversion.h>
42 
43 #include "AudioStreamInternal.h"
44 
45 // We do this after the #includes because if a header uses ALOG.
46 // it would fail on the reference to mInService.
47 #undef LOG_TAG
48 // This file is used in both client and server processes.
49 // This is needed to make sense of the logs more easily.
50 #define LOG_TAG (mInService ? "AudioStreamInternal_Service" : "AudioStreamInternal_Client")
51 
52 using android::Mutex;
53 using android::WrappingBuffer;
54 using android::content::AttributionSourceState;
55 
56 using namespace aaudio;
57 
58 #define MIN_TIMEOUT_NANOS        (1000 * AAUDIO_NANOS_PER_MILLISECOND)
59 
60 // Wait at least this many times longer than the operation should take.
61 #define MIN_TIMEOUT_OPERATIONS    4
62 
63 #define LOG_TIMESTAMPS            0
64 
AudioStreamInternal(AAudioServiceInterface & serviceInterface,bool inService)65 AudioStreamInternal::AudioStreamInternal(AAudioServiceInterface  &serviceInterface, bool inService)
66         : AudioStream()
67         , mClockModel()
68         , mServiceStreamHandle(AAUDIO_HANDLE_INVALID)
69         , mInService(inService)
70         , mServiceInterface(serviceInterface)
71         , mAtomicInternalTimestamp()
72         , mWakeupDelayNanos(AAudioProperty_getWakeupDelayMicros() * AAUDIO_NANOS_PER_MICROSECOND)
73         , mMinimumSleepNanos(AAudioProperty_getMinimumSleepMicros() * AAUDIO_NANOS_PER_MICROSECOND)
74         {
75 }
76 
~AudioStreamInternal()77 AudioStreamInternal::~AudioStreamInternal() {
78     ALOGD("%s() %p called", __func__, this);
79 }
80 
open(const AudioStreamBuilder & builder)81 aaudio_result_t AudioStreamInternal::open(const AudioStreamBuilder &builder) {
82 
83     aaudio_result_t result = AAUDIO_OK;
84     int32_t framesPerBurst;
85     int32_t framesPerHardwareBurst;
86     AAudioStreamRequest request;
87     AAudioStreamConfiguration configurationOutput;
88 
89     if (getState() != AAUDIO_STREAM_STATE_UNINITIALIZED) {
90         ALOGE("%s - already open! state = %d", __func__, getState());
91         return AAUDIO_ERROR_INVALID_STATE;
92     }
93 
94     // Copy requested parameters to the stream.
95     result = AudioStream::open(builder);
96     if (result < 0) {
97         return result;
98     }
99 
100     const int32_t burstMinMicros = AAudioProperty_getHardwareBurstMinMicros();
101     int32_t burstMicros = 0;
102 
103     const audio_format_t requestedFormat = getFormat();
104     // We have to do volume scaling. So we prefer FLOAT format.
105     if (requestedFormat == AUDIO_FORMAT_DEFAULT) {
106         setFormat(AUDIO_FORMAT_PCM_FLOAT);
107     }
108     // Request FLOAT for the shared mixer or the device.
109     request.getConfiguration().setFormat(AUDIO_FORMAT_PCM_FLOAT);
110 
111     // TODO b/182392769: use attribution source util
112     AttributionSourceState attributionSource;
113     attributionSource.uid = VALUE_OR_FATAL(android::legacy2aidl_uid_t_int32_t(getuid()));
114     attributionSource.pid = VALUE_OR_FATAL(android::legacy2aidl_pid_t_int32_t(getpid()));
115     attributionSource.packageName = builder.getOpPackageName();
116     attributionSource.attributionTag = builder.getAttributionTag();
117     attributionSource.token = sp<android::BBinder>::make();
118 
119     // Build the request to send to the server.
120     request.setAttributionSource(attributionSource);
121     request.setSharingModeMatchRequired(isSharingModeMatchRequired());
122     request.setInService(isInService());
123 
124     request.getConfiguration().setDeviceId(getDeviceId());
125     request.getConfiguration().setSampleRate(getSampleRate());
126     request.getConfiguration().setDirection(getDirection());
127     request.getConfiguration().setSharingMode(getSharingMode());
128     request.getConfiguration().setChannelMask(getChannelMask());
129 
130     request.getConfiguration().setUsage(getUsage());
131     request.getConfiguration().setContentType(getContentType());
132     request.getConfiguration().setSpatializationBehavior(getSpatializationBehavior());
133     request.getConfiguration().setIsContentSpatialized(isContentSpatialized());
134     request.getConfiguration().setInputPreset(getInputPreset());
135     request.getConfiguration().setPrivacySensitive(isPrivacySensitive());
136 
137     request.getConfiguration().setBufferCapacity(builder.getBufferCapacity());
138 
139     mDeviceChannelCount = getSamplesPerFrame(); // Assume it will be the same. Update if not.
140 
141     mServiceStreamHandle = mServiceInterface.openStream(request, configurationOutput);
142     if (mServiceStreamHandle < 0
143             && (request.getConfiguration().getSamplesPerFrame() == 1
144                     || request.getConfiguration().getChannelMask() == AAUDIO_CHANNEL_MONO)
145             && getDirection() == AAUDIO_DIRECTION_OUTPUT
146             && !isInService()) {
147         // if that failed then try switching from mono to stereo if OUTPUT.
148         // Only do this in the client. Otherwise we end up with a mono mixer in the service
149         // that writes to a stereo MMAP stream.
150         ALOGD("%s() - openStream() returned %d, try switching from MONO to STEREO",
151               __func__, mServiceStreamHandle);
152         request.getConfiguration().setChannelMask(AAUDIO_CHANNEL_STEREO);
153         mServiceStreamHandle = mServiceInterface.openStream(request, configurationOutput);
154     }
155     if (mServiceStreamHandle < 0) {
156         return mServiceStreamHandle;
157     }
158 
159     // This must match the key generated in oboeservice/AAudioServiceStreamBase.cpp
160     // so the client can have permission to log.
161     if (!mInService) {
162         // No need to log if it is from service side.
163         mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_STREAM)
164                      + std::to_string(mServiceStreamHandle);
165     }
166 
167     android::mediametrics::LogItem(mMetricsId)
168             .set(AMEDIAMETRICS_PROP_PERFORMANCEMODE,
169                  AudioGlobal_convertPerformanceModeToText(builder.getPerformanceMode()))
170             .set(AMEDIAMETRICS_PROP_SHARINGMODE,
171                  AudioGlobal_convertSharingModeToText(builder.getSharingMode()))
172             .set(AMEDIAMETRICS_PROP_ENCODINGCLIENT,
173                  android::toString(requestedFormat).c_str()).record();
174 
175     result = configurationOutput.validate();
176     if (result != AAUDIO_OK) {
177         goto error;
178     }
179     // Save results of the open.
180     if (getChannelMask() == AAUDIO_UNSPECIFIED) {
181         setChannelMask(configurationOutput.getChannelMask());
182     }
183 
184     mDeviceChannelCount = configurationOutput.getSamplesPerFrame();
185 
186     setSampleRate(configurationOutput.getSampleRate());
187     setDeviceId(configurationOutput.getDeviceId());
188     setSessionId(configurationOutput.getSessionId());
189     setSharingMode(configurationOutput.getSharingMode());
190 
191     setUsage(configurationOutput.getUsage());
192     setContentType(configurationOutput.getContentType());
193     setSpatializationBehavior(configurationOutput.getSpatializationBehavior());
194     setIsContentSpatialized(configurationOutput.isContentSpatialized());
195     setInputPreset(configurationOutput.getInputPreset());
196 
197     // Save device format so we can do format conversion and volume scaling together.
198     setDeviceFormat(configurationOutput.getFormat());
199 
200     result = mServiceInterface.getStreamDescription(mServiceStreamHandle, mEndPointParcelable);
201     if (result != AAUDIO_OK) {
202         goto error;
203     }
204 
205     // Resolve parcelable into a descriptor.
206     result = mEndPointParcelable.resolve(&mEndpointDescriptor);
207     if (result != AAUDIO_OK) {
208         goto error;
209     }
210 
211     // Configure endpoint based on descriptor.
212     mAudioEndpoint = std::make_unique<AudioEndpoint>();
213     result = mAudioEndpoint->configure(&mEndpointDescriptor, getDirection());
214     if (result != AAUDIO_OK) {
215         goto error;
216     }
217 
218     framesPerHardwareBurst = mEndpointDescriptor.dataQueueDescriptor.framesPerBurst;
219 
220     // Scale up the burst size to meet the minimum equivalent in microseconds.
221     // This is to avoid waking the CPU too often when the HW burst is very small
222     // or at high sample rates.
223     framesPerBurst = framesPerHardwareBurst;
224     do {
225         if (burstMicros > 0) {  // skip first loop
226             framesPerBurst *= 2;
227         }
228         burstMicros = framesPerBurst * static_cast<int64_t>(1000000) / getSampleRate();
229     } while (burstMicros < burstMinMicros);
230     ALOGD("%s() original HW burst = %d, minMicros = %d => SW burst = %d\n",
231           __func__, framesPerHardwareBurst, burstMinMicros, framesPerBurst);
232 
233     // Validate final burst size.
234     if (framesPerBurst < MIN_FRAMES_PER_BURST || framesPerBurst > MAX_FRAMES_PER_BURST) {
235         ALOGE("%s - framesPerBurst out of range = %d", __func__, framesPerBurst);
236         result = AAUDIO_ERROR_OUT_OF_RANGE;
237         goto error;
238     }
239     setFramesPerBurst(framesPerBurst); // only save good value
240 
241     mBufferCapacityInFrames = mEndpointDescriptor.dataQueueDescriptor.capacityInFrames;
242     if (mBufferCapacityInFrames < getFramesPerBurst()
243             || mBufferCapacityInFrames > MAX_BUFFER_CAPACITY_IN_FRAMES) {
244         ALOGE("%s - bufferCapacity out of range = %d", __func__, mBufferCapacityInFrames);
245         result = AAUDIO_ERROR_OUT_OF_RANGE;
246         goto error;
247     }
248 
249     mClockModel.setSampleRate(getSampleRate());
250     mClockModel.setFramesPerBurst(framesPerHardwareBurst);
251 
252     if (isDataCallbackSet()) {
253         mCallbackFrames = builder.getFramesPerDataCallback();
254         if (mCallbackFrames > getBufferCapacity() / 2) {
255             ALOGW("%s - framesPerCallback too big = %d, capacity = %d",
256                   __func__, mCallbackFrames, getBufferCapacity());
257             result = AAUDIO_ERROR_OUT_OF_RANGE;
258             goto error;
259 
260         } else if (mCallbackFrames < 0) {
261             ALOGW("%s - framesPerCallback negative", __func__);
262             result = AAUDIO_ERROR_OUT_OF_RANGE;
263             goto error;
264 
265         }
266         if (mCallbackFrames == AAUDIO_UNSPECIFIED) {
267             mCallbackFrames = getFramesPerBurst();
268         }
269 
270         const int32_t callbackBufferSize = mCallbackFrames * getBytesPerFrame();
271         mCallbackBuffer = std::make_unique<uint8_t[]>(callbackBufferSize);
272     }
273 
274     // For debugging and analyzing the distribution of MMAP timestamps.
275     // For OUTPUT, use a NEGATIVE offset to move the CPU writes further BEFORE the HW reads.
276     // For INPUT, use a POSITIVE offset to move the CPU reads further AFTER the HW writes.
277     // You can use this offset to reduce glitching.
278     // You can also use this offset to force glitching. By iterating over multiple
279     // values you can reveal the distribution of the hardware timing jitter.
280     if (mAudioEndpoint->isFreeRunning()) { // MMAP?
281         int32_t offsetMicros = (getDirection() == AAUDIO_DIRECTION_OUTPUT)
282                 ? AAudioProperty_getOutputMMapOffsetMicros()
283                 : AAudioProperty_getInputMMapOffsetMicros();
284         // This log is used to debug some tricky glitch issues. Please leave.
285         ALOGD_IF(offsetMicros, "%s() - %s mmap offset = %d micros",
286                 __func__,
287                 (getDirection() == AAUDIO_DIRECTION_OUTPUT) ? "output" : "input",
288                 offsetMicros);
289         mTimeOffsetNanos = offsetMicros * AAUDIO_NANOS_PER_MICROSECOND;
290     }
291 
292     setBufferSize(mBufferCapacityInFrames / 2); // Default buffer size to match Q
293 
294     setState(AAUDIO_STREAM_STATE_OPEN);
295 
296     return result;
297 
298 error:
299     safeReleaseClose();
300     return result;
301 }
302 
303 // This must be called under mStreamLock.
release_l()304 aaudio_result_t AudioStreamInternal::release_l() {
305     aaudio_result_t result = AAUDIO_OK;
306     ALOGD("%s(): mServiceStreamHandle = 0x%08X", __func__, mServiceStreamHandle);
307     if (mServiceStreamHandle != AAUDIO_HANDLE_INVALID) {
308         aaudio_stream_state_t currentState = getState();
309         // Don't release a stream while it is running. Stop it first.
310         // If DISCONNECTED then we should still try to stop in case the
311         // error callback is still running.
312         if (isActive() || currentState == AAUDIO_STREAM_STATE_DISCONNECTED) {
313             requestStop_l();
314         }
315 
316         logReleaseBufferState();
317 
318         setState(AAUDIO_STREAM_STATE_CLOSING);
319         aaudio_handle_t serviceStreamHandle = mServiceStreamHandle;
320         mServiceStreamHandle = AAUDIO_HANDLE_INVALID;
321 
322         mServiceInterface.closeStream(serviceStreamHandle);
323         mCallbackBuffer.reset();
324 
325         // Update local frame counters so we can query them after releasing the endpoint.
326         getFramesRead();
327         getFramesWritten();
328         mAudioEndpoint.reset();
329         result = mEndPointParcelable.close();
330         aaudio_result_t result2 = AudioStream::release_l();
331         return (result != AAUDIO_OK) ? result : result2;
332     } else {
333         return AAUDIO_ERROR_INVALID_HANDLE;
334     }
335 }
336 
aaudio_callback_thread_proc(void * context)337 static void *aaudio_callback_thread_proc(void *context)
338 {
339     AudioStreamInternal *stream = (AudioStreamInternal *)context;
340     //LOGD("oboe_callback_thread, stream = %p", stream);
341     if (stream != NULL) {
342         return stream->callbackLoop();
343     } else {
344         return NULL;
345     }
346 }
347 
348 /*
349  * It normally takes about 20-30 msec to start a stream on the server.
350  * But the first time can take as much as 200-300 msec. The HW
351  * starts right away so by the time the client gets a chance to write into
352  * the buffer, it is already in a deep underflow state. That can cause the
353  * XRunCount to be non-zero, which could lead an app to tune its latency higher.
354  * To avoid this problem, we set a request for the processing code to start the
355  * client stream at the same position as the server stream.
356  * The processing code will then save the current offset
357  * between client and server and apply that to any position given to the app.
358  */
requestStart_l()359 aaudio_result_t AudioStreamInternal::requestStart_l()
360 {
361     int64_t startTime;
362     if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
363         ALOGD("requestStart() mServiceStreamHandle invalid");
364         return AAUDIO_ERROR_INVALID_STATE;
365     }
366     if (isActive()) {
367         ALOGD("requestStart() already active");
368         return AAUDIO_ERROR_INVALID_STATE;
369     }
370 
371     aaudio_stream_state_t originalState = getState();
372     if (originalState == AAUDIO_STREAM_STATE_DISCONNECTED) {
373         ALOGD("requestStart() but DISCONNECTED");
374         return AAUDIO_ERROR_DISCONNECTED;
375     }
376     setState(AAUDIO_STREAM_STATE_STARTING);
377 
378     // Clear any stale timestamps from the previous run.
379     drainTimestampsFromService();
380 
381     prepareBuffersForStart(); // tell subclasses to get ready
382 
383     aaudio_result_t result = mServiceInterface.startStream(mServiceStreamHandle);
384     if (result == AAUDIO_ERROR_INVALID_HANDLE) {
385         ALOGD("%s() INVALID_HANDLE, stream was probably stolen", __func__);
386         // Stealing was added in R. Coerce result to improve backward compatibility.
387         result = AAUDIO_ERROR_DISCONNECTED;
388         setState(AAUDIO_STREAM_STATE_DISCONNECTED);
389     }
390 
391     startTime = AudioClock::getNanoseconds();
392     mClockModel.start(startTime);
393     mNeedCatchUp.request();  // Ask data processing code to catch up when first timestamp received.
394 
395     // Start data callback thread.
396     if (result == AAUDIO_OK && isDataCallbackSet()) {
397         // Launch the callback loop thread.
398         int64_t periodNanos = mCallbackFrames
399                               * AAUDIO_NANOS_PER_SECOND
400                               / getSampleRate();
401         mCallbackEnabled.store(true);
402         result = createThread_l(periodNanos, aaudio_callback_thread_proc, this);
403     }
404     if (result != AAUDIO_OK) {
405         setState(originalState);
406     }
407     return result;
408 }
409 
calculateReasonableTimeout(int32_t framesPerOperation)410 int64_t AudioStreamInternal::calculateReasonableTimeout(int32_t framesPerOperation) {
411 
412     // Wait for at least a second or some number of callbacks to join the thread.
413     int64_t timeoutNanoseconds = (MIN_TIMEOUT_OPERATIONS
414                                   * framesPerOperation
415                                   * AAUDIO_NANOS_PER_SECOND)
416                                   / getSampleRate();
417     if (timeoutNanoseconds < MIN_TIMEOUT_NANOS) { // arbitrary number of seconds
418         timeoutNanoseconds = MIN_TIMEOUT_NANOS;
419     }
420     return timeoutNanoseconds;
421 }
422 
calculateReasonableTimeout()423 int64_t AudioStreamInternal::calculateReasonableTimeout() {
424     return calculateReasonableTimeout(getFramesPerBurst());
425 }
426 
427 // This must be called under mStreamLock.
stopCallback_l()428 aaudio_result_t AudioStreamInternal::stopCallback_l()
429 {
430     if (isDataCallbackSet()
431             && (isActive() || getState() == AAUDIO_STREAM_STATE_DISCONNECTED)) {
432         mCallbackEnabled.store(false);
433         aaudio_result_t result = joinThread_l(NULL); // may temporarily unlock mStreamLock
434         if (result == AAUDIO_ERROR_INVALID_HANDLE) {
435             ALOGD("%s() INVALID_HANDLE, stream was probably stolen", __func__);
436             result = AAUDIO_OK;
437         }
438         return result;
439     } else {
440         ALOGD("%s() skipped, isDataCallbackSet() = %d, isActive() = %d, getState()  = %d", __func__,
441             isDataCallbackSet(), isActive(), getState());
442         return AAUDIO_OK;
443     }
444 }
445 
requestStop_l()446 aaudio_result_t AudioStreamInternal::requestStop_l() {
447     aaudio_result_t result = stopCallback_l();
448     if (result != AAUDIO_OK) {
449         ALOGW("%s() stop callback returned %d, returning early", __func__, result);
450         return result;
451     }
452     // The stream may have been unlocked temporarily to let a callback finish
453     // and the callback may have stopped the stream.
454     // Check to make sure the stream still needs to be stopped.
455     // See also AudioStream::safeStop_l().
456     if (!(isActive() || getState() == AAUDIO_STREAM_STATE_DISCONNECTED)) {
457         ALOGD("%s() returning early, not active or disconnected", __func__);
458         return AAUDIO_OK;
459     }
460 
461     if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
462         ALOGW("%s() mServiceStreamHandle invalid = 0x%08X",
463               __func__, mServiceStreamHandle);
464         return AAUDIO_ERROR_INVALID_STATE;
465     }
466 
467     mClockModel.stop(AudioClock::getNanoseconds());
468     setState(AAUDIO_STREAM_STATE_STOPPING);
469     mAtomicInternalTimestamp.clear();
470 
471     result = mServiceInterface.stopStream(mServiceStreamHandle);
472     if (result == AAUDIO_ERROR_INVALID_HANDLE) {
473         ALOGD("%s() INVALID_HANDLE, stream was probably stolen", __func__);
474         result = AAUDIO_OK;
475     }
476     return result;
477 }
478 
registerThread()479 aaudio_result_t AudioStreamInternal::registerThread() {
480     if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
481         ALOGW("%s() mServiceStreamHandle invalid", __func__);
482         return AAUDIO_ERROR_INVALID_STATE;
483     }
484     return mServiceInterface.registerAudioThread(mServiceStreamHandle,
485                                               gettid(),
486                                               getPeriodNanoseconds());
487 }
488 
unregisterThread()489 aaudio_result_t AudioStreamInternal::unregisterThread() {
490     if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
491         ALOGW("%s() mServiceStreamHandle invalid", __func__);
492         return AAUDIO_ERROR_INVALID_STATE;
493     }
494     return mServiceInterface.unregisterAudioThread(mServiceStreamHandle, gettid());
495 }
496 
startClient(const android::AudioClient & client,const audio_attributes_t * attr,audio_port_handle_t * portHandle)497 aaudio_result_t AudioStreamInternal::startClient(const android::AudioClient& client,
498                                                  const audio_attributes_t *attr,
499                                                  audio_port_handle_t *portHandle) {
500     ALOGV("%s() called", __func__);
501     if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
502         return AAUDIO_ERROR_INVALID_STATE;
503     }
504     aaudio_result_t result =  mServiceInterface.startClient(mServiceStreamHandle,
505                                                             client, attr, portHandle);
506     ALOGV("%s(%d) returning %d", __func__, *portHandle, result);
507     return result;
508 }
509 
stopClient(audio_port_handle_t portHandle)510 aaudio_result_t AudioStreamInternal::stopClient(audio_port_handle_t portHandle) {
511     ALOGV("%s(%d) called", __func__, portHandle);
512     if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) {
513         return AAUDIO_ERROR_INVALID_STATE;
514     }
515     aaudio_result_t result = mServiceInterface.stopClient(mServiceStreamHandle, portHandle);
516     ALOGV("%s(%d) returning %d", __func__, portHandle, result);
517     return result;
518 }
519 
getTimestamp(clockid_t clockId,int64_t * framePosition,int64_t * timeNanoseconds)520 aaudio_result_t AudioStreamInternal::getTimestamp(clockid_t clockId,
521                            int64_t *framePosition,
522                            int64_t *timeNanoseconds) {
523     // Generated in server and passed to client. Return latest.
524     if (mAtomicInternalTimestamp.isValid()) {
525         Timestamp timestamp = mAtomicInternalTimestamp.read();
526         int64_t position = timestamp.getPosition() + mFramesOffsetFromService;
527         if (position >= 0) {
528             *framePosition = position;
529             *timeNanoseconds = timestamp.getNanoseconds();
530             return AAUDIO_OK;
531         }
532     }
533     return AAUDIO_ERROR_INVALID_STATE;
534 }
535 
updateStateMachine()536 aaudio_result_t AudioStreamInternal::updateStateMachine() {
537     if (isDataCallbackActive()) {
538         return AAUDIO_OK; // state is getting updated by the callback thread read/write call
539     }
540     return processCommands();
541 }
542 
logTimestamp(AAudioServiceMessage & command)543 void AudioStreamInternal::logTimestamp(AAudioServiceMessage &command) {
544     static int64_t oldPosition = 0;
545     static int64_t oldTime = 0;
546     int64_t framePosition = command.timestamp.position;
547     int64_t nanoTime = command.timestamp.timestamp;
548     ALOGD("logTimestamp: timestamp says framePosition = %8lld at nanoTime %lld",
549          (long long) framePosition,
550          (long long) nanoTime);
551     int64_t nanosDelta = nanoTime - oldTime;
552     if (nanosDelta > 0 && oldTime > 0) {
553         int64_t framesDelta = framePosition - oldPosition;
554         int64_t rate = (framesDelta * AAUDIO_NANOS_PER_SECOND) / nanosDelta;
555         ALOGD("logTimestamp:     framesDelta = %8lld, nanosDelta = %8lld, rate = %lld",
556               (long long) framesDelta, (long long) nanosDelta, (long long) rate);
557     }
558     oldPosition = framePosition;
559     oldTime = nanoTime;
560 }
561 
onTimestampService(AAudioServiceMessage * message)562 aaudio_result_t AudioStreamInternal::onTimestampService(AAudioServiceMessage *message) {
563 #if LOG_TIMESTAMPS
564     logTimestamp(*message);
565 #endif
566     processTimestamp(message->timestamp.position,
567             message->timestamp.timestamp + mTimeOffsetNanos);
568     return AAUDIO_OK;
569 }
570 
onTimestampHardware(AAudioServiceMessage * message)571 aaudio_result_t AudioStreamInternal::onTimestampHardware(AAudioServiceMessage *message) {
572     Timestamp timestamp(message->timestamp.position, message->timestamp.timestamp);
573     mAtomicInternalTimestamp.write(timestamp);
574     return AAUDIO_OK;
575 }
576 
onEventFromServer(AAudioServiceMessage * message)577 aaudio_result_t AudioStreamInternal::onEventFromServer(AAudioServiceMessage *message) {
578     aaudio_result_t result = AAUDIO_OK;
579     switch (message->event.event) {
580         case AAUDIO_SERVICE_EVENT_STARTED:
581             ALOGD("%s - got AAUDIO_SERVICE_EVENT_STARTED", __func__);
582             if (getState() == AAUDIO_STREAM_STATE_STARTING) {
583                 setState(AAUDIO_STREAM_STATE_STARTED);
584             }
585             break;
586         case AAUDIO_SERVICE_EVENT_PAUSED:
587             ALOGD("%s - got AAUDIO_SERVICE_EVENT_PAUSED", __func__);
588             if (getState() == AAUDIO_STREAM_STATE_PAUSING) {
589                 setState(AAUDIO_STREAM_STATE_PAUSED);
590             }
591             break;
592         case AAUDIO_SERVICE_EVENT_STOPPED:
593             ALOGD("%s - got AAUDIO_SERVICE_EVENT_STOPPED", __func__);
594             if (getState() == AAUDIO_STREAM_STATE_STOPPING) {
595                 setState(AAUDIO_STREAM_STATE_STOPPED);
596             }
597             break;
598         case AAUDIO_SERVICE_EVENT_FLUSHED:
599             ALOGD("%s - got AAUDIO_SERVICE_EVENT_FLUSHED", __func__);
600             if (getState() == AAUDIO_STREAM_STATE_FLUSHING) {
601                 setState(AAUDIO_STREAM_STATE_FLUSHED);
602                 onFlushFromServer();
603             }
604             break;
605         case AAUDIO_SERVICE_EVENT_DISCONNECTED:
606             // Prevent hardware from looping on old data and making buzzing sounds.
607             if (getDirection() == AAUDIO_DIRECTION_OUTPUT) {
608                 mAudioEndpoint->eraseDataMemory();
609             }
610             result = AAUDIO_ERROR_DISCONNECTED;
611             setState(AAUDIO_STREAM_STATE_DISCONNECTED);
612             ALOGW("%s - AAUDIO_SERVICE_EVENT_DISCONNECTED - FIFO cleared", __func__);
613             break;
614         case AAUDIO_SERVICE_EVENT_VOLUME:
615             ALOGD("%s - AAUDIO_SERVICE_EVENT_VOLUME %lf", __func__, message->event.dataDouble);
616             mStreamVolume = (float)message->event.dataDouble;
617             doSetVolume();
618             break;
619         case AAUDIO_SERVICE_EVENT_XRUN:
620             mXRunCount = static_cast<int32_t>(message->event.dataLong);
621             break;
622         default:
623             ALOGE("%s - Unrecognized event = %d", __func__, (int) message->event.event);
624             break;
625     }
626     return result;
627 }
628 
drainTimestampsFromService()629 aaudio_result_t AudioStreamInternal::drainTimestampsFromService() {
630     aaudio_result_t result = AAUDIO_OK;
631 
632     while (result == AAUDIO_OK) {
633         AAudioServiceMessage message;
634         if (!mAudioEndpoint) {
635             break;
636         }
637         if (mAudioEndpoint->readUpCommand(&message) != 1) {
638             break; // no command this time, no problem
639         }
640         switch (message.what) {
641             // ignore most messages
642             case AAudioServiceMessage::code::TIMESTAMP_SERVICE:
643             case AAudioServiceMessage::code::TIMESTAMP_HARDWARE:
644                 break;
645 
646             case AAudioServiceMessage::code::EVENT:
647                 result = onEventFromServer(&message);
648                 break;
649 
650             default:
651                 ALOGE("%s - unrecognized message.what = %d", __func__, (int) message.what);
652                 result = AAUDIO_ERROR_INTERNAL;
653                 break;
654         }
655     }
656     return result;
657 }
658 
659 // Process all the commands coming from the server.
processCommands()660 aaudio_result_t AudioStreamInternal::processCommands() {
661     aaudio_result_t result = AAUDIO_OK;
662 
663     while (result == AAUDIO_OK) {
664         AAudioServiceMessage message;
665         if (!mAudioEndpoint) {
666             break;
667         }
668         if (mAudioEndpoint->readUpCommand(&message) != 1) {
669             break; // no command this time, no problem
670         }
671         switch (message.what) {
672         case AAudioServiceMessage::code::TIMESTAMP_SERVICE:
673             result = onTimestampService(&message);
674             break;
675 
676         case AAudioServiceMessage::code::TIMESTAMP_HARDWARE:
677             result = onTimestampHardware(&message);
678             break;
679 
680         case AAudioServiceMessage::code::EVENT:
681             result = onEventFromServer(&message);
682             break;
683 
684         default:
685             ALOGE("%s - unrecognized message.what = %d", __func__, (int) message.what);
686             result = AAUDIO_ERROR_INTERNAL;
687             break;
688         }
689     }
690     return result;
691 }
692 
693 // Read or write the data, block if needed and timeoutMillis > 0
processData(void * buffer,int32_t numFrames,int64_t timeoutNanoseconds)694 aaudio_result_t AudioStreamInternal::processData(void *buffer, int32_t numFrames,
695                                                  int64_t timeoutNanoseconds)
696 {
697     const char * traceName = "aaProc";
698     const char * fifoName = "aaRdy";
699     ATRACE_BEGIN(traceName);
700     if (ATRACE_ENABLED()) {
701         int32_t fullFrames = mAudioEndpoint->getFullFramesAvailable();
702         ATRACE_INT(fifoName, fullFrames);
703     }
704 
705     aaudio_result_t result = AAUDIO_OK;
706     int32_t loopCount = 0;
707     uint8_t* audioData = (uint8_t*)buffer;
708     int64_t currentTimeNanos = AudioClock::getNanoseconds();
709     const int64_t entryTimeNanos = currentTimeNanos;
710     const int64_t deadlineNanos = currentTimeNanos + timeoutNanoseconds;
711     int32_t framesLeft = numFrames;
712 
713     // Loop until all the data has been processed or until a timeout occurs.
714     while (framesLeft > 0) {
715         // The call to processDataNow() will not block. It will just process as much as it can.
716         int64_t wakeTimeNanos = 0;
717         aaudio_result_t framesProcessed = processDataNow(audioData, framesLeft,
718                                                   currentTimeNanos, &wakeTimeNanos);
719         if (framesProcessed < 0) {
720             result = framesProcessed;
721             break;
722         }
723         framesLeft -= (int32_t) framesProcessed;
724         audioData += framesProcessed * getBytesPerFrame();
725 
726         // Should we block?
727         if (timeoutNanoseconds == 0) {
728             break; // don't block
729         } else if (wakeTimeNanos != 0) {
730             if (!mAudioEndpoint->isFreeRunning()) {
731                 // If there is software on the other end of the FIFO then it may get delayed.
732                 // So wake up just a little after we expect it to be ready.
733                 wakeTimeNanos += mWakeupDelayNanos;
734             }
735 
736             currentTimeNanos = AudioClock::getNanoseconds();
737             int64_t earliestWakeTime = currentTimeNanos + mMinimumSleepNanos;
738             // Guarantee a minimum sleep time.
739             if (wakeTimeNanos < earliestWakeTime) {
740                 wakeTimeNanos = earliestWakeTime;
741             }
742 
743             if (wakeTimeNanos > deadlineNanos) {
744                 // If we time out, just return the framesWritten so far.
745                 // TODO remove after we fix the deadline bug
746                 ALOGW("processData(): entered at %lld nanos, currently %lld",
747                       (long long) entryTimeNanos, (long long) currentTimeNanos);
748                 ALOGW("processData(): TIMEOUT after %lld nanos",
749                       (long long) timeoutNanoseconds);
750                 ALOGW("processData(): wakeTime = %lld, deadline = %lld nanos",
751                       (long long) wakeTimeNanos, (long long) deadlineNanos);
752                 ALOGW("processData(): past deadline by %d micros",
753                       (int)((wakeTimeNanos - deadlineNanos) / AAUDIO_NANOS_PER_MICROSECOND));
754                 mClockModel.dump();
755                 mAudioEndpoint->dump();
756                 break;
757             }
758 
759             if (ATRACE_ENABLED()) {
760                 int32_t fullFrames = mAudioEndpoint->getFullFramesAvailable();
761                 ATRACE_INT(fifoName, fullFrames);
762                 int64_t sleepForNanos = wakeTimeNanos - currentTimeNanos;
763                 ATRACE_INT("aaSlpNs", (int32_t)sleepForNanos);
764             }
765 
766             AudioClock::sleepUntilNanoTime(wakeTimeNanos);
767             currentTimeNanos = AudioClock::getNanoseconds();
768         }
769     }
770 
771     if (ATRACE_ENABLED()) {
772         int32_t fullFrames = mAudioEndpoint->getFullFramesAvailable();
773         ATRACE_INT(fifoName, fullFrames);
774     }
775 
776     // return error or framesProcessed
777     (void) loopCount;
778     ATRACE_END();
779     return (result < 0) ? result : numFrames - framesLeft;
780 }
781 
processTimestamp(uint64_t position,int64_t time)782 void AudioStreamInternal::processTimestamp(uint64_t position, int64_t time) {
783     mClockModel.processTimestamp(position, time);
784 }
785 
setBufferSize(int32_t requestedFrames)786 aaudio_result_t AudioStreamInternal::setBufferSize(int32_t requestedFrames) {
787     int32_t adjustedFrames = requestedFrames;
788     const int32_t maximumSize = getBufferCapacity() - getFramesPerBurst();
789     // Minimum size should be a multiple number of bursts.
790     const int32_t minimumSize = 1 * getFramesPerBurst();
791 
792     // Clip to minimum size so that rounding up will work better.
793     adjustedFrames = std::max(minimumSize, adjustedFrames);
794 
795     // Prevent arithmetic overflow by clipping before we round.
796     if (adjustedFrames >= maximumSize) {
797         adjustedFrames = maximumSize;
798     } else {
799         // Round to the next highest burst size.
800         int32_t numBursts = (adjustedFrames + getFramesPerBurst() - 1) / getFramesPerBurst();
801         adjustedFrames = numBursts * getFramesPerBurst();
802         // Clip just in case maximumSize is not a multiple of getFramesPerBurst().
803         adjustedFrames = std::min(maximumSize, adjustedFrames);
804     }
805 
806     if (mAudioEndpoint) {
807         // Clip against the actual size from the endpoint.
808         int32_t actualFrames = 0;
809         // Set to maximum size so we can write extra data when ready in order to reduce glitches.
810         // The amount we keep in the buffer is controlled by mBufferSizeInFrames.
811         mAudioEndpoint->setBufferSizeInFrames(maximumSize, &actualFrames);
812         // actualFrames should be <= actual maximum size of endpoint
813         adjustedFrames = std::min(actualFrames, adjustedFrames);
814     }
815 
816     if (adjustedFrames != mBufferSizeInFrames) {
817         android::mediametrics::LogItem(mMetricsId)
818                 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETBUFFERSIZE)
819                 .set(AMEDIAMETRICS_PROP_BUFFERSIZEFRAMES, adjustedFrames)
820                 .set(AMEDIAMETRICS_PROP_UNDERRUN, (int32_t) getXRunCount())
821                 .record();
822     }
823 
824     mBufferSizeInFrames = adjustedFrames;
825     ALOGV("%s(%d) returns %d", __func__, requestedFrames, adjustedFrames);
826     return (aaudio_result_t) adjustedFrames;
827 }
828 
getBufferSize() const829 int32_t AudioStreamInternal::getBufferSize() const {
830     return mBufferSizeInFrames;
831 }
832 
getBufferCapacity() const833 int32_t AudioStreamInternal::getBufferCapacity() const {
834     return mBufferCapacityInFrames;
835 }
836 
isClockModelInControl() const837 bool AudioStreamInternal::isClockModelInControl() const {
838     return isActive() && mAudioEndpoint->isFreeRunning() && mClockModel.isRunning();
839 }
840