blob: 2ee5cdca832cb35d6b9524cbd76c5c282feb83fa [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
Philip P. Moltmannbda45752020-07-17 16:41:18 -070036using media::permission::Identity;
37
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
Phil Burke1ce4912016-11-21 10:40:25 -080069 // Try to create an AudioTrack
Phil Burk5204d312017-05-04 17:16:13 -070070 // Use stereo if unspecified.
Phil Burk5ed503c2017-02-01 09:38:15 -080071 int32_t samplesPerFrame = (getSamplesPerFrame() == AAUDIO_UNSPECIFIED)
Phil Burke1ce4912016-11-21 10:40:25 -080072 ? 2 : getSamplesPerFrame();
Eric Laurent16c66dd2019-05-01 17:54:10 -070073 audio_channel_mask_t channelMask = samplesPerFrame <= 2 ?
74 audio_channel_out_mask_from_count(samplesPerFrame) :
75 audio_channel_mask_for_index_assignment_from_count(samplesPerFrame);
Phil Burke1ce4912016-11-21 10:40:25 -080076
Phil Burk8ffcf612018-05-23 14:38:07 -070077 audio_output_flags_t flags;
Phil Burk30a70772017-05-16 11:20:36 -070078 aaudio_performance_mode_t perfMode = getPerformanceMode();
79 switch(perfMode) {
Phil Burke2fbb592017-05-01 15:05:52 -070080 case AAUDIO_PERFORMANCE_MODE_LOW_LATENCY:
81 // Bypass the normal mixer and go straight to the FAST mixer.
Phil Burk8ffcf612018-05-23 14:38:07 -070082 // If the app asks for a sessionId then it means they want to use effects.
83 // So don't use RAW flag.
84 flags = (audio_output_flags_t) ((requestedSessionId == AAUDIO_SESSION_ID_NONE)
85 ? (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_RAW)
86 : (AUDIO_OUTPUT_FLAG_FAST));
Phil Burke2fbb592017-05-01 15:05:52 -070087 break;
88
89 case AAUDIO_PERFORMANCE_MODE_POWER_SAVING:
90 // This uses a mixer that wakes up less often than the FAST mixer.
91 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
92 break;
93
94 case AAUDIO_PERFORMANCE_MODE_NONE:
95 default:
96 // No flags. Use a normal mixer in front of the FAST mixer.
Phil Burk8ffcf612018-05-23 14:38:07 -070097 flags = AUDIO_OUTPUT_FLAG_NONE;
Phil Burke2fbb592017-05-01 15:05:52 -070098 break;
99 }
Phil Burke4d7bb42017-03-28 11:32:39 -0700100
Phil Burkcf5f6d22017-05-26 12:35:07 -0700101 size_t frameCount = (size_t)builder.getBufferCapacity();
Phil Burke4d7bb42017-03-28 11:32:39 -0700102
Phil Burke69bfcb2020-08-20 00:10:35 +0000103 // To avoid glitching, let AudioFlinger pick the optimal burst size.
Phil Burke4d7bb42017-03-28 11:32:39 -0700104 int32_t notificationFrames = 0;
105
Phil Burk0127c1b2018-03-29 13:48:06 -0700106 const audio_format_t format = (getFormat() == AUDIO_FORMAT_DEFAULT)
Phil Burke1ce4912016-11-21 10:40:25 -0800107 ? AUDIO_FORMAT_PCM_FLOAT
Phil Burk0127c1b2018-03-29 13:48:06 -0700108 : getFormat();
Phil Burke1ce4912016-11-21 10:40:25 -0800109
Phil Burke4d7bb42017-03-28 11:32:39 -0700110 // Setup the callback if there is one.
111 AudioTrack::callback_t callback = nullptr;
112 void *callbackData = nullptr;
113 // Note that TRANSFER_SYNC does not allow FAST track
114 AudioTrack::transfer_type streamTransferType = AudioTrack::transfer_type::TRANSFER_SYNC;
115 if (builder.getDataCallbackProc() != nullptr) {
116 streamTransferType = AudioTrack::transfer_type::TRANSFER_CALLBACK;
117 callback = getLegacyCallback();
118 callbackData = this;
119
Phil Burke4d7bb42017-03-28 11:32:39 -0700120 // If the total buffer size is unspecified then base the size on the burst size.
Phil Burk4485d412017-05-09 15:55:02 -0700121 if (frameCount == 0
122 && ((flags & AUDIO_OUTPUT_FLAG_FAST) != 0)) {
Phil Burke4d7bb42017-03-28 11:32:39 -0700123 // Take advantage of a special trick that allows us to create a buffer
124 // that is some multiple of the burst size.
125 notificationFrames = 0 - DEFAULT_BURSTS_PER_BUFFER_CAPACITY;
126 }
127 }
128 mCallbackBufferSize = builder.getFramesPerDataCallback();
129
Phil Burkfbf031e2017-10-12 15:58:31 -0700130 ALOGD("open(), request notificationFrames = %d, frameCount = %u",
Phil Burkcf5f6d22017-05-26 12:35:07 -0700131 notificationFrames, (uint)frameCount);
Phil Burkee995392017-12-11 11:44:36 -0800132
133 // Don't call mAudioTrack->setDeviceId() because it will be overwritten by set()!
134 audio_port_handle_t selectedDeviceId = (getDeviceId() == AAUDIO_UNSPECIFIED)
135 ? AUDIO_PORT_HANDLE_NONE
136 : getDeviceId();
137
Phil Burkd4ccc622017-12-20 15:32:44 -0800138 const audio_content_type_t contentType =
139 AAudioConvert_contentTypeToInternal(builder.getContentType());
140 const audio_usage_t usage =
141 AAudioConvert_usageToInternal(builder.getUsage());
Kevin Rocard68646ba2019-03-20 13:26:49 -0700142 const audio_flags_mask_t attributesFlags =
143 AAudioConvert_allowCapturePolicyToAudioFlagsMask(builder.getAllowedCapturePolicy());
Phil Burkd4ccc622017-12-20 15:32:44 -0800144
145 const audio_attributes_t attributes = {
146 .content_type = contentType,
147 .usage = usage,
148 .source = AUDIO_SOURCE_DEFAULT, // only used for recording
Kevin Rocard68646ba2019-03-20 13:26:49 -0700149 .flags = attributesFlags,
Phil Burkd4ccc622017-12-20 15:32:44 -0800150 .tags = ""
151 };
152
Phil Burkee995392017-12-11 11:44:36 -0800153 mAudioTrack = new AudioTrack();
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700154 // TODO b/182392769: use identity util
Eric Laurentfb00fc72017-05-25 18:17:12 -0700155 mAudioTrack->set(
Phil Burkd4ccc622017-12-20 15:32:44 -0800156 AUDIO_STREAM_DEFAULT, // ignored because we pass attributes below
Phil Burke1ce4912016-11-21 10:40:25 -0800157 getSampleRate(),
158 format,
159 channelMask,
160 frameCount,
161 flags,
162 callback,
Phil Burke4d7bb42017-03-28 11:32:39 -0700163 callbackData,
164 notificationFrames,
Phil Burkee995392017-12-11 11:44:36 -0800165 0, // DEFAULT sharedBuffer*/,
166 false, // DEFAULT threadCanCallJava
Phil Burk4e1af9f2018-01-03 15:54:35 -0800167 sessionId,
Phil Burkee995392017-12-11 11:44:36 -0800168 streamTransferType,
169 NULL, // DEFAULT audio_offload_info_t
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700170 Identity(), // DEFAULT uid and pid
Phil Burkd4ccc622017-12-20 15:32:44 -0800171 &attributes,
Phil Burkee995392017-12-11 11:44:36 -0800172 // WARNING - If doNotReconnect set true then audio stops after plugging and unplugging
173 // headphones a few times.
174 false, // DEFAULT doNotReconnect,
175 1.0f, // DEFAULT maxRequiredSpeed
176 selectedDeviceId
177 );
Phil Burke1ce4912016-11-21 10:40:25 -0800178
Phil Burkd3813f32020-04-23 16:26:15 -0700179 // Set it here so it can be logged by the destructor if the open failed.
180 mAudioTrack->setCallerName(kCallerName);
181
Phil Burke1ce4912016-11-21 10:40:25 -0800182 // Did we get a valid track?
183 status_t status = mAudioTrack->initCheck();
Phil Burkdec33ab2017-01-17 14:48:16 -0800184 if (status != NO_ERROR) {
Phil Burkdd582922020-10-15 20:29:51 +0000185 safeReleaseClose();
Phil Burkfbf031e2017-10-12 15:58:31 -0700186 ALOGE("open(), initCheck() returned %d", status);
Phil Burk5ed503c2017-02-01 09:38:15 -0800187 return AAudioConvert_androidToAAudioResult(status);
Phil Burke1ce4912016-11-21 10:40:25 -0800188 }
189
Phil Burka9876702020-04-20 18:16:15 -0700190 mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_TRACK)
191 + std::to_string(mAudioTrack->getPortId());
jiabinef348b82021-04-19 16:53:08 +0000192 android::mediametrics::LogItem(mMetricsId)
193 .set(AMEDIAMETRICS_PROP_PERFORMANCEMODE,
194 AudioGlobal_convertPerformanceModeToText(getPerformanceMode()))
195 .set(AMEDIAMETRICS_PROP_ENCODINGCLIENT, toString(getFormat()).c_str()).record();
Phil Burka9876702020-04-20 18:16:15 -0700196
Phil Burk965650e2017-09-07 21:00:09 -0700197 doSetVolume();
Eric Laurent1d32e9f2017-06-02 14:01:32 -0700198
Phil Burke1ce4912016-11-21 10:40:25 -0800199 // Get the actual values from the AudioTrack.
200 setSamplesPerFrame(mAudioTrack->channelCount());
Phil Burk0127c1b2018-03-29 13:48:06 -0700201 setFormat(mAudioTrack->format());
202 setDeviceFormat(mAudioTrack->format());
Phil Burk8d97b8e2020-09-25 23:18:14 +0000203 setSampleRate(mAudioTrack->getSampleRate());
204 setBufferCapacity(getBufferCapacityFromDevice());
205 setFramesPerBurst(getFramesPerBurstFromDevice());
Phil Burkcf5f6d22017-05-26 12:35:07 -0700206
Phil Burke4d7bb42017-03-28 11:32:39 -0700207 // We may need to pass the data through a block size adapter to guarantee constant size.
208 if (mCallbackBufferSize != AAUDIO_UNSPECIFIED) {
Phil Burk4b867492020-02-12 10:58:05 -0800209 // This may need to change if we add format conversion before
210 // the block size adaptation.
211 mBlockAdapterBytesPerFrame = getBytesPerFrame();
212 int callbackSizeBytes = mBlockAdapterBytesPerFrame * mCallbackBufferSize;
Phil Burke4d7bb42017-03-28 11:32:39 -0700213 mFixedBlockReader.open(callbackSizeBytes);
214 mBlockAdapter = &mFixedBlockReader;
215 } else {
216 mBlockAdapter = nullptr;
217 }
Phil Burke1ce4912016-11-21 10:40:25 -0800218
Phil Burk5ed503c2017-02-01 09:38:15 -0800219 setState(AAUDIO_STREAM_STATE_OPEN);
Phil Burkc0c70e32017-02-09 13:18:38 -0800220 setDeviceId(mAudioTrack->getRoutedDeviceId());
Phil Burk4e1af9f2018-01-03 15:54:35 -0800221
222 aaudio_session_id_t actualSessionId =
223 (requestedSessionId == AAUDIO_SESSION_ID_NONE)
224 ? AAUDIO_SESSION_ID_NONE
225 : (aaudio_session_id_t) mAudioTrack->getSessionId();
226 setSessionId(actualSessionId);
227
Phil Burk58f5ce12020-08-12 14:29:10 +0000228 mAudioTrack->addAudioDeviceCallback(this);
Phil Burke1ce4912016-11-21 10:40:25 -0800229
Phil Burk09c27ca2017-08-24 22:12:56 -0700230 // Update performance mode based on the actual stream flags.
Phil Burk30a70772017-05-16 11:20:36 -0700231 // For example, if the sample rate is not allowed then you won't get a FAST track.
232 audio_output_flags_t actualFlags = mAudioTrack->getFlags();
233 aaudio_performance_mode_t actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_NONE;
Phil Burk09c27ca2017-08-24 22:12:56 -0700234 // We may not get the RAW flag. But as long as we get the FAST flag we can call it LOW_LATENCY.
235 if ((actualFlags & AUDIO_OUTPUT_FLAG_FAST) != 0) {
Phil Burk30a70772017-05-16 11:20:36 -0700236 actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_LOW_LATENCY;
Phil Burk30a70772017-05-16 11:20:36 -0700237 } else if ((actualFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
238 actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_POWER_SAVING;
239 }
240 setPerformanceMode(actualPerformanceMode);
Phil Burkefa56002017-08-02 15:07:21 -0700241
242 setSharingMode(AAUDIO_SHARING_MODE_SHARED); // EXCLUSIVE mode not supported in legacy
243
Phil Burk7216b3f2020-06-23 23:29:18 +0000244 // Log if we did not get what we asked for.
245 ALOGD_IF(actualFlags != flags,
Phil Burkfbf031e2017-10-12 15:58:31 -0700246 "open() flags changed from 0x%08X to 0x%08X",
Phil Burk30a70772017-05-16 11:20:36 -0700247 flags, actualFlags);
Phil Burk7216b3f2020-06-23 23:29:18 +0000248 ALOGD_IF(actualPerformanceMode != perfMode,
Phil Burkfbf031e2017-10-12 15:58:31 -0700249 "open() perfMode changed from %d to %d",
Phil Burk30a70772017-05-16 11:20:36 -0700250 perfMode, actualPerformanceMode);
251
Phil Burk5ed503c2017-02-01 09:38:15 -0800252 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800253}
254
Phil Burk8b4e05e2019-12-17 12:12:09 -0800255aaudio_result_t AudioStreamTrack::release_l() {
256 if (getState() != AAUDIO_STREAM_STATE_CLOSING) {
Phil Burk58f5ce12020-08-12 14:29:10 +0000257 status_t err = mAudioTrack->removeAudioDeviceCallback(this);
258 ALOGE_IF(err, "%s() removeAudioDeviceCallback returned %d", __func__, err);
Phil Burk64e16a72020-06-01 13:25:51 -0700259 logReleaseBufferState();
Phil Burk320910f2020-08-12 14:29:10 +0000260 // Data callbacks may still be running!
Phil Burk8b4e05e2019-12-17 12:12:09 -0800261 return AudioStream::release_l();
262 } else {
263 return AAUDIO_OK; // already released
Phil Burke1ce4912016-11-21 10:40:25 -0800264 }
Phil Burke1ce4912016-11-21 10:40:25 -0800265}
266
Phil Burk320910f2020-08-12 14:29:10 +0000267void AudioStreamTrack::close_l() {
Phil Burk7a9577c2021-03-12 20:12:11 +0000268 // The callbacks are normally joined in the AudioTrack destructor.
269 // But if another object has a reference to the AudioTrack then
270 // it will not get deleted here.
271 // So we should join callbacks explicitly before returning.
272 // Unlock around the join to avoid deadlocks if the callback tries to lock.
273 // This can happen if the callback returns AAUDIO_CALLBACK_RESULT_STOP
274 mStreamLock.unlock();
275 mAudioTrack->stopAndJoinCallbacks();
276 mStreamLock.lock();
Phil Burk320910f2020-08-12 14:29:10 +0000277 mAudioTrack.clear();
Phil Burk7a9577c2021-03-12 20:12:11 +0000278 // Do not close mFixedBlockReader. It has a unique_ptr to its buffer
279 // so it will clean up by itself.
Phil Burk320910f2020-08-12 14:29:10 +0000280 AudioStream::close_l();
281}
282
Phil Burke4d7bb42017-03-28 11:32:39 -0700283void AudioStreamTrack::processCallback(int event, void *info) {
284
285 switch (event) {
286 case AudioTrack::EVENT_MORE_DATA:
287 processCallbackCommon(AAUDIO_CALLBACK_OPERATION_PROCESS_DATA, info);
288 break;
289
290 // Stream got rerouted so we disconnect.
291 case AudioTrack::EVENT_NEW_IAUDIOTRACK:
Eric Laurent68eff052020-04-10 18:28:41 -0700292 // request stream disconnect if the restored AudioTrack has properties not matching
293 // what was requested initially
294 if (mAudioTrack->channelCount() != getSamplesPerFrame()
295 || mAudioTrack->format() != getFormat()
296 || mAudioTrack->getSampleRate() != getSampleRate()
297 || mAudioTrack->getRoutedDeviceId() != getDeviceId()
Phil Burk8d97b8e2020-09-25 23:18:14 +0000298 || getBufferCapacityFromDevice() != getBufferCapacity()
299 || getFramesPerBurstFromDevice() != getFramesPerBurst()) {
Eric Laurent68eff052020-04-10 18:28:41 -0700300 processCallbackCommon(AAUDIO_CALLBACK_OPERATION_DISCONNECTED, info);
301 }
Phil Burke4d7bb42017-03-28 11:32:39 -0700302 break;
303
304 default:
305 break;
306 }
307 return;
308}
309
Phil Burkdd582922020-10-15 20:29:51 +0000310aaudio_result_t AudioStreamTrack::requestStart_l() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800311 if (mAudioTrack.get() == nullptr) {
Phil Burkfbf031e2017-10-12 15:58:31 -0700312 ALOGE("requestStart() no AudioTrack");
Phil Burk5ed503c2017-02-01 09:38:15 -0800313 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800314 }
315 // Get current position so we can detect when the track is playing.
316 status_t err = mAudioTrack->getPosition(&mPositionWhenStarting);
317 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800318 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800319 }
Phil Burke4d7bb42017-03-28 11:32:39 -0700320
Phil Burk9e9a95b2018-01-18 12:14:15 -0800321 // Enable callback before starting AudioTrack to avoid shutting
322 // down because of a race condition.
323 mCallbackEnabled.store(true);
Phil Burk4c377ef2020-06-25 10:03:23 -0700324 aaudio_stream_state_t originalState = getState();
325 // Set before starting the callback so that we are in the correct state
326 // before updateStateMachine() can be called by the callback.
327 setState(AAUDIO_STREAM_STATE_STARTING);
Phil Burk965650e2017-09-07 21:00:09 -0700328 err = mAudioTrack->start();
Phil Burke1ce4912016-11-21 10:40:25 -0800329 if (err != OK) {
Phil Burk4c377ef2020-06-25 10:03:23 -0700330 mCallbackEnabled.store(false);
331 setState(originalState);
Phil Burk5ed503c2017-02-01 09:38:15 -0800332 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800333 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800334 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800335}
336
Phil Burkdd582922020-10-15 20:29:51 +0000337aaudio_result_t AudioStreamTrack::requestPause_l() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800338 if (mAudioTrack.get() == nullptr) {
Phil Burk1e83bee2018-12-17 14:15:20 -0800339 ALOGE("%s() no AudioTrack", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800340 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800341 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800342
Phil Burk5ed503c2017-02-01 09:38:15 -0800343 setState(AAUDIO_STREAM_STATE_PAUSING);
Phil Burk965650e2017-09-07 21:00:09 -0700344 mAudioTrack->pause();
Phil Burk9e9a95b2018-01-18 12:14:15 -0800345 mCallbackEnabled.store(false);
Phil Burke1ce4912016-11-21 10:40:25 -0800346 status_t err = mAudioTrack->getPosition(&mPositionWhenPausing);
347 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800348 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800349 }
Phil Burk134f1972017-12-08 13:06:11 -0800350 return checkForDisconnectRequest(false);
Phil Burke1ce4912016-11-21 10:40:25 -0800351}
352
Phil Burkdd582922020-10-15 20:29:51 +0000353aaudio_result_t AudioStreamTrack::requestFlush_l() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800354 if (mAudioTrack.get() == nullptr) {
Phil Burk1e83bee2018-12-17 14:15:20 -0800355 ALOGE("%s() no AudioTrack", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800356 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800357 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800358
Phil Burk5ed503c2017-02-01 09:38:15 -0800359 setState(AAUDIO_STREAM_STATE_FLUSHING);
Phil Burke1ce4912016-11-21 10:40:25 -0800360 incrementFramesRead(getFramesWritten() - getFramesRead());
361 mAudioTrack->flush();
Phil Burk2b6f1282018-05-10 15:26:30 -0700362 mFramesRead.reset32(); // service reads frames, service position reset on flush
Phil Burk7328a802017-08-30 09:29:48 -0700363 mTimestampPosition.reset32();
Phil Burk5ed503c2017-02-01 09:38:15 -0800364 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800365}
366
Phil Burkdd582922020-10-15 20:29:51 +0000367aaudio_result_t AudioStreamTrack::requestStop_l() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800368 if (mAudioTrack.get() == nullptr) {
Phil Burk1e83bee2018-12-17 14:15:20 -0800369 ALOGE("%s() no AudioTrack", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800370 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800371 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800372
Phil Burk5ed503c2017-02-01 09:38:15 -0800373 setState(AAUDIO_STREAM_STATE_STOPPING);
Phil Burk18c84762018-12-18 12:15:35 -0800374 mFramesRead.catchUpTo(getFramesWritten());
375 mTimestampPosition.catchUpTo(getFramesWritten());
Phil Burk2b6f1282018-05-10 15:26:30 -0700376 mFramesRead.reset32(); // service reads frames, service position reset on stop
Phil Burk7328a802017-08-30 09:29:48 -0700377 mTimestampPosition.reset32();
Phil Burk965650e2017-09-07 21:00:09 -0700378 mAudioTrack->stop();
Phil Burk9e9a95b2018-01-18 12:14:15 -0800379 mCallbackEnabled.store(false);
Phil Burk134f1972017-12-08 13:06:11 -0800380 return checkForDisconnectRequest(false);;
Phil Burke1ce4912016-11-21 10:40:25 -0800381}
382
Phil Burk0befec62017-07-28 15:12:13 -0700383aaudio_result_t AudioStreamTrack::updateStateMachine()
Phil Burke1ce4912016-11-21 10:40:25 -0800384{
385 status_t err;
Phil Burk5ed503c2017-02-01 09:38:15 -0800386 aaudio_wrapping_frames_t position;
Phil Burke1ce4912016-11-21 10:40:25 -0800387 switch (getState()) {
388 // TODO add better state visibility to AudioTrack
Phil Burk5ed503c2017-02-01 09:38:15 -0800389 case AAUDIO_STREAM_STATE_STARTING:
Phil Burke1ce4912016-11-21 10:40:25 -0800390 if (mAudioTrack->hasStarted()) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800391 setState(AAUDIO_STREAM_STATE_STARTED);
Phil Burke1ce4912016-11-21 10:40:25 -0800392 }
393 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800394 case AAUDIO_STREAM_STATE_PAUSING:
Phil Burke1ce4912016-11-21 10:40:25 -0800395 if (mAudioTrack->stopped()) {
396 err = mAudioTrack->getPosition(&position);
397 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800398 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800399 } else if (position == mPositionWhenPausing) {
400 // Has stream really stopped advancing?
Phil Burk5ed503c2017-02-01 09:38:15 -0800401 setState(AAUDIO_STREAM_STATE_PAUSED);
Phil Burke1ce4912016-11-21 10:40:25 -0800402 }
403 mPositionWhenPausing = position;
404 }
405 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800406 case AAUDIO_STREAM_STATE_FLUSHING:
Phil Burke1ce4912016-11-21 10:40:25 -0800407 {
408 err = mAudioTrack->getPosition(&position);
409 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800410 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800411 } else if (position == 0) {
Phil Burk5204d312017-05-04 17:16:13 -0700412 // TODO Advance frames read to match written.
Phil Burk5ed503c2017-02-01 09:38:15 -0800413 setState(AAUDIO_STREAM_STATE_FLUSHED);
Phil Burke1ce4912016-11-21 10:40:25 -0800414 }
415 }
416 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800417 case AAUDIO_STREAM_STATE_STOPPING:
Phil Burke1ce4912016-11-21 10:40:25 -0800418 if (mAudioTrack->stopped()) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800419 setState(AAUDIO_STREAM_STATE_STOPPED);
Phil Burke1ce4912016-11-21 10:40:25 -0800420 }
421 break;
422 default:
423 break;
424 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800425 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800426}
427
Phil Burk5ed503c2017-02-01 09:38:15 -0800428aaudio_result_t AudioStreamTrack::write(const void *buffer,
Phil Burk3316d5e2017-02-15 11:23:01 -0800429 int32_t numFrames,
430 int64_t timeoutNanoseconds)
Phil Burke1ce4912016-11-21 10:40:25 -0800431{
Phil Burk3316d5e2017-02-15 11:23:01 -0800432 int32_t bytesPerFrame = getBytesPerFrame();
433 int32_t numBytes;
Phil Burk5ed503c2017-02-01 09:38:15 -0800434 aaudio_result_t result = AAudioConvert_framesToBytes(numFrames, bytesPerFrame, &numBytes);
435 if (result != AAUDIO_OK) {
Phil Burke1ce4912016-11-21 10:40:25 -0800436 return result;
437 }
438
Eric Laurentfb00fc72017-05-25 18:17:12 -0700439 if (getState() == AAUDIO_STREAM_STATE_DISCONNECTED) {
440 return AAUDIO_ERROR_DISCONNECTED;
441 }
442
Phil Burke1ce4912016-11-21 10:40:25 -0800443 // TODO add timeout to AudioTrack
444 bool blocking = timeoutNanoseconds > 0;
445 ssize_t bytesWritten = mAudioTrack->write(buffer, numBytes, blocking);
446 if (bytesWritten == WOULD_BLOCK) {
447 return 0;
448 } else if (bytesWritten < 0) {
449 ALOGE("invalid write, returned %d", (int)bytesWritten);
Eric Laurentfb00fc72017-05-25 18:17:12 -0700450 // in this context, a DEAD_OBJECT is more likely to be a disconnect notification due to
451 // AudioTrack invalidation
452 if (bytesWritten == DEAD_OBJECT) {
453 setState(AAUDIO_STREAM_STATE_DISCONNECTED);
454 return AAUDIO_ERROR_DISCONNECTED;
455 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800456 return AAudioConvert_androidToAAudioResult(bytesWritten);
Phil Burke1ce4912016-11-21 10:40:25 -0800457 }
Phil Burk3316d5e2017-02-15 11:23:01 -0800458 int32_t framesWritten = (int32_t)(bytesWritten / bytesPerFrame);
Phil Burke1ce4912016-11-21 10:40:25 -0800459 incrementFramesWritten(framesWritten);
Phil Burk0befec62017-07-28 15:12:13 -0700460
461 result = updateStateMachine();
462 if (result != AAUDIO_OK) {
463 return result;
464 }
465
Phil Burke1ce4912016-11-21 10:40:25 -0800466 return framesWritten;
467}
468
Phil Burk3316d5e2017-02-15 11:23:01 -0800469aaudio_result_t AudioStreamTrack::setBufferSize(int32_t requestedFrames)
Phil Burke1ce4912016-11-21 10:40:25 -0800470{
Phil Burk41852682019-03-29 10:58:15 -0700471 // Do not ask for less than one burst.
472 if (requestedFrames < getFramesPerBurst()) {
473 requestedFrames = getFramesPerBurst();
474 }
Phil Burke1ce4912016-11-21 10:40:25 -0800475 ssize_t result = mAudioTrack->setBufferSizeInFrames(requestedFrames);
Phil Burk3316d5e2017-02-15 11:23:01 -0800476 if (result < 0) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800477 return AAudioConvert_androidToAAudioResult(result);
Phil Burke1ce4912016-11-21 10:40:25 -0800478 } else {
Phil Burk3316d5e2017-02-15 11:23:01 -0800479 return result;
Phil Burke1ce4912016-11-21 10:40:25 -0800480 }
481}
482
Phil Burk3316d5e2017-02-15 11:23:01 -0800483int32_t AudioStreamTrack::getBufferSize() const
Phil Burke1ce4912016-11-21 10:40:25 -0800484{
Phil Burk3316d5e2017-02-15 11:23:01 -0800485 return static_cast<int32_t>(mAudioTrack->getBufferSizeInFrames());
Phil Burke1ce4912016-11-21 10:40:25 -0800486}
487
Phil Burk8d97b8e2020-09-25 23:18:14 +0000488int32_t AudioStreamTrack::getBufferCapacityFromDevice() const
Phil Burke1ce4912016-11-21 10:40:25 -0800489{
Phil Burk3316d5e2017-02-15 11:23:01 -0800490 return static_cast<int32_t>(mAudioTrack->frameCount());
Phil Burke1ce4912016-11-21 10:40:25 -0800491}
492
493int32_t AudioStreamTrack::getXRunCount() const
494{
495 return static_cast<int32_t>(mAudioTrack->getUnderrunCount());
496}
497
Phil Burk8d97b8e2020-09-25 23:18:14 +0000498int32_t AudioStreamTrack::getFramesPerBurstFromDevice() const {
Phil Burkb5884022017-03-27 15:26:14 -0700499 return static_cast<int32_t>(mAudioTrack->getNotificationPeriodInFrames());
Phil Burke1ce4912016-11-21 10:40:25 -0800500}
501
Phil Burk3316d5e2017-02-15 11:23:01 -0800502int64_t AudioStreamTrack::getFramesRead() {
Phil Burk5ed503c2017-02-01 09:38:15 -0800503 aaudio_wrapping_frames_t position;
Phil Burke1ce4912016-11-21 10:40:25 -0800504 status_t result;
505 switch (getState()) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800506 case AAUDIO_STREAM_STATE_STARTING:
507 case AAUDIO_STREAM_STATE_STARTED:
508 case AAUDIO_STREAM_STATE_STOPPING:
Phil Burk4c5129b2017-04-28 15:17:32 -0700509 case AAUDIO_STREAM_STATE_PAUSING:
510 case AAUDIO_STREAM_STATE_PAUSED:
Phil Burke1ce4912016-11-21 10:40:25 -0800511 result = mAudioTrack->getPosition(&position);
512 if (result == OK) {
513 mFramesRead.update32(position);
514 }
515 break;
516 default:
517 break;
518 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700519 return AudioStreamLegacy::getFramesRead();
Phil Burke1ce4912016-11-21 10:40:25 -0800520}
Phil Burk35e80f32017-03-28 10:25:21 -0700521
522aaudio_result_t AudioStreamTrack::getTimestamp(clockid_t clockId,
523 int64_t *framePosition,
524 int64_t *timeNanoseconds) {
525 ExtendedTimestamp extendedTimestamp;
526 status_t status = mAudioTrack->getTimestamp(&extendedTimestamp);
Phil Burkc75d97f2017-09-08 15:48:36 -0700527 if (status == WOULD_BLOCK) {
528 return AAUDIO_ERROR_INVALID_STATE;
529 } if (status != NO_ERROR) {
Phil Burk35e80f32017-03-28 10:25:21 -0700530 return AAudioConvert_androidToAAudioResult(status);
531 }
Phil Burk7328a802017-08-30 09:29:48 -0700532 int64_t position = 0;
533 int64_t nanoseconds = 0;
534 aaudio_result_t result = getBestTimestamp(clockId, &position,
535 &nanoseconds, &extendedTimestamp);
536 if (result == AAUDIO_OK) {
537 if (position < getFramesWritten()) {
538 *framePosition = position;
539 *timeNanoseconds = nanoseconds;
540 return result;
541 } else {
542 return AAUDIO_ERROR_INVALID_STATE; // TODO review, documented but not consistent
543 }
544 }
545 return result;
Phil Burk35e80f32017-03-28 10:25:21 -0700546}
Phil Burk965650e2017-09-07 21:00:09 -0700547
548status_t AudioStreamTrack::doSetVolume() {
549 status_t status = NO_INIT;
550 if (mAudioTrack.get() != nullptr) {
551 float volume = getDuckAndMuteVolume();
552 mAudioTrack->setVolume(volume, volume);
553 status = NO_ERROR;
554 }
555 return status;
556}
557
558#if AAUDIO_USE_VOLUME_SHAPER
Phil Burk8a8a9e52017-09-12 16:25:15 -0700559
560using namespace android::media::VolumeShaper;
561
Phil Burk965650e2017-09-07 21:00:09 -0700562binder::Status AudioStreamTrack::applyVolumeShaper(
563 const VolumeShaper::Configuration& configuration,
564 const VolumeShaper::Operation& operation) {
565
566 sp<VolumeShaper::Configuration> spConfiguration = new VolumeShaper::Configuration(configuration);
567 sp<VolumeShaper::Operation> spOperation = new VolumeShaper::Operation(operation);
568
569 if (mAudioTrack.get() != nullptr) {
570 ALOGD("applyVolumeShaper() from IPlayer");
Phil Burk8a8a9e52017-09-12 16:25:15 -0700571 binder::Status status = mAudioTrack->applyVolumeShaper(spConfiguration, spOperation);
Phil Burk965650e2017-09-07 21:00:09 -0700572 if (status < 0) { // a non-negative value is the volume shaper id.
573 ALOGE("applyVolumeShaper() failed with status %d", status);
574 }
Andy Hung1131b6e2020-12-08 20:47:45 -0800575 return aidl_utils::binderStatusFromStatusT(status);
Phil Burk965650e2017-09-07 21:00:09 -0700576 } else {
577 ALOGD("applyVolumeShaper()"
578 " no AudioTrack for volume control from IPlayer");
579 return binder::Status::ok();
580 }
581}
582#endif