blob: fe84ec5d0ebaff2bf93cd7ad5708e32dce553419 [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.
Atneya Nair6a8238eb2021-10-26 19:26:41 -0400106 AudioTrack::legacy_callback_t callback = nullptr;
Phil Burke4d7bb42017-03-28 11:32:39 -0700107 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 =
Jean-Michel Trivi656bfdc2021-09-20 18:42:37 -0700138 AAudioConvert_allowCapturePolicyToAudioFlagsMask(builder.getAllowedCapturePolicy(),
139 builder.getSpatializationBehavior(),
140 builder.isContentSpatialized());
Phil Burkd4ccc622017-12-20 15:32:44 -0800141
142 const audio_attributes_t attributes = {
143 .content_type = contentType,
144 .usage = usage,
145 .source = AUDIO_SOURCE_DEFAULT, // only used for recording
Kevin Rocard68646ba2019-03-20 13:26:49 -0700146 .flags = attributesFlags,
Phil Burkd4ccc622017-12-20 15:32:44 -0800147 .tags = ""
148 };
149
Phil Burkee995392017-12-11 11:44:36 -0800150 mAudioTrack = new AudioTrack();
Svet Ganov3e5f14f2021-05-13 22:51:08 +0000151 // TODO b/182392769: use attribution source util
Eric Laurentfb00fc72017-05-25 18:17:12 -0700152 mAudioTrack->set(
Phil Burkd4ccc622017-12-20 15:32:44 -0800153 AUDIO_STREAM_DEFAULT, // ignored because we pass attributes below
Phil Burke1ce4912016-11-21 10:40:25 -0800154 getSampleRate(),
155 format,
156 channelMask,
157 frameCount,
158 flags,
159 callback,
Phil Burke4d7bb42017-03-28 11:32:39 -0700160 callbackData,
161 notificationFrames,
jiabind5bd06a2021-04-27 22:04:08 +0000162 nullptr, // DEFAULT sharedBuffer*/,
Phil Burkee995392017-12-11 11:44:36 -0800163 false, // DEFAULT threadCanCallJava
Phil Burk4e1af9f2018-01-03 15:54:35 -0800164 sessionId,
Phil Burkee995392017-12-11 11:44:36 -0800165 streamTransferType,
jiabind5bd06a2021-04-27 22:04:08 +0000166 nullptr, // DEFAULT audio_offload_info_t
Svet Ganov3e5f14f2021-05-13 22:51:08 +0000167 AttributionSourceState(), // DEFAULT uid and pid
Phil Burkd4ccc622017-12-20 15:32:44 -0800168 &attributes,
Phil Burkee995392017-12-11 11:44:36 -0800169 // WARNING - If doNotReconnect set true then audio stops after plugging and unplugging
170 // headphones a few times.
171 false, // DEFAULT doNotReconnect,
172 1.0f, // DEFAULT maxRequiredSpeed
173 selectedDeviceId
174 );
Phil Burke1ce4912016-11-21 10:40:25 -0800175
Phil Burkd3813f32020-04-23 16:26:15 -0700176 // Set it here so it can be logged by the destructor if the open failed.
177 mAudioTrack->setCallerName(kCallerName);
178
Phil Burke1ce4912016-11-21 10:40:25 -0800179 // Did we get a valid track?
180 status_t status = mAudioTrack->initCheck();
Phil Burkdec33ab2017-01-17 14:48:16 -0800181 if (status != NO_ERROR) {
Phil Burkdd582922020-10-15 20:29:51 +0000182 safeReleaseClose();
Phil Burkfbf031e2017-10-12 15:58:31 -0700183 ALOGE("open(), initCheck() returned %d", status);
Phil Burk5ed503c2017-02-01 09:38:15 -0800184 return AAudioConvert_androidToAAudioResult(status);
Phil Burke1ce4912016-11-21 10:40:25 -0800185 }
186
Phil Burka9876702020-04-20 18:16:15 -0700187 mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_TRACK)
188 + std::to_string(mAudioTrack->getPortId());
jiabinef348b82021-04-19 16:53:08 +0000189 android::mediametrics::LogItem(mMetricsId)
190 .set(AMEDIAMETRICS_PROP_PERFORMANCEMODE,
jiabinc8da9032021-04-28 20:42:36 +0000191 AudioGlobal_convertPerformanceModeToText(builder.getPerformanceMode()))
192 .set(AMEDIAMETRICS_PROP_SHARINGMODE,
193 AudioGlobal_convertSharingModeToText(builder.getSharingMode()))
jiabinef348b82021-04-19 16:53:08 +0000194 .set(AMEDIAMETRICS_PROP_ENCODINGCLIENT, toString(getFormat()).c_str()).record();
Phil Burka9876702020-04-20 18:16:15 -0700195
Phil Burk965650e2017-09-07 21:00:09 -0700196 doSetVolume();
Eric Laurent1d32e9f2017-06-02 14:01:32 -0700197
Phil Burke1ce4912016-11-21 10:40:25 -0800198 // Get the actual values from the AudioTrack.
jiabina9094092021-06-28 20:36:45 +0000199 setChannelMask(AAudioConvert_androidToAAudioChannelMask(
200 mAudioTrack->channelMask(), false /*isInput*/,
201 AAudio_isChannelIndexMask(getChannelMask())));
Phil Burk0127c1b2018-03-29 13:48:06 -0700202 setFormat(mAudioTrack->format());
203 setDeviceFormat(mAudioTrack->format());
Phil Burk8d97b8e2020-09-25 23:18:14 +0000204 setSampleRate(mAudioTrack->getSampleRate());
205 setBufferCapacity(getBufferCapacityFromDevice());
206 setFramesPerBurst(getFramesPerBurstFromDevice());
Phil Burkcf5f6d22017-05-26 12:35:07 -0700207
Phil Burke4d7bb42017-03-28 11:32:39 -0700208 // We may need to pass the data through a block size adapter to guarantee constant size.
209 if (mCallbackBufferSize != AAUDIO_UNSPECIFIED) {
Phil Burk4b867492020-02-12 10:58:05 -0800210 // This may need to change if we add format conversion before
211 // the block size adaptation.
212 mBlockAdapterBytesPerFrame = getBytesPerFrame();
213 int callbackSizeBytes = mBlockAdapterBytesPerFrame * mCallbackBufferSize;
Phil Burke4d7bb42017-03-28 11:32:39 -0700214 mFixedBlockReader.open(callbackSizeBytes);
215 mBlockAdapter = &mFixedBlockReader;
216 } else {
217 mBlockAdapter = nullptr;
218 }
Phil Burke1ce4912016-11-21 10:40:25 -0800219
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
Robert Wudaf7b242021-09-07 18:32:04 +0000252 if (getState() != AAUDIO_STREAM_STATE_UNINITIALIZED) {
253 ALOGE("%s - Open canceled since state = %d", __func__, getState());
254 if (getState() == AAUDIO_STREAM_STATE_DISCONNECTED)
255 {
256 ALOGE("%s - Opening while state is disconnected", __func__);
257 safeReleaseClose();
258 return AAUDIO_ERROR_DISCONNECTED;
259 }
260 safeReleaseClose();
261 return AAUDIO_ERROR_INVALID_STATE;
262 }
263
264 setState(AAUDIO_STREAM_STATE_OPEN);
Phil Burk5ed503c2017-02-01 09:38:15 -0800265 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800266}
267
Phil Burk8b4e05e2019-12-17 12:12:09 -0800268aaudio_result_t AudioStreamTrack::release_l() {
269 if (getState() != AAUDIO_STREAM_STATE_CLOSING) {
Phil Burk58f5ce12020-08-12 14:29:10 +0000270 status_t err = mAudioTrack->removeAudioDeviceCallback(this);
271 ALOGE_IF(err, "%s() removeAudioDeviceCallback returned %d", __func__, err);
Phil Burk64e16a72020-06-01 13:25:51 -0700272 logReleaseBufferState();
Phil Burk320910f2020-08-12 14:29:10 +0000273 // Data callbacks may still be running!
Phil Burk8b4e05e2019-12-17 12:12:09 -0800274 return AudioStream::release_l();
275 } else {
276 return AAUDIO_OK; // already released
Phil Burke1ce4912016-11-21 10:40:25 -0800277 }
Phil Burke1ce4912016-11-21 10:40:25 -0800278}
279
Phil Burk320910f2020-08-12 14:29:10 +0000280void AudioStreamTrack::close_l() {
Phil Burk7a9577c2021-03-12 20:12:11 +0000281 // The callbacks are normally joined in the AudioTrack destructor.
282 // But if another object has a reference to the AudioTrack then
283 // it will not get deleted here.
284 // So we should join callbacks explicitly before returning.
285 // Unlock around the join to avoid deadlocks if the callback tries to lock.
286 // This can happen if the callback returns AAUDIO_CALLBACK_RESULT_STOP
287 mStreamLock.unlock();
288 mAudioTrack->stopAndJoinCallbacks();
289 mStreamLock.lock();
Phil Burk320910f2020-08-12 14:29:10 +0000290 mAudioTrack.clear();
Phil Burk7a9577c2021-03-12 20:12:11 +0000291 // Do not close mFixedBlockReader. It has a unique_ptr to its buffer
292 // so it will clean up by itself.
Phil Burk320910f2020-08-12 14:29:10 +0000293 AudioStream::close_l();
294}
295
Phil Burke4d7bb42017-03-28 11:32:39 -0700296void AudioStreamTrack::processCallback(int event, void *info) {
297
298 switch (event) {
299 case AudioTrack::EVENT_MORE_DATA:
300 processCallbackCommon(AAUDIO_CALLBACK_OPERATION_PROCESS_DATA, info);
301 break;
302
303 // Stream got rerouted so we disconnect.
304 case AudioTrack::EVENT_NEW_IAUDIOTRACK:
Eric Laurent68eff052020-04-10 18:28:41 -0700305 // request stream disconnect if the restored AudioTrack has properties not matching
306 // what was requested initially
307 if (mAudioTrack->channelCount() != getSamplesPerFrame()
308 || mAudioTrack->format() != getFormat()
309 || mAudioTrack->getSampleRate() != getSampleRate()
310 || mAudioTrack->getRoutedDeviceId() != getDeviceId()
Phil Burk8d97b8e2020-09-25 23:18:14 +0000311 || getBufferCapacityFromDevice() != getBufferCapacity()
312 || getFramesPerBurstFromDevice() != getFramesPerBurst()) {
Eric Laurent68eff052020-04-10 18:28:41 -0700313 processCallbackCommon(AAUDIO_CALLBACK_OPERATION_DISCONNECTED, info);
314 }
Phil Burke4d7bb42017-03-28 11:32:39 -0700315 break;
316
317 default:
318 break;
319 }
320 return;
321}
322
Phil Burkdd582922020-10-15 20:29:51 +0000323aaudio_result_t AudioStreamTrack::requestStart_l() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800324 if (mAudioTrack.get() == nullptr) {
Phil Burkfbf031e2017-10-12 15:58:31 -0700325 ALOGE("requestStart() no AudioTrack");
Phil Burk5ed503c2017-02-01 09:38:15 -0800326 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800327 }
328 // Get current position so we can detect when the track is playing.
329 status_t err = mAudioTrack->getPosition(&mPositionWhenStarting);
330 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800331 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800332 }
Phil Burke4d7bb42017-03-28 11:32:39 -0700333
Phil Burk9e9a95b2018-01-18 12:14:15 -0800334 // Enable callback before starting AudioTrack to avoid shutting
335 // down because of a race condition.
336 mCallbackEnabled.store(true);
Phil Burk4c377ef2020-06-25 10:03:23 -0700337 aaudio_stream_state_t originalState = getState();
338 // Set before starting the callback so that we are in the correct state
339 // before updateStateMachine() can be called by the callback.
340 setState(AAUDIO_STREAM_STATE_STARTING);
Phil Burk965650e2017-09-07 21:00:09 -0700341 err = mAudioTrack->start();
Phil Burke1ce4912016-11-21 10:40:25 -0800342 if (err != OK) {
Phil Burk4c377ef2020-06-25 10:03:23 -0700343 mCallbackEnabled.store(false);
344 setState(originalState);
Phil Burk5ed503c2017-02-01 09:38:15 -0800345 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800346 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800347 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800348}
349
Phil Burkdd582922020-10-15 20:29:51 +0000350aaudio_result_t AudioStreamTrack::requestPause_l() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800351 if (mAudioTrack.get() == nullptr) {
Phil Burk1e83bee2018-12-17 14:15:20 -0800352 ALOGE("%s() no AudioTrack", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800353 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800354 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800355
Phil Burk5ed503c2017-02-01 09:38:15 -0800356 setState(AAUDIO_STREAM_STATE_PAUSING);
Phil Burk965650e2017-09-07 21:00:09 -0700357 mAudioTrack->pause();
Phil Burk9e9a95b2018-01-18 12:14:15 -0800358 mCallbackEnabled.store(false);
Phil Burke1ce4912016-11-21 10:40:25 -0800359 status_t err = mAudioTrack->getPosition(&mPositionWhenPausing);
360 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800361 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800362 }
Phil Burk134f1972017-12-08 13:06:11 -0800363 return checkForDisconnectRequest(false);
Phil Burke1ce4912016-11-21 10:40:25 -0800364}
365
Phil Burkdd582922020-10-15 20:29:51 +0000366aaudio_result_t AudioStreamTrack::requestFlush_l() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800367 if (mAudioTrack.get() == nullptr) {
Phil Burk1e83bee2018-12-17 14:15:20 -0800368 ALOGE("%s() no AudioTrack", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800369 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800370 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800371
Phil Burk5ed503c2017-02-01 09:38:15 -0800372 setState(AAUDIO_STREAM_STATE_FLUSHING);
Phil Burke1ce4912016-11-21 10:40:25 -0800373 incrementFramesRead(getFramesWritten() - getFramesRead());
374 mAudioTrack->flush();
Phil Burk2b6f1282018-05-10 15:26:30 -0700375 mFramesRead.reset32(); // service reads frames, service position reset on flush
Phil Burk7328a802017-08-30 09:29:48 -0700376 mTimestampPosition.reset32();
Phil Burk5ed503c2017-02-01 09:38:15 -0800377 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800378}
379
Phil Burkdd582922020-10-15 20:29:51 +0000380aaudio_result_t AudioStreamTrack::requestStop_l() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800381 if (mAudioTrack.get() == nullptr) {
Phil Burk1e83bee2018-12-17 14:15:20 -0800382 ALOGE("%s() no AudioTrack", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800383 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800384 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800385
Phil Burk5ed503c2017-02-01 09:38:15 -0800386 setState(AAUDIO_STREAM_STATE_STOPPING);
Phil Burk18c84762018-12-18 12:15:35 -0800387 mFramesRead.catchUpTo(getFramesWritten());
388 mTimestampPosition.catchUpTo(getFramesWritten());
Phil Burk2b6f1282018-05-10 15:26:30 -0700389 mFramesRead.reset32(); // service reads frames, service position reset on stop
Phil Burk7328a802017-08-30 09:29:48 -0700390 mTimestampPosition.reset32();
Phil Burk965650e2017-09-07 21:00:09 -0700391 mAudioTrack->stop();
Phil Burk9e9a95b2018-01-18 12:14:15 -0800392 mCallbackEnabled.store(false);
Phil Burk134f1972017-12-08 13:06:11 -0800393 return checkForDisconnectRequest(false);;
Phil Burke1ce4912016-11-21 10:40:25 -0800394}
395
Phil Burk0befec62017-07-28 15:12:13 -0700396aaudio_result_t AudioStreamTrack::updateStateMachine()
Phil Burke1ce4912016-11-21 10:40:25 -0800397{
398 status_t err;
Phil Burk5ed503c2017-02-01 09:38:15 -0800399 aaudio_wrapping_frames_t position;
Phil Burke1ce4912016-11-21 10:40:25 -0800400 switch (getState()) {
401 // TODO add better state visibility to AudioTrack
Phil Burk5ed503c2017-02-01 09:38:15 -0800402 case AAUDIO_STREAM_STATE_STARTING:
Phil Burke1ce4912016-11-21 10:40:25 -0800403 if (mAudioTrack->hasStarted()) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800404 setState(AAUDIO_STREAM_STATE_STARTED);
Phil Burke1ce4912016-11-21 10:40:25 -0800405 }
406 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800407 case AAUDIO_STREAM_STATE_PAUSING:
Phil Burke1ce4912016-11-21 10:40:25 -0800408 if (mAudioTrack->stopped()) {
409 err = mAudioTrack->getPosition(&position);
410 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800411 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800412 } else if (position == mPositionWhenPausing) {
413 // Has stream really stopped advancing?
Phil Burk5ed503c2017-02-01 09:38:15 -0800414 setState(AAUDIO_STREAM_STATE_PAUSED);
Phil Burke1ce4912016-11-21 10:40:25 -0800415 }
416 mPositionWhenPausing = position;
417 }
418 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800419 case AAUDIO_STREAM_STATE_FLUSHING:
Phil Burke1ce4912016-11-21 10:40:25 -0800420 {
421 err = mAudioTrack->getPosition(&position);
422 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800423 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800424 } else if (position == 0) {
Phil Burk5204d312017-05-04 17:16:13 -0700425 // TODO Advance frames read to match written.
Phil Burk5ed503c2017-02-01 09:38:15 -0800426 setState(AAUDIO_STREAM_STATE_FLUSHED);
Phil Burke1ce4912016-11-21 10:40:25 -0800427 }
428 }
429 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800430 case AAUDIO_STREAM_STATE_STOPPING:
Phil Burke1ce4912016-11-21 10:40:25 -0800431 if (mAudioTrack->stopped()) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800432 setState(AAUDIO_STREAM_STATE_STOPPED);
Phil Burke1ce4912016-11-21 10:40:25 -0800433 }
434 break;
435 default:
436 break;
437 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800438 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800439}
440
Phil Burk5ed503c2017-02-01 09:38:15 -0800441aaudio_result_t AudioStreamTrack::write(const void *buffer,
Phil Burk3316d5e2017-02-15 11:23:01 -0800442 int32_t numFrames,
443 int64_t timeoutNanoseconds)
Phil Burke1ce4912016-11-21 10:40:25 -0800444{
Phil Burk3316d5e2017-02-15 11:23:01 -0800445 int32_t bytesPerFrame = getBytesPerFrame();
446 int32_t numBytes;
Phil Burk5ed503c2017-02-01 09:38:15 -0800447 aaudio_result_t result = AAudioConvert_framesToBytes(numFrames, bytesPerFrame, &numBytes);
448 if (result != AAUDIO_OK) {
Phil Burke1ce4912016-11-21 10:40:25 -0800449 return result;
450 }
451
Eric Laurentfb00fc72017-05-25 18:17:12 -0700452 if (getState() == AAUDIO_STREAM_STATE_DISCONNECTED) {
453 return AAUDIO_ERROR_DISCONNECTED;
454 }
455
Phil Burke1ce4912016-11-21 10:40:25 -0800456 // TODO add timeout to AudioTrack
457 bool blocking = timeoutNanoseconds > 0;
458 ssize_t bytesWritten = mAudioTrack->write(buffer, numBytes, blocking);
459 if (bytesWritten == WOULD_BLOCK) {
460 return 0;
461 } else if (bytesWritten < 0) {
462 ALOGE("invalid write, returned %d", (int)bytesWritten);
Eric Laurentfb00fc72017-05-25 18:17:12 -0700463 // in this context, a DEAD_OBJECT is more likely to be a disconnect notification due to
464 // AudioTrack invalidation
465 if (bytesWritten == DEAD_OBJECT) {
466 setState(AAUDIO_STREAM_STATE_DISCONNECTED);
467 return AAUDIO_ERROR_DISCONNECTED;
468 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800469 return AAudioConvert_androidToAAudioResult(bytesWritten);
Phil Burke1ce4912016-11-21 10:40:25 -0800470 }
Phil Burk3316d5e2017-02-15 11:23:01 -0800471 int32_t framesWritten = (int32_t)(bytesWritten / bytesPerFrame);
Phil Burke1ce4912016-11-21 10:40:25 -0800472 incrementFramesWritten(framesWritten);
Phil Burk0befec62017-07-28 15:12:13 -0700473
474 result = updateStateMachine();
475 if (result != AAUDIO_OK) {
476 return result;
477 }
478
Phil Burke1ce4912016-11-21 10:40:25 -0800479 return framesWritten;
480}
481
Phil Burk3316d5e2017-02-15 11:23:01 -0800482aaudio_result_t AudioStreamTrack::setBufferSize(int32_t requestedFrames)
Phil Burke1ce4912016-11-21 10:40:25 -0800483{
Phil Burk41852682019-03-29 10:58:15 -0700484 // Do not ask for less than one burst.
485 if (requestedFrames < getFramesPerBurst()) {
486 requestedFrames = getFramesPerBurst();
487 }
Phil Burke1ce4912016-11-21 10:40:25 -0800488 ssize_t result = mAudioTrack->setBufferSizeInFrames(requestedFrames);
Phil Burk3316d5e2017-02-15 11:23:01 -0800489 if (result < 0) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800490 return AAudioConvert_androidToAAudioResult(result);
Phil Burke1ce4912016-11-21 10:40:25 -0800491 } else {
Phil Burk3316d5e2017-02-15 11:23:01 -0800492 return result;
Phil Burke1ce4912016-11-21 10:40:25 -0800493 }
494}
495
Phil Burk3316d5e2017-02-15 11:23:01 -0800496int32_t AudioStreamTrack::getBufferSize() const
Phil Burke1ce4912016-11-21 10:40:25 -0800497{
Phil Burk3316d5e2017-02-15 11:23:01 -0800498 return static_cast<int32_t>(mAudioTrack->getBufferSizeInFrames());
Phil Burke1ce4912016-11-21 10:40:25 -0800499}
500
Phil Burk8d97b8e2020-09-25 23:18:14 +0000501int32_t AudioStreamTrack::getBufferCapacityFromDevice() const
Phil Burke1ce4912016-11-21 10:40:25 -0800502{
Phil Burk3316d5e2017-02-15 11:23:01 -0800503 return static_cast<int32_t>(mAudioTrack->frameCount());
Phil Burke1ce4912016-11-21 10:40:25 -0800504}
505
506int32_t AudioStreamTrack::getXRunCount() const
507{
508 return static_cast<int32_t>(mAudioTrack->getUnderrunCount());
509}
510
Phil Burk8d97b8e2020-09-25 23:18:14 +0000511int32_t AudioStreamTrack::getFramesPerBurstFromDevice() const {
Phil Burkb5884022017-03-27 15:26:14 -0700512 return static_cast<int32_t>(mAudioTrack->getNotificationPeriodInFrames());
Phil Burke1ce4912016-11-21 10:40:25 -0800513}
514
Phil Burk3316d5e2017-02-15 11:23:01 -0800515int64_t AudioStreamTrack::getFramesRead() {
Phil Burk5ed503c2017-02-01 09:38:15 -0800516 aaudio_wrapping_frames_t position;
Phil Burke1ce4912016-11-21 10:40:25 -0800517 status_t result;
518 switch (getState()) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800519 case AAUDIO_STREAM_STATE_STARTING:
520 case AAUDIO_STREAM_STATE_STARTED:
521 case AAUDIO_STREAM_STATE_STOPPING:
Phil Burk4c5129b2017-04-28 15:17:32 -0700522 case AAUDIO_STREAM_STATE_PAUSING:
523 case AAUDIO_STREAM_STATE_PAUSED:
Phil Burke1ce4912016-11-21 10:40:25 -0800524 result = mAudioTrack->getPosition(&position);
525 if (result == OK) {
526 mFramesRead.update32(position);
527 }
528 break;
529 default:
530 break;
531 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700532 return AudioStreamLegacy::getFramesRead();
Phil Burke1ce4912016-11-21 10:40:25 -0800533}
Phil Burk35e80f32017-03-28 10:25:21 -0700534
535aaudio_result_t AudioStreamTrack::getTimestamp(clockid_t clockId,
536 int64_t *framePosition,
537 int64_t *timeNanoseconds) {
538 ExtendedTimestamp extendedTimestamp;
539 status_t status = mAudioTrack->getTimestamp(&extendedTimestamp);
Phil Burkc75d97f2017-09-08 15:48:36 -0700540 if (status == WOULD_BLOCK) {
541 return AAUDIO_ERROR_INVALID_STATE;
542 } if (status != NO_ERROR) {
Phil Burk35e80f32017-03-28 10:25:21 -0700543 return AAudioConvert_androidToAAudioResult(status);
544 }
Phil Burk7328a802017-08-30 09:29:48 -0700545 int64_t position = 0;
546 int64_t nanoseconds = 0;
547 aaudio_result_t result = getBestTimestamp(clockId, &position,
548 &nanoseconds, &extendedTimestamp);
549 if (result == AAUDIO_OK) {
550 if (position < getFramesWritten()) {
551 *framePosition = position;
552 *timeNanoseconds = nanoseconds;
553 return result;
554 } else {
555 return AAUDIO_ERROR_INVALID_STATE; // TODO review, documented but not consistent
556 }
557 }
558 return result;
Phil Burk35e80f32017-03-28 10:25:21 -0700559}
Phil Burk965650e2017-09-07 21:00:09 -0700560
561status_t AudioStreamTrack::doSetVolume() {
562 status_t status = NO_INIT;
563 if (mAudioTrack.get() != nullptr) {
564 float volume = getDuckAndMuteVolume();
565 mAudioTrack->setVolume(volume, volume);
566 status = NO_ERROR;
567 }
568 return status;
569}
570
571#if AAUDIO_USE_VOLUME_SHAPER
Phil Burk8a8a9e52017-09-12 16:25:15 -0700572
573using namespace android::media::VolumeShaper;
574
Phil Burk965650e2017-09-07 21:00:09 -0700575binder::Status AudioStreamTrack::applyVolumeShaper(
576 const VolumeShaper::Configuration& configuration,
577 const VolumeShaper::Operation& operation) {
578
579 sp<VolumeShaper::Configuration> spConfiguration = new VolumeShaper::Configuration(configuration);
580 sp<VolumeShaper::Operation> spOperation = new VolumeShaper::Operation(operation);
581
582 if (mAudioTrack.get() != nullptr) {
583 ALOGD("applyVolumeShaper() from IPlayer");
Phil Burk8a8a9e52017-09-12 16:25:15 -0700584 binder::Status status = mAudioTrack->applyVolumeShaper(spConfiguration, spOperation);
Phil Burk965650e2017-09-07 21:00:09 -0700585 if (status < 0) { // a non-negative value is the volume shaper id.
586 ALOGE("applyVolumeShaper() failed with status %d", status);
587 }
Andy Hung1131b6e2020-12-08 20:47:45 -0800588 return aidl_utils::binderStatusFromStatusT(status);
Phil Burk965650e2017-09-07 21:00:09 -0700589 } else {
590 ALOGD("applyVolumeShaper()"
591 " no AudioTrack for volume control from IPlayer");
592 return binder::Status::ok();
593 }
594}
595#endif