blob: 1d036d0ce36bca525d0c465d54ed4b83f1de0993 [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>
Phil Burkc0c70e32017-02-09 13:18:38 -080026#include "utility/AudioClock.h"
Phil Burke4d7bb42017-03-28 11:32:39 -070027#include "legacy/AudioStreamLegacy.h"
28#include "legacy/AudioStreamTrack.h"
29#include "utility/FixedBlockReader.h"
Phil Burke1ce4912016-11-21 10:40:25 -080030
31using namespace android;
Phil Burk5ed503c2017-02-01 09:38:15 -080032using namespace aaudio;
Phil Burke1ce4912016-11-21 10:40:25 -080033
Phil Burke4d7bb42017-03-28 11:32:39 -070034// Arbitrary and somewhat generous number of bursts.
35#define DEFAULT_BURSTS_PER_BUFFER_CAPACITY 8
36
Phil Burke1ce4912016-11-21 10:40:25 -080037/*
38 * Create a stream that uses the AudioTrack.
39 */
40AudioStreamTrack::AudioStreamTrack()
Phil Burke4d7bb42017-03-28 11:32:39 -070041 : AudioStreamLegacy()
42 , mFixedBlockReader(*this)
Phil Burke1ce4912016-11-21 10:40:25 -080043{
44}
45
46AudioStreamTrack::~AudioStreamTrack()
47{
Phil Burk5ed503c2017-02-01 09:38:15 -080048 const aaudio_stream_state_t state = getState();
49 bool bad = !(state == AAUDIO_STREAM_STATE_UNINITIALIZED || state == AAUDIO_STREAM_STATE_CLOSED);
Phil Burke1ce4912016-11-21 10:40:25 -080050 ALOGE_IF(bad, "stream not closed, in state %d", state);
51}
52
Phil Burk5ed503c2017-02-01 09:38:15 -080053aaudio_result_t AudioStreamTrack::open(const AudioStreamBuilder& builder)
Phil Burke1ce4912016-11-21 10:40:25 -080054{
Phil Burk5ed503c2017-02-01 09:38:15 -080055 aaudio_result_t result = AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -080056
57 result = AudioStream::open(builder);
58 if (result != OK) {
59 return result;
60 }
61
Phil Burk8ffcf612018-05-23 14:38:07 -070062 const aaudio_session_id_t requestedSessionId = builder.getSessionId();
63 const audio_session_t sessionId = AAudioConvert_aaudioToAndroidSessionId(requestedSessionId);
64
Phil Burke1ce4912016-11-21 10:40:25 -080065 // Try to create an AudioTrack
Phil Burk5204d312017-05-04 17:16:13 -070066 // Use stereo if unspecified.
Phil Burk5ed503c2017-02-01 09:38:15 -080067 int32_t samplesPerFrame = (getSamplesPerFrame() == AAUDIO_UNSPECIFIED)
Phil Burke1ce4912016-11-21 10:40:25 -080068 ? 2 : getSamplesPerFrame();
Eric Laurent16c66dd2019-05-01 17:54:10 -070069 audio_channel_mask_t channelMask = samplesPerFrame <= 2 ?
70 audio_channel_out_mask_from_count(samplesPerFrame) :
71 audio_channel_mask_for_index_assignment_from_count(samplesPerFrame);
Phil Burke1ce4912016-11-21 10:40:25 -080072
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 Burke2fbb592017-05-01 15:05:52 -070076 case AAUDIO_PERFORMANCE_MODE_LOW_LATENCY:
77 // Bypass the normal mixer and go straight to the FAST mixer.
Phil Burk8ffcf612018-05-23 14:38:07 -070078 // If the app asks for a sessionId then it means they want to use effects.
79 // So don't use RAW flag.
80 flags = (audio_output_flags_t) ((requestedSessionId == AAUDIO_SESSION_ID_NONE)
81 ? (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_RAW)
82 : (AUDIO_OUTPUT_FLAG_FAST));
Phil Burke2fbb592017-05-01 15:05:52 -070083 break;
84
85 case AAUDIO_PERFORMANCE_MODE_POWER_SAVING:
86 // This uses a mixer that wakes up less often than the FAST mixer.
87 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
88 break;
89
90 case AAUDIO_PERFORMANCE_MODE_NONE:
91 default:
92 // No flags. Use a normal mixer in front of the FAST mixer.
Phil Burk8ffcf612018-05-23 14:38:07 -070093 flags = AUDIO_OUTPUT_FLAG_NONE;
Phil Burke2fbb592017-05-01 15:05:52 -070094 break;
95 }
Phil Burke4d7bb42017-03-28 11:32:39 -070096
Phil Burkcf5f6d22017-05-26 12:35:07 -070097 size_t frameCount = (size_t)builder.getBufferCapacity();
Phil Burke4d7bb42017-03-28 11:32:39 -070098
Phil Burke69bfcb2020-08-20 00:10:35 +000099 // To avoid glitching, let AudioFlinger pick the optimal burst size.
Phil Burke4d7bb42017-03-28 11:32:39 -0700100 int32_t notificationFrames = 0;
101
Phil Burk0127c1b2018-03-29 13:48:06 -0700102 const audio_format_t format = (getFormat() == AUDIO_FORMAT_DEFAULT)
Phil Burke1ce4912016-11-21 10:40:25 -0800103 ? AUDIO_FORMAT_PCM_FLOAT
Phil Burk0127c1b2018-03-29 13:48:06 -0700104 : getFormat();
Phil Burke1ce4912016-11-21 10:40:25 -0800105
Phil Burke4d7bb42017-03-28 11:32:39 -0700106 // Setup the callback if there is one.
107 AudioTrack::callback_t callback = nullptr;
108 void *callbackData = nullptr;
109 // Note that TRANSFER_SYNC does not allow FAST track
110 AudioTrack::transfer_type streamTransferType = AudioTrack::transfer_type::TRANSFER_SYNC;
111 if (builder.getDataCallbackProc() != nullptr) {
112 streamTransferType = AudioTrack::transfer_type::TRANSFER_CALLBACK;
113 callback = getLegacyCallback();
114 callbackData = this;
115
Phil Burke4d7bb42017-03-28 11:32:39 -0700116 // If the total buffer size is unspecified then base the size on the burst size.
Phil Burk4485d412017-05-09 15:55:02 -0700117 if (frameCount == 0
118 && ((flags & AUDIO_OUTPUT_FLAG_FAST) != 0)) {
Phil Burke4d7bb42017-03-28 11:32:39 -0700119 // Take advantage of a special trick that allows us to create a buffer
120 // that is some multiple of the burst size.
121 notificationFrames = 0 - DEFAULT_BURSTS_PER_BUFFER_CAPACITY;
122 }
123 }
124 mCallbackBufferSize = builder.getFramesPerDataCallback();
125
Phil Burkfbf031e2017-10-12 15:58:31 -0700126 ALOGD("open(), request notificationFrames = %d, frameCount = %u",
Phil Burkcf5f6d22017-05-26 12:35:07 -0700127 notificationFrames, (uint)frameCount);
Phil Burkee995392017-12-11 11:44:36 -0800128
129 // Don't call mAudioTrack->setDeviceId() because it will be overwritten by set()!
130 audio_port_handle_t selectedDeviceId = (getDeviceId() == AAUDIO_UNSPECIFIED)
131 ? AUDIO_PORT_HANDLE_NONE
132 : getDeviceId();
133
Phil Burkd4ccc622017-12-20 15:32:44 -0800134 const audio_content_type_t contentType =
135 AAudioConvert_contentTypeToInternal(builder.getContentType());
136 const audio_usage_t usage =
137 AAudioConvert_usageToInternal(builder.getUsage());
Kevin Rocard68646ba2019-03-20 13:26:49 -0700138 const audio_flags_mask_t attributesFlags =
139 AAudioConvert_allowCapturePolicyToAudioFlagsMask(builder.getAllowedCapturePolicy());
Phil Burkd4ccc622017-12-20 15:32:44 -0800140
141 const audio_attributes_t attributes = {
142 .content_type = contentType,
143 .usage = usage,
144 .source = AUDIO_SOURCE_DEFAULT, // only used for recording
Kevin Rocard68646ba2019-03-20 13:26:49 -0700145 .flags = attributesFlags,
Phil Burkd4ccc622017-12-20 15:32:44 -0800146 .tags = ""
147 };
148
Phil Burkee995392017-12-11 11:44:36 -0800149 mAudioTrack = new AudioTrack();
Eric Laurentfb00fc72017-05-25 18:17:12 -0700150 mAudioTrack->set(
Phil Burkd4ccc622017-12-20 15:32:44 -0800151 AUDIO_STREAM_DEFAULT, // ignored because we pass attributes below
Phil Burke1ce4912016-11-21 10:40:25 -0800152 getSampleRate(),
153 format,
154 channelMask,
155 frameCount,
156 flags,
157 callback,
Phil Burke4d7bb42017-03-28 11:32:39 -0700158 callbackData,
159 notificationFrames,
Phil Burkee995392017-12-11 11:44:36 -0800160 0, // DEFAULT sharedBuffer*/,
161 false, // DEFAULT threadCanCallJava
Phil Burk4e1af9f2018-01-03 15:54:35 -0800162 sessionId,
Phil Burkee995392017-12-11 11:44:36 -0800163 streamTransferType,
164 NULL, // DEFAULT audio_offload_info_t
165 AUDIO_UID_INVALID, // DEFAULT uid
166 -1, // DEFAULT pid
Phil Burkd4ccc622017-12-20 15:32:44 -0800167 &attributes,
Phil Burkee995392017-12-11 11:44:36 -0800168 // WARNING - If doNotReconnect set true then audio stops after plugging and unplugging
169 // headphones a few times.
170 false, // DEFAULT doNotReconnect,
171 1.0f, // DEFAULT maxRequiredSpeed
172 selectedDeviceId
173 );
Phil Burke1ce4912016-11-21 10:40:25 -0800174
Phil Burkd3813f32020-04-23 16:26:15 -0700175 // Set it here so it can be logged by the destructor if the open failed.
176 mAudioTrack->setCallerName(kCallerName);
177
Phil Burke1ce4912016-11-21 10:40:25 -0800178 // Did we get a valid track?
179 status_t status = mAudioTrack->initCheck();
Phil Burkdec33ab2017-01-17 14:48:16 -0800180 if (status != NO_ERROR) {
Phil Burkdd582922020-10-15 20:29:51 +0000181 safeReleaseClose();
Phil Burkfbf031e2017-10-12 15:58:31 -0700182 ALOGE("open(), initCheck() returned %d", status);
Phil Burk5ed503c2017-02-01 09:38:15 -0800183 return AAudioConvert_androidToAAudioResult(status);
Phil Burke1ce4912016-11-21 10:40:25 -0800184 }
185
Phil Burka9876702020-04-20 18:16:15 -0700186 mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_TRACK)
187 + std::to_string(mAudioTrack->getPortId());
188
Phil Burk965650e2017-09-07 21:00:09 -0700189 doSetVolume();
Eric Laurent1d32e9f2017-06-02 14:01:32 -0700190
Phil Burke1ce4912016-11-21 10:40:25 -0800191 // Get the actual values from the AudioTrack.
192 setSamplesPerFrame(mAudioTrack->channelCount());
Phil Burk0127c1b2018-03-29 13:48:06 -0700193 setFormat(mAudioTrack->format());
194 setDeviceFormat(mAudioTrack->format());
Phil Burk8d97b8e2020-09-25 23:18:14 +0000195 setSampleRate(mAudioTrack->getSampleRate());
196 setBufferCapacity(getBufferCapacityFromDevice());
197 setFramesPerBurst(getFramesPerBurstFromDevice());
Phil Burkcf5f6d22017-05-26 12:35:07 -0700198
Phil Burke4d7bb42017-03-28 11:32:39 -0700199 // We may need to pass the data through a block size adapter to guarantee constant size.
200 if (mCallbackBufferSize != AAUDIO_UNSPECIFIED) {
Phil Burk4b867492020-02-12 10:58:05 -0800201 // This may need to change if we add format conversion before
202 // the block size adaptation.
203 mBlockAdapterBytesPerFrame = getBytesPerFrame();
204 int callbackSizeBytes = mBlockAdapterBytesPerFrame * mCallbackBufferSize;
Phil Burke4d7bb42017-03-28 11:32:39 -0700205 mFixedBlockReader.open(callbackSizeBytes);
206 mBlockAdapter = &mFixedBlockReader;
207 } else {
208 mBlockAdapter = nullptr;
209 }
Phil Burke1ce4912016-11-21 10:40:25 -0800210
Phil Burk5ed503c2017-02-01 09:38:15 -0800211 setState(AAUDIO_STREAM_STATE_OPEN);
Phil Burkc0c70e32017-02-09 13:18:38 -0800212 setDeviceId(mAudioTrack->getRoutedDeviceId());
Phil Burk4e1af9f2018-01-03 15:54:35 -0800213
214 aaudio_session_id_t actualSessionId =
215 (requestedSessionId == AAUDIO_SESSION_ID_NONE)
216 ? AAUDIO_SESSION_ID_NONE
217 : (aaudio_session_id_t) mAudioTrack->getSessionId();
218 setSessionId(actualSessionId);
219
Phil Burk58f5ce12020-08-12 14:29:10 +0000220 mAudioTrack->addAudioDeviceCallback(this);
Phil Burke1ce4912016-11-21 10:40:25 -0800221
Phil Burk09c27ca2017-08-24 22:12:56 -0700222 // Update performance mode based on the actual stream flags.
Phil Burk30a70772017-05-16 11:20:36 -0700223 // For example, if the sample rate is not allowed then you won't get a FAST track.
224 audio_output_flags_t actualFlags = mAudioTrack->getFlags();
225 aaudio_performance_mode_t actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_NONE;
Phil Burk09c27ca2017-08-24 22:12:56 -0700226 // We may not get the RAW flag. But as long as we get the FAST flag we can call it LOW_LATENCY.
227 if ((actualFlags & AUDIO_OUTPUT_FLAG_FAST) != 0) {
Phil Burk30a70772017-05-16 11:20:36 -0700228 actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_LOW_LATENCY;
Phil Burk30a70772017-05-16 11:20:36 -0700229 } else if ((actualFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
230 actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_POWER_SAVING;
231 }
232 setPerformanceMode(actualPerformanceMode);
Phil Burkefa56002017-08-02 15:07:21 -0700233
234 setSharingMode(AAUDIO_SHARING_MODE_SHARED); // EXCLUSIVE mode not supported in legacy
235
Phil Burk7216b3f2020-06-23 23:29:18 +0000236 // Log if we did not get what we asked for.
237 ALOGD_IF(actualFlags != flags,
Phil Burkfbf031e2017-10-12 15:58:31 -0700238 "open() flags changed from 0x%08X to 0x%08X",
Phil Burk30a70772017-05-16 11:20:36 -0700239 flags, actualFlags);
Phil Burk7216b3f2020-06-23 23:29:18 +0000240 ALOGD_IF(actualPerformanceMode != perfMode,
Phil Burkfbf031e2017-10-12 15:58:31 -0700241 "open() perfMode changed from %d to %d",
Phil Burk30a70772017-05-16 11:20:36 -0700242 perfMode, actualPerformanceMode);
243
Phil Burk5ed503c2017-02-01 09:38:15 -0800244 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800245}
246
Phil Burk8b4e05e2019-12-17 12:12:09 -0800247aaudio_result_t AudioStreamTrack::release_l() {
248 if (getState() != AAUDIO_STREAM_STATE_CLOSING) {
Phil Burk58f5ce12020-08-12 14:29:10 +0000249 status_t err = mAudioTrack->removeAudioDeviceCallback(this);
250 ALOGE_IF(err, "%s() removeAudioDeviceCallback returned %d", __func__, err);
Phil Burk64e16a72020-06-01 13:25:51 -0700251 logReleaseBufferState();
Phil Burk320910f2020-08-12 14:29:10 +0000252 // Data callbacks may still be running!
Phil Burk8b4e05e2019-12-17 12:12:09 -0800253 return AudioStream::release_l();
254 } else {
255 return AAUDIO_OK; // already released
Phil Burke1ce4912016-11-21 10:40:25 -0800256 }
Phil Burke1ce4912016-11-21 10:40:25 -0800257}
258
Phil Burk320910f2020-08-12 14:29:10 +0000259void AudioStreamTrack::close_l() {
260 // Stop callbacks before deleting mFixedBlockReader memory.
261 mAudioTrack.clear();
Phil Burk58f5ce12020-08-12 14:29:10 +0000262 // Do not close mFixedBlockReader because a data callback
263 // thread might still be running if someone else has a reference
264 // to mAudioRecord.
265 // It has a unique_ptr to its buffer so it will clean up by itself.
Phil Burk320910f2020-08-12 14:29:10 +0000266 AudioStream::close_l();
267}
268
Phil Burke4d7bb42017-03-28 11:32:39 -0700269void AudioStreamTrack::processCallback(int event, void *info) {
270
271 switch (event) {
272 case AudioTrack::EVENT_MORE_DATA:
273 processCallbackCommon(AAUDIO_CALLBACK_OPERATION_PROCESS_DATA, info);
274 break;
275
276 // Stream got rerouted so we disconnect.
277 case AudioTrack::EVENT_NEW_IAUDIOTRACK:
Eric Laurent68eff052020-04-10 18:28:41 -0700278 // request stream disconnect if the restored AudioTrack has properties not matching
279 // what was requested initially
280 if (mAudioTrack->channelCount() != getSamplesPerFrame()
281 || mAudioTrack->format() != getFormat()
282 || mAudioTrack->getSampleRate() != getSampleRate()
283 || mAudioTrack->getRoutedDeviceId() != getDeviceId()
Phil Burk8d97b8e2020-09-25 23:18:14 +0000284 || getBufferCapacityFromDevice() != getBufferCapacity()
285 || getFramesPerBurstFromDevice() != getFramesPerBurst()) {
Eric Laurent68eff052020-04-10 18:28:41 -0700286 processCallbackCommon(AAUDIO_CALLBACK_OPERATION_DISCONNECTED, info);
287 }
Phil Burke4d7bb42017-03-28 11:32:39 -0700288 break;
289
290 default:
291 break;
292 }
293 return;
294}
295
Phil Burkdd582922020-10-15 20:29:51 +0000296aaudio_result_t AudioStreamTrack::requestStart_l() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800297 if (mAudioTrack.get() == nullptr) {
Phil Burkfbf031e2017-10-12 15:58:31 -0700298 ALOGE("requestStart() no AudioTrack");
Phil Burk5ed503c2017-02-01 09:38:15 -0800299 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800300 }
301 // Get current position so we can detect when the track is playing.
302 status_t err = mAudioTrack->getPosition(&mPositionWhenStarting);
303 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800304 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800305 }
Phil Burke4d7bb42017-03-28 11:32:39 -0700306
Phil Burk9e9a95b2018-01-18 12:14:15 -0800307 // Enable callback before starting AudioTrack to avoid shutting
308 // down because of a race condition.
309 mCallbackEnabled.store(true);
Phil Burk4c377ef2020-06-25 10:03:23 -0700310 aaudio_stream_state_t originalState = getState();
311 // Set before starting the callback so that we are in the correct state
312 // before updateStateMachine() can be called by the callback.
313 setState(AAUDIO_STREAM_STATE_STARTING);
Phil Burk965650e2017-09-07 21:00:09 -0700314 err = mAudioTrack->start();
Phil Burke1ce4912016-11-21 10:40:25 -0800315 if (err != OK) {
Phil Burk4c377ef2020-06-25 10:03:23 -0700316 mCallbackEnabled.store(false);
317 setState(originalState);
Phil Burk5ed503c2017-02-01 09:38:15 -0800318 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800319 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800320 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800321}
322
Phil Burkdd582922020-10-15 20:29:51 +0000323aaudio_result_t AudioStreamTrack::requestPause_l() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800324 if (mAudioTrack.get() == nullptr) {
Phil Burk1e83bee2018-12-17 14:15:20 -0800325 ALOGE("%s() no AudioTrack", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800326 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800327 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800328
Phil Burk5ed503c2017-02-01 09:38:15 -0800329 setState(AAUDIO_STREAM_STATE_PAUSING);
Phil Burk965650e2017-09-07 21:00:09 -0700330 mAudioTrack->pause();
Phil Burk9e9a95b2018-01-18 12:14:15 -0800331 mCallbackEnabled.store(false);
Phil Burke1ce4912016-11-21 10:40:25 -0800332 status_t err = mAudioTrack->getPosition(&mPositionWhenPausing);
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 Burk134f1972017-12-08 13:06:11 -0800336 return checkForDisconnectRequest(false);
Phil Burke1ce4912016-11-21 10:40:25 -0800337}
338
Phil Burkdd582922020-10-15 20:29:51 +0000339aaudio_result_t AudioStreamTrack::requestFlush_l() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800340 if (mAudioTrack.get() == nullptr) {
Phil Burk1e83bee2018-12-17 14:15:20 -0800341 ALOGE("%s() no AudioTrack", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800342 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800343 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800344
Phil Burk5ed503c2017-02-01 09:38:15 -0800345 setState(AAUDIO_STREAM_STATE_FLUSHING);
Phil Burke1ce4912016-11-21 10:40:25 -0800346 incrementFramesRead(getFramesWritten() - getFramesRead());
347 mAudioTrack->flush();
Phil Burk2b6f1282018-05-10 15:26:30 -0700348 mFramesRead.reset32(); // service reads frames, service position reset on flush
Phil Burk7328a802017-08-30 09:29:48 -0700349 mTimestampPosition.reset32();
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::requestStop_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_STOPPING);
Phil Burk18c84762018-12-18 12:15:35 -0800360 mFramesRead.catchUpTo(getFramesWritten());
361 mTimestampPosition.catchUpTo(getFramesWritten());
Phil Burk2b6f1282018-05-10 15:26:30 -0700362 mFramesRead.reset32(); // service reads frames, service position reset on stop
Phil Burk7328a802017-08-30 09:29:48 -0700363 mTimestampPosition.reset32();
Phil Burk965650e2017-09-07 21:00:09 -0700364 mAudioTrack->stop();
Phil Burk9e9a95b2018-01-18 12:14:15 -0800365 mCallbackEnabled.store(false);
Phil Burk134f1972017-12-08 13:06:11 -0800366 return checkForDisconnectRequest(false);;
Phil Burke1ce4912016-11-21 10:40:25 -0800367}
368
Phil Burk0befec62017-07-28 15:12:13 -0700369aaudio_result_t AudioStreamTrack::updateStateMachine()
Phil Burke1ce4912016-11-21 10:40:25 -0800370{
371 status_t err;
Phil Burk5ed503c2017-02-01 09:38:15 -0800372 aaudio_wrapping_frames_t position;
Phil Burke1ce4912016-11-21 10:40:25 -0800373 switch (getState()) {
374 // TODO add better state visibility to AudioTrack
Phil Burk5ed503c2017-02-01 09:38:15 -0800375 case AAUDIO_STREAM_STATE_STARTING:
Phil Burke1ce4912016-11-21 10:40:25 -0800376 if (mAudioTrack->hasStarted()) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800377 setState(AAUDIO_STREAM_STATE_STARTED);
Phil Burke1ce4912016-11-21 10:40:25 -0800378 }
379 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800380 case AAUDIO_STREAM_STATE_PAUSING:
Phil Burke1ce4912016-11-21 10:40:25 -0800381 if (mAudioTrack->stopped()) {
382 err = mAudioTrack->getPosition(&position);
383 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800384 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800385 } else if (position == mPositionWhenPausing) {
386 // Has stream really stopped advancing?
Phil Burk5ed503c2017-02-01 09:38:15 -0800387 setState(AAUDIO_STREAM_STATE_PAUSED);
Phil Burke1ce4912016-11-21 10:40:25 -0800388 }
389 mPositionWhenPausing = position;
390 }
391 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800392 case AAUDIO_STREAM_STATE_FLUSHING:
Phil Burke1ce4912016-11-21 10:40:25 -0800393 {
394 err = mAudioTrack->getPosition(&position);
395 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800396 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800397 } else if (position == 0) {
Phil Burk5204d312017-05-04 17:16:13 -0700398 // TODO Advance frames read to match written.
Phil Burk5ed503c2017-02-01 09:38:15 -0800399 setState(AAUDIO_STREAM_STATE_FLUSHED);
Phil Burke1ce4912016-11-21 10:40:25 -0800400 }
401 }
402 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800403 case AAUDIO_STREAM_STATE_STOPPING:
Phil Burke1ce4912016-11-21 10:40:25 -0800404 if (mAudioTrack->stopped()) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800405 setState(AAUDIO_STREAM_STATE_STOPPED);
Phil Burke1ce4912016-11-21 10:40:25 -0800406 }
407 break;
408 default:
409 break;
410 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800411 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800412}
413
Phil Burk5ed503c2017-02-01 09:38:15 -0800414aaudio_result_t AudioStreamTrack::write(const void *buffer,
Phil Burk3316d5e2017-02-15 11:23:01 -0800415 int32_t numFrames,
416 int64_t timeoutNanoseconds)
Phil Burke1ce4912016-11-21 10:40:25 -0800417{
Phil Burk3316d5e2017-02-15 11:23:01 -0800418 int32_t bytesPerFrame = getBytesPerFrame();
419 int32_t numBytes;
Phil Burk5ed503c2017-02-01 09:38:15 -0800420 aaudio_result_t result = AAudioConvert_framesToBytes(numFrames, bytesPerFrame, &numBytes);
421 if (result != AAUDIO_OK) {
Phil Burke1ce4912016-11-21 10:40:25 -0800422 return result;
423 }
424
Eric Laurentfb00fc72017-05-25 18:17:12 -0700425 if (getState() == AAUDIO_STREAM_STATE_DISCONNECTED) {
426 return AAUDIO_ERROR_DISCONNECTED;
427 }
428
Phil Burke1ce4912016-11-21 10:40:25 -0800429 // TODO add timeout to AudioTrack
430 bool blocking = timeoutNanoseconds > 0;
431 ssize_t bytesWritten = mAudioTrack->write(buffer, numBytes, blocking);
432 if (bytesWritten == WOULD_BLOCK) {
433 return 0;
434 } else if (bytesWritten < 0) {
435 ALOGE("invalid write, returned %d", (int)bytesWritten);
Eric Laurentfb00fc72017-05-25 18:17:12 -0700436 // in this context, a DEAD_OBJECT is more likely to be a disconnect notification due to
437 // AudioTrack invalidation
438 if (bytesWritten == DEAD_OBJECT) {
439 setState(AAUDIO_STREAM_STATE_DISCONNECTED);
440 return AAUDIO_ERROR_DISCONNECTED;
441 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800442 return AAudioConvert_androidToAAudioResult(bytesWritten);
Phil Burke1ce4912016-11-21 10:40:25 -0800443 }
Phil Burk3316d5e2017-02-15 11:23:01 -0800444 int32_t framesWritten = (int32_t)(bytesWritten / bytesPerFrame);
Phil Burke1ce4912016-11-21 10:40:25 -0800445 incrementFramesWritten(framesWritten);
Phil Burk0befec62017-07-28 15:12:13 -0700446
447 result = updateStateMachine();
448 if (result != AAUDIO_OK) {
449 return result;
450 }
451
Phil Burke1ce4912016-11-21 10:40:25 -0800452 return framesWritten;
453}
454
Phil Burk3316d5e2017-02-15 11:23:01 -0800455aaudio_result_t AudioStreamTrack::setBufferSize(int32_t requestedFrames)
Phil Burke1ce4912016-11-21 10:40:25 -0800456{
Phil Burk41852682019-03-29 10:58:15 -0700457 // Do not ask for less than one burst.
458 if (requestedFrames < getFramesPerBurst()) {
459 requestedFrames = getFramesPerBurst();
460 }
Phil Burke1ce4912016-11-21 10:40:25 -0800461 ssize_t result = mAudioTrack->setBufferSizeInFrames(requestedFrames);
Phil Burk3316d5e2017-02-15 11:23:01 -0800462 if (result < 0) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800463 return AAudioConvert_androidToAAudioResult(result);
Phil Burke1ce4912016-11-21 10:40:25 -0800464 } else {
Phil Burk3316d5e2017-02-15 11:23:01 -0800465 return result;
Phil Burke1ce4912016-11-21 10:40:25 -0800466 }
467}
468
Phil Burk3316d5e2017-02-15 11:23:01 -0800469int32_t AudioStreamTrack::getBufferSize() const
Phil Burke1ce4912016-11-21 10:40:25 -0800470{
Phil Burk3316d5e2017-02-15 11:23:01 -0800471 return static_cast<int32_t>(mAudioTrack->getBufferSizeInFrames());
Phil Burke1ce4912016-11-21 10:40:25 -0800472}
473
Phil Burk8d97b8e2020-09-25 23:18:14 +0000474int32_t AudioStreamTrack::getBufferCapacityFromDevice() const
Phil Burke1ce4912016-11-21 10:40:25 -0800475{
Phil Burk3316d5e2017-02-15 11:23:01 -0800476 return static_cast<int32_t>(mAudioTrack->frameCount());
Phil Burke1ce4912016-11-21 10:40:25 -0800477}
478
479int32_t AudioStreamTrack::getXRunCount() const
480{
481 return static_cast<int32_t>(mAudioTrack->getUnderrunCount());
482}
483
Phil Burk8d97b8e2020-09-25 23:18:14 +0000484int32_t AudioStreamTrack::getFramesPerBurstFromDevice() const {
Phil Burkb5884022017-03-27 15:26:14 -0700485 return static_cast<int32_t>(mAudioTrack->getNotificationPeriodInFrames());
Phil Burke1ce4912016-11-21 10:40:25 -0800486}
487
Phil Burk3316d5e2017-02-15 11:23:01 -0800488int64_t AudioStreamTrack::getFramesRead() {
Phil Burk5ed503c2017-02-01 09:38:15 -0800489 aaudio_wrapping_frames_t position;
Phil Burke1ce4912016-11-21 10:40:25 -0800490 status_t result;
491 switch (getState()) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800492 case AAUDIO_STREAM_STATE_STARTING:
493 case AAUDIO_STREAM_STATE_STARTED:
494 case AAUDIO_STREAM_STATE_STOPPING:
Phil Burk4c5129b2017-04-28 15:17:32 -0700495 case AAUDIO_STREAM_STATE_PAUSING:
496 case AAUDIO_STREAM_STATE_PAUSED:
Phil Burke1ce4912016-11-21 10:40:25 -0800497 result = mAudioTrack->getPosition(&position);
498 if (result == OK) {
499 mFramesRead.update32(position);
500 }
501 break;
502 default:
503 break;
504 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700505 return AudioStreamLegacy::getFramesRead();
Phil Burke1ce4912016-11-21 10:40:25 -0800506}
Phil Burk35e80f32017-03-28 10:25:21 -0700507
508aaudio_result_t AudioStreamTrack::getTimestamp(clockid_t clockId,
509 int64_t *framePosition,
510 int64_t *timeNanoseconds) {
511 ExtendedTimestamp extendedTimestamp;
512 status_t status = mAudioTrack->getTimestamp(&extendedTimestamp);
Phil Burkc75d97f2017-09-08 15:48:36 -0700513 if (status == WOULD_BLOCK) {
514 return AAUDIO_ERROR_INVALID_STATE;
515 } if (status != NO_ERROR) {
Phil Burk35e80f32017-03-28 10:25:21 -0700516 return AAudioConvert_androidToAAudioResult(status);
517 }
Phil Burk7328a802017-08-30 09:29:48 -0700518 int64_t position = 0;
519 int64_t nanoseconds = 0;
520 aaudio_result_t result = getBestTimestamp(clockId, &position,
521 &nanoseconds, &extendedTimestamp);
522 if (result == AAUDIO_OK) {
523 if (position < getFramesWritten()) {
524 *framePosition = position;
525 *timeNanoseconds = nanoseconds;
526 return result;
527 } else {
528 return AAUDIO_ERROR_INVALID_STATE; // TODO review, documented but not consistent
529 }
530 }
531 return result;
Phil Burk35e80f32017-03-28 10:25:21 -0700532}
Phil Burk965650e2017-09-07 21:00:09 -0700533
534status_t AudioStreamTrack::doSetVolume() {
535 status_t status = NO_INIT;
536 if (mAudioTrack.get() != nullptr) {
537 float volume = getDuckAndMuteVolume();
538 mAudioTrack->setVolume(volume, volume);
539 status = NO_ERROR;
540 }
541 return status;
542}
543
544#if AAUDIO_USE_VOLUME_SHAPER
Phil Burk8a8a9e52017-09-12 16:25:15 -0700545
546using namespace android::media::VolumeShaper;
547
Phil Burk965650e2017-09-07 21:00:09 -0700548binder::Status AudioStreamTrack::applyVolumeShaper(
549 const VolumeShaper::Configuration& configuration,
550 const VolumeShaper::Operation& operation) {
551
552 sp<VolumeShaper::Configuration> spConfiguration = new VolumeShaper::Configuration(configuration);
553 sp<VolumeShaper::Operation> spOperation = new VolumeShaper::Operation(operation);
554
555 if (mAudioTrack.get() != nullptr) {
556 ALOGD("applyVolumeShaper() from IPlayer");
Phil Burk8a8a9e52017-09-12 16:25:15 -0700557 binder::Status status = mAudioTrack->applyVolumeShaper(spConfiguration, spOperation);
Phil Burk965650e2017-09-07 21:00:09 -0700558 if (status < 0) { // a non-negative value is the volume shaper id.
559 ALOGE("applyVolumeShaper() failed with status %d", status);
560 }
561 return binder::Status::fromStatusT(status);
562 } else {
563 ALOGD("applyVolumeShaper()"
564 " no AudioTrack for volume control from IPlayer");
565 return binder::Status::ok();
566 }
567}
568#endif