blob: 55907b3b68a660455017f2d9c05a67d7359cfca5 [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
99 int32_t notificationFrames = 0;
100
Phil Burk0127c1b2018-03-29 13:48:06 -0700101 const audio_format_t format = (getFormat() == AUDIO_FORMAT_DEFAULT)
Phil Burke1ce4912016-11-21 10:40:25 -0800102 ? AUDIO_FORMAT_PCM_FLOAT
Phil Burk0127c1b2018-03-29 13:48:06 -0700103 : getFormat();
Phil Burke1ce4912016-11-21 10:40:25 -0800104
Phil Burke4d7bb42017-03-28 11:32:39 -0700105 // Setup the callback if there is one.
106 AudioTrack::callback_t callback = nullptr;
107 void *callbackData = nullptr;
108 // Note that TRANSFER_SYNC does not allow FAST track
109 AudioTrack::transfer_type streamTransferType = AudioTrack::transfer_type::TRANSFER_SYNC;
110 if (builder.getDataCallbackProc() != nullptr) {
111 streamTransferType = AudioTrack::transfer_type::TRANSFER_CALLBACK;
112 callback = getLegacyCallback();
113 callbackData = this;
114
Phil Burke4d7bb42017-03-28 11:32:39 -0700115 // If the total buffer size is unspecified then base the size on the burst size.
Phil Burk4485d412017-05-09 15:55:02 -0700116 if (frameCount == 0
117 && ((flags & AUDIO_OUTPUT_FLAG_FAST) != 0)) {
Phil Burke4d7bb42017-03-28 11:32:39 -0700118 // Take advantage of a special trick that allows us to create a buffer
119 // that is some multiple of the burst size.
120 notificationFrames = 0 - DEFAULT_BURSTS_PER_BUFFER_CAPACITY;
Phil Burk4485d412017-05-09 15:55:02 -0700121 } else {
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000122 // To avoid glitching, let AudioFlinger pick the optimal burst size.
123 notificationFrames = 0;
Phil Burke4d7bb42017-03-28 11:32:39 -0700124 }
125 }
126 mCallbackBufferSize = builder.getFramesPerDataCallback();
127
Phil Burkfbf031e2017-10-12 15:58:31 -0700128 ALOGD("open(), request notificationFrames = %d, frameCount = %u",
Phil Burkcf5f6d22017-05-26 12:35:07 -0700129 notificationFrames, (uint)frameCount);
Phil Burkee995392017-12-11 11:44:36 -0800130
131 // Don't call mAudioTrack->setDeviceId() because it will be overwritten by set()!
132 audio_port_handle_t selectedDeviceId = (getDeviceId() == AAUDIO_UNSPECIFIED)
133 ? AUDIO_PORT_HANDLE_NONE
134 : getDeviceId();
135
Phil Burkd4ccc622017-12-20 15:32:44 -0800136 const audio_content_type_t contentType =
137 AAudioConvert_contentTypeToInternal(builder.getContentType());
138 const audio_usage_t usage =
139 AAudioConvert_usageToInternal(builder.getUsage());
Kevin Rocard68646ba2019-03-20 13:26:49 -0700140 const audio_flags_mask_t attributesFlags =
141 AAudioConvert_allowCapturePolicyToAudioFlagsMask(builder.getAllowedCapturePolicy());
Phil Burkd4ccc622017-12-20 15:32:44 -0800142
143 const audio_attributes_t attributes = {
144 .content_type = contentType,
145 .usage = usage,
146 .source = AUDIO_SOURCE_DEFAULT, // only used for recording
Kevin Rocard68646ba2019-03-20 13:26:49 -0700147 .flags = attributesFlags,
Phil Burkd4ccc622017-12-20 15:32:44 -0800148 .tags = ""
149 };
150
Phil Burkee995392017-12-11 11:44:36 -0800151 mAudioTrack = new AudioTrack();
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,
Phil Burkee995392017-12-11 11:44:36 -0800162 0, // DEFAULT sharedBuffer*/,
163 false, // DEFAULT threadCanCallJava
Phil Burk4e1af9f2018-01-03 15:54:35 -0800164 sessionId,
Phil Burkee995392017-12-11 11:44:36 -0800165 streamTransferType,
166 NULL, // DEFAULT audio_offload_info_t
167 AUDIO_UID_INVALID, // DEFAULT uid
168 -1, // DEFAULT pid
Phil Burkd4ccc622017-12-20 15:32:44 -0800169 &attributes,
Phil Burkee995392017-12-11 11:44:36 -0800170 // WARNING - If doNotReconnect set true then audio stops after plugging and unplugging
171 // headphones a few times.
172 false, // DEFAULT doNotReconnect,
173 1.0f, // DEFAULT maxRequiredSpeed
174 selectedDeviceId
175 );
Phil Burke1ce4912016-11-21 10:40:25 -0800176
Phil Burkd3813f32020-04-23 16:26:15 -0700177 // Set it here so it can be logged by the destructor if the open failed.
178 mAudioTrack->setCallerName(kCallerName);
179
Phil Burke1ce4912016-11-21 10:40:25 -0800180 // Did we get a valid track?
181 status_t status = mAudioTrack->initCheck();
Phil Burkdec33ab2017-01-17 14:48:16 -0800182 if (status != NO_ERROR) {
Phil Burk8b4e05e2019-12-17 12:12:09 -0800183 releaseCloseFinal();
Phil Burkfbf031e2017-10-12 15:58:31 -0700184 ALOGE("open(), initCheck() returned %d", status);
Phil Burk5ed503c2017-02-01 09:38:15 -0800185 return AAudioConvert_androidToAAudioResult(status);
Phil Burke1ce4912016-11-21 10:40:25 -0800186 }
187
Phil Burka9876702020-04-20 18:16:15 -0700188 mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_TRACK)
189 + std::to_string(mAudioTrack->getPortId());
190
Phil Burk965650e2017-09-07 21:00:09 -0700191 doSetVolume();
Eric Laurent1d32e9f2017-06-02 14:01:32 -0700192
Phil Burke1ce4912016-11-21 10:40:25 -0800193 // Get the actual values from the AudioTrack.
194 setSamplesPerFrame(mAudioTrack->channelCount());
Phil Burk0127c1b2018-03-29 13:48:06 -0700195 setFormat(mAudioTrack->format());
196 setDeviceFormat(mAudioTrack->format());
Phil Burke4d7bb42017-03-28 11:32:39 -0700197
Phil Burkcf5f6d22017-05-26 12:35:07 -0700198 int32_t actualSampleRate = mAudioTrack->getSampleRate();
Phil Burkcf5f6d22017-05-26 12:35:07 -0700199 setSampleRate(actualSampleRate);
200
Phil Burke4d7bb42017-03-28 11:32:39 -0700201 // We may need to pass the data through a block size adapter to guarantee constant size.
202 if (mCallbackBufferSize != AAUDIO_UNSPECIFIED) {
Phil Burk4b867492020-02-12 10:58:05 -0800203 // This may need to change if we add format conversion before
204 // the block size adaptation.
205 mBlockAdapterBytesPerFrame = getBytesPerFrame();
206 int callbackSizeBytes = mBlockAdapterBytesPerFrame * mCallbackBufferSize;
Phil Burke4d7bb42017-03-28 11:32:39 -0700207 mFixedBlockReader.open(callbackSizeBytes);
208 mBlockAdapter = &mFixedBlockReader;
209 } else {
210 mBlockAdapter = nullptr;
211 }
Phil Burke1ce4912016-11-21 10:40:25 -0800212
Phil Burk5ed503c2017-02-01 09:38:15 -0800213 setState(AAUDIO_STREAM_STATE_OPEN);
Phil Burkc0c70e32017-02-09 13:18:38 -0800214 setDeviceId(mAudioTrack->getRoutedDeviceId());
Phil Burk4e1af9f2018-01-03 15:54:35 -0800215
216 aaudio_session_id_t actualSessionId =
217 (requestedSessionId == AAUDIO_SESSION_ID_NONE)
218 ? AAUDIO_SESSION_ID_NONE
219 : (aaudio_session_id_t) mAudioTrack->getSessionId();
220 setSessionId(actualSessionId);
221
Eric Laurent68eff052020-04-10 18:28:41 -0700222 mInitialBufferCapacity = getBufferCapacity();
223 mInitialFramesPerBurst = getFramesPerBurst();
224
Phil Burk58f5ce12020-08-12 14:29:10 +0000225 mAudioTrack->addAudioDeviceCallback(this);
Phil Burke1ce4912016-11-21 10:40:25 -0800226
Phil Burk09c27ca2017-08-24 22:12:56 -0700227 // Update performance mode based on the actual stream flags.
Phil Burk30a70772017-05-16 11:20:36 -0700228 // For example, if the sample rate is not allowed then you won't get a FAST track.
229 audio_output_flags_t actualFlags = mAudioTrack->getFlags();
230 aaudio_performance_mode_t actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_NONE;
Phil Burk09c27ca2017-08-24 22:12:56 -0700231 // We may not get the RAW flag. But as long as we get the FAST flag we can call it LOW_LATENCY.
232 if ((actualFlags & AUDIO_OUTPUT_FLAG_FAST) != 0) {
Phil Burk30a70772017-05-16 11:20:36 -0700233 actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_LOW_LATENCY;
Phil Burk30a70772017-05-16 11:20:36 -0700234 } else if ((actualFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
235 actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_POWER_SAVING;
236 }
237 setPerformanceMode(actualPerformanceMode);
Phil Burkefa56002017-08-02 15:07:21 -0700238
239 setSharingMode(AAUDIO_SHARING_MODE_SHARED); // EXCLUSIVE mode not supported in legacy
240
Phil Burk7216b3f2020-06-23 23:29:18 +0000241 // Log if we did not get what we asked for.
242 ALOGD_IF(actualFlags != flags,
Phil Burkfbf031e2017-10-12 15:58:31 -0700243 "open() flags changed from 0x%08X to 0x%08X",
Phil Burk30a70772017-05-16 11:20:36 -0700244 flags, actualFlags);
Phil Burk7216b3f2020-06-23 23:29:18 +0000245 ALOGD_IF(actualPerformanceMode != perfMode,
Phil Burkfbf031e2017-10-12 15:58:31 -0700246 "open() perfMode changed from %d to %d",
Phil Burk30a70772017-05-16 11:20:36 -0700247 perfMode, actualPerformanceMode);
248
Phil Burk5ed503c2017-02-01 09:38:15 -0800249 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800250}
251
Phil Burk8b4e05e2019-12-17 12:12:09 -0800252aaudio_result_t AudioStreamTrack::release_l() {
253 if (getState() != AAUDIO_STREAM_STATE_CLOSING) {
Phil Burk58f5ce12020-08-12 14:29:10 +0000254 status_t err = mAudioTrack->removeAudioDeviceCallback(this);
255 ALOGE_IF(err, "%s() removeAudioDeviceCallback returned %d", __func__, err);
Phil Burk64e16a72020-06-01 13:25:51 -0700256 logReleaseBufferState();
Phil Burk320910f2020-08-12 14:29:10 +0000257 // Data callbacks may still be running!
Phil Burk8b4e05e2019-12-17 12:12:09 -0800258 return AudioStream::release_l();
259 } else {
260 return AAUDIO_OK; // already released
Phil Burke1ce4912016-11-21 10:40:25 -0800261 }
Phil Burke1ce4912016-11-21 10:40:25 -0800262}
263
Phil Burk320910f2020-08-12 14:29:10 +0000264void AudioStreamTrack::close_l() {
265 // Stop callbacks before deleting mFixedBlockReader memory.
266 mAudioTrack.clear();
Phil Burk58f5ce12020-08-12 14:29:10 +0000267 // Do not close mFixedBlockReader because a data callback
268 // thread might still be running if someone else has a reference
269 // to mAudioRecord.
270 // It has a unique_ptr to its buffer so it will clean up by itself.
Phil Burk320910f2020-08-12 14:29:10 +0000271 AudioStream::close_l();
272}
273
Phil Burke4d7bb42017-03-28 11:32:39 -0700274void AudioStreamTrack::processCallback(int event, void *info) {
275
276 switch (event) {
277 case AudioTrack::EVENT_MORE_DATA:
278 processCallbackCommon(AAUDIO_CALLBACK_OPERATION_PROCESS_DATA, info);
279 break;
280
281 // Stream got rerouted so we disconnect.
282 case AudioTrack::EVENT_NEW_IAUDIOTRACK:
Eric Laurent68eff052020-04-10 18:28:41 -0700283 // request stream disconnect if the restored AudioTrack has properties not matching
284 // what was requested initially
285 if (mAudioTrack->channelCount() != getSamplesPerFrame()
286 || mAudioTrack->format() != getFormat()
287 || mAudioTrack->getSampleRate() != getSampleRate()
288 || mAudioTrack->getRoutedDeviceId() != getDeviceId()
289 || getBufferCapacity() != mInitialBufferCapacity
290 || getFramesPerBurst() != mInitialFramesPerBurst) {
291 processCallbackCommon(AAUDIO_CALLBACK_OPERATION_DISCONNECTED, info);
292 }
Phil Burke4d7bb42017-03-28 11:32:39 -0700293 break;
294
295 default:
296 break;
297 }
298 return;
299}
300
Phil Burk965650e2017-09-07 21:00:09 -0700301aaudio_result_t AudioStreamTrack::requestStart() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800302 if (mAudioTrack.get() == nullptr) {
Phil Burkfbf031e2017-10-12 15:58:31 -0700303 ALOGE("requestStart() no AudioTrack");
Phil Burk5ed503c2017-02-01 09:38:15 -0800304 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800305 }
306 // Get current position so we can detect when the track is playing.
307 status_t err = mAudioTrack->getPosition(&mPositionWhenStarting);
308 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800309 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800310 }
Phil Burke4d7bb42017-03-28 11:32:39 -0700311
Phil Burk9e9a95b2018-01-18 12:14:15 -0800312 // Enable callback before starting AudioTrack to avoid shutting
313 // down because of a race condition.
314 mCallbackEnabled.store(true);
Phil Burk4c377ef2020-06-25 10:03:23 -0700315 aaudio_stream_state_t originalState = getState();
316 // Set before starting the callback so that we are in the correct state
317 // before updateStateMachine() can be called by the callback.
318 setState(AAUDIO_STREAM_STATE_STARTING);
Phil Burk965650e2017-09-07 21:00:09 -0700319 err = mAudioTrack->start();
Phil Burke1ce4912016-11-21 10:40:25 -0800320 if (err != OK) {
Phil Burk4c377ef2020-06-25 10:03:23 -0700321 mCallbackEnabled.store(false);
322 setState(originalState);
Phil Burk5ed503c2017-02-01 09:38:15 -0800323 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800324 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800325 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800326}
327
Phil Burk965650e2017-09-07 21:00:09 -0700328aaudio_result_t AudioStreamTrack::requestPause() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800329 if (mAudioTrack.get() == nullptr) {
Phil Burk1e83bee2018-12-17 14:15:20 -0800330 ALOGE("%s() no AudioTrack", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800331 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800332 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800333
Phil Burk5ed503c2017-02-01 09:38:15 -0800334 setState(AAUDIO_STREAM_STATE_PAUSING);
Phil Burk965650e2017-09-07 21:00:09 -0700335 mAudioTrack->pause();
Phil Burk9e9a95b2018-01-18 12:14:15 -0800336 mCallbackEnabled.store(false);
Phil Burke1ce4912016-11-21 10:40:25 -0800337 status_t err = mAudioTrack->getPosition(&mPositionWhenPausing);
338 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800339 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800340 }
Phil Burk134f1972017-12-08 13:06:11 -0800341 return checkForDisconnectRequest(false);
Phil Burke1ce4912016-11-21 10:40:25 -0800342}
343
Phil Burk5ed503c2017-02-01 09:38:15 -0800344aaudio_result_t AudioStreamTrack::requestFlush() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800345 if (mAudioTrack.get() == nullptr) {
Phil Burk1e83bee2018-12-17 14:15:20 -0800346 ALOGE("%s() no AudioTrack", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800347 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800348 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800349
Phil Burk5ed503c2017-02-01 09:38:15 -0800350 setState(AAUDIO_STREAM_STATE_FLUSHING);
Phil Burke1ce4912016-11-21 10:40:25 -0800351 incrementFramesRead(getFramesWritten() - getFramesRead());
352 mAudioTrack->flush();
Phil Burk2b6f1282018-05-10 15:26:30 -0700353 mFramesRead.reset32(); // service reads frames, service position reset on flush
Phil Burk7328a802017-08-30 09:29:48 -0700354 mTimestampPosition.reset32();
Phil Burk5ed503c2017-02-01 09:38:15 -0800355 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800356}
357
Phil Burk5ed503c2017-02-01 09:38:15 -0800358aaudio_result_t AudioStreamTrack::requestStop() {
Phil Burkd8bdcab2017-01-03 17:20:30 -0800359 if (mAudioTrack.get() == nullptr) {
Phil Burk1e83bee2018-12-17 14:15:20 -0800360 ALOGE("%s() no AudioTrack", __func__);
Phil Burk5ed503c2017-02-01 09:38:15 -0800361 return AAUDIO_ERROR_INVALID_STATE;
Phil Burke1ce4912016-11-21 10:40:25 -0800362 }
Phil Burk5cc83c32017-11-28 15:43:18 -0800363
Phil Burk5ed503c2017-02-01 09:38:15 -0800364 setState(AAUDIO_STREAM_STATE_STOPPING);
Phil Burk18c84762018-12-18 12:15:35 -0800365 mFramesRead.catchUpTo(getFramesWritten());
366 mTimestampPosition.catchUpTo(getFramesWritten());
Phil Burk2b6f1282018-05-10 15:26:30 -0700367 mFramesRead.reset32(); // service reads frames, service position reset on stop
Phil Burk7328a802017-08-30 09:29:48 -0700368 mTimestampPosition.reset32();
Phil Burk965650e2017-09-07 21:00:09 -0700369 mAudioTrack->stop();
Phil Burk9e9a95b2018-01-18 12:14:15 -0800370 mCallbackEnabled.store(false);
Phil Burk134f1972017-12-08 13:06:11 -0800371 return checkForDisconnectRequest(false);;
Phil Burke1ce4912016-11-21 10:40:25 -0800372}
373
Phil Burk0befec62017-07-28 15:12:13 -0700374aaudio_result_t AudioStreamTrack::updateStateMachine()
Phil Burke1ce4912016-11-21 10:40:25 -0800375{
376 status_t err;
Phil Burk5ed503c2017-02-01 09:38:15 -0800377 aaudio_wrapping_frames_t position;
Phil Burke1ce4912016-11-21 10:40:25 -0800378 switch (getState()) {
379 // TODO add better state visibility to AudioTrack
Phil Burk5ed503c2017-02-01 09:38:15 -0800380 case AAUDIO_STREAM_STATE_STARTING:
Phil Burke1ce4912016-11-21 10:40:25 -0800381 if (mAudioTrack->hasStarted()) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800382 setState(AAUDIO_STREAM_STATE_STARTED);
Phil Burke1ce4912016-11-21 10:40:25 -0800383 }
384 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800385 case AAUDIO_STREAM_STATE_PAUSING:
Phil Burke1ce4912016-11-21 10:40:25 -0800386 if (mAudioTrack->stopped()) {
387 err = mAudioTrack->getPosition(&position);
388 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800389 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800390 } else if (position == mPositionWhenPausing) {
391 // Has stream really stopped advancing?
Phil Burk5ed503c2017-02-01 09:38:15 -0800392 setState(AAUDIO_STREAM_STATE_PAUSED);
Phil Burke1ce4912016-11-21 10:40:25 -0800393 }
394 mPositionWhenPausing = position;
395 }
396 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800397 case AAUDIO_STREAM_STATE_FLUSHING:
Phil Burke1ce4912016-11-21 10:40:25 -0800398 {
399 err = mAudioTrack->getPosition(&position);
400 if (err != OK) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800401 return AAudioConvert_androidToAAudioResult(err);
Phil Burke1ce4912016-11-21 10:40:25 -0800402 } else if (position == 0) {
Phil Burk5204d312017-05-04 17:16:13 -0700403 // TODO Advance frames read to match written.
Phil Burk5ed503c2017-02-01 09:38:15 -0800404 setState(AAUDIO_STREAM_STATE_FLUSHED);
Phil Burke1ce4912016-11-21 10:40:25 -0800405 }
406 }
407 break;
Phil Burk5ed503c2017-02-01 09:38:15 -0800408 case AAUDIO_STREAM_STATE_STOPPING:
Phil Burke1ce4912016-11-21 10:40:25 -0800409 if (mAudioTrack->stopped()) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800410 setState(AAUDIO_STREAM_STATE_STOPPED);
Phil Burke1ce4912016-11-21 10:40:25 -0800411 }
412 break;
413 default:
414 break;
415 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800416 return AAUDIO_OK;
Phil Burke1ce4912016-11-21 10:40:25 -0800417}
418
Phil Burk5ed503c2017-02-01 09:38:15 -0800419aaudio_result_t AudioStreamTrack::write(const void *buffer,
Phil Burk3316d5e2017-02-15 11:23:01 -0800420 int32_t numFrames,
421 int64_t timeoutNanoseconds)
Phil Burke1ce4912016-11-21 10:40:25 -0800422{
Phil Burk3316d5e2017-02-15 11:23:01 -0800423 int32_t bytesPerFrame = getBytesPerFrame();
424 int32_t numBytes;
Phil Burk5ed503c2017-02-01 09:38:15 -0800425 aaudio_result_t result = AAudioConvert_framesToBytes(numFrames, bytesPerFrame, &numBytes);
426 if (result != AAUDIO_OK) {
Phil Burke1ce4912016-11-21 10:40:25 -0800427 return result;
428 }
429
Eric Laurentfb00fc72017-05-25 18:17:12 -0700430 if (getState() == AAUDIO_STREAM_STATE_DISCONNECTED) {
431 return AAUDIO_ERROR_DISCONNECTED;
432 }
433
Phil Burke1ce4912016-11-21 10:40:25 -0800434 // TODO add timeout to AudioTrack
435 bool blocking = timeoutNanoseconds > 0;
436 ssize_t bytesWritten = mAudioTrack->write(buffer, numBytes, blocking);
437 if (bytesWritten == WOULD_BLOCK) {
438 return 0;
439 } else if (bytesWritten < 0) {
440 ALOGE("invalid write, returned %d", (int)bytesWritten);
Eric Laurentfb00fc72017-05-25 18:17:12 -0700441 // in this context, a DEAD_OBJECT is more likely to be a disconnect notification due to
442 // AudioTrack invalidation
443 if (bytesWritten == DEAD_OBJECT) {
444 setState(AAUDIO_STREAM_STATE_DISCONNECTED);
445 return AAUDIO_ERROR_DISCONNECTED;
446 }
Phil Burk5ed503c2017-02-01 09:38:15 -0800447 return AAudioConvert_androidToAAudioResult(bytesWritten);
Phil Burke1ce4912016-11-21 10:40:25 -0800448 }
Phil Burk3316d5e2017-02-15 11:23:01 -0800449 int32_t framesWritten = (int32_t)(bytesWritten / bytesPerFrame);
Phil Burke1ce4912016-11-21 10:40:25 -0800450 incrementFramesWritten(framesWritten);
Phil Burk0befec62017-07-28 15:12:13 -0700451
452 result = updateStateMachine();
453 if (result != AAUDIO_OK) {
454 return result;
455 }
456
Phil Burke1ce4912016-11-21 10:40:25 -0800457 return framesWritten;
458}
459
Phil Burk3316d5e2017-02-15 11:23:01 -0800460aaudio_result_t AudioStreamTrack::setBufferSize(int32_t requestedFrames)
Phil Burke1ce4912016-11-21 10:40:25 -0800461{
Phil Burk41852682019-03-29 10:58:15 -0700462 // Do not ask for less than one burst.
463 if (requestedFrames < getFramesPerBurst()) {
464 requestedFrames = getFramesPerBurst();
465 }
Phil Burke1ce4912016-11-21 10:40:25 -0800466 ssize_t result = mAudioTrack->setBufferSizeInFrames(requestedFrames);
Phil Burk3316d5e2017-02-15 11:23:01 -0800467 if (result < 0) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800468 return AAudioConvert_androidToAAudioResult(result);
Phil Burke1ce4912016-11-21 10:40:25 -0800469 } else {
Phil Burk3316d5e2017-02-15 11:23:01 -0800470 return result;
Phil Burke1ce4912016-11-21 10:40:25 -0800471 }
472}
473
Phil Burk3316d5e2017-02-15 11:23:01 -0800474int32_t AudioStreamTrack::getBufferSize() const
Phil Burke1ce4912016-11-21 10:40:25 -0800475{
Phil Burk3316d5e2017-02-15 11:23:01 -0800476 return static_cast<int32_t>(mAudioTrack->getBufferSizeInFrames());
Phil Burke1ce4912016-11-21 10:40:25 -0800477}
478
Phil Burk3316d5e2017-02-15 11:23:01 -0800479int32_t AudioStreamTrack::getBufferCapacity() const
Phil Burke1ce4912016-11-21 10:40:25 -0800480{
Phil Burk3316d5e2017-02-15 11:23:01 -0800481 return static_cast<int32_t>(mAudioTrack->frameCount());
Phil Burke1ce4912016-11-21 10:40:25 -0800482}
483
484int32_t AudioStreamTrack::getXRunCount() const
485{
486 return static_cast<int32_t>(mAudioTrack->getUnderrunCount());
487}
488
489int32_t AudioStreamTrack::getFramesPerBurst() const
490{
Phil Burkb5884022017-03-27 15:26:14 -0700491 return static_cast<int32_t>(mAudioTrack->getNotificationPeriodInFrames());
Phil Burke1ce4912016-11-21 10:40:25 -0800492}
493
Phil Burk3316d5e2017-02-15 11:23:01 -0800494int64_t AudioStreamTrack::getFramesRead() {
Phil Burk5ed503c2017-02-01 09:38:15 -0800495 aaudio_wrapping_frames_t position;
Phil Burke1ce4912016-11-21 10:40:25 -0800496 status_t result;
497 switch (getState()) {
Phil Burk5ed503c2017-02-01 09:38:15 -0800498 case AAUDIO_STREAM_STATE_STARTING:
499 case AAUDIO_STREAM_STATE_STARTED:
500 case AAUDIO_STREAM_STATE_STOPPING:
Phil Burk4c5129b2017-04-28 15:17:32 -0700501 case AAUDIO_STREAM_STATE_PAUSING:
502 case AAUDIO_STREAM_STATE_PAUSED:
Phil Burke1ce4912016-11-21 10:40:25 -0800503 result = mAudioTrack->getPosition(&position);
504 if (result == OK) {
505 mFramesRead.update32(position);
506 }
507 break;
508 default:
509 break;
510 }
Phil Burkec89b2e2017-06-20 15:05:06 -0700511 return AudioStreamLegacy::getFramesRead();
Phil Burke1ce4912016-11-21 10:40:25 -0800512}
Phil Burk35e80f32017-03-28 10:25:21 -0700513
514aaudio_result_t AudioStreamTrack::getTimestamp(clockid_t clockId,
515 int64_t *framePosition,
516 int64_t *timeNanoseconds) {
517 ExtendedTimestamp extendedTimestamp;
518 status_t status = mAudioTrack->getTimestamp(&extendedTimestamp);
Phil Burkc75d97f2017-09-08 15:48:36 -0700519 if (status == WOULD_BLOCK) {
520 return AAUDIO_ERROR_INVALID_STATE;
521 } if (status != NO_ERROR) {
Phil Burk35e80f32017-03-28 10:25:21 -0700522 return AAudioConvert_androidToAAudioResult(status);
523 }
Phil Burk7328a802017-08-30 09:29:48 -0700524 int64_t position = 0;
525 int64_t nanoseconds = 0;
526 aaudio_result_t result = getBestTimestamp(clockId, &position,
527 &nanoseconds, &extendedTimestamp);
528 if (result == AAUDIO_OK) {
529 if (position < getFramesWritten()) {
530 *framePosition = position;
531 *timeNanoseconds = nanoseconds;
532 return result;
533 } else {
534 return AAUDIO_ERROR_INVALID_STATE; // TODO review, documented but not consistent
535 }
536 }
537 return result;
Phil Burk35e80f32017-03-28 10:25:21 -0700538}
Phil Burk965650e2017-09-07 21:00:09 -0700539
540status_t AudioStreamTrack::doSetVolume() {
541 status_t status = NO_INIT;
542 if (mAudioTrack.get() != nullptr) {
543 float volume = getDuckAndMuteVolume();
544 mAudioTrack->setVolume(volume, volume);
545 status = NO_ERROR;
546 }
547 return status;
548}
549
550#if AAUDIO_USE_VOLUME_SHAPER
Phil Burk8a8a9e52017-09-12 16:25:15 -0700551
552using namespace android::media::VolumeShaper;
553
Phil Burk965650e2017-09-07 21:00:09 -0700554binder::Status AudioStreamTrack::applyVolumeShaper(
555 const VolumeShaper::Configuration& configuration,
556 const VolumeShaper::Operation& operation) {
557
558 sp<VolumeShaper::Configuration> spConfiguration = new VolumeShaper::Configuration(configuration);
559 sp<VolumeShaper::Operation> spOperation = new VolumeShaper::Operation(operation);
560
561 if (mAudioTrack.get() != nullptr) {
562 ALOGD("applyVolumeShaper() from IPlayer");
Phil Burk8a8a9e52017-09-12 16:25:15 -0700563 binder::Status status = mAudioTrack->applyVolumeShaper(spConfiguration, spOperation);
Phil Burk965650e2017-09-07 21:00:09 -0700564 if (status < 0) { // a non-negative value is the volume shaper id.
565 ALOGE("applyVolumeShaper() failed with status %d", status);
566 }
567 return binder::Status::fromStatusT(status);
568 } else {
569 ALOGD("applyVolumeShaper()"
570 " no AudioTrack for volume control from IPlayer");
571 return binder::Status::ok();
572 }
573}
574#endif