blob: 2e57f0d716590c66d74136dccd87e5627155d5ac [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 Burk8ae85a72024-01-04 22:24:10 +000072 // Set flags based on selected parameters.
Phil Burk8ffcf612018-05-23 14:38:07 -070073 audio_output_flags_t flags;
Phil Burk30a70772017-05-16 11:20:36 -070074 aaudio_performance_mode_t perfMode = getPerformanceMode();
75 switch(perfMode) {
Phil Burk8ae85a72024-01-04 22:24:10 +000076 case AAUDIO_PERFORMANCE_MODE_LOW_LATENCY: {
Phil Burke2fbb592017-05-01 15:05:52 -070077 // Bypass the normal mixer and go straight to the FAST mixer.
Phil Burk8ae85a72024-01-04 22:24:10 +000078 // Some Usages need RAW mode so they can get the lowest possible latency.
79 // Other Usages should avoid RAW because it can interfere with
80 // dual sink routing or other features.
81 bool usageBenefitsFromRaw = getUsage() == AAUDIO_USAGE_GAME ||
82 getUsage() == AAUDIO_USAGE_MEDIA;
83 // If an app does not ask for a sessionId then there will be no effects.
84 // So we can use the use RAW flag.
85 flags = (audio_output_flags_t) (((requestedSessionId == AAUDIO_SESSION_ID_NONE)
86 && usageBenefitsFromRaw)
87 ? (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_RAW)
88 : (AUDIO_OUTPUT_FLAG_FAST));
89 }
Phil Burke2fbb592017-05-01 15:05:52 -070090 break;
91
92 case AAUDIO_PERFORMANCE_MODE_POWER_SAVING:
93 // This uses a mixer that wakes up less often than the FAST mixer.
94 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
95 break;
96
97 case AAUDIO_PERFORMANCE_MODE_NONE:
98 default:
99 // No flags. Use a normal mixer in front of the FAST mixer.
Phil Burk8ffcf612018-05-23 14:38:07 -0700100 flags = AUDIO_OUTPUT_FLAG_NONE;
Phil Burke2fbb592017-05-01 15:05:52 -0700101 break;
102 }
Phil Burke4d7bb42017-03-28 11:32:39 -0700103
Phil Burkcf5f6d22017-05-26 12:35:07 -0700104 size_t frameCount = (size_t)builder.getBufferCapacity();
Phil Burke4d7bb42017-03-28 11:32:39 -0700105
Phil Burke69bfcb2020-08-20 00:10:35 +0000106 // To avoid glitching, let AudioFlinger pick the optimal burst size.
Phil Burke4d7bb42017-03-28 11:32:39 -0700107 int32_t notificationFrames = 0;
108
Phil Burk0127c1b2018-03-29 13:48:06 -0700109 const audio_format_t format = (getFormat() == AUDIO_FORMAT_DEFAULT)
Phil Burke1ce4912016-11-21 10:40:25 -0800110 ? AUDIO_FORMAT_PCM_FLOAT
Phil Burk0127c1b2018-03-29 13:48:06 -0700111 : getFormat();
Phil Burke1ce4912016-11-21 10:40:25 -0800112
Phil Burke4d7bb42017-03-28 11:32:39 -0700113 // Setup the callback if there is one.
Atneya Nair7daa4f92021-11-19 14:00:24 -0500114 wp<AudioTrack::IAudioTrackCallback> callback;
Phil Burke4d7bb42017-03-28 11:32:39 -0700115 // Note that TRANSFER_SYNC does not allow FAST track
116 AudioTrack::transfer_type streamTransferType = AudioTrack::transfer_type::TRANSFER_SYNC;
117 if (builder.getDataCallbackProc() != nullptr) {
118 streamTransferType = AudioTrack::transfer_type::TRANSFER_CALLBACK;
Atneya Nair7daa4f92021-11-19 14:00:24 -0500119 callback = wp<AudioTrack::IAudioTrackCallback>::fromExisting(this);
Phil Burke4d7bb42017-03-28 11:32:39 -0700120
Phil Burke4d7bb42017-03-28 11:32:39 -0700121 // If the total buffer size is unspecified then base the size on the burst size.
Phil Burk4485d412017-05-09 15:55:02 -0700122 if (frameCount == 0
123 && ((flags & AUDIO_OUTPUT_FLAG_FAST) != 0)) {
Phil Burke4d7bb42017-03-28 11:32:39 -0700124 // Take advantage of a special trick that allows us to create a buffer
125 // that is some multiple of the burst size.
126 notificationFrames = 0 - DEFAULT_BURSTS_PER_BUFFER_CAPACITY;
127 }
128 }
129 mCallbackBufferSize = builder.getFramesPerDataCallback();
130
Phil Burkfbf031e2017-10-12 15:58:31 -0700131 ALOGD("open(), request notificationFrames = %d, frameCount = %u",
Phil Burkcf5f6d22017-05-26 12:35:07 -0700132 notificationFrames, (uint)frameCount);
Phil Burkee995392017-12-11 11:44:36 -0800133
134 // Don't call mAudioTrack->setDeviceId() because it will be overwritten by set()!
Robert Wub7f8edc2024-11-04 19:54:38 +0000135 audio_port_handle_t selectedDeviceId = getFirstDeviceId(getDeviceIds());
Phil Burkee995392017-12-11 11:44:36 -0800136
Phil Burkd4ccc622017-12-20 15:32:44 -0800137 const audio_content_type_t contentType =
138 AAudioConvert_contentTypeToInternal(builder.getContentType());
139 const audio_usage_t usage =
140 AAudioConvert_usageToInternal(builder.getUsage());
Eric Laurentfa7fe4d2023-04-21 15:58:59 +0200141 const audio_flags_mask_t attributesFlags = AAudio_computeAudioFlagsMask(
142 builder.getAllowedCapturePolicy(),
143 builder.getSpatializationBehavior(),
144 builder.isContentSpatialized(),
145 flags);
Phil Burkd4ccc622017-12-20 15:32:44 -0800146
Jiabin Huang51a8a772024-10-30 21:57:48 +0000147 const std::optional<std::string> tags = builder.getTags();
148 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
149 attributes.content_type = contentType;
150 attributes.usage = usage;
151 attributes.flags = attributesFlags;
152 if (tags.has_value() && !tags.value().empty()) {
153 strcpy(attributes.tags, tags.value().c_str());
154 }
Phil Burkee995392017-12-11 11:44:36 -0800155 mAudioTrack = new AudioTrack();
Svet Ganov3e5f14f2021-05-13 22:51:08 +0000156 // TODO b/182392769: use attribution source util
Eric Laurentfb00fc72017-05-25 18:17:12 -0700157 mAudioTrack->set(
Phil Burkd4ccc622017-12-20 15:32:44 -0800158 AUDIO_STREAM_DEFAULT, // ignored because we pass attributes below
Phil Burke1ce4912016-11-21 10:40:25 -0800159 getSampleRate(),
160 format,
161 channelMask,
162 frameCount,
163 flags,
164 callback,
Phil Burke4d7bb42017-03-28 11:32:39 -0700165 notificationFrames,
jiabind5bd06a2021-04-27 22:04:08 +0000166 nullptr, // DEFAULT sharedBuffer*/,
Phil Burkee995392017-12-11 11:44:36 -0800167 false, // DEFAULT threadCanCallJava
Phil Burk4e1af9f2018-01-03 15:54:35 -0800168 sessionId,
Phil Burkee995392017-12-11 11:44:36 -0800169 streamTransferType,
jiabind5bd06a2021-04-27 22:04:08 +0000170 nullptr, // DEFAULT audio_offload_info_t
Svet Ganov3e5f14f2021-05-13 22:51:08 +0000171 AttributionSourceState(), // DEFAULT uid and pid
Phil Burkd4ccc622017-12-20 15:32:44 -0800172 &attributes,
Phil Burkee995392017-12-11 11:44:36 -0800173 // WARNING - If doNotReconnect set true then audio stops after plugging and unplugging
174 // headphones a few times.
175 false, // DEFAULT doNotReconnect,
176 1.0f, // DEFAULT maxRequiredSpeed
177 selectedDeviceId
178 );
Phil Burke1ce4912016-11-21 10:40:25 -0800179
Phil Burkd3813f32020-04-23 16:26:15 -0700180 // Set it here so it can be logged by the destructor if the open failed.
181 mAudioTrack->setCallerName(kCallerName);
182
Phil Burke1ce4912016-11-21 10:40:25 -0800183 // Did we get a valid track?
184 status_t status = mAudioTrack->initCheck();
Phil Burkdec33ab2017-01-17 14:48:16 -0800185 if (status != NO_ERROR) {
Phil Burkdd582922020-10-15 20:29:51 +0000186 safeReleaseClose();
Phil Burkfbf031e2017-10-12 15:58:31 -0700187 ALOGE("open(), initCheck() returned %d", status);
Phil Burk5ed503c2017-02-01 09:38:15 -0800188 return AAudioConvert_androidToAAudioResult(status);
Phil Burke1ce4912016-11-21 10:40:25 -0800189 }
190
Phil Burka9876702020-04-20 18:16:15 -0700191 mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_TRACK)
192 + std::to_string(mAudioTrack->getPortId());
jiabinef348b82021-04-19 16:53:08 +0000193 android::mediametrics::LogItem(mMetricsId)
194 .set(AMEDIAMETRICS_PROP_PERFORMANCEMODE,
jiabinc8da9032021-04-28 20:42:36 +0000195 AudioGlobal_convertPerformanceModeToText(builder.getPerformanceMode()))
196 .set(AMEDIAMETRICS_PROP_SHARINGMODE,
197 AudioGlobal_convertSharingModeToText(builder.getSharingMode()))
Robert Wub7f8edc2024-11-04 19:54:38 +0000198 .set(AMEDIAMETRICS_PROP_ENCODINGCLIENT,
199 android::toString(getFormat()).c_str()).record();
Phil Burka9876702020-04-20 18:16:15 -0700200
Phil Burk965650e2017-09-07 21:00:09 -0700201 doSetVolume();
Eric Laurent1d32e9f2017-06-02 14:01:32 -0700202
Phil Burke1ce4912016-11-21 10:40:25 -0800203 // Get the actual values from the AudioTrack.
jiabina9094092021-06-28 20:36:45 +0000204 setChannelMask(AAudioConvert_androidToAAudioChannelMask(
205 mAudioTrack->channelMask(), false /*isInput*/,
206 AAudio_isChannelIndexMask(getChannelMask())));
Phil Burk0127c1b2018-03-29 13:48:06 -0700207 setFormat(mAudioTrack->format());
208 setDeviceFormat(mAudioTrack->format());
Phil Burk8d97b8e2020-09-25 23:18:14 +0000209 setSampleRate(mAudioTrack->getSampleRate());
210 setBufferCapacity(getBufferCapacityFromDevice());
211 setFramesPerBurst(getFramesPerBurstFromDevice());
Robert Wue8b58962023-07-21 19:48:56 +0000212
213 // Use the same values for device values.
214 setDeviceSamplesPerFrame(getSamplesPerFrame());
Robert Wud559ba52023-06-29 00:08:51 +0000215 setDeviceSampleRate(mAudioTrack->getSampleRate());
216 setDeviceBufferCapacity(getBufferCapacityFromDevice());
217 setDeviceFramesPerBurst(getFramesPerBurstFromDevice());
Phil Burkcf5f6d22017-05-26 12:35:07 -0700218
Robert Wu310037a2022-09-06 21:48:18 +0000219 setHardwareSamplesPerFrame(mAudioTrack->getHalChannelCount());
220 setHardwareSampleRate(mAudioTrack->getHalSampleRate());
221 setHardwareFormat(mAudioTrack->getHalFormat());
222
Phil Burke4d7bb42017-03-28 11:32:39 -0700223 // We may need to pass the data through a block size adapter to guarantee constant size.
224 if (mCallbackBufferSize != AAUDIO_UNSPECIFIED) {
Phil Burk4b867492020-02-12 10:58:05 -0800225 // This may need to change if we add format conversion before
226 // the block size adaptation.
227 mBlockAdapterBytesPerFrame = getBytesPerFrame();
228 int callbackSizeBytes = mBlockAdapterBytesPerFrame * mCallbackBufferSize;
Phil Burke4d7bb42017-03-28 11:32:39 -0700229 mFixedBlockReader.open(callbackSizeBytes);
230 mBlockAdapter = &mFixedBlockReader;
231 } else {
232 mBlockAdapter = nullptr;
233 }
Phil Burke1ce4912016-11-21 10:40:25 -0800234
Robert Wub7f8edc2024-11-04 19:54:38 +0000235 setDeviceIds(mAudioTrack->getRoutedDeviceIds());
Phil Burk4e1af9f2018-01-03 15:54:35 -0800236
237 aaudio_session_id_t actualSessionId =
238 (requestedSessionId == AAUDIO_SESSION_ID_NONE)
239 ? AAUDIO_SESSION_ID_NONE
240 : (aaudio_session_id_t) mAudioTrack->getSessionId();
241 setSessionId(actualSessionId);
242
Phil Burk58f5ce12020-08-12 14:29:10 +0000243 mAudioTrack->addAudioDeviceCallback(this);
Phil Burke1ce4912016-11-21 10:40:25 -0800244
Phil Burk09c27ca2017-08-24 22:12:56 -0700245 // Update performance mode based on the actual stream flags.
Phil Burk30a70772017-05-16 11:20:36 -0700246 // For example, if the sample rate is not allowed then you won't get a FAST track.
247 audio_output_flags_t actualFlags = mAudioTrack->getFlags();
248 aaudio_performance_mode_t actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_NONE;
Phil Burk09c27ca2017-08-24 22:12:56 -0700249 // We may not get the RAW flag. But as long as we get the FAST flag we can call it LOW_LATENCY.
250 if ((actualFlags & AUDIO_OUTPUT_FLAG_FAST) != 0) {
Phil Burk30a70772017-05-16 11:20:36 -0700251 actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_LOW_LATENCY;
Phil Burk30a70772017-05-16 11:20:36 -0700252 } else if ((actualFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
253 actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_POWER_SAVING;
254 }
255 setPerformanceMode(actualPerformanceMode);
Phil Burkefa56002017-08-02 15:07:21 -0700256
257 setSharingMode(AAUDIO_SHARING_MODE_SHARED); // EXCLUSIVE mode not supported in legacy
258
Phil Burk7216b3f2020-06-23 23:29:18 +0000259 // Log if we did not get what we asked for.
260 ALOGD_IF(actualFlags != flags,
Phil Burkfbf031e2017-10-12 15:58:31 -0700261 "open() flags changed from 0x%08X to 0x%08X",
Phil Burk30a70772017-05-16 11:20:36 -0700262 flags, actualFlags);
Phil Burk7216b3f2020-06-23 23:29:18 +0000263 ALOGD_IF(actualPerformanceMode != perfMode,
Phil Burkfbf031e2017-10-12 15:58:31 -0700264 "open() perfMode changed from %d to %d",
Phil Burk30a70772017-05-16 11:20:36 -0700265 perfMode, actualPerformanceMode);
266
Robert Wudaf7b242021-09-07 18:32:04 +0000267 if (getState() != AAUDIO_STREAM_STATE_UNINITIALIZED) {
268 ALOGE("%s - Open canceled since state = %d", __func__, getState());
jiabincb212cd2022-08-24 16:50:44 -0700269 if (isDisconnected())
Robert Wudaf7b242021-09-07 18:32:04 +0000270 {
271 ALOGE("%s - Opening while state is disconnected", __func__);
272 safeReleaseClose();
273 return AAUDIO_ERROR_DISCONNECTED;
274 }
275 safeReleaseClose();
276 return AAUDIO_ERROR_INVALID_STATE;
277 }
278
279 setState(AAUDIO_STREAM_STATE_OPEN);
Phil Burk5ed503c2017-02-01 09:38:15 -0800280 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800281}
282
Phil Burk8b4e05e2019-12-17 12:12:09 -0800283aaudio_result_t AudioStreamTrack::release_l() {
284 if (getState() != AAUDIO_STREAM_STATE_CLOSING) {
Phil Burk58f5ce12020-08-12 14:29:10 +0000285 status_t err = mAudioTrack->removeAudioDeviceCallback(this);
286 ALOGE_IF(err, "%s() removeAudioDeviceCallback returned %d", __func__, err);
Phil Burk64e16a72020-06-01 13:25:51 -0700287 logReleaseBufferState();
Phil Burk320910f2020-08-12 14:29:10 +0000288 // Data callbacks may still be running!
Phil Burk8b4e05e2019-12-17 12:12:09 -0800289 return AudioStream::release_l();
290 } else {
291 return AAUDIO_OK; // already released
Phil Burke1ce4912016-11-21 10:40:25 -0800292 }
Phil Burke1ce4912016-11-21 10:40:25 -0800293}
294
Phil Burk320910f2020-08-12 14:29:10 +0000295void AudioStreamTrack::close_l() {
Phil Burk7a9577c2021-03-12 20:12:11 +0000296 // The callbacks are normally joined in the AudioTrack destructor.
297 // But if another object has a reference to the AudioTrack then
298 // it will not get deleted here.
299 // So we should join callbacks explicitly before returning.
300 // Unlock around the join to avoid deadlocks if the callback tries to lock.
301 // This can happen if the callback returns AAUDIO_CALLBACK_RESULT_STOP
302 mStreamLock.unlock();
303 mAudioTrack->stopAndJoinCallbacks();
304 mStreamLock.lock();
Phil Burk320910f2020-08-12 14:29:10 +0000305 mAudioTrack.clear();
Phil Burk7a9577c2021-03-12 20:12:11 +0000306 // Do not close mFixedBlockReader. It has a unique_ptr to its buffer
307 // so it will clean up by itself.
Phil Burk320910f2020-08-12 14:29:10 +0000308 AudioStream::close_l();
309}
310
Phil Burke4d7bb42017-03-28 11:32:39 -0700311
Atneya Nair7daa4f92021-11-19 14:00:24 -0500312void AudioStreamTrack::onNewIAudioTrack() {
313 // Stream got rerouted so we disconnect.
314 // request stream disconnect if the restored AudioTrack has properties not matching
315 // what was requested initially
316 if (mAudioTrack->channelCount() != getSamplesPerFrame()
317 || mAudioTrack->format() != getFormat()
318 || mAudioTrack->getSampleRate() != getSampleRate()
Robert Wub7f8edc2024-11-04 19:54:38 +0000319 || !areDeviceIdsEqual(mAudioTrack->getRoutedDeviceIds(), getDeviceIds())
Atneya Nair7daa4f92021-11-19 14:00:24 -0500320 || getBufferCapacityFromDevice() != getBufferCapacity()
321 || getFramesPerBurstFromDevice() != getFramesPerBurst()) {
322 AudioStreamLegacy::onNewIAudioTrack();
Phil Burke4d7bb42017-03-28 11:32:39 -0700323 }
Phil Burke4d7bb42017-03-28 11:32:39 -0700324}
325
Phil Burkdd582922020-10-15 20:29:51 +0000326aaudio_result_t AudioStreamTrack::requestStart_l() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800327 if (mAudioTrack.get() == nullptr) {
Phil Burkfbf031e2017-10-12 15:58:31 -0700328 ALOGE("requestStart() no AudioTrack");
Phil Burk5ed503c2017-02-01 09:38:15 -0800329 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800330 }
331 // Get current position so we can detect when the track is playing.
332 status_t err = mAudioTrack->getPosition(&mPositionWhenStarting);
333 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800334 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800335 }
Phil Burke4d7bb42017-03-28 11:32:39 -0700336
Phil Burk9e9a95b2018-01-18 12:14:15 -0800337 // Enable callback before starting AudioTrack to avoid shutting
338 // down because of a race condition.
339 mCallbackEnabled.store(true);
Phil Burk4c377ef2020-06-25 10:03:23 -0700340 aaudio_stream_state_t originalState = getState();
341 // Set before starting the callback so that we are in the correct state
342 // before updateStateMachine() can be called by the callback.
343 setState(AAUDIO_STREAM_STATE_STARTING);
Phil Burk965650e2017-09-07 21:00:09 -0700344 err = mAudioTrack->start();
Phil Burke1ce4912016-11-21 10:40:25 -0800345 if (err != OK) {
Phil Burk4c377ef2020-06-25 10:03:23 -0700346 mCallbackEnabled.store(false);
347 setState(originalState);
Phil Burk5ed503c2017-02-01 09:38:15 -0800348 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800349 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800350 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800351}
352
Phil Burkdd582922020-10-15 20:29:51 +0000353aaudio_result_t AudioStreamTrack::requestPause_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_PAUSING);
Phil Burk965650e2017-09-07 21:00:09 -0700360 mAudioTrack->pause();
Phil Burk9e9a95b2018-01-18 12:14:15 -0800361 mCallbackEnabled.store(false);
Phil Burke1ce4912016-11-21 10:40:25 -0800362 status_t err = mAudioTrack->getPosition(&mPositionWhenPausing);
363 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800364 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800365 }
Phil Burk134f1972017-12-08 13:06:11 -0800366 return checkForDisconnectRequest(false);
Phil Burke1ce4912016-11-21 10:40:25 -0800367}
368
Phil Burkdd582922020-10-15 20:29:51 +0000369aaudio_result_t AudioStreamTrack::requestFlush_l() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800370 if (mAudioTrack.get() == nullptr) {
Phil Burk1e83bee2018-12-17 14:15:20 -0800371 ALOGE("%s() no AudioTrack", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800372 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800373 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800374
Phil Burk5ed503c2017-02-01 09:38:15 -0800375 setState(AAUDIO_STREAM_STATE_FLUSHING);
Phil Burke1ce4912016-11-21 10:40:25 -0800376 incrementFramesRead(getFramesWritten() - getFramesRead());
377 mAudioTrack->flush();
Phil Burk2b6f1282018-05-10 15:26:30 -0700378 mFramesRead.reset32(); // service reads frames, service position reset on flush
Phil Burk7328a802017-08-30 09:29:48 -0700379 mTimestampPosition.reset32();
Phil Burk5ed503c2017-02-01 09:38:15 -0800380 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800381}
382
Phil Burkdd582922020-10-15 20:29:51 +0000383aaudio_result_t AudioStreamTrack::requestStop_l() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800384 if (mAudioTrack.get() == nullptr) {
Phil Burk1e83bee2018-12-17 14:15:20 -0800385 ALOGE("%s() no AudioTrack", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800386 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800387 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800388
Phil Burk5ed503c2017-02-01 09:38:15 -0800389 setState(AAUDIO_STREAM_STATE_STOPPING);
Phil Burk18c84762018-12-18 12:15:35 -0800390 mFramesRead.catchUpTo(getFramesWritten());
391 mTimestampPosition.catchUpTo(getFramesWritten());
Phil Burk2b6f1282018-05-10 15:26:30 -0700392 mFramesRead.reset32(); // service reads frames, service position reset on stop
Phil Burk7328a802017-08-30 09:29:48 -0700393 mTimestampPosition.reset32();
Phil Burk965650e2017-09-07 21:00:09 -0700394 mAudioTrack->stop();
Phil Burk9e9a95b2018-01-18 12:14:15 -0800395 mCallbackEnabled.store(false);
Phil Burk134f1972017-12-08 13:06:11 -0800396 return checkForDisconnectRequest(false);;
Phil Burke1ce4912016-11-21 10:40:25 -0800397}
398
Robert Wu3da128d2022-03-04 23:17:25 +0000399aaudio_result_t AudioStreamTrack::processCommands() {
Phil Burke1ce4912016-11-21 10:40:25 -0800400 status_t err;
Phil Burk5ed503c2017-02-01 09:38:15 -0800401 aaudio_wrapping_frames_t position;
Phil Burke1ce4912016-11-21 10:40:25 -0800402 switch (getState()) {
403 // TODO add better state visibility to AudioTrack
Phil Burk5ed503c2017-02-01 09:38:15 -0800404 case AAUDIO_STREAM_STATE_STARTING:
Phil Burke1ce4912016-11-21 10:40:25 -0800405 if (mAudioTrack->hasStarted()) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800406 setState(AAUDIO_STREAM_STATE_STARTED);
Phil Burke1ce4912016-11-21 10:40:25 -0800407 }
408 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800409 case AAUDIO_STREAM_STATE_PAUSING:
Phil Burke1ce4912016-11-21 10:40:25 -0800410 if (mAudioTrack->stopped()) {
411 err = mAudioTrack->getPosition(&position);
412 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800413 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800414 } else if (position == mPositionWhenPausing) {
415 // Has stream really stopped advancing?
Phil Burk5ed503c2017-02-01 09:38:15 -0800416 setState(AAUDIO_STREAM_STATE_PAUSED);
Phil Burke1ce4912016-11-21 10:40:25 -0800417 }
418 mPositionWhenPausing = position;
419 }
420 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800421 case AAUDIO_STREAM_STATE_FLUSHING:
Phil Burke1ce4912016-11-21 10:40:25 -0800422 {
423 err = mAudioTrack->getPosition(&position);
424 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800425 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800426 } else if (position == 0) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800427 setState(AAUDIO_STREAM_STATE_FLUSHED);
Phil Burke1ce4912016-11-21 10:40:25 -0800428 }
429 }
430 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800431 case AAUDIO_STREAM_STATE_STOPPING:
Phil Burke1ce4912016-11-21 10:40:25 -0800432 if (mAudioTrack->stopped()) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800433 setState(AAUDIO_STREAM_STATE_STOPPED);
Phil Burke1ce4912016-11-21 10:40:25 -0800434 }
435 break;
436 default:
437 break;
438 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800439 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800440}
441
Phil Burk5ed503c2017-02-01 09:38:15 -0800442aaudio_result_t AudioStreamTrack::write(const void *buffer,
Phil Burk3316d5e2017-02-15 11:23:01 -0800443 int32_t numFrames,
444 int64_t timeoutNanoseconds)
Phil Burke1ce4912016-11-21 10:40:25 -0800445{
Phil Burk3316d5e2017-02-15 11:23:01 -0800446 int32_t bytesPerFrame = getBytesPerFrame();
447 int32_t numBytes;
Phil Burk5ed503c2017-02-01 09:38:15 -0800448 aaudio_result_t result = AAudioConvert_framesToBytes(numFrames, bytesPerFrame, &numBytes);
449 if (result != AAUDIO_OK) {
Phil Burke1ce4912016-11-21 10:40:25 -0800450 return result;
451 }
452
jiabincb212cd2022-08-24 16:50:44 -0700453 if (isDisconnected()) {
Eric Laurentfb00fc72017-05-25 18:17:12 -0700454 return AAUDIO_ERROR_DISCONNECTED;
455 }
456
Phil Burke1ce4912016-11-21 10:40:25 -0800457 // TODO add timeout to AudioTrack
458 bool blocking = timeoutNanoseconds > 0;
459 ssize_t bytesWritten = mAudioTrack->write(buffer, numBytes, blocking);
460 if (bytesWritten == WOULD_BLOCK) {
461 return 0;
462 } else if (bytesWritten < 0) {
463 ALOGE("invalid write, returned %d", (int)bytesWritten);
Eric Laurentfb00fc72017-05-25 18:17:12 -0700464 // in this context, a DEAD_OBJECT is more likely to be a disconnect notification due to
465 // AudioTrack invalidation
466 if (bytesWritten == DEAD_OBJECT) {
jiabincb212cd2022-08-24 16:50:44 -0700467 setDisconnected();
Eric Laurentfb00fc72017-05-25 18:17:12 -0700468 return AAUDIO_ERROR_DISCONNECTED;
469 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800470 return AAudioConvert_androidToAAudioResult(bytesWritten);
Phil Burke1ce4912016-11-21 10:40:25 -0800471 }
Phil Burk3316d5e2017-02-15 11:23:01 -0800472 int32_t framesWritten = (int32_t)(bytesWritten / bytesPerFrame);
Phil Burke1ce4912016-11-21 10:40:25 -0800473 incrementFramesWritten(framesWritten);
Phil Burk0befec62017-07-28 15:12:13 -0700474
475 result = updateStateMachine();
476 if (result != AAUDIO_OK) {
477 return result;
478 }
479
Phil Burke1ce4912016-11-21 10:40:25 -0800480 return framesWritten;
481}
482
Phil Burk3316d5e2017-02-15 11:23:01 -0800483aaudio_result_t AudioStreamTrack::setBufferSize(int32_t requestedFrames)
Phil Burke1ce4912016-11-21 10:40:25 -0800484{
Phil Burk41852682019-03-29 10:58:15 -0700485 // Do not ask for less than one burst.
486 if (requestedFrames < getFramesPerBurst()) {
487 requestedFrames = getFramesPerBurst();
488 }
Phil Burke1ce4912016-11-21 10:40:25 -0800489 ssize_t result = mAudioTrack->setBufferSizeInFrames(requestedFrames);
Phil Burk3316d5e2017-02-15 11:23:01 -0800490 if (result < 0) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800491 return AAudioConvert_androidToAAudioResult(result);
Phil Burke1ce4912016-11-21 10:40:25 -0800492 } else {
Phil Burk3316d5e2017-02-15 11:23:01 -0800493 return result;
Phil Burke1ce4912016-11-21 10:40:25 -0800494 }
495}
496
Phil Burk3316d5e2017-02-15 11:23:01 -0800497int32_t AudioStreamTrack::getBufferSize() const
Phil Burke1ce4912016-11-21 10:40:25 -0800498{
Phil Burk3316d5e2017-02-15 11:23:01 -0800499 return static_cast<int32_t>(mAudioTrack->getBufferSizeInFrames());
Phil Burke1ce4912016-11-21 10:40:25 -0800500}
501
Phil Burk8d97b8e2020-09-25 23:18:14 +0000502int32_t AudioStreamTrack::getBufferCapacityFromDevice() const
Phil Burke1ce4912016-11-21 10:40:25 -0800503{
Phil Burk3316d5e2017-02-15 11:23:01 -0800504 return static_cast<int32_t>(mAudioTrack->frameCount());
Phil Burke1ce4912016-11-21 10:40:25 -0800505}
506
507int32_t AudioStreamTrack::getXRunCount() const
508{
509 return static_cast<int32_t>(mAudioTrack->getUnderrunCount());
510}
511
Phil Burk8d97b8e2020-09-25 23:18:14 +0000512int32_t AudioStreamTrack::getFramesPerBurstFromDevice() const {
Phil Burkb5884022017-03-27 15:26:14 -0700513 return static_cast<int32_t>(mAudioTrack->getNotificationPeriodInFrames());
Phil Burke1ce4912016-11-21 10:40:25 -0800514}
515
Phil Burk3316d5e2017-02-15 11:23:01 -0800516int64_t AudioStreamTrack::getFramesRead() {
Phil Burk5ed503c2017-02-01 09:38:15 -0800517 aaudio_wrapping_frames_t position;
Phil Burke1ce4912016-11-21 10:40:25 -0800518 status_t result;
519 switch (getState()) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800520 case AAUDIO_STREAM_STATE_STARTING:
521 case AAUDIO_STREAM_STATE_STARTED:
522 case AAUDIO_STREAM_STATE_STOPPING:
Phil Burk4c5129b2017-04-28 15:17:32 -0700523 case AAUDIO_STREAM_STATE_PAUSING:
524 case AAUDIO_STREAM_STATE_PAUSED:
Phil Burke1ce4912016-11-21 10:40:25 -0800525 result = mAudioTrack->getPosition(&position);
526 if (result == OK) {
Phil Burk58c1e6d2022-01-17 17:28:28 +0000527 mFramesRead.update32((int32_t)position);
Phil Burke1ce4912016-11-21 10:40:25 -0800528 }
529 break;
530 default:
531 break;
532 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700533 return AudioStreamLegacy::getFramesRead();
Phil Burke1ce4912016-11-21 10:40:25 -0800534}
Phil Burk35e80f32017-03-28 10:25:21 -0700535
536aaudio_result_t AudioStreamTrack::getTimestamp(clockid_t clockId,
537 int64_t *framePosition,
538 int64_t *timeNanoseconds) {
539 ExtendedTimestamp extendedTimestamp;
540 status_t status = mAudioTrack->getTimestamp(&extendedTimestamp);
Phil Burkc75d97f2017-09-08 15:48:36 -0700541 if (status == WOULD_BLOCK) {
542 return AAUDIO_ERROR_INVALID_STATE;
543 } if (status != NO_ERROR) {
Phil Burk35e80f32017-03-28 10:25:21 -0700544 return AAudioConvert_androidToAAudioResult(status);
545 }
Phil Burk7328a802017-08-30 09:29:48 -0700546 int64_t position = 0;
547 int64_t nanoseconds = 0;
548 aaudio_result_t result = getBestTimestamp(clockId, &position,
549 &nanoseconds, &extendedTimestamp);
550 if (result == AAUDIO_OK) {
551 if (position < getFramesWritten()) {
552 *framePosition = position;
553 *timeNanoseconds = nanoseconds;
554 return result;
555 } else {
556 return AAUDIO_ERROR_INVALID_STATE; // TODO review, documented but not consistent
557 }
558 }
559 return result;
Phil Burk35e80f32017-03-28 10:25:21 -0700560}
Phil Burk965650e2017-09-07 21:00:09 -0700561
562status_t AudioStreamTrack::doSetVolume() {
563 status_t status = NO_INIT;
564 if (mAudioTrack.get() != nullptr) {
565 float volume = getDuckAndMuteVolume();
566 mAudioTrack->setVolume(volume, volume);
567 status = NO_ERROR;
568 }
569 return status;
570}
571
Vlad Popa1b29d702022-08-10 13:15:04 +0200572void AudioStreamTrack::registerPlayerBase() {
573 AudioStream::registerPlayerBase();
574
575 if (mAudioTrack == nullptr) {
576 ALOGW("%s: cannot set piid, AudioTrack is null", __func__);
577 return;
578 }
579 mAudioTrack->setPlayerIId(mPlayerBase->getPlayerIId());
580}
581
Phil Burk965650e2017-09-07 21:00:09 -0700582#if AAUDIO_USE_VOLUME_SHAPER
Phil Burk8a8a9e52017-09-12 16:25:15 -0700583
584using namespace android::media::VolumeShaper;
585
Phil Burk965650e2017-09-07 21:00:09 -0700586binder::Status AudioStreamTrack::applyVolumeShaper(
587 const VolumeShaper::Configuration& configuration,
588 const VolumeShaper::Operation& operation) {
589
590 sp<VolumeShaper::Configuration> spConfiguration = new VolumeShaper::Configuration(configuration);
591 sp<VolumeShaper::Operation> spOperation = new VolumeShaper::Operation(operation);
592
593 if (mAudioTrack.get() != nullptr) {
594 ALOGD("applyVolumeShaper() from IPlayer");
Phil Burk8a8a9e52017-09-12 16:25:15 -0700595 binder::Status status = mAudioTrack->applyVolumeShaper(spConfiguration, spOperation);
Phil Burk965650e2017-09-07 21:00:09 -0700596 if (status < 0) { // a non-negative value is the volume shaper id.
597 ALOGE("applyVolumeShaper() failed with status %d", status);
598 }
Andy Hung1131b6e2020-12-08 20:47:45 -0800599 return aidl_utils::binderStatusFromStatusT(status);
Phil Burk965650e2017-09-07 21:00:09 -0700600 } else {
601 ALOGD("applyVolumeShaper()"
602 " no AudioTrack for volume control from IPlayer");
603 return binder::Status::ok();
604 }
605}
606#endif