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