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