1 /*
2  * Copyright 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 "AudioStreamTrack"
18 //#define LOG_NDEBUG 0
19 #include <utils/Log.h>
20 
21 #include <stdint.h>
22 #include <media/AudioTrack.h>
23 
24 #include <aaudio/AAudio.h>
25 #include <system/audio.h>
26 
27 #include "core/AudioGlobal.h"
28 #include "legacy/AudioStreamLegacy.h"
29 #include "legacy/AudioStreamTrack.h"
30 #include "utility/AudioClock.h"
31 #include "utility/FixedBlockReader.h"
32 
33 using namespace android;
34 using namespace aaudio;
35 
36 using android::content::AttributionSourceState;
37 
38 // Arbitrary and somewhat generous number of bursts.
39 #define DEFAULT_BURSTS_PER_BUFFER_CAPACITY     8
40 
41 /*
42  * Create a stream that uses the AudioTrack.
43  */
AudioStreamTrack()44 AudioStreamTrack::AudioStreamTrack()
45     : AudioStreamLegacy()
46     , mFixedBlockReader(*this)
47 {
48 }
49 
~AudioStreamTrack()50 AudioStreamTrack::~AudioStreamTrack()
51 {
52     const aaudio_stream_state_t state = getState();
53     bool bad = !(state == AAUDIO_STREAM_STATE_UNINITIALIZED || state == AAUDIO_STREAM_STATE_CLOSED);
54     ALOGE_IF(bad, "stream not closed, in state %d", state);
55 }
56 
open(const AudioStreamBuilder & builder)57 aaudio_result_t AudioStreamTrack::open(const AudioStreamBuilder& builder)
58 {
59     aaudio_result_t result = AAUDIO_OK;
60 
61     result = AudioStream::open(builder);
62     if (result != OK) {
63         return result;
64     }
65 
66     const aaudio_session_id_t requestedSessionId = builder.getSessionId();
67     const audio_session_t sessionId = AAudioConvert_aaudioToAndroidSessionId(requestedSessionId);
68 
69     audio_channel_mask_t channelMask =
70             AAudio_getChannelMaskForOpen(getChannelMask(), getSamplesPerFrame(), false /*isInput*/);
71 
72     // Set flags based on selected parameters.
73     audio_output_flags_t flags;
74     aaudio_performance_mode_t perfMode = getPerformanceMode();
75     switch(perfMode) {
76         case AAUDIO_PERFORMANCE_MODE_LOW_LATENCY: {
77             // Bypass the normal mixer and go straight to the FAST mixer.
78             // Some Usages need RAW mode so they can get the lowest possible latency.
79             // Other Usages should avoid RAW because it can interfere with
80             // dual sink routing or other features.
81             bool usageBenefitsFromRaw = getUsage() == AAUDIO_USAGE_GAME ||
82                     getUsage() == AAUDIO_USAGE_MEDIA;
83             // If an app does not ask for a sessionId then there will be no effects.
84             // So we can use the use RAW flag.
85             flags = (audio_output_flags_t) (((requestedSessionId == AAUDIO_SESSION_ID_NONE)
86                                              && usageBenefitsFromRaw)
87                                             ? (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_RAW)
88                                             : (AUDIO_OUTPUT_FLAG_FAST));
89         }
90             break;
91 
92         case AAUDIO_PERFORMANCE_MODE_POWER_SAVING:
93             // This uses a mixer that wakes up less often than the FAST mixer.
94             flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
95             break;
96 
97         case AAUDIO_PERFORMANCE_MODE_NONE:
98         default:
99             // No flags. Use a normal mixer in front of the FAST mixer.
100             flags = AUDIO_OUTPUT_FLAG_NONE;
101             break;
102     }
103 
104     size_t frameCount = (size_t)builder.getBufferCapacity();
105 
106     // To avoid glitching, let AudioFlinger pick the optimal burst size.
107     int32_t notificationFrames = 0;
108 
109     const audio_format_t format = (getFormat() == AUDIO_FORMAT_DEFAULT)
110             ? AUDIO_FORMAT_PCM_FLOAT
111             : getFormat();
112 
113     // Setup the callback if there is one.
114     wp<AudioTrack::IAudioTrackCallback> callback;
115     // Note that TRANSFER_SYNC does not allow FAST track
116     AudioTrack::transfer_type streamTransferType = AudioTrack::transfer_type::TRANSFER_SYNC;
117     if (builder.getDataCallbackProc() != nullptr) {
118         streamTransferType = AudioTrack::transfer_type::TRANSFER_CALLBACK;
119         callback = wp<AudioTrack::IAudioTrackCallback>::fromExisting(this);
120 
121         // If the total buffer size is unspecified then base the size on the burst size.
122         if (frameCount == 0
123                 && ((flags & AUDIO_OUTPUT_FLAG_FAST) != 0)) {
124             // Take advantage of a special trick that allows us to create a buffer
125             // that is some multiple of the burst size.
126             notificationFrames = 0 - DEFAULT_BURSTS_PER_BUFFER_CAPACITY;
127         }
128     }
129     mCallbackBufferSize = builder.getFramesPerDataCallback();
130 
131     ALOGD("open(), request notificationFrames = %d, frameCount = %u",
132           notificationFrames, (uint)frameCount);
133 
134     // Don't call mAudioTrack->setDeviceId() because it will be overwritten by set()!
135     audio_port_handle_t selectedDeviceId = (getDeviceId() == AAUDIO_UNSPECIFIED)
136                                            ? AUDIO_PORT_HANDLE_NONE
137                                            : getDeviceId();
138 
139     const audio_content_type_t contentType =
140             AAudioConvert_contentTypeToInternal(builder.getContentType());
141     const audio_usage_t usage =
142             AAudioConvert_usageToInternal(builder.getUsage());
143     const audio_flags_mask_t attributesFlags = AAudio_computeAudioFlagsMask(
144                                                             builder.getAllowedCapturePolicy(),
145                                                             builder.getSpatializationBehavior(),
146                                                             builder.isContentSpatialized(),
147                                                             flags);
148 
149     const audio_attributes_t attributes = {
150             .content_type = contentType,
151             .usage = usage,
152             .source = AUDIO_SOURCE_DEFAULT, // only used for recording
153             .flags = attributesFlags,
154             .tags = ""
155     };
156 
157     mAudioTrack = new AudioTrack();
158     // TODO b/182392769: use attribution source util
159     mAudioTrack->set(
160             AUDIO_STREAM_DEFAULT,  // ignored because we pass attributes below
161             getSampleRate(),
162             format,
163             channelMask,
164             frameCount,
165             flags,
166             callback,
167             notificationFrames,
168             nullptr,       // DEFAULT sharedBuffer*/,
169             false,   // DEFAULT threadCanCallJava
170             sessionId,
171             streamTransferType,
172             nullptr,    // DEFAULT audio_offload_info_t
173             AttributionSourceState(), // DEFAULT uid and pid
174             &attributes,
175             // WARNING - If doNotReconnect set true then audio stops after plugging and unplugging
176             // headphones a few times.
177             false,   // DEFAULT doNotReconnect,
178             1.0f,    // DEFAULT maxRequiredSpeed
179             selectedDeviceId
180     );
181 
182     // Set it here so it can be logged by the destructor if the open failed.
183     mAudioTrack->setCallerName(kCallerName);
184 
185     // Did we get a valid track?
186     status_t status = mAudioTrack->initCheck();
187     if (status != NO_ERROR) {
188         safeReleaseClose();
189         ALOGE("open(), initCheck() returned %d", status);
190         return AAudioConvert_androidToAAudioResult(status);
191     }
192 
193     mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_TRACK)
194             + std::to_string(mAudioTrack->getPortId());
195     android::mediametrics::LogItem(mMetricsId)
196             .set(AMEDIAMETRICS_PROP_PERFORMANCEMODE,
197                  AudioGlobal_convertPerformanceModeToText(builder.getPerformanceMode()))
198             .set(AMEDIAMETRICS_PROP_SHARINGMODE,
199                  AudioGlobal_convertSharingModeToText(builder.getSharingMode()))
200             .set(AMEDIAMETRICS_PROP_ENCODINGCLIENT, toString(getFormat()).c_str()).record();
201 
202     doSetVolume();
203 
204     // Get the actual values from the AudioTrack.
205     setChannelMask(AAudioConvert_androidToAAudioChannelMask(
206         mAudioTrack->channelMask(), false /*isInput*/,
207         AAudio_isChannelIndexMask(getChannelMask())));
208     setFormat(mAudioTrack->format());
209     setDeviceFormat(mAudioTrack->format());
210     setSampleRate(mAudioTrack->getSampleRate());
211     setBufferCapacity(getBufferCapacityFromDevice());
212     setFramesPerBurst(getFramesPerBurstFromDevice());
213 
214     // Use the same values for device values.
215     setDeviceSamplesPerFrame(getSamplesPerFrame());
216     setDeviceSampleRate(mAudioTrack->getSampleRate());
217     setDeviceBufferCapacity(getBufferCapacityFromDevice());
218     setDeviceFramesPerBurst(getFramesPerBurstFromDevice());
219 
220     setHardwareSamplesPerFrame(mAudioTrack->getHalChannelCount());
221     setHardwareSampleRate(mAudioTrack->getHalSampleRate());
222     setHardwareFormat(mAudioTrack->getHalFormat());
223 
224     // We may need to pass the data through a block size adapter to guarantee constant size.
225     if (mCallbackBufferSize != AAUDIO_UNSPECIFIED) {
226         // This may need to change if we add format conversion before
227         // the block size adaptation.
228         mBlockAdapterBytesPerFrame = getBytesPerFrame();
229         int callbackSizeBytes = mBlockAdapterBytesPerFrame * mCallbackBufferSize;
230         mFixedBlockReader.open(callbackSizeBytes);
231         mBlockAdapter = &mFixedBlockReader;
232     } else {
233         mBlockAdapter = nullptr;
234     }
235 
236     setDeviceId(mAudioTrack->getRoutedDeviceId());
237 
238     aaudio_session_id_t actualSessionId =
239             (requestedSessionId == AAUDIO_SESSION_ID_NONE)
240             ? AAUDIO_SESSION_ID_NONE
241             : (aaudio_session_id_t) mAudioTrack->getSessionId();
242     setSessionId(actualSessionId);
243 
244     mAudioTrack->addAudioDeviceCallback(this);
245 
246     // Update performance mode based on the actual stream flags.
247     // For example, if the sample rate is not allowed then you won't get a FAST track.
248     audio_output_flags_t actualFlags = mAudioTrack->getFlags();
249     aaudio_performance_mode_t actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_NONE;
250     // We may not get the RAW flag. But as long as we get the FAST flag we can call it LOW_LATENCY.
251     if ((actualFlags & AUDIO_OUTPUT_FLAG_FAST) != 0) {
252         actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_LOW_LATENCY;
253     } else if ((actualFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
254         actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_POWER_SAVING;
255     }
256     setPerformanceMode(actualPerformanceMode);
257 
258     setSharingMode(AAUDIO_SHARING_MODE_SHARED); // EXCLUSIVE mode not supported in legacy
259 
260     // Log if we did not get what we asked for.
261     ALOGD_IF(actualFlags != flags,
262              "open() flags changed from 0x%08X to 0x%08X",
263              flags, actualFlags);
264     ALOGD_IF(actualPerformanceMode != perfMode,
265              "open() perfMode changed from %d to %d",
266              perfMode, actualPerformanceMode);
267 
268     if (getState() != AAUDIO_STREAM_STATE_UNINITIALIZED) {
269         ALOGE("%s - Open canceled since state = %d", __func__, getState());
270         if (isDisconnected())
271         {
272             ALOGE("%s - Opening while state is disconnected", __func__);
273             safeReleaseClose();
274             return AAUDIO_ERROR_DISCONNECTED;
275         }
276         safeReleaseClose();
277         return AAUDIO_ERROR_INVALID_STATE;
278     }
279 
280     setState(AAUDIO_STREAM_STATE_OPEN);
281     return AAUDIO_OK;
282 }
283 
release_l()284 aaudio_result_t AudioStreamTrack::release_l() {
285     if (getState() != AAUDIO_STREAM_STATE_CLOSING) {
286         status_t err = mAudioTrack->removeAudioDeviceCallback(this);
287         ALOGE_IF(err, "%s() removeAudioDeviceCallback returned %d", __func__, err);
288         logReleaseBufferState();
289         // Data callbacks may still be running!
290         return AudioStream::release_l();
291     } else {
292         return AAUDIO_OK; // already released
293     }
294 }
295 
close_l()296 void AudioStreamTrack::close_l() {
297     // The callbacks are normally joined in the AudioTrack destructor.
298     // But if another object has a reference to the AudioTrack then
299     // it will not get deleted here.
300     // So we should join callbacks explicitly before returning.
301     // Unlock around the join to avoid deadlocks if the callback tries to lock.
302     // This can happen if the callback returns AAUDIO_CALLBACK_RESULT_STOP
303     mStreamLock.unlock();
304     mAudioTrack->stopAndJoinCallbacks();
305     mStreamLock.lock();
306     mAudioTrack.clear();
307     // Do not close mFixedBlockReader. It has a unique_ptr to its buffer
308     // so it will clean up by itself.
309     AudioStream::close_l();
310 }
311 
312 
onNewIAudioTrack()313 void AudioStreamTrack::onNewIAudioTrack() {
314     // Stream got rerouted so we disconnect.
315     // request stream disconnect if the restored AudioTrack has properties not matching
316     // what was requested initially
317     if (mAudioTrack->channelCount() != getSamplesPerFrame()
318           || mAudioTrack->format() != getFormat()
319           || mAudioTrack->getSampleRate() != getSampleRate()
320           || mAudioTrack->getRoutedDeviceId() != getDeviceId()
321           || getBufferCapacityFromDevice() != getBufferCapacity()
322           || getFramesPerBurstFromDevice() != getFramesPerBurst()) {
323         AudioStreamLegacy::onNewIAudioTrack();
324     }
325 }
326 
requestStart_l()327 aaudio_result_t AudioStreamTrack::requestStart_l() {
328     if (mAudioTrack.get() == nullptr) {
329         ALOGE("requestStart() no AudioTrack");
330         return AAUDIO_ERROR_INVALID_STATE;
331     }
332     // Get current position so we can detect when the track is playing.
333     status_t err = mAudioTrack->getPosition(&mPositionWhenStarting);
334     if (err != OK) {
335         return AAudioConvert_androidToAAudioResult(err);
336     }
337 
338     // Enable callback before starting AudioTrack to avoid shutting
339     // down because of a race condition.
340     mCallbackEnabled.store(true);
341     aaudio_stream_state_t originalState = getState();
342     // Set before starting the callback so that we are in the correct state
343     // before updateStateMachine() can be called by the callback.
344     setState(AAUDIO_STREAM_STATE_STARTING);
345     err = mAudioTrack->start();
346     if (err != OK) {
347         mCallbackEnabled.store(false);
348         setState(originalState);
349         return AAudioConvert_androidToAAudioResult(err);
350     }
351     return AAUDIO_OK;
352 }
353 
requestPause_l()354 aaudio_result_t AudioStreamTrack::requestPause_l() {
355     if (mAudioTrack.get() == nullptr) {
356         ALOGE("%s() no AudioTrack", __func__);
357         return AAUDIO_ERROR_INVALID_STATE;
358     }
359 
360     setState(AAUDIO_STREAM_STATE_PAUSING);
361     mAudioTrack->pause();
362     mCallbackEnabled.store(false);
363     status_t err = mAudioTrack->getPosition(&mPositionWhenPausing);
364     if (err != OK) {
365         return AAudioConvert_androidToAAudioResult(err);
366     }
367     return checkForDisconnectRequest(false);
368 }
369 
requestFlush_l()370 aaudio_result_t AudioStreamTrack::requestFlush_l() {
371     if (mAudioTrack.get() == nullptr) {
372         ALOGE("%s() no AudioTrack", __func__);
373         return AAUDIO_ERROR_INVALID_STATE;
374     }
375 
376     setState(AAUDIO_STREAM_STATE_FLUSHING);
377     incrementFramesRead(getFramesWritten() - getFramesRead());
378     mAudioTrack->flush();
379     mFramesRead.reset32(); // service reads frames, service position reset on flush
380     mTimestampPosition.reset32();
381     return AAUDIO_OK;
382 }
383 
requestStop_l()384 aaudio_result_t AudioStreamTrack::requestStop_l() {
385     if (mAudioTrack.get() == nullptr) {
386         ALOGE("%s() no AudioTrack", __func__);
387         return AAUDIO_ERROR_INVALID_STATE;
388     }
389 
390     setState(AAUDIO_STREAM_STATE_STOPPING);
391     mFramesRead.catchUpTo(getFramesWritten());
392     mTimestampPosition.catchUpTo(getFramesWritten());
393     mFramesRead.reset32(); // service reads frames, service position reset on stop
394     mTimestampPosition.reset32();
395     mAudioTrack->stop();
396     mCallbackEnabled.store(false);
397     return checkForDisconnectRequest(false);;
398 }
399 
processCommands()400 aaudio_result_t AudioStreamTrack::processCommands() {
401     status_t err;
402     aaudio_wrapping_frames_t position;
403     switch (getState()) {
404     // TODO add better state visibility to AudioTrack
405     case AAUDIO_STREAM_STATE_STARTING:
406         if (mAudioTrack->hasStarted()) {
407             setState(AAUDIO_STREAM_STATE_STARTED);
408         }
409         break;
410     case AAUDIO_STREAM_STATE_PAUSING:
411         if (mAudioTrack->stopped()) {
412             err = mAudioTrack->getPosition(&position);
413             if (err != OK) {
414                 return AAudioConvert_androidToAAudioResult(err);
415             } else if (position == mPositionWhenPausing) {
416                 // Has stream really stopped advancing?
417                 setState(AAUDIO_STREAM_STATE_PAUSED);
418             }
419             mPositionWhenPausing = position;
420         }
421         break;
422     case AAUDIO_STREAM_STATE_FLUSHING:
423         {
424             err = mAudioTrack->getPosition(&position);
425             if (err != OK) {
426                 return AAudioConvert_androidToAAudioResult(err);
427             } else if (position == 0) {
428                 setState(AAUDIO_STREAM_STATE_FLUSHED);
429             }
430         }
431         break;
432     case AAUDIO_STREAM_STATE_STOPPING:
433         if (mAudioTrack->stopped()) {
434             setState(AAUDIO_STREAM_STATE_STOPPED);
435         }
436         break;
437     default:
438         break;
439     }
440     return AAUDIO_OK;
441 }
442 
write(const void * buffer,int32_t numFrames,int64_t timeoutNanoseconds)443 aaudio_result_t AudioStreamTrack::write(const void *buffer,
444                                       int32_t numFrames,
445                                       int64_t timeoutNanoseconds)
446 {
447     int32_t bytesPerFrame = getBytesPerFrame();
448     int32_t numBytes;
449     aaudio_result_t result = AAudioConvert_framesToBytes(numFrames, bytesPerFrame, &numBytes);
450     if (result != AAUDIO_OK) {
451         return result;
452     }
453 
454     if (isDisconnected()) {
455         return AAUDIO_ERROR_DISCONNECTED;
456     }
457 
458     // TODO add timeout to AudioTrack
459     bool blocking = timeoutNanoseconds > 0;
460     ssize_t bytesWritten = mAudioTrack->write(buffer, numBytes, blocking);
461     if (bytesWritten == WOULD_BLOCK) {
462         return 0;
463     } else if (bytesWritten < 0) {
464         ALOGE("invalid write, returned %d", (int)bytesWritten);
465         // in this context, a DEAD_OBJECT is more likely to be a disconnect notification due to
466         // AudioTrack invalidation
467         if (bytesWritten == DEAD_OBJECT) {
468             setDisconnected();
469             return AAUDIO_ERROR_DISCONNECTED;
470         }
471         return AAudioConvert_androidToAAudioResult(bytesWritten);
472     }
473     int32_t framesWritten = (int32_t)(bytesWritten / bytesPerFrame);
474     incrementFramesWritten(framesWritten);
475 
476     result = updateStateMachine();
477     if (result != AAUDIO_OK) {
478         return result;
479     }
480 
481     return framesWritten;
482 }
483 
setBufferSize(int32_t requestedFrames)484 aaudio_result_t AudioStreamTrack::setBufferSize(int32_t requestedFrames)
485 {
486     // Do not ask for less than one burst.
487     if (requestedFrames < getFramesPerBurst()) {
488         requestedFrames = getFramesPerBurst();
489     }
490     ssize_t result = mAudioTrack->setBufferSizeInFrames(requestedFrames);
491     if (result < 0) {
492         return AAudioConvert_androidToAAudioResult(result);
493     } else {
494         return result;
495     }
496 }
497 
getBufferSize() const498 int32_t AudioStreamTrack::getBufferSize() const
499 {
500     return static_cast<int32_t>(mAudioTrack->getBufferSizeInFrames());
501 }
502 
getBufferCapacityFromDevice() const503 int32_t AudioStreamTrack::getBufferCapacityFromDevice() const
504 {
505     return static_cast<int32_t>(mAudioTrack->frameCount());
506 }
507 
getXRunCount() const508 int32_t AudioStreamTrack::getXRunCount() const
509 {
510     return static_cast<int32_t>(mAudioTrack->getUnderrunCount());
511 }
512 
getFramesPerBurstFromDevice() const513 int32_t AudioStreamTrack::getFramesPerBurstFromDevice() const {
514     return static_cast<int32_t>(mAudioTrack->getNotificationPeriodInFrames());
515 }
516 
getFramesRead()517 int64_t AudioStreamTrack::getFramesRead() {
518     aaudio_wrapping_frames_t position;
519     status_t result;
520     switch (getState()) {
521     case AAUDIO_STREAM_STATE_STARTING:
522     case AAUDIO_STREAM_STATE_STARTED:
523     case AAUDIO_STREAM_STATE_STOPPING:
524     case AAUDIO_STREAM_STATE_PAUSING:
525     case AAUDIO_STREAM_STATE_PAUSED:
526         result = mAudioTrack->getPosition(&position);
527         if (result == OK) {
528             mFramesRead.update32((int32_t)position);
529         }
530         break;
531     default:
532         break;
533     }
534     return AudioStreamLegacy::getFramesRead();
535 }
536 
getTimestamp(clockid_t clockId,int64_t * framePosition,int64_t * timeNanoseconds)537 aaudio_result_t AudioStreamTrack::getTimestamp(clockid_t clockId,
538                                      int64_t *framePosition,
539                                      int64_t *timeNanoseconds) {
540     ExtendedTimestamp extendedTimestamp;
541     status_t status = mAudioTrack->getTimestamp(&extendedTimestamp);
542     if (status == WOULD_BLOCK) {
543         return AAUDIO_ERROR_INVALID_STATE;
544     } if (status != NO_ERROR) {
545         return AAudioConvert_androidToAAudioResult(status);
546     }
547     int64_t position = 0;
548     int64_t nanoseconds = 0;
549     aaudio_result_t result = getBestTimestamp(clockId, &position,
550                                               &nanoseconds, &extendedTimestamp);
551     if (result == AAUDIO_OK) {
552         if (position < getFramesWritten()) {
553             *framePosition = position;
554             *timeNanoseconds = nanoseconds;
555             return result;
556         } else {
557             return AAUDIO_ERROR_INVALID_STATE; // TODO review, documented but not consistent
558         }
559     }
560     return result;
561 }
562 
doSetVolume()563 status_t AudioStreamTrack::doSetVolume() {
564     status_t status = NO_INIT;
565     if (mAudioTrack.get() != nullptr) {
566         float volume = getDuckAndMuteVolume();
567         mAudioTrack->setVolume(volume, volume);
568         status = NO_ERROR;
569     }
570     return status;
571 }
572 
registerPlayerBase()573 void AudioStreamTrack::registerPlayerBase() {
574     AudioStream::registerPlayerBase();
575 
576     if (mAudioTrack == nullptr) {
577         ALOGW("%s: cannot set piid, AudioTrack is null", __func__);
578         return;
579     }
580     mAudioTrack->setPlayerIId(mPlayerBase->getPlayerIId());
581 }
582 
583 #if AAUDIO_USE_VOLUME_SHAPER
584 
585 using namespace android::media::VolumeShaper;
586 
applyVolumeShaper(const VolumeShaper::Configuration & configuration,const VolumeShaper::Operation & operation)587 binder::Status AudioStreamTrack::applyVolumeShaper(
588         const VolumeShaper::Configuration& configuration,
589         const VolumeShaper::Operation& operation) {
590 
591     sp<VolumeShaper::Configuration> spConfiguration = new VolumeShaper::Configuration(configuration);
592     sp<VolumeShaper::Operation> spOperation = new VolumeShaper::Operation(operation);
593 
594     if (mAudioTrack.get() != nullptr) {
595         ALOGD("applyVolumeShaper() from IPlayer");
596         binder::Status status = mAudioTrack->applyVolumeShaper(spConfiguration, spOperation);
597         if (status < 0) { // a non-negative value is the volume shaper id.
598             ALOGE("applyVolumeShaper() failed with status %d", status);
599         }
600         return aidl_utils::binderStatusFromStatusT(status);
601     } else {
602         ALOGD("applyVolumeShaper()"
603                       " no AudioTrack for volume control from IPlayer");
604         return binder::Status::ok();
605     }
606 }
607 #endif
608