blob: 8e58949727edf2a4cb2aa1e39d918b4f830fc7a9 [file] [log] [blame]
Phil Burke1ce4912016-11-21 10:40:25 -08001/*
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
Phil Burk965650e2017-09-07 21:00:09 -070017#define LOG_TAG "AudioStreamTrack"
Phil Burke1ce4912016-11-21 10:40:25 -080018//#define LOG_NDEBUG 0
19#include <utils/Log.h>
20
21#include <stdint.h>
22#include <media/AudioTrack.h>
Phil Burke1ce4912016-11-21 10:40:25 -080023
Phil Burke4d7bb42017-03-28 11:32:39 -070024#include <aaudio/AAudio.h>
Phil Burked816012018-02-06 12:40:50 -080025#include <system/audio.h>
jiabinef348b82021-04-19 16:53:08 +000026
27#include "core/AudioGlobal.h"
Phil Burke4d7bb42017-03-28 11:32:39 -070028#include "legacy/AudioStreamLegacy.h"
29#include "legacy/AudioStreamTrack.h"
jiabinef348b82021-04-19 16:53:08 +000030#include "utility/AudioClock.h"
Phil Burke4d7bb42017-03-28 11:32:39 -070031#include "utility/FixedBlockReader.h"
Phil Burke1ce4912016-11-21 10:40:25 -080032
33using namespace android;
Phil Burk5ed503c2017-02-01 09:38:15 -080034using namespace aaudio;
Phil Burke1ce4912016-11-21 10:40:25 -080035
Svet Ganov3e5f14f2021-05-13 22:51:08 +000036using android::content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070037
Phil Burke4d7bb42017-03-28 11:32:39 -070038// Arbitrary and somewhat generous number of bursts.
39#define DEFAULT_BURSTS_PER_BUFFER_CAPACITY 8
40
Phil Burke1ce4912016-11-21 10:40:25 -080041/*
42 * Create a stream that uses the AudioTrack.
43 */
44AudioStreamTrack::AudioStreamTrack()
Phil Burke4d7bb42017-03-28 11:32:39 -070045 : AudioStreamLegacy()
46 , mFixedBlockReader(*this)
Phil Burke1ce4912016-11-21 10:40:25 -080047{
48}
49
50AudioStreamTrack::~AudioStreamTrack()
51{
Phil Burk5ed503c2017-02-01 09:38:15 -080052 const aaudio_stream_state_t state = getState();
53 bool bad = !(state == AAUDIO_STREAM_STATE_UNINITIALIZED || state == AAUDIO_STREAM_STATE_CLOSED);
Phil Burke1ce4912016-11-21 10:40:25 -080054 ALOGE_IF(bad, "stream not closed, in state %d", state);
55}
56
Phil Burk5ed503c2017-02-01 09:38:15 -080057aaudio_result_t AudioStreamTrack::open(const AudioStreamBuilder& builder)
Phil Burke1ce4912016-11-21 10:40:25 -080058{
Phil Burk5ed503c2017-02-01 09:38:15 -080059 aaudio_result_t result = AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -080060
61 result = AudioStream::open(builder);
62 if (result != OK) {
63 return result;
64 }
65
Phil Burk8ffcf612018-05-23 14:38:07 -070066 const aaudio_session_id_t requestedSessionId = builder.getSessionId();
67 const audio_session_t sessionId = AAudioConvert_aaudioToAndroidSessionId(requestedSessionId);
68
jiabina9094092021-06-28 20:36:45 +000069 audio_channel_mask_t channelMask =
70 AAudio_getChannelMaskForOpen(getChannelMask(), getSamplesPerFrame(), false /*isInput*/);
Phil Burke1ce4912016-11-21 10:40:25 -080071
Phil Burk8ffcf612018-05-23 14:38:07 -070072 audio_output_flags_t flags;
Phil Burk30a70772017-05-16 11:20:36 -070073 aaudio_performance_mode_t perfMode = getPerformanceMode();
74 switch(perfMode) {
Phil Burke2fbb592017-05-01 15:05:52 -070075 case AAUDIO_PERFORMANCE_MODE_LOW_LATENCY:
76 // Bypass the normal mixer and go straight to the FAST mixer.
Phil Burk8ffcf612018-05-23 14:38:07 -070077 // If the app asks for a sessionId then it means they want to use effects.
78 // So don't use RAW flag.
79 flags = (audio_output_flags_t) ((requestedSessionId == AAUDIO_SESSION_ID_NONE)
80 ? (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_RAW)
81 : (AUDIO_OUTPUT_FLAG_FAST));
Phil Burke2fbb592017-05-01 15:05:52 -070082 break;
83
84 case AAUDIO_PERFORMANCE_MODE_POWER_SAVING:
85 // This uses a mixer that wakes up less often than the FAST mixer.
86 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
87 break;
88
89 case AAUDIO_PERFORMANCE_MODE_NONE:
90 default:
91 // No flags. Use a normal mixer in front of the FAST mixer.
Phil Burk8ffcf612018-05-23 14:38:07 -070092 flags = AUDIO_OUTPUT_FLAG_NONE;
Phil Burke2fbb592017-05-01 15:05:52 -070093 break;
94 }
Phil Burke4d7bb42017-03-28 11:32:39 -070095
Phil Burkcf5f6d22017-05-26 12:35:07 -070096 size_t frameCount = (size_t)builder.getBufferCapacity();
Phil Burke4d7bb42017-03-28 11:32:39 -070097
Phil Burke69bfcb2020-08-20 00:10:35 +000098 // To avoid glitching, let AudioFlinger pick the optimal burst size.
Phil Burke4d7bb42017-03-28 11:32:39 -070099 int32_t notificationFrames = 0;
100
Phil Burk0127c1b2018-03-29 13:48:06 -0700101 const audio_format_t format = (getFormat() == AUDIO_FORMAT_DEFAULT)
Phil Burke1ce4912016-11-21 10:40:25 -0800102 ? AUDIO_FORMAT_PCM_FLOAT
Phil Burk0127c1b2018-03-29 13:48:06 -0700103 : getFormat();
Phil Burke1ce4912016-11-21 10:40:25 -0800104
Phil Burke4d7bb42017-03-28 11:32:39 -0700105 // Setup the callback if there is one.
106 AudioTrack::callback_t callback = nullptr;
107 void *callbackData = nullptr;
108 // Note that TRANSFER_SYNC does not allow FAST track
109 AudioTrack::transfer_type streamTransferType = AudioTrack::transfer_type::TRANSFER_SYNC;
110 if (builder.getDataCallbackProc() != nullptr) {
111 streamTransferType = AudioTrack::transfer_type::TRANSFER_CALLBACK;
112 callback = getLegacyCallback();
113 callbackData = this;
114
Phil Burke4d7bb42017-03-28 11:32:39 -0700115 // If the total buffer size is unspecified then base the size on the burst size.
Phil Burk4485d412017-05-09 15:55:02 -0700116 if (frameCount == 0
117 && ((flags & AUDIO_OUTPUT_FLAG_FAST) != 0)) {
Phil Burke4d7bb42017-03-28 11:32:39 -0700118 // Take advantage of a special trick that allows us to create a buffer
119 // that is some multiple of the burst size.
120 notificationFrames = 0 - DEFAULT_BURSTS_PER_BUFFER_CAPACITY;
121 }
122 }
123 mCallbackBufferSize = builder.getFramesPerDataCallback();
124
Phil Burkfbf031e2017-10-12 15:58:31 -0700125 ALOGD("open(), request notificationFrames = %d, frameCount = %u",
Phil Burkcf5f6d22017-05-26 12:35:07 -0700126 notificationFrames, (uint)frameCount);
Phil Burkee995392017-12-11 11:44:36 -0800127
128 // Don't call mAudioTrack->setDeviceId() because it will be overwritten by set()!
129 audio_port_handle_t selectedDeviceId = (getDeviceId() == AAUDIO_UNSPECIFIED)
130 ? AUDIO_PORT_HANDLE_NONE
131 : getDeviceId();
132
Phil Burkd4ccc622017-12-20 15:32:44 -0800133 const audio_content_type_t contentType =
134 AAudioConvert_contentTypeToInternal(builder.getContentType());
135 const audio_usage_t usage =
136 AAudioConvert_usageToInternal(builder.getUsage());
Kevin Rocard68646ba2019-03-20 13:26:49 -0700137 const audio_flags_mask_t attributesFlags =
138 AAudioConvert_allowCapturePolicyToAudioFlagsMask(builder.getAllowedCapturePolicy());
Phil Burkd4ccc622017-12-20 15:32:44 -0800139
140 const audio_attributes_t attributes = {
141 .content_type = contentType,
142 .usage = usage,
143 .source = AUDIO_SOURCE_DEFAULT, // only used for recording
Kevin Rocard68646ba2019-03-20 13:26:49 -0700144 .flags = attributesFlags,
Phil Burkd4ccc622017-12-20 15:32:44 -0800145 .tags = ""
146 };
147
Phil Burkee995392017-12-11 11:44:36 -0800148 mAudioTrack = new AudioTrack();
Svet Ganov3e5f14f2021-05-13 22:51:08 +0000149 // TODO b/182392769: use attribution source util
Eric Laurentfb00fc72017-05-25 18:17:12 -0700150 mAudioTrack->set(
Phil Burkd4ccc622017-12-20 15:32:44 -0800151 AUDIO_STREAM_DEFAULT, // ignored because we pass attributes below
Phil Burke1ce4912016-11-21 10:40:25 -0800152 getSampleRate(),
153 format,
154 channelMask,
155 frameCount,
156 flags,
157 callback,
Phil Burke4d7bb42017-03-28 11:32:39 -0700158 callbackData,
159 notificationFrames,
jiabind5bd06a2021-04-27 22:04:08 +0000160 nullptr, // DEFAULT sharedBuffer*/,
Phil Burkee995392017-12-11 11:44:36 -0800161 false, // DEFAULT threadCanCallJava
Phil Burk4e1af9f2018-01-03 15:54:35 -0800162 sessionId,
Phil Burkee995392017-12-11 11:44:36 -0800163 streamTransferType,
jiabind5bd06a2021-04-27 22:04:08 +0000164 nullptr, // DEFAULT audio_offload_info_t
Svet Ganov3e5f14f2021-05-13 22:51:08 +0000165 AttributionSourceState(), // DEFAULT uid and pid
Phil Burkd4ccc622017-12-20 15:32:44 -0800166 &attributes,
Phil Burkee995392017-12-11 11:44:36 -0800167 // WARNING - If doNotReconnect set true then audio stops after plugging and unplugging
168 // headphones a few times.
169 false, // DEFAULT doNotReconnect,
170 1.0f, // DEFAULT maxRequiredSpeed
171 selectedDeviceId
172 );
Phil Burke1ce4912016-11-21 10:40:25 -0800173
Phil Burkd3813f32020-04-23 16:26:15 -0700174 // Set it here so it can be logged by the destructor if the open failed.
175 mAudioTrack->setCallerName(kCallerName);
176
Phil Burke1ce4912016-11-21 10:40:25 -0800177 // Did we get a valid track?
178 status_t status = mAudioTrack->initCheck();
Phil Burkdec33ab2017-01-17 14:48:16 -0800179 if (status != NO_ERROR) {
Phil Burkdd582922020-10-15 20:29:51 +0000180 safeReleaseClose();
Phil Burkfbf031e2017-10-12 15:58:31 -0700181 ALOGE("open(), initCheck() returned %d", status);
Phil Burk5ed503c2017-02-01 09:38:15 -0800182 return AAudioConvert_androidToAAudioResult(status);
Phil Burke1ce4912016-11-21 10:40:25 -0800183 }
184
Phil Burka9876702020-04-20 18:16:15 -0700185 mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_TRACK)
186 + std::to_string(mAudioTrack->getPortId());
jiabinef348b82021-04-19 16:53:08 +0000187 android::mediametrics::LogItem(mMetricsId)
188 .set(AMEDIAMETRICS_PROP_PERFORMANCEMODE,
jiabinc8da9032021-04-28 20:42:36 +0000189 AudioGlobal_convertPerformanceModeToText(builder.getPerformanceMode()))
190 .set(AMEDIAMETRICS_PROP_SHARINGMODE,
191 AudioGlobal_convertSharingModeToText(builder.getSharingMode()))
jiabinef348b82021-04-19 16:53:08 +0000192 .set(AMEDIAMETRICS_PROP_ENCODINGCLIENT, toString(getFormat()).c_str()).record();
Phil Burka9876702020-04-20 18:16:15 -0700193
Phil Burk965650e2017-09-07 21:00:09 -0700194 doSetVolume();
Eric Laurent1d32e9f2017-06-02 14:01:32 -0700195
Phil Burke1ce4912016-11-21 10:40:25 -0800196 // Get the actual values from the AudioTrack.
jiabina9094092021-06-28 20:36:45 +0000197 setChannelMask(AAudioConvert_androidToAAudioChannelMask(
198 mAudioTrack->channelMask(), false /*isInput*/,
199 AAudio_isChannelIndexMask(getChannelMask())));
Phil Burk0127c1b2018-03-29 13:48:06 -0700200 setFormat(mAudioTrack->format());
201 setDeviceFormat(mAudioTrack->format());
Phil Burk8d97b8e2020-09-25 23:18:14 +0000202 setSampleRate(mAudioTrack->getSampleRate());
203 setBufferCapacity(getBufferCapacityFromDevice());
204 setFramesPerBurst(getFramesPerBurstFromDevice());
Phil Burkcf5f6d22017-05-26 12:35:07 -0700205
Phil Burke4d7bb42017-03-28 11:32:39 -0700206 // We may need to pass the data through a block size adapter to guarantee constant size.
207 if (mCallbackBufferSize != AAUDIO_UNSPECIFIED) {
Phil Burk4b867492020-02-12 10:58:05 -0800208 // This may need to change if we add format conversion before
209 // the block size adaptation.
210 mBlockAdapterBytesPerFrame = getBytesPerFrame();
211 int callbackSizeBytes = mBlockAdapterBytesPerFrame * mCallbackBufferSize;
Phil Burke4d7bb42017-03-28 11:32:39 -0700212 mFixedBlockReader.open(callbackSizeBytes);
213 mBlockAdapter = &mFixedBlockReader;
214 } else {
215 mBlockAdapter = nullptr;
216 }
Phil Burke1ce4912016-11-21 10:40:25 -0800217
Phil Burkc0c70e32017-02-09 13:18:38 -0800218 setDeviceId(mAudioTrack->getRoutedDeviceId());
Phil Burk4e1af9f2018-01-03 15:54:35 -0800219
220 aaudio_session_id_t actualSessionId =
221 (requestedSessionId == AAUDIO_SESSION_ID_NONE)
222 ? AAUDIO_SESSION_ID_NONE
223 : (aaudio_session_id_t) mAudioTrack->getSessionId();
224 setSessionId(actualSessionId);
225
Phil Burk58f5ce12020-08-12 14:29:10 +0000226 mAudioTrack->addAudioDeviceCallback(this);
Phil Burke1ce4912016-11-21 10:40:25 -0800227
Phil Burk09c27ca2017-08-24 22:12:56 -0700228 // Update performance mode based on the actual stream flags.
Phil Burk30a70772017-05-16 11:20:36 -0700229 // For example, if the sample rate is not allowed then you won't get a FAST track.
230 audio_output_flags_t actualFlags = mAudioTrack->getFlags();
231 aaudio_performance_mode_t actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_NONE;
Phil Burk09c27ca2017-08-24 22:12:56 -0700232 // We may not get the RAW flag. But as long as we get the FAST flag we can call it LOW_LATENCY.
233 if ((actualFlags & AUDIO_OUTPUT_FLAG_FAST) != 0) {
Phil Burk30a70772017-05-16 11:20:36 -0700234 actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_LOW_LATENCY;
Phil Burk30a70772017-05-16 11:20:36 -0700235 } else if ((actualFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
236 actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_POWER_SAVING;
237 }
238 setPerformanceMode(actualPerformanceMode);
Phil Burkefa56002017-08-02 15:07:21 -0700239
240 setSharingMode(AAUDIO_SHARING_MODE_SHARED); // EXCLUSIVE mode not supported in legacy
241
Phil Burk7216b3f2020-06-23 23:29:18 +0000242 // Log if we did not get what we asked for.
243 ALOGD_IF(actualFlags != flags,
Phil Burkfbf031e2017-10-12 15:58:31 -0700244 "open() flags changed from 0x%08X to 0x%08X",
Phil Burk30a70772017-05-16 11:20:36 -0700245 flags, actualFlags);
Phil Burk7216b3f2020-06-23 23:29:18 +0000246 ALOGD_IF(actualPerformanceMode != perfMode,
Phil Burkfbf031e2017-10-12 15:58:31 -0700247 "open() perfMode changed from %d to %d",
Phil Burk30a70772017-05-16 11:20:36 -0700248 perfMode, actualPerformanceMode);
249
Robert Wudaf7b242021-09-07 18:32:04 +0000250 if (getState() != AAUDIO_STREAM_STATE_UNINITIALIZED) {
251 ALOGE("%s - Open canceled since state = %d", __func__, getState());
252 if (getState() == AAUDIO_STREAM_STATE_DISCONNECTED)
253 {
254 ALOGE("%s - Opening while state is disconnected", __func__);
255 safeReleaseClose();
256 return AAUDIO_ERROR_DISCONNECTED;
257 }
258 safeReleaseClose();
259 return AAUDIO_ERROR_INVALID_STATE;
260 }
261
262 setState(AAUDIO_STREAM_STATE_OPEN);
Phil Burk5ed503c2017-02-01 09:38:15 -0800263 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800264}
265
Phil Burk8b4e05e2019-12-17 12:12:09 -0800266aaudio_result_t AudioStreamTrack::release_l() {
267 if (getState() != AAUDIO_STREAM_STATE_CLOSING) {
Phil Burk58f5ce12020-08-12 14:29:10 +0000268 status_t err = mAudioTrack->removeAudioDeviceCallback(this);
269 ALOGE_IF(err, "%s() removeAudioDeviceCallback returned %d", __func__, err);
Phil Burk64e16a72020-06-01 13:25:51 -0700270 logReleaseBufferState();
Phil Burk320910f2020-08-12 14:29:10 +0000271 // Data callbacks may still be running!
Phil Burk8b4e05e2019-12-17 12:12:09 -0800272 return AudioStream::release_l();
273 } else {
274 return AAUDIO_OK; // already released
Phil Burke1ce4912016-11-21 10:40:25 -0800275 }
Phil Burke1ce4912016-11-21 10:40:25 -0800276}
277
Phil Burk320910f2020-08-12 14:29:10 +0000278void AudioStreamTrack::close_l() {
Phil Burk7a9577c2021-03-12 20:12:11 +0000279 // The callbacks are normally joined in the AudioTrack destructor.
280 // But if another object has a reference to the AudioTrack then
281 // it will not get deleted here.
282 // So we should join callbacks explicitly before returning.
283 // Unlock around the join to avoid deadlocks if the callback tries to lock.
284 // This can happen if the callback returns AAUDIO_CALLBACK_RESULT_STOP
285 mStreamLock.unlock();
286 mAudioTrack->stopAndJoinCallbacks();
287 mStreamLock.lock();
Phil Burk320910f2020-08-12 14:29:10 +0000288 mAudioTrack.clear();
Phil Burk7a9577c2021-03-12 20:12:11 +0000289 // Do not close mFixedBlockReader. It has a unique_ptr to its buffer
290 // so it will clean up by itself.
Phil Burk320910f2020-08-12 14:29:10 +0000291 AudioStream::close_l();
292}
293
Phil Burke4d7bb42017-03-28 11:32:39 -0700294void AudioStreamTrack::processCallback(int event, void *info) {
295
296 switch (event) {
297 case AudioTrack::EVENT_MORE_DATA:
298 processCallbackCommon(AAUDIO_CALLBACK_OPERATION_PROCESS_DATA, info);
299 break;
300
301 // Stream got rerouted so we disconnect.
302 case AudioTrack::EVENT_NEW_IAUDIOTRACK:
Eric Laurent68eff052020-04-10 18:28:41 -0700303 // request stream disconnect if the restored AudioTrack has properties not matching
304 // what was requested initially
305 if (mAudioTrack->channelCount() != getSamplesPerFrame()
306 || mAudioTrack->format() != getFormat()
307 || mAudioTrack->getSampleRate() != getSampleRate()
308 || mAudioTrack->getRoutedDeviceId() != getDeviceId()
Phil Burk8d97b8e2020-09-25 23:18:14 +0000309 || getBufferCapacityFromDevice() != getBufferCapacity()
310 || getFramesPerBurstFromDevice() != getFramesPerBurst()) {
Eric Laurent68eff052020-04-10 18:28:41 -0700311 processCallbackCommon(AAUDIO_CALLBACK_OPERATION_DISCONNECTED, info);
312 }
Phil Burke4d7bb42017-03-28 11:32:39 -0700313 break;
314
315 default:
316 break;
317 }
318 return;
319}
320
Phil Burkdd582922020-10-15 20:29:51 +0000321aaudio_result_t AudioStreamTrack::requestStart_l() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800322 if (mAudioTrack.get() == nullptr) {
Phil Burkfbf031e2017-10-12 15:58:31 -0700323 ALOGE("requestStart() no AudioTrack");
Phil Burk5ed503c2017-02-01 09:38:15 -0800324 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800325 }
326 // Get current position so we can detect when the track is playing.
327 status_t err = mAudioTrack->getPosition(&mPositionWhenStarting);
328 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800329 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800330 }
Phil Burke4d7bb42017-03-28 11:32:39 -0700331
Phil Burk9e9a95b2018-01-18 12:14:15 -0800332 // Enable callback before starting AudioTrack to avoid shutting
333 // down because of a race condition.
334 mCallbackEnabled.store(true);
Phil Burk4c377ef2020-06-25 10:03:23 -0700335 aaudio_stream_state_t originalState = getState();
336 // Set before starting the callback so that we are in the correct state
337 // before updateStateMachine() can be called by the callback.
338 setState(AAUDIO_STREAM_STATE_STARTING);
Phil Burk965650e2017-09-07 21:00:09 -0700339 err = mAudioTrack->start();
Phil Burke1ce4912016-11-21 10:40:25 -0800340 if (err != OK) {
Phil Burk4c377ef2020-06-25 10:03:23 -0700341 mCallbackEnabled.store(false);
342 setState(originalState);
Phil Burk5ed503c2017-02-01 09:38:15 -0800343 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800344 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800345 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800346}
347
Phil Burkdd582922020-10-15 20:29:51 +0000348aaudio_result_t AudioStreamTrack::requestPause_l() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800349 if (mAudioTrack.get() == nullptr) {
Phil Burk1e83bee2018-12-17 14:15:20 -0800350 ALOGE("%s() no AudioTrack", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800351 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800352 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800353
Phil Burk5ed503c2017-02-01 09:38:15 -0800354 setState(AAUDIO_STREAM_STATE_PAUSING);
Phil Burk965650e2017-09-07 21:00:09 -0700355 mAudioTrack->pause();
Phil Burk9e9a95b2018-01-18 12:14:15 -0800356 mCallbackEnabled.store(false);
Phil Burke1ce4912016-11-21 10:40:25 -0800357 status_t err = mAudioTrack->getPosition(&mPositionWhenPausing);
358 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800359 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800360 }
Phil Burk134f1972017-12-08 13:06:11 -0800361 return checkForDisconnectRequest(false);
Phil Burke1ce4912016-11-21 10:40:25 -0800362}
363
Phil Burkdd582922020-10-15 20:29:51 +0000364aaudio_result_t AudioStreamTrack::requestFlush_l() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800365 if (mAudioTrack.get() == nullptr) {
Phil Burk1e83bee2018-12-17 14:15:20 -0800366 ALOGE("%s() no AudioTrack", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800367 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800368 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800369
Phil Burk5ed503c2017-02-01 09:38:15 -0800370 setState(AAUDIO_STREAM_STATE_FLUSHING);
Phil Burke1ce4912016-11-21 10:40:25 -0800371 incrementFramesRead(getFramesWritten() - getFramesRead());
372 mAudioTrack->flush();
Phil Burk2b6f1282018-05-10 15:26:30 -0700373 mFramesRead.reset32(); // service reads frames, service position reset on flush
Phil Burk7328a802017-08-30 09:29:48 -0700374 mTimestampPosition.reset32();
Phil Burk5ed503c2017-02-01 09:38:15 -0800375 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800376}
377
Phil Burkdd582922020-10-15 20:29:51 +0000378aaudio_result_t AudioStreamTrack::requestStop_l() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800379 if (mAudioTrack.get() == nullptr) {
Phil Burk1e83bee2018-12-17 14:15:20 -0800380 ALOGE("%s() no AudioTrack", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800381 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800382 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800383
Phil Burk5ed503c2017-02-01 09:38:15 -0800384 setState(AAUDIO_STREAM_STATE_STOPPING);
Phil Burk18c84762018-12-18 12:15:35 -0800385 mFramesRead.catchUpTo(getFramesWritten());
386 mTimestampPosition.catchUpTo(getFramesWritten());
Phil Burk2b6f1282018-05-10 15:26:30 -0700387 mFramesRead.reset32(); // service reads frames, service position reset on stop
Phil Burk7328a802017-08-30 09:29:48 -0700388 mTimestampPosition.reset32();
Phil Burk965650e2017-09-07 21:00:09 -0700389 mAudioTrack->stop();
Phil Burk9e9a95b2018-01-18 12:14:15 -0800390 mCallbackEnabled.store(false);
Phil Burk134f1972017-12-08 13:06:11 -0800391 return checkForDisconnectRequest(false);;
Phil Burke1ce4912016-11-21 10:40:25 -0800392}
393
Phil Burk0befec62017-07-28 15:12:13 -0700394aaudio_result_t AudioStreamTrack::updateStateMachine()
Phil Burke1ce4912016-11-21 10:40:25 -0800395{
396 status_t err;
Phil Burk5ed503c2017-02-01 09:38:15 -0800397 aaudio_wrapping_frames_t position;
Phil Burke1ce4912016-11-21 10:40:25 -0800398 switch (getState()) {
399 // TODO add better state visibility to AudioTrack
Phil Burk5ed503c2017-02-01 09:38:15 -0800400 case AAUDIO_STREAM_STATE_STARTING:
Phil Burke1ce4912016-11-21 10:40:25 -0800401 if (mAudioTrack->hasStarted()) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800402 setState(AAUDIO_STREAM_STATE_STARTED);
Phil Burke1ce4912016-11-21 10:40:25 -0800403 }
404 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800405 case AAUDIO_STREAM_STATE_PAUSING:
Phil Burke1ce4912016-11-21 10:40:25 -0800406 if (mAudioTrack->stopped()) {
407 err = mAudioTrack->getPosition(&position);
408 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800409 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800410 } else if (position == mPositionWhenPausing) {
411 // Has stream really stopped advancing?
Phil Burk5ed503c2017-02-01 09:38:15 -0800412 setState(AAUDIO_STREAM_STATE_PAUSED);
Phil Burke1ce4912016-11-21 10:40:25 -0800413 }
414 mPositionWhenPausing = position;
415 }
416 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800417 case AAUDIO_STREAM_STATE_FLUSHING:
Phil Burke1ce4912016-11-21 10:40:25 -0800418 {
419 err = mAudioTrack->getPosition(&position);
420 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800421 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800422 } else if (position == 0) {
Phil Burk5204d312017-05-04 17:16:13 -0700423 // TODO Advance frames read to match written.
Phil Burk5ed503c2017-02-01 09:38:15 -0800424 setState(AAUDIO_STREAM_STATE_FLUSHED);
Phil Burke1ce4912016-11-21 10:40:25 -0800425 }
426 }
427 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800428 case AAUDIO_STREAM_STATE_STOPPING:
Phil Burke1ce4912016-11-21 10:40:25 -0800429 if (mAudioTrack->stopped()) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800430 setState(AAUDIO_STREAM_STATE_STOPPED);
Phil Burke1ce4912016-11-21 10:40:25 -0800431 }
432 break;
433 default:
434 break;
435 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800436 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800437}
438
Phil Burk5ed503c2017-02-01 09:38:15 -0800439aaudio_result_t AudioStreamTrack::write(const void *buffer,
Phil Burk3316d5e2017-02-15 11:23:01 -0800440 int32_t numFrames,
441 int64_t timeoutNanoseconds)
Phil Burke1ce4912016-11-21 10:40:25 -0800442{
Phil Burk3316d5e2017-02-15 11:23:01 -0800443 int32_t bytesPerFrame = getBytesPerFrame();
444 int32_t numBytes;
Phil Burk5ed503c2017-02-01 09:38:15 -0800445 aaudio_result_t result = AAudioConvert_framesToBytes(numFrames, bytesPerFrame, &numBytes);
446 if (result != AAUDIO_OK) {
Phil Burke1ce4912016-11-21 10:40:25 -0800447 return result;
448 }
449
Eric Laurentfb00fc72017-05-25 18:17:12 -0700450 if (getState() == AAUDIO_STREAM_STATE_DISCONNECTED) {
451 return AAUDIO_ERROR_DISCONNECTED;
452 }
453
Phil Burke1ce4912016-11-21 10:40:25 -0800454 // TODO add timeout to AudioTrack
455 bool blocking = timeoutNanoseconds > 0;
456 ssize_t bytesWritten = mAudioTrack->write(buffer, numBytes, blocking);
457 if (bytesWritten == WOULD_BLOCK) {
458 return 0;
459 } else if (bytesWritten < 0) {
460 ALOGE("invalid write, returned %d", (int)bytesWritten);
Eric Laurentfb00fc72017-05-25 18:17:12 -0700461 // in this context, a DEAD_OBJECT is more likely to be a disconnect notification due to
462 // AudioTrack invalidation
463 if (bytesWritten == DEAD_OBJECT) {
464 setState(AAUDIO_STREAM_STATE_DISCONNECTED);
465 return AAUDIO_ERROR_DISCONNECTED;
466 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800467 return AAudioConvert_androidToAAudioResult(bytesWritten);
Phil Burke1ce4912016-11-21 10:40:25 -0800468 }
Phil Burk3316d5e2017-02-15 11:23:01 -0800469 int32_t framesWritten = (int32_t)(bytesWritten / bytesPerFrame);
Phil Burke1ce4912016-11-21 10:40:25 -0800470 incrementFramesWritten(framesWritten);
Phil Burk0befec62017-07-28 15:12:13 -0700471
472 result = updateStateMachine();
473 if (result != AAUDIO_OK) {
474 return result;
475 }
476
Phil Burke1ce4912016-11-21 10:40:25 -0800477 return framesWritten;
478}
479
Phil Burk3316d5e2017-02-15 11:23:01 -0800480aaudio_result_t AudioStreamTrack::setBufferSize(int32_t requestedFrames)
Phil Burke1ce4912016-11-21 10:40:25 -0800481{
Phil Burk41852682019-03-29 10:58:15 -0700482 // Do not ask for less than one burst.
483 if (requestedFrames < getFramesPerBurst()) {
484 requestedFrames = getFramesPerBurst();
485 }
Phil Burke1ce4912016-11-21 10:40:25 -0800486 ssize_t result = mAudioTrack->setBufferSizeInFrames(requestedFrames);
Phil Burk3316d5e2017-02-15 11:23:01 -0800487 if (result < 0) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800488 return AAudioConvert_androidToAAudioResult(result);
Phil Burke1ce4912016-11-21 10:40:25 -0800489 } else {
Phil Burk3316d5e2017-02-15 11:23:01 -0800490 return result;
Phil Burke1ce4912016-11-21 10:40:25 -0800491 }
492}
493
Phil Burk3316d5e2017-02-15 11:23:01 -0800494int32_t AudioStreamTrack::getBufferSize() const
Phil Burke1ce4912016-11-21 10:40:25 -0800495{
Phil Burk3316d5e2017-02-15 11:23:01 -0800496 return static_cast<int32_t>(mAudioTrack->getBufferSizeInFrames());
Phil Burke1ce4912016-11-21 10:40:25 -0800497}
498
Phil Burk8d97b8e2020-09-25 23:18:14 +0000499int32_t AudioStreamTrack::getBufferCapacityFromDevice() const
Phil Burke1ce4912016-11-21 10:40:25 -0800500{
Phil Burk3316d5e2017-02-15 11:23:01 -0800501 return static_cast<int32_t>(mAudioTrack->frameCount());
Phil Burke1ce4912016-11-21 10:40:25 -0800502}
503
504int32_t AudioStreamTrack::getXRunCount() const
505{
506 return static_cast<int32_t>(mAudioTrack->getUnderrunCount());
507}
508
Phil Burk8d97b8e2020-09-25 23:18:14 +0000509int32_t AudioStreamTrack::getFramesPerBurstFromDevice() const {
Phil Burkb5884022017-03-27 15:26:14 -0700510 return static_cast<int32_t>(mAudioTrack->getNotificationPeriodInFrames());
Phil Burke1ce4912016-11-21 10:40:25 -0800511}
512
Phil Burk3316d5e2017-02-15 11:23:01 -0800513int64_t AudioStreamTrack::getFramesRead() {
Phil Burk5ed503c2017-02-01 09:38:15 -0800514 aaudio_wrapping_frames_t position;
Phil Burke1ce4912016-11-21 10:40:25 -0800515 status_t result;
516 switch (getState()) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800517 case AAUDIO_STREAM_STATE_STARTING:
518 case AAUDIO_STREAM_STATE_STARTED:
519 case AAUDIO_STREAM_STATE_STOPPING:
Phil Burk4c5129b2017-04-28 15:17:32 -0700520 case AAUDIO_STREAM_STATE_PAUSING:
521 case AAUDIO_STREAM_STATE_PAUSED:
Phil Burke1ce4912016-11-21 10:40:25 -0800522 result = mAudioTrack->getPosition(&position);
523 if (result == OK) {
524 mFramesRead.update32(position);
525 }
526 break;
527 default:
528 break;
529 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700530 return AudioStreamLegacy::getFramesRead();
Phil Burke1ce4912016-11-21 10:40:25 -0800531}
Phil Burk35e80f32017-03-28 10:25:21 -0700532
533aaudio_result_t AudioStreamTrack::getTimestamp(clockid_t clockId,
534 int64_t *framePosition,
535 int64_t *timeNanoseconds) {
536 ExtendedTimestamp extendedTimestamp;
537 status_t status = mAudioTrack->getTimestamp(&extendedTimestamp);
Phil Burkc75d97f2017-09-08 15:48:36 -0700538 if (status == WOULD_BLOCK) {
539 return AAUDIO_ERROR_INVALID_STATE;
540 } if (status != NO_ERROR) {
Phil Burk35e80f32017-03-28 10:25:21 -0700541 return AAudioConvert_androidToAAudioResult(status);
542 }
Phil Burk7328a802017-08-30 09:29:48 -0700543 int64_t position = 0;
544 int64_t nanoseconds = 0;
545 aaudio_result_t result = getBestTimestamp(clockId, &position,
546 &nanoseconds, &extendedTimestamp);
547 if (result == AAUDIO_OK) {
548 if (position < getFramesWritten()) {
549 *framePosition = position;
550 *timeNanoseconds = nanoseconds;
551 return result;
552 } else {
553 return AAUDIO_ERROR_INVALID_STATE; // TODO review, documented but not consistent
554 }
555 }
556 return result;
Phil Burk35e80f32017-03-28 10:25:21 -0700557}
Phil Burk965650e2017-09-07 21:00:09 -0700558
559status_t AudioStreamTrack::doSetVolume() {
560 status_t status = NO_INIT;
561 if (mAudioTrack.get() != nullptr) {
562 float volume = getDuckAndMuteVolume();
563 mAudioTrack->setVolume(volume, volume);
564 status = NO_ERROR;
565 }
566 return status;
567}
568
569#if AAUDIO_USE_VOLUME_SHAPER
Phil Burk8a8a9e52017-09-12 16:25:15 -0700570
571using namespace android::media::VolumeShaper;
572
Phil Burk965650e2017-09-07 21:00:09 -0700573binder::Status AudioStreamTrack::applyVolumeShaper(
574 const VolumeShaper::Configuration& configuration,
575 const VolumeShaper::Operation& operation) {
576
577 sp<VolumeShaper::Configuration> spConfiguration = new VolumeShaper::Configuration(configuration);
578 sp<VolumeShaper::Operation> spOperation = new VolumeShaper::Operation(operation);
579
580 if (mAudioTrack.get() != nullptr) {
581 ALOGD("applyVolumeShaper() from IPlayer");
Phil Burk8a8a9e52017-09-12 16:25:15 -0700582 binder::Status status = mAudioTrack->applyVolumeShaper(spConfiguration, spOperation);
Phil Burk965650e2017-09-07 21:00:09 -0700583 if (status < 0) { // a non-negative value is the volume shaper id.
584 ALOGE("applyVolumeShaper() failed with status %d", status);
585 }
Andy Hung1131b6e2020-12-08 20:47:45 -0800586 return aidl_utils::binderStatusFromStatusT(status);
Phil Burk965650e2017-09-07 21:00:09 -0700587 } else {
588 ALOGD("applyVolumeShaper()"
589 " no AudioTrack for volume control from IPlayer");
590 return binder::Status::ok();
591 }
592}
593#endif