blob: 36961d6498f03f85b179d7cd39961db93bea5032 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080018//#define LOG_NDEBUG 0
19#define LOG_TAG "AudioTrack"
20
Mark Salyzyn34fb2962014-06-18 16:30:56 -070021#include <inttypes.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070022#include <math.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080023#include <sys/resource.h>
Mark Salyzyn34fb2962014-06-18 16:30:56 -070024
Andy Hung2b01f002017-07-05 12:01:36 -070025#include <audio_utils/clock.h>
Glenn Kasten9f80dd22012-12-18 15:57:32 -080026#include <audio_utils/primitives.h>
27#include <binder/IPCThreadState.h>
28#include <media/AudioTrack.h>
29#include <utils/Log.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080030#include <private/media/AudioTrackShared.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070031#include <media/IAudioFlinger.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080032#include <media/AudioPolicyHelper.h>
Andy Hungcd044842014-08-07 11:04:34 -070033#include <media/AudioResamplerPublic.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080034
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010035#define WAIT_PERIOD_MS 10
36#define WAIT_STREAM_END_TIMEOUT_SEC 120
Andy Hung53c3b5f2014-12-15 16:42:05 -080037static const int kMaxLoopCountNotifications = 32;
Glenn Kasten511754b2012-01-11 09:52:19 -080038
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080039namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080040// ---------------------------------------------------------------------------
41
Ivan Lozano8cf3a072017-08-09 09:01:33 -070042using media::VolumeShaper;
43
Andy Hunga7f03352015-05-31 21:54:49 -070044// TODO: Move to a separate .h
45
Andy Hung4ede21d2014-12-12 15:37:34 -080046template <typename T>
Andy Hunga7f03352015-05-31 21:54:49 -070047static inline const T &min(const T &x, const T &y) {
Andy Hung4ede21d2014-12-12 15:37:34 -080048 return x < y ? x : y;
49}
50
Andy Hunga7f03352015-05-31 21:54:49 -070051template <typename T>
52static inline const T &max(const T &x, const T &y) {
53 return x > y ? x : y;
54}
55
Andy Hung5d313802016-10-10 15:09:39 -070056static const int32_t NANOS_PER_SECOND = 1000000000;
57
Andy Hunga7f03352015-05-31 21:54:49 -070058static inline nsecs_t framesToNanoseconds(ssize_t frames, uint32_t sampleRate, float speed)
59{
60 return ((double)frames * 1000000000) / ((double)sampleRate * speed);
61}
62
Andy Hung7f1bc8a2014-09-12 14:43:11 -070063static int64_t convertTimespecToUs(const struct timespec &tv)
64{
65 return tv.tv_sec * 1000000ll + tv.tv_nsec / 1000;
66}
67
Andy Hungffa36952017-08-17 10:41:51 -070068// TODO move to audio_utils.
69static inline struct timespec convertNsToTimespec(int64_t ns) {
70 struct timespec tv;
71 tv.tv_sec = static_cast<time_t>(ns / NANOS_PER_SECOND);
72 tv.tv_nsec = static_cast<long>(ns % NANOS_PER_SECOND);
73 return tv;
74}
75
Andy Hung7f1bc8a2014-09-12 14:43:11 -070076// current monotonic time in microseconds.
77static int64_t getNowUs()
78{
79 struct timespec tv;
80 (void) clock_gettime(CLOCK_MONOTONIC, &tv);
81 return convertTimespecToUs(tv);
82}
83
Andy Hung26145642015-04-15 21:56:53 -070084// FIXME: we don't use the pitch setting in the time stretcher (not working);
85// instead we emulate it using our sample rate converter.
86static const bool kFixPitch = true; // enable pitch fix
87static inline uint32_t adjustSampleRate(uint32_t sampleRate, float pitch)
88{
89 return kFixPitch ? (sampleRate * pitch + 0.5) : sampleRate;
90}
91
92static inline float adjustSpeed(float speed, float pitch)
93{
Ricardo Garcia6c7f0622015-04-30 18:39:16 -070094 return kFixPitch ? speed / max(pitch, AUDIO_TIMESTRETCH_PITCH_MIN_DELTA) : speed;
Andy Hung26145642015-04-15 21:56:53 -070095}
96
97static inline float adjustPitch(float pitch)
98{
99 return kFixPitch ? AUDIO_TIMESTRETCH_PITCH_NORMAL : pitch;
100}
101
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800102// static
103status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -0800104 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800105 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800106 uint32_t sampleRate)
107{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700108 if (frameCount == NULL) {
109 return BAD_VALUE;
110 }
Glenn Kasten04cd0182012-06-25 11:49:27 -0700111
Andy Hung0e48d252015-01-26 11:43:15 -0800112 // FIXME handle in server, like createTrack_l(), possible missing info:
Glenn Kastene0fa4672012-04-24 14:35:14 -0700113 // audio_io_handle_t output
114 // audio_format_t format
115 // audio_channel_mask_t channelMask
Andy Hung0e48d252015-01-26 11:43:15 -0800116 // audio_output_flags_t flags (FAST)
Glenn Kasten3b16c762012-11-14 08:44:39 -0800117 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -0800118 status_t status;
119 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
120 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -0800121 ALOGE("Unable to query output sample rate for stream type %d; status %d",
122 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800123 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800124 }
Glenn Kastene33054e2012-11-14 12:54:39 -0800125 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -0800126 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
127 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -0800128 ALOGE("Unable to query output frame count for stream type %d; status %d",
129 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800130 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800131 }
132 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -0800133 status = AudioSystem::getOutputLatency(&afLatency, streamType);
134 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -0800135 ALOGE("Unable to query output latency for stream type %d; status %d",
136 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800137 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800138 }
139
Andy Hung8edb8dc2015-03-26 19:13:55 -0700140 // When called from createTrack, speed is 1.0f (normal speed).
141 // This is rechecked again on setting playback rate (TODO: on setting sample rate, too).
Eric Laurent21da6472017-11-09 16:29:26 -0800142 *frameCount = AudioSystem::calculateMinFrameCount(afLatency, afFrameCount, afSampleRate,
143 sampleRate, 1.0f /*, 0 notificationsPerBufferReq*/);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800144
Andy Hung0e48d252015-01-26 11:43:15 -0800145 // The formula above should always produce a non-zero value under normal circumstances:
146 // AudioTrack.SAMPLE_RATE_HZ_MIN <= sampleRate <= AudioTrack.SAMPLE_RATE_HZ_MAX.
147 // Return error in the unlikely event that it does not, as that's part of the API contract.
Glenn Kasten66a04672014-01-08 08:53:44 -0800148 if (*frameCount == 0) {
Andy Hung0e48d252015-01-26 11:43:15 -0800149 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %u",
Glenn Kasten66a04672014-01-08 08:53:44 -0800150 streamType, sampleRate);
151 return BAD_VALUE;
152 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700153 ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, afSampleRate=%u, afLatency=%u",
154 *frameCount, afFrameCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800155 return NO_ERROR;
156}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800157
158// ---------------------------------------------------------------------------
159
160AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700161 : mStatus(NO_INIT),
Haynes Mathew George9b3359f2016-03-23 19:09:10 -0700162 mState(STATE_STOPPED),
John Grossman4ff14ba2012-02-08 16:37:41 -0800163 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800164 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700165 mPausedPosition(0),
Eric Laurent20b9ef02016-12-05 11:03:16 -0800166 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
Eric Laurent21da6472017-11-09 16:29:26 -0800167 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800168{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700169 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
170 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
171 mAttributes.flags = 0x0;
172 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800173}
174
175AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800176 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800177 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800178 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700179 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800180 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700181 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800182 callback_t cbf,
183 void* user,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700184 int32_t notificationFrames,
Glenn Kastend848eb42016-03-08 13:42:11 -0800185 audio_session_t sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000186 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800187 const audio_offload_info_t *offloadInfo,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800188 uid_t uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700189 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700190 const audio_attributes_t* pAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -0700191 bool doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -0700192 float maxRequiredSpeed,
193 audio_port_handle_t selectedDeviceId)
Glenn Kasten87913512011-06-22 16:15:25 -0700194 : mStatus(NO_INIT),
Haynes Mathew George9b3359f2016-03-23 19:09:10 -0700195 mState(STATE_STOPPED),
John Grossman4ff14ba2012-02-08 16:37:41 -0800196 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800197 mPreviousSchedulingGroup(SP_DEFAULT),
Eric Laurent21da6472017-11-09 16:29:26 -0800198 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800199{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700200 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700201 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800202 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
jiabin156c6872017-10-06 09:47:15 -0700203 offloadInfo, uid, pid, pAttributes, doNotReconnect, maxRequiredSpeed, selectedDeviceId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800204}
205
Andreas Huberc8139852012-01-18 10:51:55 -0800206AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800207 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800208 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800209 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700210 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800211 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700212 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800213 callback_t cbf,
214 void* user,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700215 int32_t notificationFrames,
Glenn Kastend848eb42016-03-08 13:42:11 -0800216 audio_session_t sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000217 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800218 const audio_offload_info_t *offloadInfo,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800219 uid_t uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700220 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700221 const audio_attributes_t* pAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -0700222 bool doNotReconnect,
223 float maxRequiredSpeed)
Glenn Kasten87913512011-06-22 16:15:25 -0700224 : mStatus(NO_INIT),
Haynes Mathew George9b3359f2016-03-23 19:09:10 -0700225 mState(STATE_STOPPED),
John Grossman4ff14ba2012-02-08 16:37:41 -0800226 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800227 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700228 mPausedPosition(0),
Eric Laurent21da6472017-11-09 16:29:26 -0800229 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800230{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700231 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800232 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800233 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Andy Hungff874dc2016-04-11 16:49:09 -0700234 uid, pid, pAttributes, doNotReconnect, maxRequiredSpeed);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800235}
236
237AudioTrack::~AudioTrack()
238{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800239 if (mStatus == NO_ERROR) {
240 // Make sure that callback function exits in the case where
241 // it is looping on buffer full condition in obtainBuffer().
242 // Otherwise the callback thread will never exit.
243 stop();
244 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100245 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800246 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800247 mAudioTrackThread->requestExitAndWait();
248 mAudioTrackThread.clear();
249 }
Eric Laurent296fb132015-05-01 11:38:42 -0700250 // No lock here: worst case we remove a NULL callback which will be a nop
251 if (mDeviceCallback != 0 && mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700252 AudioSystem::removeAudioDeviceCallback(this, mOutput);
Eric Laurent296fb132015-05-01 11:38:42 -0700253 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800254 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700255 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700256 mCblkMemory.clear();
257 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800258 IPCThreadState::self()->flushCommands();
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700259 ALOGV("~AudioTrack, releasing session id %d from %d on behalf of %d",
260 mSessionId, IPCThreadState::self()->getCallingPid(), mClientPid);
Marco Nelissend457c972014-02-11 08:47:07 -0800261 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800262 }
263}
264
265status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800266 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800267 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800268 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700269 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800270 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700271 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800272 callback_t cbf,
273 void* user,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700274 int32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800275 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700276 bool threadCanCallJava,
Glenn Kastend848eb42016-03-08 13:42:11 -0800277 audio_session_t sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000278 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800279 const audio_offload_info_t *offloadInfo,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800280 uid_t uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700281 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700282 const audio_attributes_t* pAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -0700283 bool doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -0700284 float maxRequiredSpeed,
285 audio_port_handle_t selectedDeviceId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800286{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800287 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kastenea38ee72016-04-18 11:08:01 -0700288 "flags #%x, notificationFrames %d, sessionId %d, transferType %d, uid %d, pid %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800289 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700290 sessionId, transferType, uid, pid);
Glenn Kasten86f04662014-02-24 15:13:05 -0800291
Phil Burk33ff89b2015-11-30 11:16:01 -0800292 mThreadCanCallJava = threadCanCallJava;
jiabin156c6872017-10-06 09:47:15 -0700293 mSelectedDeviceId = selectedDeviceId;
Eric Laurent21da6472017-11-09 16:29:26 -0800294 mSessionId = sessionId;
Phil Burk33ff89b2015-11-30 11:16:01 -0800295
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800296 switch (transferType) {
297 case TRANSFER_DEFAULT:
298 if (sharedBuffer != 0) {
299 transferType = TRANSFER_SHARED;
300 } else if (cbf == NULL || threadCanCallJava) {
301 transferType = TRANSFER_SYNC;
302 } else {
303 transferType = TRANSFER_CALLBACK;
304 }
305 break;
306 case TRANSFER_CALLBACK:
307 if (cbf == NULL || sharedBuffer != 0) {
308 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
309 return BAD_VALUE;
310 }
311 break;
312 case TRANSFER_OBTAIN:
313 case TRANSFER_SYNC:
314 if (sharedBuffer != 0) {
315 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
316 return BAD_VALUE;
317 }
318 break;
319 case TRANSFER_SHARED:
320 if (sharedBuffer == 0) {
321 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
322 return BAD_VALUE;
323 }
324 break;
325 default:
326 ALOGE("Invalid transfer type %d", transferType);
327 return BAD_VALUE;
328 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800329 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800330 mTransfer = transferType;
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700331 mDoNotReconnect = doNotReconnect;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800332
Eric Laurent97c9f4f2015-08-11 18:04:14 -0700333 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %zu", sharedBuffer->pointer(),
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700334 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800335
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700336 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700337
Glenn Kasten53cec222013-08-29 09:01:02 -0700338 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700339 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000340 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800341 return INVALID_OPERATION;
342 }
343
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800344 // handle default values first.
Eric Laurente83b55d2014-11-14 10:06:21 -0800345 if (streamType == AUDIO_STREAM_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700346 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800347 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700348 if (pAttributes == NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800349 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700350 ALOGE("Invalid stream type %d", streamType);
351 return BAD_VALUE;
352 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700353 mStreamType = streamType;
Eric Laurente83b55d2014-11-14 10:06:21 -0800354
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700355 } else {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700356 // stream type shouldn't be looked at, this track has audio attributes
357 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700358 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
359 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800360 mStreamType = AUDIO_STREAM_DEFAULT;
Eric Laurentc6bd5db2015-03-09 16:29:33 -0700361 if ((mAttributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
362 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
363 }
Phil Burk33ff89b2015-11-30 11:16:01 -0800364 if ((mAttributes.flags & AUDIO_FLAG_LOW_LATENCY) != 0) {
365 flags = (audio_output_flags_t) (flags | AUDIO_OUTPUT_FLAG_FAST);
366 }
Andy Hungfff204c2017-01-12 19:09:55 -0800367 // check deep buffer after flags have been modified above
368 if (flags == AUDIO_OUTPUT_FLAG_NONE && (mAttributes.flags & AUDIO_FLAG_DEEP_BUFFER) != 0) {
369 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
370 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800371 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700372
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800373 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800374 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700375 format = AUDIO_FORMAT_PCM_16_BIT;
Phil Burkfdb3c072016-02-09 10:47:02 -0800376 } else if (format == AUDIO_FORMAT_IEC61937) { // HDMI pass-through?
377 mAttributes.flags |= AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800378 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800379
380 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700381 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800382 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800383 return BAD_VALUE;
384 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800385 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700386
Glenn Kasten8ba90322013-10-30 11:29:27 -0700387 if (!audio_is_output_channel(channelMask)) {
388 ALOGE("Invalid channel mask %#x", channelMask);
389 return BAD_VALUE;
390 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800391 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700392 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800393 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700394
Eric Laurentc2f1f072009-07-17 12:17:14 -0700395 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100396 // or offload was requested
397 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
398 || !audio_is_linear_pcm(format)) {
399 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
400 ? "Offload request, forcing to Direct Output"
401 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700402 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800403 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700404 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700405 }
406
Eric Laurentd1f69b02014-12-15 14:33:13 -0800407 // force direct flag if HW A/V sync requested
408 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
409 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
410 }
411
Glenn Kastenb7730382014-04-30 15:50:31 -0700412 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Phil Burkfdb3c072016-02-09 10:47:02 -0800413 if (audio_has_proportional_frames(format)) {
Glenn Kastenb7730382014-04-30 15:50:31 -0700414 mFrameSize = channelCount * audio_bytes_per_sample(format);
415 } else {
416 mFrameSize = sizeof(uint8_t);
417 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800418 } else {
Phil Burkfdb3c072016-02-09 10:47:02 -0800419 ALOG_ASSERT(audio_has_proportional_frames(format));
Glenn Kastenb7730382014-04-30 15:50:31 -0700420 mFrameSize = channelCount * audio_bytes_per_sample(format);
Glenn Kastenb7730382014-04-30 15:50:31 -0700421 // createTrack will return an error if PCM format is not supported by server,
422 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800423 }
424
Eric Laurent0d6db582014-11-12 18:39:44 -0800425 // sampling rate must be specified for direct outputs
426 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
427 return BAD_VALUE;
428 }
429 mSampleRate = sampleRate;
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700430 mOriginalSampleRate = sampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700431 mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT;
Andy Hungff874dc2016-04-11 16:49:09 -0700432 // 1.0 <= mMaxRequiredSpeed <= AUDIO_TIMESTRETCH_SPEED_MAX
433 mMaxRequiredSpeed = min(max(maxRequiredSpeed, 1.0f), AUDIO_TIMESTRETCH_SPEED_MAX);
Eric Laurent0d6db582014-11-12 18:39:44 -0800434
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800435 // Make copy of input parameter offloadInfo so that in the future:
436 // (a) createTrack_l doesn't need it as an input parameter
437 // (b) we can support re-creation of offloaded tracks
438 if (offloadInfo != NULL) {
439 mOffloadInfoCopy = *offloadInfo;
440 mOffloadInfo = &mOffloadInfoCopy;
441 } else {
442 mOffloadInfo = NULL;
Eric Laurent20b9ef02016-12-05 11:03:16 -0800443 memset(&mOffloadInfoCopy, 0, sizeof(audio_offload_info_t));
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800444 }
445
Glenn Kasten66e46352014-01-16 17:44:23 -0800446 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
447 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800448 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800449 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800450 mReqFrameCount = frameCount;
Glenn Kastenea38ee72016-04-18 11:08:01 -0700451 if (notificationFrames >= 0) {
452 mNotificationFramesReq = notificationFrames;
453 mNotificationsPerBufferReq = 0;
454 } else {
455 if (!(flags & AUDIO_OUTPUT_FLAG_FAST)) {
456 ALOGE("notificationFrames=%d not permitted for non-fast track",
457 notificationFrames);
458 return BAD_VALUE;
459 }
460 if (frameCount > 0) {
461 ALOGE("notificationFrames=%d not permitted with non-zero frameCount=%zu",
462 notificationFrames, frameCount);
463 return BAD_VALUE;
464 }
465 mNotificationFramesReq = 0;
466 const uint32_t minNotificationsPerBuffer = 1;
467 const uint32_t maxNotificationsPerBuffer = 8;
468 mNotificationsPerBufferReq = min(maxNotificationsPerBuffer,
469 max((uint32_t) -notificationFrames, minNotificationsPerBuffer));
470 ALOGW_IF(mNotificationsPerBufferReq != (uint32_t) -notificationFrames,
471 "notificationFrames=%d clamped to the range -%u to -%u",
472 notificationFrames, minNotificationsPerBuffer, maxNotificationsPerBuffer);
473 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800474 mNotificationFramesAct = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800475 int callingpid = IPCThreadState::self()->getCallingPid();
476 int mypid = getpid();
Andy Hung1f12a8a2016-11-07 16:10:30 -0800477 if (uid == AUDIO_UID_INVALID || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800478 mClientUid = IPCThreadState::self()->getCallingUid();
479 } else {
480 mClientUid = uid;
481 }
Marco Nelissend457c972014-02-11 08:47:07 -0800482 if (pid == -1 || (callingpid != mypid)) {
483 mClientPid = callingpid;
484 } else {
485 mClientPid = pid;
486 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700487 mAuxEffectId = 0;
Haynes Mathew Georgeae34ed22016-01-28 11:58:39 -0800488 mOrigFlags = mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700489 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700490
Glenn Kastena997e7a2012-08-07 09:44:19 -0700491 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700492 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700493 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
Glenn Kastenbfd31842015-03-20 09:01:44 -0700494 // thread begins in paused state, and will not reference us until start()
Glenn Kastena997e7a2012-08-07 09:44:19 -0700495 }
496
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800497 // create the IAudioTrack
Eric Laurent0d6db582014-11-12 18:39:44 -0800498 status_t status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800499
Glenn Kastena997e7a2012-08-07 09:44:19 -0700500 if (status != NO_ERROR) {
501 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100502 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
503 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700504 mAudioTrackThread.clear();
505 }
506 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700507 }
508
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800509 mStatus = NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800510 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800511 mLoopCount = 0;
512 mLoopStart = 0;
513 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800514 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800515 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700516 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800517 mNewPosition = 0;
518 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700519 mPosition = 0;
520 mReleased = 0;
Andy Hungffa36952017-08-17 10:41:51 -0700521 mStartNs = 0;
522 mStartFromZeroUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800523 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800524 mSequence = 1;
525 mObservedSequence = mSequence;
526 mInUnderrun = false;
Phil Burk1b420972015-04-22 10:52:21 -0700527 mPreviousTimestampValid = false;
Andy Hungc8e09c62015-06-03 23:43:36 -0700528 mTimestampStartupGlitchReported = false;
529 mRetrogradeMotionReported = false;
Andy Hungb01faa32016-04-27 12:51:32 -0700530 mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
Andy Hung65ffdfc2016-10-10 15:52:11 -0700531 mStartTs.mPosition = 0;
Phil Burk2812d9e2016-01-04 10:34:30 -0800532 mUnderrunCountOffset = 0;
Andy Hungea2b9c02016-02-12 17:06:53 -0800533 mFramesWritten = 0;
534 mFramesWrittenServerOffset = 0;
Andy Hungf20a4e92016-08-15 19:10:34 -0700535 mFramesWrittenAtRestore = -1; // -1 is a unique initializer.
Ivan Lozano8cf3a072017-08-09 09:01:33 -0700536 mVolumeHandler = new media::VolumeHandler();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800537 return NO_ERROR;
538}
539
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800540// -------------------------------------------------------------------------
541
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100542status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800543{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800544 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100545
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800546 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100547 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800548 }
549
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800550 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800551
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800552 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100553 if (previousState == STATE_PAUSED_STOPPING) {
554 mState = STATE_STOPPING;
555 } else {
556 mState = STATE_ACTIVE;
557 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700558 (void) updateAndGetPosition_l();
Andy Hung65ffdfc2016-10-10 15:52:11 -0700559
560 // save start timestamp
561 if (isOffloadedOrDirect_l()) {
562 if (getTimestamp_l(mStartTs) != OK) {
563 mStartTs.mPosition = 0;
564 }
565 } else {
566 if (getTimestamp_l(&mStartEts) != OK) {
567 mStartEts.clear();
568 }
569 }
Andy Hungffa36952017-08-17 10:41:51 -0700570 mStartNs = systemTime(); // save this for timestamp adjustment after starting.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800571 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
572 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700573 mPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -0700574 mPreviousTimestampValid = false;
Andy Hungc8e09c62015-06-03 23:43:36 -0700575 mTimestampStartupGlitchReported = false;
576 mRetrogradeMotionReported = false;
Andy Hungb01faa32016-04-27 12:51:32 -0700577 mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
Phil Burk1b420972015-04-22 10:52:21 -0700578
Andy Hung65ffdfc2016-10-10 15:52:11 -0700579 if (!isOffloadedOrDirect_l()
580 && mStartEts.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] > 0) {
Andy Hunge1e98462016-04-12 10:18:51 -0700581 // Server side has consumed something, but is it finished consuming?
582 // It is possible since flush and stop are asynchronous that the server
583 // is still active at this point.
584 ALOGV("start: server read:%lld cumulative flushed:%lld client written:%lld",
585 (long long)(mFramesWrittenServerOffset
Andy Hung65ffdfc2016-10-10 15:52:11 -0700586 + mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER]),
587 (long long)mStartEts.mFlushed,
Andy Hunge1e98462016-04-12 10:18:51 -0700588 (long long)mFramesWritten);
Andy Hungc4e60eb2017-09-06 11:14:57 -0700589 // mStartEts is already adjusted by mFramesWrittenServerOffset, so we delta adjust.
590 mFramesWrittenServerOffset -= mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung61be8412015-10-06 10:51:09 -0700591 }
Andy Hunge1e98462016-04-12 10:18:51 -0700592 mFramesWritten = 0;
593 mProxy->clearTimestamp(); // need new server push for valid timestamp
594 mMarkerReached = false;
Andy Hung61be8412015-10-06 10:51:09 -0700595
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700596 // For offloaded tracks, we don't know if the hardware counters are really zero here,
597 // since the flush is asynchronous and stop may not fully drain.
598 // We save the time when the track is started to later verify whether
599 // the counters are realistic (i.e. start from zero after this time).
Andy Hungffa36952017-08-17 10:41:51 -0700600 mStartFromZeroUs = mStartNs / 1000;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700601
Eric Laurentec9a0322013-08-28 10:23:01 -0700602 // force refresh of remaining frames by processAudioBuffer() as last
603 // write before stop could be partial.
604 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800605 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700606 mNewPosition = mPosition + mUpdatePeriod;
Andy Hung4be3b832016-10-13 17:51:43 -0700607 int32_t flags = android_atomic_and(~(CBLK_STREAM_END_DONE | CBLK_DISABLED), &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800608
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800609 status_t status = NO_ERROR;
610 if (!(flags & CBLK_INVALID)) {
611 status = mAudioTrack->start();
612 if (status == DEAD_OBJECT) {
613 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800614 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800615 }
616 if (flags & CBLK_INVALID) {
617 status = restoreTrack_l("start");
618 }
619
Andy Hung79629f02016-03-24 13:57:40 -0700620 // resume or pause the callback thread as needed.
621 sp<AudioTrackThread> t = mAudioTrackThread;
622 if (status == NO_ERROR) {
623 if (t != 0) {
624 if (previousState == STATE_STOPPING) {
625 mProxy->interrupt();
626 } else {
627 t->resume();
628 }
629 } else {
630 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
631 get_sched_policy(0, &mPreviousSchedulingGroup);
632 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
633 }
Andy Hung39399b62017-04-21 15:07:45 -0700634
635 // Start our local VolumeHandler for restoration purposes.
636 mVolumeHandler->setStarted();
Andy Hung79629f02016-03-24 13:57:40 -0700637 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800638 ALOGE("start() status %d", status);
639 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800640 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100641 if (previousState != STATE_STOPPING) {
642 t->pause();
643 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800644 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700645 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700646 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800647 }
648 }
649
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100650 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800651}
652
653void AudioTrack::stop()
654{
655 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700656 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800657 return;
658 }
659
Glenn Kasten23a75452014-01-13 10:37:17 -0800660 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100661 mState = STATE_STOPPING;
662 } else {
663 mState = STATE_STOPPED;
Andy Hung2148bf02016-11-28 19:01:02 -0800664 ALOGD_IF(mSharedBuffer == nullptr,
665 "stop() called with %u frames delivered", mReleased.value());
Andy Hungc2813e52014-10-16 17:54:34 -0700666 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100667 }
668
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800669 mProxy->interrupt();
670 mAudioTrack->stop();
Andy Hung61be8412015-10-06 10:51:09 -0700671
672 // Note: legacy handling - stop does not clear playback marker
673 // and periodic update counter, but flush does for streaming tracks.
Andy Hung9b461582014-12-01 17:56:29 -0800674
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800675 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800676 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800677 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
678 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800679 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100680
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800681 sp<AudioTrackThread> t = mAudioTrackThread;
682 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800683 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100684 t->pause();
685 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800686 } else {
687 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
688 set_sched_policy(0, mPreviousSchedulingGroup);
689 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800690}
691
692bool AudioTrack::stopped() const
693{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800694 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800695 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800696}
697
698void AudioTrack::flush()
699{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800700 if (mSharedBuffer != 0) {
701 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800702 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800703 AutoMutex lock(mLock);
704 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
705 return;
706 }
707 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800708}
709
Eric Laurent1703cdf2011-03-07 14:52:59 -0800710void AudioTrack::flush_l()
711{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800712 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700713
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700714 // clear playback marker and periodic update counter
715 mMarkerPosition = 0;
716 mMarkerReached = false;
717 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100718 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700719
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800720 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700721 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800722 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100723 mProxy->interrupt();
724 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800725 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800726 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800727}
728
729void AudioTrack::pause()
730{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800731 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100732 if (mState == STATE_ACTIVE) {
733 mState = STATE_PAUSED;
734 } else if (mState == STATE_STOPPING) {
735 mState = STATE_PAUSED_STOPPING;
736 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800737 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800738 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800739 mProxy->interrupt();
740 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800741
Marco Nelissen3a90f282014-03-10 11:21:43 -0700742 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700743 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700744 // An offload output can be re-used between two audio tracks having
745 // the same configuration. A timestamp query for a paused track
746 // while the other is running would return an incorrect time.
747 // To fix this, cache the playback position on a pause() and return
748 // this time when requested until the track is resumed.
749
750 // OffloadThread sends HAL pause in its threadLoop. Time saved
751 // here can be slightly off.
752
753 // TODO: check return code for getRenderPosition.
754
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800755 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800756 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
757 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
758 }
759 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800760}
761
Eric Laurentbe916aa2010-06-01 23:49:17 -0700762status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800763{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700764 // This duplicates a test by AudioTrack JNI, but that is not the only caller
765 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
766 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700767 return BAD_VALUE;
768 }
769
Eric Laurent1703cdf2011-03-07 14:52:59 -0800770 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800771 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
772 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800773
Glenn Kastenc56f3422014-03-21 17:53:17 -0700774 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700775
Glenn Kasten23a75452014-01-13 10:37:17 -0800776 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700777 mAudioTrack->signal();
778 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700779 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800780}
781
Glenn Kastenb1c09932012-02-27 16:21:04 -0800782status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800783{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800784 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700785}
786
Eric Laurent2beeb502010-07-16 07:43:46 -0700787status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700788{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700789 // This duplicates a test by AudioTrack JNI, but that is not the only caller
790 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700791 return BAD_VALUE;
792 }
793
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800794 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700795 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800796 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700797
798 return NO_ERROR;
799}
800
Glenn Kastena5224f32012-01-04 12:41:44 -0800801void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700802{
803 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800804 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700805 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800806}
807
Glenn Kasten3b16c762012-11-14 08:44:39 -0800808status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800809{
Andy Hung5cbb5782015-03-27 18:39:59 -0700810 AutoMutex lock(mLock);
811 if (rate == mSampleRate) {
812 return NO_ERROR;
813 }
Glenn Kastend79072e2016-01-06 08:41:20 -0800814 if (isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800815 return INVALID_OPERATION;
816 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800817 if (mOutput == AUDIO_IO_HANDLE_NONE) {
818 return NO_INIT;
819 }
Andy Hung5cbb5782015-03-27 18:39:59 -0700820 // NOTE: it is theoretically possible, but highly unlikely, that a device change
821 // could mean a previously allowed sampling rate is no longer allowed.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800822 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800823 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700824 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800825 }
Andy Hung26145642015-04-15 21:56:53 -0700826 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700827 const uint32_t effectiveSampleRate = adjustSampleRate(rate, mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -0700828 if (rate == 0 || effectiveSampleRate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700829 return BAD_VALUE;
830 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700831 // TODO: Should we also check if the buffer size is compatible?
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800832
Glenn Kastene3aa6592012-12-04 12:22:46 -0800833 mSampleRate = rate;
Andy Hung26145642015-04-15 21:56:53 -0700834 mProxy->setSampleRate(effectiveSampleRate);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800835
Eric Laurent57326622009-07-07 07:10:45 -0700836 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800837}
838
Glenn Kastena5224f32012-01-04 12:41:44 -0800839uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800840{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800841 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700842
843 // sample rate can be updated during playback by the offloaded decoder so we need to
844 // query the HAL and update if needed.
845// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700846 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700847 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700848 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700849 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700850 if (status == NO_ERROR) {
851 mSampleRate = sampleRate;
852 }
853 }
854 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800855 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800856}
857
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700858uint32_t AudioTrack::getOriginalSampleRate() const
859{
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700860 return mOriginalSampleRate;
861}
862
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700863status_t AudioTrack::setPlaybackRate(const AudioPlaybackRate &playbackRate)
Andy Hung8edb8dc2015-03-26 19:13:55 -0700864{
Andy Hung8edb8dc2015-03-26 19:13:55 -0700865 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700866 if (isAudioPlaybackRateEqual(playbackRate, mPlaybackRate)) {
Andy Hung8edb8dc2015-03-26 19:13:55 -0700867 return NO_ERROR;
868 }
Glenn Kastend79072e2016-01-06 08:41:20 -0800869 if (isOffloadedOrDirect_l()) {
Andy Hung8edb8dc2015-03-26 19:13:55 -0700870 return INVALID_OPERATION;
871 }
872 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
873 return INVALID_OPERATION;
874 }
Andy Hungff874dc2016-04-11 16:49:09 -0700875
876 ALOGV("setPlaybackRate (input): mSampleRate:%u mSpeed:%f mPitch:%f",
877 mSampleRate, playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -0700878 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700879 const uint32_t effectiveRate = adjustSampleRate(mSampleRate, playbackRate.mPitch);
880 const float effectiveSpeed = adjustSpeed(playbackRate.mSpeed, playbackRate.mPitch);
881 const float effectivePitch = adjustPitch(playbackRate.mPitch);
Ricardo Garcia6c7f0622015-04-30 18:39:16 -0700882 AudioPlaybackRate playbackRateTemp = playbackRate;
883 playbackRateTemp.mSpeed = effectiveSpeed;
884 playbackRateTemp.mPitch = effectivePitch;
885
Andy Hungff874dc2016-04-11 16:49:09 -0700886 ALOGV("setPlaybackRate (effective): mSampleRate:%u mSpeed:%f mPitch:%f",
887 effectiveRate, effectiveSpeed, effectivePitch);
888
Ricardo Garcia6c7f0622015-04-30 18:39:16 -0700889 if (!isAudioPlaybackRateValid(playbackRateTemp)) {
Kevin Rocard4e728d42017-04-06 18:00:40 -0700890 ALOGW("setPlaybackRate(%f, %f) failed (effective rate out of bounds)",
Andy Hungff874dc2016-04-11 16:49:09 -0700891 playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -0700892 return BAD_VALUE;
893 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700894 // Check if the buffer size is compatible.
Andy Hung26145642015-04-15 21:56:53 -0700895 if (!isSampleRateSpeedAllowed_l(effectiveRate, effectiveSpeed)) {
Kevin Rocard4e728d42017-04-06 18:00:40 -0700896 ALOGW("setPlaybackRate(%f, %f) failed (buffer size)",
Andy Hungff874dc2016-04-11 16:49:09 -0700897 playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung8edb8dc2015-03-26 19:13:55 -0700898 return BAD_VALUE;
899 }
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700900
Ricardo Garcia6c7f0622015-04-30 18:39:16 -0700901 // Check resampler ratios are within bounds
Glenn Kastend3bb6452016-12-05 18:14:37 -0800902 if ((uint64_t)effectiveRate > (uint64_t)mSampleRate *
903 (uint64_t)AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Kevin Rocard4e728d42017-04-06 18:00:40 -0700904 ALOGW("setPlaybackRate(%f, %f) failed. Resample rate exceeds max accepted value",
Ricardo Garcia6c7f0622015-04-30 18:39:16 -0700905 playbackRate.mSpeed, playbackRate.mPitch);
906 return BAD_VALUE;
907 }
908
Dan Austine34eae22015-10-27 16:14:52 -0700909 if ((uint64_t)effectiveRate * (uint64_t)AUDIO_RESAMPLER_UP_RATIO_MAX < (uint64_t)mSampleRate) {
Kevin Rocard4e728d42017-04-06 18:00:40 -0700910 ALOGW("setPlaybackRate(%f, %f) failed. Resample rate below min accepted value",
Ricardo Garcia6c7f0622015-04-30 18:39:16 -0700911 playbackRate.mSpeed, playbackRate.mPitch);
912 return BAD_VALUE;
913 }
914 mPlaybackRate = playbackRate;
915 //set effective rates
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700916 mProxy->setPlaybackRate(playbackRateTemp);
Andy Hung26145642015-04-15 21:56:53 -0700917 mProxy->setSampleRate(effectiveRate); // FIXME: not quite "atomic" with setPlaybackRate
Andy Hung8edb8dc2015-03-26 19:13:55 -0700918 return NO_ERROR;
919}
920
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700921const AudioPlaybackRate& AudioTrack::getPlaybackRate() const
Andy Hung8edb8dc2015-03-26 19:13:55 -0700922{
923 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700924 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700925}
926
Phil Burkc0adecb2016-01-08 12:44:11 -0800927ssize_t AudioTrack::getBufferSizeInFrames()
928{
929 AutoMutex lock(mLock);
930 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
931 return NO_INIT;
932 }
Phil Burke8972b02016-03-04 11:29:57 -0800933 return (ssize_t) mProxy->getBufferSizeInFrames();
Phil Burkc0adecb2016-01-08 12:44:11 -0800934}
935
Andy Hungf2c87b32016-04-07 19:49:29 -0700936status_t AudioTrack::getBufferDurationInUs(int64_t *duration)
937{
938 if (duration == nullptr) {
939 return BAD_VALUE;
940 }
941 AutoMutex lock(mLock);
942 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
943 return NO_INIT;
944 }
945 ssize_t bufferSizeInFrames = (ssize_t) mProxy->getBufferSizeInFrames();
946 if (bufferSizeInFrames < 0) {
947 return (status_t)bufferSizeInFrames;
948 }
949 *duration = (int64_t)((double)bufferSizeInFrames * 1000000
950 / ((double)mSampleRate * mPlaybackRate.mSpeed));
951 return NO_ERROR;
952}
953
Phil Burkc0adecb2016-01-08 12:44:11 -0800954ssize_t AudioTrack::setBufferSizeInFrames(size_t bufferSizeInFrames)
955{
956 AutoMutex lock(mLock);
957 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
958 return NO_INIT;
959 }
960 // Reject if timed track or compressed audio.
Glenn Kastend79072e2016-01-06 08:41:20 -0800961 if (!audio_is_linear_pcm(mFormat)) {
Phil Burkc0adecb2016-01-08 12:44:11 -0800962 return INVALID_OPERATION;
963 }
Phil Burke8972b02016-03-04 11:29:57 -0800964 return (ssize_t) mProxy->setBufferSizeInFrames((uint32_t) bufferSizeInFrames);
Phil Burkc0adecb2016-01-08 12:44:11 -0800965}
966
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800967status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
968{
Glenn Kastend79072e2016-01-06 08:41:20 -0800969 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800970 return INVALID_OPERATION;
971 }
972
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800973 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800974 ;
975 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
976 loopEnd - loopStart >= MIN_LOOP) {
977 ;
978 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800979 return BAD_VALUE;
980 }
981
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800982 AutoMutex lock(mLock);
983 // See setPosition() regarding setting parameters such as loop points or position while active
984 if (mState == STATE_ACTIVE) {
985 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700986 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800987 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800988 return NO_ERROR;
989}
990
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800991void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
992{
Andy Hung4ede21d2014-12-12 15:37:34 -0800993 // We do not update the periodic notification point.
994 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
995 mLoopCount = loopCount;
996 mLoopEnd = loopEnd;
997 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800998 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800999 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -08001000
1001 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001002}
1003
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001004status_t AudioTrack::setMarkerPosition(uint32_t marker)
1005{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001006 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -07001007 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001008 return INVALID_OPERATION;
1009 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001010
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001011 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001012 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -07001013 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001014
Andy Hung3c09c782014-12-29 18:39:32 -08001015 sp<AudioTrackThread> t = mAudioTrackThread;
1016 if (t != 0) {
1017 t->wake();
1018 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001019 return NO_ERROR;
1020}
1021
Glenn Kastena5224f32012-01-04 12:41:44 -08001022status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001023{
Eric Laurentab5cdba2014-06-09 17:22:27 -07001024 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001025 return INVALID_OPERATION;
1026 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001027 if (marker == NULL) {
1028 return BAD_VALUE;
1029 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001030
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001031 AutoMutex lock(mLock);
Andy Hung90e8a972015-11-09 16:42:40 -08001032 mMarkerPosition.getValue(marker);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001033
1034 return NO_ERROR;
1035}
1036
1037status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
1038{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001039 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -07001040 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001041 return INVALID_OPERATION;
1042 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001043
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001044 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001045 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001046 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -08001047
Andy Hung3c09c782014-12-29 18:39:32 -08001048 sp<AudioTrackThread> t = mAudioTrackThread;
1049 if (t != 0) {
1050 t->wake();
1051 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001052 return NO_ERROR;
1053}
1054
Glenn Kastena5224f32012-01-04 12:41:44 -08001055status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001056{
Eric Laurentab5cdba2014-06-09 17:22:27 -07001057 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001058 return INVALID_OPERATION;
1059 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001060 if (updatePeriod == NULL) {
1061 return BAD_VALUE;
1062 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001063
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001064 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001065 *updatePeriod = mUpdatePeriod;
1066
1067 return NO_ERROR;
1068}
1069
1070status_t AudioTrack::setPosition(uint32_t position)
1071{
Glenn Kastend79072e2016-01-06 08:41:20 -08001072 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001073 return INVALID_OPERATION;
1074 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001075 if (position > mFrameCount) {
1076 return BAD_VALUE;
1077 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001078
Eric Laurent1703cdf2011-03-07 14:52:59 -08001079 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001080 // Currently we require that the player is inactive before setting parameters such as position
1081 // or loop points. Otherwise, there could be a race condition: the application could read the
1082 // current position, compute a new position or loop parameters, and then set that position or
1083 // loop parameters but it would do the "wrong" thing since the position has continued to advance
1084 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
1085 // to specify how it wants to handle such scenarios.
1086 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001087 return INVALID_OPERATION;
1088 }
Andy Hung9b461582014-12-01 17:56:29 -08001089 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -07001090 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -08001091 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -08001092
1093 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001094 return NO_ERROR;
1095}
1096
Glenn Kasten200092b2014-08-15 15:13:30 -07001097status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001098{
Glenn Kastend65d73c2012-06-22 17:21:07 -07001099 if (position == NULL) {
1100 return BAD_VALUE;
1101 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001102
Eric Laurent1703cdf2011-03-07 14:52:59 -08001103 AutoMutex lock(mLock);
Andy Hung7a490e72016-03-23 15:58:10 -07001104 // FIXME: offloaded and direct tracks call into the HAL for render positions
1105 // for compressed/synced data; however, we use proxy position for pure linear pcm data
1106 // as we do not know the capability of the HAL for pcm position support and standby.
1107 // There may be some latency differences between the HAL position and the proxy position.
1108 if (isOffloadedOrDirect_l() && !isPurePcmData_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001109 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001110
Eric Laurentab5cdba2014-06-09 17:22:27 -07001111 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -08001112 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
1113 *position = mPausedPosition;
1114 return NO_ERROR;
1115 }
1116
Glenn Kasten142f5192014-03-25 17:44:59 -07001117 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung1f1db832015-06-08 13:26:10 -07001118 uint32_t halFrames; // actually unused
1119 (void) AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
1120 // FIXME: on getRenderPosition() error, we return OK with frame position 0.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001121 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001122 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
1123 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001124 *position = dspFrames;
1125 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -08001126 if (mCblk->mFlags & CBLK_INVALID) {
Andy Hung1f1db832015-06-08 13:26:10 -07001127 (void) restoreTrack_l("getPosition");
1128 // FIXME: for compatibility with the Java API we ignore the restoreTrack_l()
1129 // error here (e.g. DEAD_OBJECT) and return OK with the last recorded server position.
Eric Laurent275e8e92014-11-30 15:14:47 -08001130 }
1131
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001132 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -07001133 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
Andy Hung90e8a972015-11-09 16:42:40 -08001134 0 : updateAndGetPosition_l().value();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001135 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001136 return NO_ERROR;
1137}
1138
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001139status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001140{
Glenn Kastend79072e2016-01-06 08:41:20 -08001141 if (mSharedBuffer == 0) {
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001142 return INVALID_OPERATION;
1143 }
1144 if (position == NULL) {
1145 return BAD_VALUE;
1146 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001147
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001148 AutoMutex lock(mLock);
1149 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001150 return NO_ERROR;
1151}
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001152
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001153status_t AudioTrack::reload()
1154{
Glenn Kastend79072e2016-01-06 08:41:20 -08001155 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -08001156 return INVALID_OPERATION;
1157 }
1158
Eric Laurent1703cdf2011-03-07 14:52:59 -08001159 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001160 // See setPosition() regarding setting parameters such as loop points or position while active
1161 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001162 return INVALID_OPERATION;
1163 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001164 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -08001165 (void) updateAndGetPosition_l();
1166 mPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -07001167 mPreviousTimestampValid = false;
Andy Hung53c3b5f2014-12-15 16:42:05 -08001168#if 0
Andy Hung9b461582014-12-01 17:56:29 -08001169 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -08001170 // of loop count. Historically we have not restored loop count, start, end,
1171 // but it makes sense if one desires to repeat playing a particular sound.
1172 if (mLoopCount != 0) {
1173 mLoopCountNotified = mLoopCount;
1174 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
1175 }
1176#endif
Andy Hung9b461582014-12-01 17:56:29 -08001177 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001178 return NO_ERROR;
1179}
1180
Glenn Kasten38e905b2014-01-13 10:21:48 -08001181audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -07001182{
Eric Laurent1703cdf2011-03-07 14:52:59 -08001183 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001184 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001185}
1186
Paul McLeanaa981192015-03-21 09:55:15 -07001187status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
1188 AutoMutex lock(mLock);
1189 if (mSelectedDeviceId != deviceId) {
1190 mSelectedDeviceId = deviceId;
Eric Laurentfb00fc72017-05-25 18:17:12 -07001191 if (mStatus == NO_ERROR) {
1192 android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
jiabin156c6872017-10-06 09:47:15 -07001193 mProxy->interrupt();
Eric Laurentfb00fc72017-05-25 18:17:12 -07001194 }
Paul McLeanaa981192015-03-21 09:55:15 -07001195 }
Eric Laurent493404d2015-04-21 15:07:36 -07001196 return NO_ERROR;
Paul McLeanaa981192015-03-21 09:55:15 -07001197}
1198
1199audio_port_handle_t AudioTrack::getOutputDevice() {
1200 AutoMutex lock(mLock);
1201 return mSelectedDeviceId;
1202}
1203
Eric Laurentad2e7b92017-09-14 20:06:42 -07001204// must be called with mLock held
1205void AudioTrack::updateRoutedDeviceId_l()
1206{
1207 // if the track is inactive, do not update actual device as the output stream maybe routed
1208 // to a device not relevant to this client because of other active use cases.
1209 if (mState != STATE_ACTIVE) {
1210 return;
1211 }
1212 if (mOutput != AUDIO_IO_HANDLE_NONE) {
1213 audio_port_handle_t deviceId = AudioSystem::getDeviceIdForIo(mOutput);
1214 if (deviceId != AUDIO_PORT_HANDLE_NONE) {
1215 mRoutedDeviceId = deviceId;
1216 }
1217 }
1218}
1219
Eric Laurent296fb132015-05-01 11:38:42 -07001220audio_port_handle_t AudioTrack::getRoutedDeviceId() {
1221 AutoMutex lock(mLock);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001222 updateRoutedDeviceId_l();
1223 return mRoutedDeviceId;
Eric Laurent296fb132015-05-01 11:38:42 -07001224}
1225
Eric Laurentbe916aa2010-06-01 23:49:17 -07001226status_t AudioTrack::attachAuxEffect(int effectId)
1227{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001228 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001229 status_t status = mAudioTrack->attachAuxEffect(effectId);
1230 if (status == NO_ERROR) {
1231 mAuxEffectId = effectId;
1232 }
1233 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -07001234}
1235
Eric Laurente83b55d2014-11-14 10:06:21 -08001236audio_stream_type_t AudioTrack::streamType() const
1237{
1238 if (mStreamType == AUDIO_STREAM_DEFAULT) {
1239 return audio_attributes_to_stream_type(&mAttributes);
1240 }
1241 return mStreamType;
1242}
1243
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001244uint32_t AudioTrack::latency()
1245{
1246 AutoMutex lock(mLock);
1247 updateLatency_l();
1248 return mLatency;
1249}
1250
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001251// -------------------------------------------------------------------------
1252
Eric Laurent1703cdf2011-03-07 14:52:59 -08001253// must be called with mLock held
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001254void AudioTrack::updateLatency_l()
1255{
1256 status_t status = AudioSystem::getLatency(mOutput, &mAfLatency);
1257 if (status != NO_ERROR) {
1258 ALOGW("getLatency(%d) failed status %d", mOutput, status);
1259 } else {
1260 // FIXME don't believe this lie
Andy Hung13969262017-09-11 17:24:21 -07001261 mLatency = mAfLatency + (1000LL * mFrameCount) / mSampleRate;
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001262 }
1263}
1264
Phil Burkadbb75a2017-06-16 12:19:42 -07001265// TODO Move this macro to a common header file for enum to string conversion in audio framework.
1266#define MEDIA_CASE_ENUM(name) case name: return #name
1267const char * AudioTrack::convertTransferToText(transfer_type transferType) {
1268 switch (transferType) {
1269 MEDIA_CASE_ENUM(TRANSFER_DEFAULT);
1270 MEDIA_CASE_ENUM(TRANSFER_CALLBACK);
1271 MEDIA_CASE_ENUM(TRANSFER_OBTAIN);
1272 MEDIA_CASE_ENUM(TRANSFER_SYNC);
1273 MEDIA_CASE_ENUM(TRANSFER_SHARED);
1274 default:
1275 return "UNRECOGNIZED";
1276 }
1277}
1278
Glenn Kasten200092b2014-08-15 15:13:30 -07001279status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001280{
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001281 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
1282 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001283 ALOGE("Could not get audioflinger");
1284 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001285 }
1286
Eric Laurent21da6472017-11-09 16:29:26 -08001287 status_t status;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001288 bool callbackAdded = false;
Eric Laurente83b55d2014-11-14 10:06:21 -08001289
Eric Laurent21da6472017-11-09 16:29:26 -08001290 {
Haynes Mathew Georgeae34ed22016-01-28 11:58:39 -08001291 // mFlags (not mOrigFlags) is modified depending on whether fast request is accepted.
1292 // After fast request is denied, we will request again if IAudioTrack is re-created.
Glenn Kastend79072e2016-01-06 08:41:20 -08001293 // Client can only express a preference for FAST. Server will perform additional tests.
Phil Burk33ff89b2015-11-30 11:16:01 -08001294 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Phil Burkadbb75a2017-06-16 12:19:42 -07001295 // either of these use cases:
1296 // use case 1: shared buffer
1297 bool sharedBuffer = mSharedBuffer != 0;
1298 bool transferAllowed =
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001299 // use case 2: callback transfer mode
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001300 (mTransfer == TRANSFER_CALLBACK) ||
1301 // use case 3: obtain/release mode
Phil Burk33ff89b2015-11-30 11:16:01 -08001302 (mTransfer == TRANSFER_OBTAIN) ||
1303 // use case 4: synchronous write
1304 ((mTransfer == TRANSFER_SYNC) && mThreadCanCallJava);
Phil Burkadbb75a2017-06-16 12:19:42 -07001305
Eric Laurent21da6472017-11-09 16:29:26 -08001306 bool fastAllowed = sharedBuffer || transferAllowed;
1307 if (!fastAllowed) {
Glenn Kasten9bf34d52017-10-24 14:26:23 -07001308 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client, not shared buffer and transfer = %s",
Phil Burkadbb75a2017-06-16 12:19:42 -07001309 convertTransferToText(mTransfer));
Phil Burk33ff89b2015-11-30 11:16:01 -08001310 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1311 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001312 }
1313
Eric Laurent21da6472017-11-09 16:29:26 -08001314 IAudioFlinger::CreateTrackInput input;
1315 if (mStreamType != AUDIO_STREAM_DEFAULT) {
1316 stream_type_to_audio_attributes(mStreamType, &input.attr);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001317 } else {
Eric Laurent21da6472017-11-09 16:29:26 -08001318 input.attr = mAttributes;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001319 }
Eric Laurent21da6472017-11-09 16:29:26 -08001320 input.config = AUDIO_CONFIG_INITIALIZER;
1321 input.config.sample_rate = mSampleRate;
1322 input.config.channel_mask = mChannelMask;
1323 input.config.format = mFormat;
1324 input.config.offload_info = mOffloadInfoCopy;
1325 input.clientInfo.clientUid = mClientUid;
1326 input.clientInfo.clientPid = mClientPid;
1327 input.clientInfo.clientTid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001328 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten47d55172017-05-23 11:19:30 -07001329 // It is currently meaningless to request SCHED_FIFO for a Java thread. Even if the
1330 // application-level code follows all non-blocking design rules, the language runtime
1331 // doesn't also follow those rules, so the thread will not benefit overall.
Phil Burk33ff89b2015-11-30 11:16:01 -08001332 if (mAudioTrackThread != 0 && !mThreadCanCallJava) {
Eric Laurent21da6472017-11-09 16:29:26 -08001333 input.clientInfo.clientTid = mAudioTrackThread->getTid();
Glenn Kasten3acbd052012-02-28 10:39:56 -08001334 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001335 }
Eric Laurent21da6472017-11-09 16:29:26 -08001336 input.sharedBuffer = mSharedBuffer;
1337 input.notificationsPerBuffer = mNotificationsPerBufferReq;
1338 input.speed = 1.0;
1339 if (audio_has_proportional_frames(mFormat) && mSharedBuffer == 0 &&
1340 (mFlags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1341 input.speed = !isPurePcmData_l() || isOffloadedOrDirect_l() ? 1.0f :
1342 max(mMaxRequiredSpeed, mPlaybackRate.mSpeed);
1343 }
1344 input.flags = mFlags;
1345 input.frameCount = mReqFrameCount;
1346 input.notificationFrameCount = mNotificationFramesReq;
1347 input.selectedDeviceId = mSelectedDeviceId;
1348 input.sessionId = mSessionId;
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001349
Eric Laurent21da6472017-11-09 16:29:26 -08001350 IAudioFlinger::CreateTrackOutput output;
1351
1352 sp<IAudioTrack> track = audioFlinger->createTrack(input,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001353 output,
Eric Laurent21da6472017-11-09 16:29:26 -08001354 &status);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001355
Eric Laurent21da6472017-11-09 16:29:26 -08001356 if (status != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
1357 ALOGE("AudioFlinger could not create track, status: %d output %d", status, output.outputId);
1358 goto error;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001359 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001360 ALOG_ASSERT(track != 0);
1361
Eric Laurent21da6472017-11-09 16:29:26 -08001362 mFrameCount = output.frameCount;
1363 mNotificationFramesAct = (uint32_t)output.notificationFrameCount;
1364 mRoutedDeviceId = output.selectedDeviceId;
1365 mSessionId = output.sessionId;
1366
1367 mSampleRate = output.sampleRate;
1368 if (mOriginalSampleRate == 0) {
1369 mOriginalSampleRate = mSampleRate;
1370 }
1371
1372 mAfFrameCount = output.afFrameCount;
1373 mAfSampleRate = output.afSampleRate;
1374 mAfLatency = output.afLatencyMs;
1375
1376 mLatency = mAfLatency + (1000LL * mFrameCount) / mSampleRate;
1377
Glenn Kasten38e905b2014-01-13 10:21:48 -08001378 // AudioFlinger now owns the reference to the I/O handle,
1379 // so we are no longer responsible for releasing it.
1380
Glenn Kasten7fd04222016-02-02 12:38:16 -08001381 // FIXME compare to AudioRecord
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001382 sp<IMemory> iMem = track->getCblk();
1383 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001384 ALOGE("Could not get control block");
Eric Laurentad2e7b92017-09-14 20:06:42 -07001385 status = NO_INIT;
Eric Laurent21da6472017-11-09 16:29:26 -08001386 goto error;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001387 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001388 void *iMemPointer = iMem->pointer();
1389 if (iMemPointer == NULL) {
1390 ALOGE("Could not get control block pointer");
Eric Laurentad2e7b92017-09-14 20:06:42 -07001391 status = NO_INIT;
Eric Laurent21da6472017-11-09 16:29:26 -08001392 goto error;
Glenn Kasten0cde0762014-01-16 15:06:36 -08001393 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001394 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001395 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001396 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001397 mDeathNotifier.clear();
1398 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001399 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001400 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001401 IPCThreadState::self()->flushCommands();
1402
Glenn Kasten0cde0762014-01-16 15:06:36 -08001403 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001404 mCblk = cblk;
Glenn Kasten5f631512014-02-24 15:16:07 -08001405
Glenn Kastena07f17c2013-04-23 12:39:37 -07001406 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001407 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent21da6472017-11-09 16:29:26 -08001408 if (output.flags & AUDIO_OUTPUT_FLAG_FAST) {
1409 ALOGI("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu -> %zu",
1410 mReqFrameCount, mFrameCount);
Phil Burk33ff89b2015-11-30 11:16:01 -08001411 if (!mThreadCanCallJava) {
1412 mAwaitBoost = true;
1413 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001414 } else {
Eric Laurent21da6472017-11-09 16:29:26 -08001415 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu -> %zu", mReqFrameCount,
1416 mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001417 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001418 }
Eric Laurent21da6472017-11-09 16:29:26 -08001419 mFlags = output.flags;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001420
Eric Laurentad2e7b92017-09-14 20:06:42 -07001421 //mOutput != output includes the case where mOutput == AUDIO_IO_HANDLE_NONE for first creation
Eric Laurent21da6472017-11-09 16:29:26 -08001422 if (mDeviceCallback != 0 && mOutput != output.outputId) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001423 if (mOutput != AUDIO_IO_HANDLE_NONE) {
1424 AudioSystem::removeAudioDeviceCallback(this, mOutput);
1425 }
Eric Laurent21da6472017-11-09 16:29:26 -08001426 AudioSystem::addAudioDeviceCallback(this, output.outputId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001427 callbackAdded = true;
1428 }
1429
Glenn Kasten38e905b2014-01-13 10:21:48 -08001430 // We retain a copy of the I/O handle, but don't own the reference
Eric Laurent21da6472017-11-09 16:29:26 -08001431 mOutput = output.outputId;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001432 mRefreshRemaining = true;
1433
1434 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1435 // is the value of pointer() for the shared buffer, otherwise buffers points
1436 // immediately after the control block. This address is for the mapping within client
1437 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1438 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001439 if (mSharedBuffer == 0) {
Glenn Kasten138d6f92015-03-20 10:54:51 -07001440 buffers = cblk + 1;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001441 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001442 buffers = mSharedBuffer->pointer();
Glenn Kasten138d6f92015-03-20 10:54:51 -07001443 if (buffers == NULL) {
1444 ALOGE("Could not get buffer pointer");
Eric Laurentad2e7b92017-09-14 20:06:42 -07001445 status = NO_INIT;
Eric Laurent21da6472017-11-09 16:29:26 -08001446 goto error;
Glenn Kasten138d6f92015-03-20 10:54:51 -07001447 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001448 }
1449
Eric Laurent2beeb502010-07-16 07:43:46 -07001450 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kasten5f631512014-02-24 15:16:07 -08001451
Glenn Kasten093000f2012-05-03 09:35:36 -07001452 // If IAudioTrack is re-created, don't let the requested frameCount
1453 // decrease. This can confuse clients that cache frameCount().
Eric Laurent21da6472017-11-09 16:29:26 -08001454 if (mFrameCount > mReqFrameCount) {
1455 mReqFrameCount = mFrameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001456 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001457
Andy Hungd7bd69e2015-07-24 07:52:41 -07001458 // reset server position to 0 as we have new cblk.
1459 mServer = 0;
1460
Glenn Kastene3aa6592012-12-04 12:22:46 -08001461 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001462 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001463 mStaticProxy.clear();
Eric Laurent21da6472017-11-09 16:29:26 -08001464 mProxy = new AudioTrackClientProxy(cblk, buffers, mFrameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001465 } else {
Eric Laurent21da6472017-11-09 16:29:26 -08001466 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, mFrameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001467 mProxy = mStaticProxy;
1468 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001469
1470 mProxy->setVolumeLR(gain_minifloat_pack(
1471 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1472 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1473
Glenn Kastene3aa6592012-12-04 12:22:46 -08001474 mProxy->setSendLevel(mSendLevel);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001475 const uint32_t effectiveSampleRate = adjustSampleRate(mSampleRate, mPlaybackRate.mPitch);
1476 const float effectiveSpeed = adjustSpeed(mPlaybackRate.mSpeed, mPlaybackRate.mPitch);
1477 const float effectivePitch = adjustPitch(mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001478 mProxy->setSampleRate(effectiveSampleRate);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001479
1480 AudioPlaybackRate playbackRateTemp = mPlaybackRate;
1481 playbackRateTemp.mSpeed = effectiveSpeed;
1482 playbackRateTemp.mPitch = effectivePitch;
1483 mProxy->setPlaybackRate(playbackRateTemp);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001484 mProxy->setMinimum(mNotificationFramesAct);
1485
1486 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001487 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001488
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001489 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001490 }
1491
Eric Laurent21da6472017-11-09 16:29:26 -08001492error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001493 if (callbackAdded) {
1494 // note: mOutput is always valid is callbackAdded is true
1495 AudioSystem::removeAudioDeviceCallback(this, mOutput);
1496 }
Glenn Kasten38e905b2014-01-13 10:21:48 -08001497 if (status == NO_ERROR) {
1498 status = NO_INIT;
1499 }
Eric Laurent21da6472017-11-09 16:29:26 -08001500
1501 // sp<IAudioTrack> track destructor will cause releaseOutput() to be called by AudioFlinger
Glenn Kasten38e905b2014-01-13 10:21:48 -08001502 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001503}
1504
Glenn Kastenb46f3942015-03-09 12:00:30 -07001505status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001506{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001507 if (audioBuffer == NULL) {
Glenn Kasten551b5352015-03-20 11:30:28 -07001508 if (nonContig != NULL) {
1509 *nonContig = 0;
1510 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001511 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001512 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001513 if (mTransfer != TRANSFER_OBTAIN) {
1514 audioBuffer->frameCount = 0;
1515 audioBuffer->size = 0;
1516 audioBuffer->raw = NULL;
Glenn Kasten551b5352015-03-20 11:30:28 -07001517 if (nonContig != NULL) {
1518 *nonContig = 0;
1519 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001520 return INVALID_OPERATION;
1521 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001522
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001523 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001524 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001525 if (waitCount == -1) {
1526 requested = &ClientProxy::kForever;
1527 } else if (waitCount == 0) {
1528 requested = &ClientProxy::kNonBlocking;
1529 } else if (waitCount > 0) {
1530 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001531 timeout.tv_sec = ms / 1000;
1532 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1533 requested = &timeout;
1534 } else {
1535 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1536 requested = NULL;
1537 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001538 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001539}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001540
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001541status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1542 struct timespec *elapsed, size_t *nonContig)
1543{
1544 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1545 uint32_t oldSequence = 0;
1546 uint32_t newSequence;
1547
1548 Proxy::Buffer buffer;
1549 status_t status = NO_ERROR;
1550
1551 static const int32_t kMaxTries = 5;
1552 int32_t tryCounter = kMaxTries;
1553
1554 do {
1555 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1556 // keep them from going away if another thread re-creates the track during obtainBuffer()
1557 sp<AudioTrackClientProxy> proxy;
1558 sp<IMemory> iMem;
1559
1560 { // start of lock scope
1561 AutoMutex lock(mLock);
1562
1563 newSequence = mSequence;
1564 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1565 if (status == DEAD_OBJECT) {
1566 // re-create track, unless someone else has already done so
1567 if (newSequence == oldSequence) {
1568 status = restoreTrack_l("obtainBuffer");
1569 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001570 buffer.mFrameCount = 0;
1571 buffer.mRaw = NULL;
1572 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001573 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001574 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001575 }
1576 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001577 oldSequence = newSequence;
1578
Eric Laurent4d231dc2016-03-11 18:38:23 -08001579 if (status == NOT_ENOUGH_DATA) {
1580 restartIfDisabled();
1581 }
1582
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001583 // Keep the extra references
1584 proxy = mProxy;
1585 iMem = mCblkMemory;
1586
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001587 if (mState == STATE_STOPPING) {
1588 status = -EINTR;
1589 buffer.mFrameCount = 0;
1590 buffer.mRaw = NULL;
1591 buffer.mNonContig = 0;
1592 break;
1593 }
1594
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001595 // Non-blocking if track is stopped or paused
1596 if (mState != STATE_ACTIVE) {
1597 requested = &ClientProxy::kNonBlocking;
1598 }
1599
1600 } // end of lock scope
1601
1602 buffer.mFrameCount = audioBuffer->frameCount;
1603 // FIXME starts the requested timeout and elapsed over from scratch
1604 status = proxy->obtainBuffer(&buffer, requested, elapsed);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001605 } while (((status == DEAD_OBJECT) || (status == NOT_ENOUGH_DATA)) && (tryCounter-- > 0));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001606
1607 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001608 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001609 audioBuffer->raw = buffer.mRaw;
1610 if (nonContig != NULL) {
1611 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001612 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001613 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001614}
1615
Glenn Kasten54a8a452015-03-09 12:03:00 -07001616void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001617{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001618 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001619 if (mTransfer == TRANSFER_SHARED) {
1620 return;
1621 }
1622
Andy Hungabdb9902015-01-12 15:08:22 -08001623 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001624 if (stepCount == 0) {
1625 return;
1626 }
1627
1628 Proxy::Buffer buffer;
1629 buffer.mFrameCount = stepCount;
1630 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001631
Eric Laurent1703cdf2011-03-07 14:52:59 -08001632 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001633 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001634 mInUnderrun = false;
1635 mProxy->releaseBuffer(&buffer);
1636
1637 // restart track if it was disabled by audioflinger due to previous underrun
Eric Laurent4d231dc2016-03-11 18:38:23 -08001638 restartIfDisabled();
1639}
1640
1641void AudioTrack::restartIfDisabled()
1642{
1643 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1644 if ((mState == STATE_ACTIVE) && (flags & CBLK_DISABLED)) {
1645 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
1646 // FIXME ignoring status
1647 mAudioTrack->start();
Eric Laurentdf839842012-05-31 14:27:14 -07001648 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001649}
1650
1651// -------------------------------------------------------------------------
1652
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001653ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001654{
Glenn Kastend79072e2016-01-06 08:41:20 -08001655 if (mTransfer != TRANSFER_SYNC) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001656 return INVALID_OPERATION;
1657 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001658
Eric Laurentab5cdba2014-06-09 17:22:27 -07001659 if (isDirect()) {
1660 AutoMutex lock(mLock);
1661 int32_t flags = android_atomic_and(
1662 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1663 &mCblk->mFlags);
1664 if (flags & CBLK_INVALID) {
1665 return DEAD_OBJECT;
1666 }
1667 }
1668
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001669 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001670 // Sanity-check: user is most-likely passing an error code, and it would
1671 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001672 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001673 return BAD_VALUE;
1674 }
1675
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001676 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001677 Buffer audioBuffer;
1678
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001679 while (userSize >= mFrameSize) {
1680 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001681
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001682 status_t err = obtainBuffer(&audioBuffer,
1683 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001684 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001685 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001686 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001687 }
Glenn Kasten0a2f1512016-07-22 08:06:37 -07001688 if (err == TIMED_OUT || err == -EINTR) {
1689 err = WOULD_BLOCK;
1690 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001691 return ssize_t(err);
1692 }
1693
Glenn Kastenae4b8792015-03-20 09:04:21 -07001694 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08001695 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001696 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001697 userSize -= toWrite;
1698 written += toWrite;
1699
1700 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001701 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001702
Andy Hungea2b9c02016-02-12 17:06:53 -08001703 if (written > 0) {
1704 mFramesWritten += written / mFrameSize;
1705 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001706 return written;
1707}
1708
1709// -------------------------------------------------------------------------
1710
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001711nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001712{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001713 // Currently the AudioTrack thread is not created if there are no callbacks.
1714 // Would it ever make sense to run the thread, even without callbacks?
1715 // If so, then replace this by checks at each use for mCbf != NULL.
1716 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1717
Eric Laurent1703cdf2011-03-07 14:52:59 -08001718 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001719 if (mAwaitBoost) {
1720 mAwaitBoost = false;
1721 mLock.unlock();
1722 static const int32_t kMaxTries = 5;
1723 int32_t tryCounter = kMaxTries;
1724 uint32_t pollUs = 10000;
1725 do {
Glenn Kasten8255ba72016-08-23 13:54:23 -07001726 int policy = sched_getscheduler(0) & ~SCHED_RESET_ON_FORK;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001727 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1728 break;
1729 }
1730 usleep(pollUs);
1731 pollUs <<= 1;
1732 } while (tryCounter-- > 0);
1733 if (tryCounter < 0) {
1734 ALOGE("did not receive expected priority boost on time");
1735 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001736 // Run again immediately
1737 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001738 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001739
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001740 // Can only reference mCblk while locked
1741 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001742 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001743
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001744 // Check for track invalidation
1745 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001746 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1747 // AudioSystem cache. We should not exit here but after calling the callback so
1748 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001749 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Lajos Molnarf1063e22015-04-17 15:19:42 -07001750 status_t status __unused = restoreTrack_l("processAudioBuffer");
1751 // FIXME unused status
Andy Hung53c3b5f2014-12-15 16:42:05 -08001752 // after restoration, continue below to make sure that the loop and buffer events
1753 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001754 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001755 }
1756
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001757 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001758 bool active = mState == STATE_ACTIVE;
1759
1760 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1761 bool newUnderrun = false;
1762 if (flags & CBLK_UNDERRUN) {
1763#if 0
1764 // Currently in shared buffer mode, when the server reaches the end of buffer,
1765 // the track stays active in continuous underrun state. It's up to the application
1766 // to pause or stop the track, or set the position to a new offset within buffer.
1767 // This was some experimental code to auto-pause on underrun. Keeping it here
1768 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1769 if (mTransfer == TRANSFER_SHARED) {
1770 mState = STATE_PAUSED;
1771 active = false;
1772 }
1773#endif
1774 if (!mInUnderrun) {
1775 mInUnderrun = true;
1776 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001777 }
1778 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001779
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001780 // Get current position of server
Andy Hung90e8a972015-11-09 16:42:40 -08001781 Modulo<uint32_t> position(updateAndGetPosition_l());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001782
1783 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001784 bool markerReached = false;
Andy Hung90e8a972015-11-09 16:42:40 -08001785 Modulo<uint32_t> markerPosition(mMarkerPosition);
1786 // uses 32 bit wraparound for comparison with position.
1787 if (!mMarkerReached && markerPosition.value() > 0 && position >= markerPosition) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001788 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001789 }
1790
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001791 // Determine number of new position callback(s) that will be needed, while locked
1792 size_t newPosCount = 0;
Andy Hung90e8a972015-11-09 16:42:40 -08001793 Modulo<uint32_t> newPosition(mNewPosition);
1794 uint32_t updatePeriod = mUpdatePeriod;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001795 // FIXME fails for wraparound, need 64 bits
1796 if (updatePeriod > 0 && position >= newPosition) {
Andy Hung90e8a972015-11-09 16:42:40 -08001797 newPosCount = ((position - newPosition).value() / updatePeriod) + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001798 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001799 }
1800
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001801 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001802 uint32_t sampleRate = mSampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001803 float speed = mPlaybackRate.mSpeed;
Andy Hunga7f03352015-05-31 21:54:49 -07001804 const uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001805 if (mRefreshRemaining) {
1806 mRefreshRemaining = false;
1807 mRemainingFrames = notificationFrames;
1808 mRetryOnPartialBuffer = false;
1809 }
1810 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001811 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001812 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001813
Andy Hung53c3b5f2014-12-15 16:42:05 -08001814 // Determine the number of new loop callback(s) that will be needed, while locked.
1815 int loopCountNotifications = 0;
1816 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1817
1818 if (mLoopCount > 0) {
1819 int loopCount;
1820 size_t bufferPosition;
1821 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1822 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1823 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1824 mLoopCountNotified = loopCount; // discard any excess notifications
1825 } else if (mLoopCount < 0) {
1826 // FIXME: We're not accurate with notification count and position with infinite looping
1827 // since loopCount from server side will always return -1 (we could decrement it).
1828 size_t bufferPosition = mStaticProxy->getBufferPosition();
1829 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1830 loopPeriod = mLoopEnd - bufferPosition;
1831 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1832 size_t bufferPosition = mStaticProxy->getBufferPosition();
1833 loopPeriod = mFrameCount - bufferPosition;
1834 }
1835
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001836 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08001837 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001838 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1839
1840 mLock.unlock();
1841
Andy Hunga7f03352015-05-31 21:54:49 -07001842 // get anchor time to account for callbacks.
1843 const nsecs_t timeBeforeCallbacks = systemTime();
1844
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001845 if (waitStreamEnd) {
Andy Hunga7f03352015-05-31 21:54:49 -07001846 // FIXME: Instead of blocking in proxy->waitStreamEndDone(), Callback thread
1847 // should wait on proxy futex and handle CBLK_STREAM_END_DONE within this function
1848 // (and make sure we don't callback for more data while we're stopping).
1849 // This helps with position, marker notifications, and track invalidation.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001850 struct timespec timeout;
1851 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1852 timeout.tv_nsec = 0;
1853
Glenn Kasten96f04882013-09-20 09:28:56 -07001854 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001855 switch (status) {
1856 case NO_ERROR:
1857 case DEAD_OBJECT:
1858 case TIMED_OUT:
Andy Hung39609a02015-09-03 16:38:38 -07001859 if (status != DEAD_OBJECT) {
1860 // for DEAD_OBJECT, we do not send a EVENT_STREAM_END after stop();
1861 // instead, the application should handle the EVENT_NEW_IAUDIOTRACK.
1862 mCbf(EVENT_STREAM_END, mUserData, NULL);
1863 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001864 {
1865 AutoMutex lock(mLock);
1866 // The previously assigned value of waitStreamEnd is no longer valid,
1867 // since the mutex has been unlocked and either the callback handler
1868 // or another thread could have re-started the AudioTrack during that time.
1869 waitStreamEnd = mState == STATE_STOPPING;
1870 if (waitStreamEnd) {
1871 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001872 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001873 }
1874 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001875 if (waitStreamEnd && status != DEAD_OBJECT) {
1876 return NS_INACTIVE;
1877 }
1878 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001879 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001880 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001881 }
1882
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001883 // perform callbacks while unlocked
1884 if (newUnderrun) {
1885 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1886 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001887 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001888 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001889 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001890 }
1891 if (flags & CBLK_BUFFER_END) {
1892 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1893 }
1894 if (markerReached) {
1895 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1896 }
1897 while (newPosCount > 0) {
Andy Hung90e8a972015-11-09 16:42:40 -08001898 size_t temp = newPosition.value(); // FIXME size_t != uint32_t
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001899 mCbf(EVENT_NEW_POS, mUserData, &temp);
1900 newPosition += updatePeriod;
1901 newPosCount--;
1902 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001903
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001904 if (mObservedSequence != sequence) {
1905 mObservedSequence = sequence;
1906 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001907 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001908 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001909 return NS_INACTIVE;
1910 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001911 }
1912
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001913 // if inactive, then don't run me again until re-started
1914 if (!active) {
1915 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001916 }
1917
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001918 // Compute the estimated time until the next timed event (position, markers, loops)
1919 // FIXME only for non-compressed audio
1920 uint32_t minFrames = ~0;
1921 if (!markerReached && position < markerPosition) {
Andy Hung90e8a972015-11-09 16:42:40 -08001922 minFrames = (markerPosition - position).value();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001923 }
1924 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08001925 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001926 minFrames = loopPeriod;
1927 }
Andy Hung2d85f092015-01-07 12:45:13 -08001928 if (updatePeriod > 0) {
Andy Hung90e8a972015-11-09 16:42:40 -08001929 minFrames = min(minFrames, (newPosition - position).value());
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001930 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001931
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001932 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1933 static const uint32_t kPoll = 0;
1934 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1935 minFrames = kPoll * notificationFrames;
1936 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001937
Andy Hunga7f03352015-05-31 21:54:49 -07001938 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1939 static const nsecs_t kWaitPeriodNs = WAIT_PERIOD_MS * 1000000LL;
1940 const nsecs_t timeAfterCallbacks = systemTime();
1941
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001942 // Convert frame units to time units
1943 nsecs_t ns = NS_WHENEVER;
1944 if (minFrames != (uint32_t) ~0) {
jiabinc7bb8322017-09-06 18:20:11 -07001945 // AudioFlinger consumption of client data may be irregular when coming out of device
1946 // standby since the kernel buffers require filling. This is throttled to no more than 2x
1947 // the expected rate in the MixerThread. Hence, we reduce the estimated time to wait by one
1948 // half (but no more than half a second) to improve callback accuracy during these temporary
1949 // data surges.
1950 const nsecs_t estimatedNs = framesToNanoseconds(minFrames, sampleRate, speed);
1951 constexpr nsecs_t maxThrottleCompensationNs = 500000000LL;
1952 ns = estimatedNs - min(estimatedNs / 2, maxThrottleCompensationNs) + kWaitPeriodNs;
Andy Hunga7f03352015-05-31 21:54:49 -07001953 ns -= (timeAfterCallbacks - timeBeforeCallbacks); // account for callback time
1954 // TODO: Should we warn if the callback time is too long?
1955 if (ns < 0) ns = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001956 }
1957
1958 // If not supplying data by EVENT_MORE_DATA, then we're done
1959 if (mTransfer != TRANSFER_CALLBACK) {
1960 return ns;
1961 }
1962
Andy Hunga7f03352015-05-31 21:54:49 -07001963 // EVENT_MORE_DATA callback handling.
1964 // Timing for linear pcm audio data formats can be derived directly from the
1965 // buffer fill level.
1966 // Timing for compressed data is not directly available from the buffer fill level,
1967 // rather indirectly from waiting for blocking mode callbacks or waiting for obtain()
1968 // to return a certain fill level.
1969
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001970 struct timespec timeout;
1971 const struct timespec *requested = &ClientProxy::kForever;
1972 if (ns != NS_WHENEVER) {
1973 timeout.tv_sec = ns / 1000000000LL;
1974 timeout.tv_nsec = ns % 1000000000LL;
1975 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1976 requested = &timeout;
1977 }
1978
Andy Hungea2b9c02016-02-12 17:06:53 -08001979 size_t writtenFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001980 while (mRemainingFrames > 0) {
1981
1982 Buffer audioBuffer;
1983 audioBuffer.frameCount = mRemainingFrames;
1984 size_t nonContig;
1985 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1986 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001987 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001988 requested = &ClientProxy::kNonBlocking;
1989 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001990 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001991 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001992 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001993 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1994 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten606fbc12015-10-22 15:28:15 -07001995 // FIXME bug 25195759
1996 return 1000000;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001997 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001998 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1999 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002000 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002001
Phil Burkfdb3c072016-02-09 10:47:02 -08002002 if (mRetryOnPartialBuffer && audio_has_proportional_frames(mFormat)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002003 mRetryOnPartialBuffer = false;
2004 if (avail < mRemainingFrames) {
Andy Hunga7f03352015-05-31 21:54:49 -07002005 if (ns > 0) { // account for obtain time
2006 const nsecs_t timeNow = systemTime();
2007 ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2008 }
2009 nsecs_t myns = framesToNanoseconds(mRemainingFrames - avail, sampleRate, speed);
2010 if (ns < 0 /* NS_WHENEVER */ || myns < ns) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002011 ns = myns;
2012 }
2013 return ns;
2014 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07002015 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002016
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002017 size_t reqSize = audioBuffer.size;
2018 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002019 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002020
2021 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002022 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002023 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
2024 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002025 return NS_NEVER;
2026 }
2027
2028 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08002029 // The callback is done filling buffers
2030 // Keep this thread going to handle timed events and
2031 // still try to get more data in intervals of WAIT_PERIOD_MS
2032 // but don't just loop and block the CPU, so wait
Andy Hunga7f03352015-05-31 21:54:49 -07002033
2034 // mCbf(EVENT_MORE_DATA, ...) might either
2035 // (1) Block until it can fill the buffer, returning 0 size on EOS.
2036 // (2) Block until it can fill the buffer, returning 0 data (silence) on EOS.
2037 // (3) Return 0 size when no data is available, does not wait for more data.
2038 //
2039 // (1) and (2) occurs with AudioPlayer/AwesomePlayer; (3) occurs with NuPlayer.
2040 // We try to compute the wait time to avoid a tight sleep-wait cycle,
2041 // especially for case (3).
2042 //
2043 // The decision to support (1) and (2) affect the sizing of mRemainingFrames
2044 // and this loop; whereas for case (3) we could simply check once with the full
2045 // buffer size and skip the loop entirely.
2046
2047 nsecs_t myns;
Phil Burkfdb3c072016-02-09 10:47:02 -08002048 if (audio_has_proportional_frames(mFormat)) {
Andy Hunga7f03352015-05-31 21:54:49 -07002049 // time to wait based on buffer occupancy
2050 const nsecs_t datans = mRemainingFrames <= avail ? 0 :
2051 framesToNanoseconds(mRemainingFrames - avail, sampleRate, speed);
2052 // audio flinger thread buffer size (TODO: adjust for fast tracks)
Glenn Kastenea38ee72016-04-18 11:08:01 -07002053 // FIXME: use mAfFrameCountHAL instead of mAfFrameCount below for fast tracks.
Andy Hunga7f03352015-05-31 21:54:49 -07002054 const nsecs_t afns = framesToNanoseconds(mAfFrameCount, mAfSampleRate, speed);
2055 // add a half the AudioFlinger buffer time to avoid soaking CPU if datans is 0.
2056 myns = datans + (afns / 2);
2057 } else {
2058 // FIXME: This could ping quite a bit if the buffer isn't full.
2059 // Note that when mState is stopping we waitStreamEnd, so it never gets here.
2060 myns = kWaitPeriodNs;
2061 }
2062 if (ns > 0) { // account for obtain and callback time
2063 const nsecs_t timeNow = systemTime();
2064 ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2065 }
2066 if (ns < 0 /* NS_WHENEVER */ || myns < ns) {
2067 ns = myns;
2068 }
2069 return ns;
Glenn Kastend65d73c2012-06-22 17:21:07 -07002070 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002071
Glenn Kasten138d6f92015-03-20 10:54:51 -07002072 size_t releasedFrames = writtenSize / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002073 audioBuffer.frameCount = releasedFrames;
2074 mRemainingFrames -= releasedFrames;
2075 if (misalignment >= releasedFrames) {
2076 misalignment -= releasedFrames;
2077 } else {
2078 misalignment = 0;
2079 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002080
2081 releaseBuffer(&audioBuffer);
Andy Hungea2b9c02016-02-12 17:06:53 -08002082 writtenFrames += releasedFrames;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002083
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002084 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
2085 // if callback doesn't like to accept the full chunk
2086 if (writtenSize < reqSize) {
2087 continue;
2088 }
2089
2090 // There could be enough non-contiguous frames available to satisfy the remaining request
2091 if (mRemainingFrames <= nonContig) {
2092 continue;
2093 }
2094
2095#if 0
2096 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
2097 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
2098 // that total to a sum == notificationFrames.
2099 if (0 < misalignment && misalignment <= mRemainingFrames) {
2100 mRemainingFrames = misalignment;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002101 return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002102 }
2103#endif
2104
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002105 }
Andy Hungea2b9c02016-02-12 17:06:53 -08002106 if (writtenFrames > 0) {
2107 AutoMutex lock(mLock);
2108 mFramesWritten += writtenFrames;
2109 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002110 mRemainingFrames = notificationFrames;
2111 mRetryOnPartialBuffer = true;
2112
2113 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
2114 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002115}
2116
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002117status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08002118{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002119 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07002120 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002121 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002122
Glenn Kastena47f3162012-11-07 10:13:08 -08002123 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08002124 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08002125 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07002126
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002127 if (isOffloadedOrDirect_l() || mDoNotReconnect) {
Andy Hung1f1db832015-06-08 13:26:10 -07002128 // FIXME re-creation of offloaded and direct tracks is not yet implemented;
2129 // reconsider enabling for linear PCM encodings when position can be preserved.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002130 return DEAD_OBJECT;
2131 }
2132
Phil Burk2812d9e2016-01-04 10:34:30 -08002133 // Save so we can return count since creation.
2134 mUnderrunCountOffset = getUnderrunCount_l();
2135
Glenn Kasten200092b2014-08-15 15:13:30 -07002136 // save the old static buffer position
Andy Hungf20a4e92016-08-15 19:10:34 -07002137 uint32_t staticPosition = 0;
Andy Hung4ede21d2014-12-12 15:37:34 -08002138 size_t bufferPosition = 0;
2139 int loopCount = 0;
2140 if (mStaticProxy != 0) {
2141 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
Andy Hungf20a4e92016-08-15 19:10:34 -07002142 staticPosition = mStaticProxy->getPosition().unsignedValue();
Andy Hung4ede21d2014-12-12 15:37:34 -08002143 }
Glenn Kasten200092b2014-08-15 15:13:30 -07002144
Haynes Mathew Georgeae34ed22016-01-28 11:58:39 -08002145 mFlags = mOrigFlags;
2146
Glenn Kasten200092b2014-08-15 15:13:30 -07002147 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08002148 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07002149 // It will also delete the strong references on previous IAudioTrack and IMemory.
2150 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Glenn Kastenae4b8792015-03-20 09:04:21 -07002151 status_t result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07002152
Glenn Kastena47f3162012-11-07 10:13:08 -08002153 if (result == NO_ERROR) {
Andy Hungd7bd69e2015-07-24 07:52:41 -07002154 // take the frames that will be lost by track recreation into account in saved position
2155 // For streaming tracks, this is the amount we obtained from the user/client
2156 // (not the number actually consumed at the server - those are already lost).
2157 if (mStaticProxy == 0) {
2158 mPosition = mReleased;
2159 }
Andy Hung4ede21d2014-12-12 15:37:34 -08002160 // Continue playback from last known position and restore loop.
2161 if (mStaticProxy != 0) {
2162 if (loopCount != 0) {
2163 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
2164 mLoopStart, mLoopEnd, loopCount);
2165 } else {
2166 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002167 if (bufferPosition == mFrameCount) {
2168 ALOGD("restoring track at end of static buffer");
2169 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002170 }
2171 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002172 // restore volume handler
Andy Hung39399b62017-04-21 15:07:45 -07002173 mVolumeHandler->forall([this](const VolumeShaper &shaper) -> VolumeShaper::Status {
2174 sp<VolumeShaper::Operation> operationToEnd =
2175 new VolumeShaper::Operation(shaper.mOperation);
Andy Hung4ef88d72017-02-21 19:47:53 -08002176 // TODO: Ideally we would restore to the exact xOffset position
2177 // as returned by getVolumeShaperState(), but we don't have that
2178 // information when restoring at the client unless we periodically poll
2179 // the server or create shared memory state.
2180 //
Andy Hung39399b62017-04-21 15:07:45 -07002181 // For now, we simply advance to the end of the VolumeShaper effect
2182 // if it has been started.
2183 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002184 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002185 }
2186 return mAudioTrack->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002187 });
2188
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002189 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08002190 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08002191 }
Andy Hungf20a4e92016-08-15 19:10:34 -07002192 // server resets to zero so we offset
2193 mFramesWrittenServerOffset =
2194 mStaticProxy.get() != nullptr ? staticPosition : mFramesWritten;
2195 mFramesWrittenAtRestore = mFramesWrittenServerOffset;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002196 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002197 if (result != NO_ERROR) {
2198 ALOGW("restoreTrack_l() failed status %d", result);
2199 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07002200 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002201 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002202
2203 return result;
2204}
2205
Andy Hung90e8a972015-11-09 16:42:40 -08002206Modulo<uint32_t> AudioTrack::updateAndGetPosition_l()
Glenn Kasten200092b2014-08-15 15:13:30 -07002207{
2208 // This is the sole place to read server consumed frames
Andy Hung90e8a972015-11-09 16:42:40 -08002209 Modulo<uint32_t> newServer(mProxy->getPosition());
2210 const int32_t delta = (newServer - mServer).signedValue();
Glenn Kasten200092b2014-08-15 15:13:30 -07002211 // TODO There is controversy about whether there can be "negative jitter" in server position.
2212 // This should be investigated further, and if possible, it should be addressed.
2213 // A more definite failure mode is infrequent polling by client.
2214 // One could call (void)getPosition_l() in releaseBuffer(),
2215 // so mReleased and mPosition are always lock-step as best possible.
2216 // That should ensure delta never goes negative for infrequent polling
2217 // unless the server has more than 2^31 frames in its buffer,
2218 // in which case the use of uint32_t for these counters has bigger issues.
Andy Hung90e8a972015-11-09 16:42:40 -08002219 ALOGE_IF(delta < 0,
2220 "detected illegal retrograde motion by the server: mServer advanced by %d",
2221 delta);
Chad Brubaker039c27a2015-09-23 15:17:29 -07002222 mServer = newServer;
Andy Hung90e8a972015-11-09 16:42:40 -08002223 if (delta > 0) { // avoid retrograde
2224 mPosition += delta;
2225 }
2226 return mPosition;
Glenn Kasten200092b2014-08-15 15:13:30 -07002227}
2228
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002229bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed)
Andy Hung8edb8dc2015-03-26 19:13:55 -07002230{
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002231 updateLatency_l();
Andy Hung8edb8dc2015-03-26 19:13:55 -07002232 // applicable for mixing tracks only (not offloaded or direct)
2233 if (mStaticProxy != 0) {
2234 return true; // static tracks do not have issues with buffer sizing.
2235 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07002236 const size_t minFrameCount =
Eric Laurent21da6472017-11-09 16:29:26 -08002237 AudioSystem::calculateMinFrameCount(mAfLatency, mAfFrameCount, mAfSampleRate,
2238 sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002239 const bool allowed = mFrameCount >= minFrameCount;
2240 ALOGD_IF(!allowed,
2241 "isSampleRateSpeedAllowed_l denied "
2242 "mAfLatency:%u mAfFrameCount:%zu mAfSampleRate:%u sampleRate:%u speed:%f "
2243 "mFrameCount:%zu < minFrameCount:%zu",
2244 mAfLatency, mAfFrameCount, mAfSampleRate, sampleRate, speed,
Andy Hung8edb8dc2015-03-26 19:13:55 -07002245 mFrameCount, minFrameCount);
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002246 return allowed;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002247}
2248
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002249status_t AudioTrack::setParameters(const String8& keyValuePairs)
2250{
2251 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07002252 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002253}
2254
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002255VolumeShaper::Status AudioTrack::applyVolumeShaper(
2256 const sp<VolumeShaper::Configuration>& configuration,
2257 const sp<VolumeShaper::Operation>& operation)
2258{
2259 AutoMutex lock(mLock);
Andy Hung4ef88d72017-02-21 19:47:53 -08002260 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002261 VolumeShaper::Status status = mAudioTrack->applyVolumeShaper(configuration, operation);
Andy Hung39399b62017-04-21 15:07:45 -07002262
2263 if (status == DEAD_OBJECT) {
2264 if (restoreTrack_l("applyVolumeShaper") == OK) {
2265 status = mAudioTrack->applyVolumeShaper(configuration, operation);
2266 }
2267 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002268 if (status >= 0) {
2269 // save VolumeShaper for restore
2270 mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung39399b62017-04-21 15:07:45 -07002271 if (mState == STATE_ACTIVE || mState == STATE_STOPPING) {
2272 mVolumeHandler->setStarted();
2273 }
2274 } else {
2275 // warn only if not an expected restore failure.
2276 ALOGW_IF(!((isOffloadedOrDirect_l() || mDoNotReconnect) && status == DEAD_OBJECT),
2277 "applyVolumeShaper failed: %d", status);
Andy Hung4ef88d72017-02-21 19:47:53 -08002278 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002279 return status;
2280}
2281
2282sp<VolumeShaper::State> AudioTrack::getVolumeShaperState(int id)
2283{
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002284 AutoMutex lock(mLock);
Andy Hung39399b62017-04-21 15:07:45 -07002285 sp<VolumeShaper::State> state = mAudioTrack->getVolumeShaperState(id);
2286 if (state.get() == nullptr && (mCblk->mFlags & CBLK_INVALID) != 0) {
2287 if (restoreTrack_l("getVolumeShaperState") == OK) {
2288 state = mAudioTrack->getVolumeShaperState(id);
2289 }
2290 }
2291 return state;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002292}
2293
Andy Hungea2b9c02016-02-12 17:06:53 -08002294status_t AudioTrack::getTimestamp(ExtendedTimestamp *timestamp)
2295{
2296 if (timestamp == nullptr) {
2297 return BAD_VALUE;
2298 }
2299 AutoMutex lock(mLock);
Andy Hunge13f8a62016-03-30 14:20:42 -07002300 return getTimestamp_l(timestamp);
2301}
2302
2303status_t AudioTrack::getTimestamp_l(ExtendedTimestamp *timestamp)
2304{
Andy Hungea2b9c02016-02-12 17:06:53 -08002305 if (mCblk->mFlags & CBLK_INVALID) {
2306 const status_t status = restoreTrack_l("getTimestampExtended");
2307 if (status != OK) {
2308 // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
2309 // recommending that the track be recreated.
2310 return DEAD_OBJECT;
2311 }
2312 }
2313 // check for offloaded/direct here in case restoring somehow changed those flags.
2314 if (isOffloadedOrDirect_l()) {
2315 return INVALID_OPERATION; // not supported
2316 }
2317 status_t status = mProxy->getTimestamp(timestamp);
Andy Hunge1e98462016-04-12 10:18:51 -07002318 LOG_ALWAYS_FATAL_IF(status != OK, "status %d not allowed from proxy getTimestamp", status);
Andy Hungea2b9c02016-02-12 17:06:53 -08002319 bool found = false;
Andy Hunge1e98462016-04-12 10:18:51 -07002320 timestamp->mPosition[ExtendedTimestamp::LOCATION_CLIENT] = mFramesWritten;
2321 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_CLIENT] = 0;
2322 // server side frame offset in case AudioTrack has been restored.
2323 for (int i = ExtendedTimestamp::LOCATION_SERVER;
2324 i < ExtendedTimestamp::LOCATION_MAX; ++i) {
2325 if (timestamp->mTimeNs[i] >= 0) {
2326 // apply server offset (frames flushed is ignored
2327 // so we don't report the jump when the flush occurs).
2328 timestamp->mPosition[i] += mFramesWrittenServerOffset;
2329 found = true;
Andy Hungea2b9c02016-02-12 17:06:53 -08002330 }
2331 }
2332 return found ? OK : WOULD_BLOCK;
2333}
2334
Glenn Kastence703742013-07-19 16:33:58 -07002335status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
2336{
Glenn Kasten53cec222013-08-29 09:01:02 -07002337 AutoMutex lock(mLock);
Andy Hung65ffdfc2016-10-10 15:52:11 -07002338 return getTimestamp_l(timestamp);
2339}
Phil Burk1b420972015-04-22 10:52:21 -07002340
Andy Hung65ffdfc2016-10-10 15:52:11 -07002341status_t AudioTrack::getTimestamp_l(AudioTimestamp& timestamp)
2342{
Phil Burk1b420972015-04-22 10:52:21 -07002343 bool previousTimestampValid = mPreviousTimestampValid;
2344 // Set false here to cover all the error return cases.
2345 mPreviousTimestampValid = false;
2346
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002347 switch (mState) {
2348 case STATE_ACTIVE:
2349 case STATE_PAUSED:
2350 break; // handle below
2351 case STATE_FLUSHED:
2352 case STATE_STOPPED:
2353 return WOULD_BLOCK;
2354 case STATE_STOPPING:
2355 case STATE_PAUSED_STOPPING:
2356 if (!isOffloaded_l()) {
2357 return INVALID_OPERATION;
2358 }
2359 break; // offloaded tracks handled below
2360 default:
2361 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
2362 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07002363 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002364
Eric Laurent275e8e92014-11-30 15:14:47 -08002365 if (mCblk->mFlags & CBLK_INVALID) {
Andy Hung6653c932015-06-08 13:27:48 -07002366 const status_t status = restoreTrack_l("getTimestamp");
2367 if (status != OK) {
2368 // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
2369 // recommending that the track be recreated.
2370 return DEAD_OBJECT;
2371 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002372 }
2373
Glenn Kasten200092b2014-08-15 15:13:30 -07002374 // The presented frame count must always lag behind the consumed frame count.
2375 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Andy Hung6ae58432016-02-16 18:32:24 -08002376
2377 status_t status;
Andy Hung818e7a32016-02-16 18:08:07 -08002378 if (isOffloadedOrDirect_l()) {
Andy Hung6ae58432016-02-16 18:32:24 -08002379 // use Binder to get timestamp
2380 status = mAudioTrack->getTimestamp(timestamp);
2381 } else {
2382 // read timestamp from shared memory
2383 ExtendedTimestamp ets;
2384 status = mProxy->getTimestamp(&ets);
2385 if (status == OK) {
Andy Hungb01faa32016-04-27 12:51:32 -07002386 ExtendedTimestamp::Location location;
2387 status = ets.getBestTimestamp(&timestamp, &location);
2388
2389 if (status == OK) {
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002390 updateLatency_l();
Andy Hungb01faa32016-04-27 12:51:32 -07002391 // It is possible that the best location has moved from the kernel to the server.
2392 // In this case we adjust the position from the previous computed latency.
2393 if (location == ExtendedTimestamp::LOCATION_SERVER) {
2394 ALOGW_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_KERNEL,
2395 "getTimestamp() location moved from kernel to server");
Andy Hung07eee802016-06-21 16:47:16 -07002396 // check that the last kernel OK time info exists and the positions
2397 // are valid (if they predate the current track, the positions may
2398 // be zero or negative).
Andy Hungb01faa32016-04-27 12:51:32 -07002399 const int64_t frames =
Andy Hung6d7b1192016-05-07 22:59:48 -07002400 (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
Andy Hung07eee802016-06-21 16:47:16 -07002401 ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0 ||
2402 ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] <= 0 ||
2403 ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] <= 0)
Andy Hung6d7b1192016-05-07 22:59:48 -07002404 ?
2405 int64_t((double)mAfLatency * mSampleRate * mPlaybackRate.mSpeed
2406 / 1000)
2407 :
2408 (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
2409 - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK]);
2410 ALOGV("frame adjustment:%lld timestamp:%s",
2411 (long long)frames, ets.toString().c_str());
Andy Hungb01faa32016-04-27 12:51:32 -07002412 if (frames >= ets.mPosition[location]) {
2413 timestamp.mPosition = 0;
2414 } else {
2415 timestamp.mPosition = (uint32_t)(ets.mPosition[location] - frames);
2416 }
Andy Hung69488c42016-05-16 18:43:33 -07002417 } else if (location == ExtendedTimestamp::LOCATION_KERNEL) {
2418 ALOGV_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_SERVER,
2419 "getTimestamp() location moved from server to kernel");
Andy Hungb01faa32016-04-27 12:51:32 -07002420 }
Andy Hung5d313802016-10-10 15:09:39 -07002421
2422 // We update the timestamp time even when paused.
2423 if (mState == STATE_PAUSED /* not needed: STATE_PAUSED_STOPPING */) {
2424 const int64_t now = systemTime();
Andy Hung2b01f002017-07-05 12:01:36 -07002425 const int64_t at = audio_utils_ns_from_timespec(&timestamp.mTime);
Andy Hung5d313802016-10-10 15:09:39 -07002426 const int64_t lag =
2427 (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
2428 ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0)
2429 ? int64_t(mAfLatency * 1000000LL)
2430 : (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
2431 - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK])
2432 * NANOS_PER_SECOND / mSampleRate;
2433 const int64_t limit = now - lag; // no earlier than this limit
2434 if (at < limit) {
2435 ALOGV("timestamp pause lag:%lld adjusting from %lld to %lld",
2436 (long long)lag, (long long)at, (long long)limit);
Andy Hungffa36952017-08-17 10:41:51 -07002437 timestamp.mTime = convertNsToTimespec(limit);
Andy Hung5d313802016-10-10 15:09:39 -07002438 }
2439 }
Andy Hungb01faa32016-04-27 12:51:32 -07002440 mPreviousLocation = location;
2441 } else {
2442 // right after AudioTrack is started, one may not find a timestamp
2443 ALOGV("getBestTimestamp did not find timestamp");
2444 }
Andy Hung6ae58432016-02-16 18:32:24 -08002445 }
2446 if (status == INVALID_OPERATION) {
Andy Hungf20a4e92016-08-15 19:10:34 -07002447 // INVALID_OPERATION occurs when no timestamp has been issued by the server;
2448 // other failures are signaled by a negative time.
2449 // If we come out of FLUSHED or STOPPED where the position is known
2450 // to be zero we convert this to WOULD_BLOCK (with the implicit meaning of
2451 // "zero" for NuPlayer). We don't convert for track restoration as position
2452 // does not reset.
2453 ALOGV("timestamp server offset:%lld restore frames:%lld",
2454 (long long)mFramesWrittenServerOffset, (long long)mFramesWrittenAtRestore);
2455 if (mFramesWrittenServerOffset != mFramesWrittenAtRestore) {
2456 status = WOULD_BLOCK;
2457 }
Andy Hung6ae58432016-02-16 18:32:24 -08002458 }
2459 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002460 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07002461 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002462 return status;
2463 }
2464 if (isOffloadedOrDirect_l()) {
2465 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
2466 // use cached paused position in case another offloaded track is running.
2467 timestamp.mPosition = mPausedPosition;
2468 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
Andy Hung5d313802016-10-10 15:09:39 -07002469 // TODO: adjust for delay
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002470 return NO_ERROR;
2471 }
2472
2473 // Check whether a pending flush or stop has completed, as those commands may
Andy Hungc8e09c62015-06-03 23:43:36 -07002474 // be asynchronous or return near finish or exhibit glitchy behavior.
2475 //
2476 // Originally this showed up as the first timestamp being a continuation of
2477 // the previous song under gapless playback.
2478 // However, we sometimes see zero timestamps, then a glitch of
2479 // the previous song's position, and then correct timestamps afterwards.
Andy Hungffa36952017-08-17 10:41:51 -07002480 if (mStartFromZeroUs != 0 && mSampleRate != 0) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002481 static const int kTimeJitterUs = 100000; // 100 ms
2482 static const int k1SecUs = 1000000;
2483
2484 const int64_t timeNow = getNowUs();
2485
Andy Hungffa36952017-08-17 10:41:51 -07002486 if (timeNow < mStartFromZeroUs + k1SecUs) { // within first second of starting
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002487 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
Andy Hungffa36952017-08-17 10:41:51 -07002488 if (timestampTimeUs < mStartFromZeroUs) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002489 return WOULD_BLOCK; // stale timestamp time, occurs before start.
2490 }
Andy Hungffa36952017-08-17 10:41:51 -07002491 const int64_t deltaTimeUs = timestampTimeUs - mStartFromZeroUs;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002492 const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002493 / ((double)mSampleRate * mPlaybackRate.mSpeed);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002494
2495 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2496 // Verify that the counter can't count faster than the sample rate
Andy Hungc8e09c62015-06-03 23:43:36 -07002497 // since the start time. If greater, then that means we may have failed
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002498 // to completely flush or stop the previous playing track.
Andy Hungc8e09c62015-06-03 23:43:36 -07002499 ALOGW_IF(!mTimestampStartupGlitchReported,
2500 "getTimestamp startup glitch detected"
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002501 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2502 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2503 timestamp.mPosition);
Andy Hungc8e09c62015-06-03 23:43:36 -07002504 mTimestampStartupGlitchReported = true;
2505 if (previousTimestampValid
2506 && mPreviousTimestamp.mPosition == 0 /* should be true if valid */) {
2507 timestamp = mPreviousTimestamp;
2508 mPreviousTimestampValid = true;
2509 return NO_ERROR;
2510 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002511 return WOULD_BLOCK;
2512 }
Andy Hungc8e09c62015-06-03 23:43:36 -07002513 if (deltaPositionByUs != 0) {
Andy Hungffa36952017-08-17 10:41:51 -07002514 mStartFromZeroUs = 0; // don't check again, we got valid nonzero position.
Andy Hungc8e09c62015-06-03 23:43:36 -07002515 }
2516 } else {
Andy Hungffa36952017-08-17 10:41:51 -07002517 mStartFromZeroUs = 0; // don't check again, start time expired.
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002518 }
Andy Hungc8e09c62015-06-03 23:43:36 -07002519 mTimestampStartupGlitchReported = false;
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002520 }
2521 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002522 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2523 (void) updateAndGetPosition_l();
2524 // Server consumed (mServer) and presented both use the same server time base,
2525 // and server consumed is always >= presented.
2526 // The delta between these represents the number of frames in the buffer pipeline.
2527 // If this delta between these is greater than the client position, it means that
2528 // actually presented is still stuck at the starting line (figuratively speaking),
2529 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
Andy Hung90e8a972015-11-09 16:42:40 -08002530 // Note: We explicitly use non-Modulo comparison here - potential wrap issue when
2531 // mPosition exceeds 32 bits.
2532 // TODO Remove when timestamp is updated to contain pipeline status info.
2533 const int32_t pipelineDepthInFrames = (mServer - timestamp.mPosition).signedValue();
2534 if (pipelineDepthInFrames > 0 /* should be true, but we check anyways */
2535 && (uint32_t)pipelineDepthInFrames > mPosition.value()) {
Glenn Kasten200092b2014-08-15 15:13:30 -07002536 return INVALID_OPERATION;
2537 }
2538 // Convert timestamp position from server time base to client time base.
2539 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2540 // But if we change it to 64-bit then this could fail.
Andy Hung90e8a972015-11-09 16:42:40 -08002541 // Use Modulo computation here.
2542 timestamp.mPosition = (mPosition - mServer + timestamp.mPosition).value();
Glenn Kasten200092b2014-08-15 15:13:30 -07002543 // Immediately after a call to getPosition_l(), mPosition and
2544 // mServer both represent the same frame position. mPosition is
2545 // in client's point of view, and mServer is in server's point of
2546 // view. So the difference between them is the "fudge factor"
2547 // between client and server views due to stop() and/or new
2548 // IAudioTrack. And timestamp.mPosition is initially in server's
2549 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002550 }
Phil Burk1b420972015-04-22 10:52:21 -07002551
2552 // Prevent retrograde motion in timestamp.
2553 // This is sometimes caused by erratic reports of the available space in the ALSA drivers.
2554 if (status == NO_ERROR) {
Andy Hungffa36952017-08-17 10:41:51 -07002555 // previousTimestampValid is set to false when starting after a stop or flush.
Phil Burk1b420972015-04-22 10:52:21 -07002556 if (previousTimestampValid) {
Andy Hung2b01f002017-07-05 12:01:36 -07002557 const int64_t previousTimeNanos =
2558 audio_utils_ns_from_timespec(&mPreviousTimestamp.mTime);
Andy Hungffa36952017-08-17 10:41:51 -07002559 int64_t currentTimeNanos = audio_utils_ns_from_timespec(&timestamp.mTime);
2560
2561 // Fix stale time when checking timestamp right after start().
2562 //
2563 // For offload compatibility, use a default lag value here.
2564 // Any time discrepancy between this update and the pause timestamp is handled
2565 // by the retrograde check afterwards.
2566 const int64_t lagNs = int64_t(mAfLatency * 1000000LL);
2567 const int64_t limitNs = mStartNs - lagNs;
2568 if (currentTimeNanos < limitNs) {
2569 ALOGD("correcting timestamp time for pause, "
2570 "currentTimeNanos: %lld < limitNs: %lld < mStartNs: %lld",
2571 (long long)currentTimeNanos, (long long)limitNs, (long long)mStartNs);
2572 timestamp.mTime = convertNsToTimespec(limitNs);
2573 currentTimeNanos = limitNs;
2574 }
2575
2576 // retrograde check
Phil Burk1b420972015-04-22 10:52:21 -07002577 if (currentTimeNanos < previousTimeNanos) {
Andy Hung5d313802016-10-10 15:09:39 -07002578 ALOGW("retrograde timestamp time corrected, %lld < %lld",
2579 (long long)currentTimeNanos, (long long)previousTimeNanos);
2580 timestamp.mTime = mPreviousTimestamp.mTime;
Andy Hungffa36952017-08-17 10:41:51 -07002581 // currentTimeNanos not used below.
Phil Burk1b420972015-04-22 10:52:21 -07002582 }
2583
2584 // Looking at signed delta will work even when the timestamps
2585 // are wrapping around.
Andy Hung90e8a972015-11-09 16:42:40 -08002586 int32_t deltaPosition = (Modulo<uint32_t>(timestamp.mPosition)
2587 - mPreviousTimestamp.mPosition).signedValue();
Phil Burk4c5a3672015-04-30 16:18:53 -07002588 if (deltaPosition < 0) {
2589 // Only report once per position instead of spamming the log.
2590 if (!mRetrogradeMotionReported) {
2591 ALOGW("retrograde timestamp position corrected, %d = %u - %u",
2592 deltaPosition,
2593 timestamp.mPosition,
2594 mPreviousTimestamp.mPosition);
2595 mRetrogradeMotionReported = true;
2596 }
2597 } else {
2598 mRetrogradeMotionReported = false;
2599 }
Andy Hung5d313802016-10-10 15:09:39 -07002600 if (deltaPosition < 0) {
2601 timestamp.mPosition = mPreviousTimestamp.mPosition;
2602 deltaPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -07002603 }
Andy Hung5d313802016-10-10 15:09:39 -07002604#if 0
2605 // Uncomment this to verify audio timestamp rate.
2606 const int64_t deltaTime =
Andy Hung2b01f002017-07-05 12:01:36 -07002607 audio_utils_ns_from_timespec(&timestamp.mTime) - previousTimeNanos;
Andy Hung5d313802016-10-10 15:09:39 -07002608 if (deltaTime != 0) {
2609 const int64_t computedSampleRate =
2610 deltaPosition * (long long)NANOS_PER_SECOND / deltaTime;
2611 ALOGD("computedSampleRate:%u sampleRate:%u",
2612 (unsigned)computedSampleRate, mSampleRate);
2613 }
2614#endif
Phil Burk1b420972015-04-22 10:52:21 -07002615 }
2616 mPreviousTimestamp = timestamp;
2617 mPreviousTimestampValid = true;
2618 }
2619
Glenn Kastenfe346c72013-08-30 13:28:22 -07002620 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002621}
2622
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002623String8 AudioTrack::getParameters(const String8& keys)
2624{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002625 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002626 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002627 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002628 } else {
2629 return String8::empty();
2630 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002631}
2632
Glenn Kasten23a75452014-01-13 10:37:17 -08002633bool AudioTrack::isOffloaded() const
2634{
2635 AutoMutex lock(mLock);
2636 return isOffloaded_l();
2637}
2638
Eric Laurentab5cdba2014-06-09 17:22:27 -07002639bool AudioTrack::isDirect() const
2640{
2641 AutoMutex lock(mLock);
2642 return isDirect_l();
2643}
2644
2645bool AudioTrack::isOffloadedOrDirect() const
2646{
2647 AutoMutex lock(mLock);
2648 return isOffloadedOrDirect_l();
2649}
2650
2651
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002652status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002653{
2654
2655 const size_t SIZE = 256;
2656 char buffer[SIZE];
2657 String8 result;
2658
2659 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002660 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002661 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002662 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002663 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002664 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002665 result.append(buffer);
Andy Hung8edb8dc2015-03-26 19:13:55 -07002666 snprintf(buffer, 255, " sample rate(%u), speed(%f), status(%d)\n",
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002667 mSampleRate, mPlaybackRate.mSpeed, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002668 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002669 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002670 result.append(buffer);
2671 ::write(fd, result.string(), result.size());
2672 return NO_ERROR;
2673}
2674
Phil Burk2812d9e2016-01-04 10:34:30 -08002675uint32_t AudioTrack::getUnderrunCount() const
2676{
2677 AutoMutex lock(mLock);
2678 return getUnderrunCount_l();
2679}
2680
2681uint32_t AudioTrack::getUnderrunCount_l() const
2682{
2683 return mProxy->getUnderrunCount() + mUnderrunCountOffset;
2684}
2685
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002686uint32_t AudioTrack::getUnderrunFrames() const
2687{
2688 AutoMutex lock(mLock);
2689 return mProxy->getUnderrunFrames();
2690}
2691
Eric Laurent296fb132015-05-01 11:38:42 -07002692status_t AudioTrack::addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback)
2693{
2694 if (callback == 0) {
2695 ALOGW("%s adding NULL callback!", __FUNCTION__);
2696 return BAD_VALUE;
2697 }
2698 AutoMutex lock(mLock);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002699 if (mDeviceCallback.unsafe_get() == callback.get()) {
Eric Laurent296fb132015-05-01 11:38:42 -07002700 ALOGW("%s adding same callback!", __FUNCTION__);
2701 return INVALID_OPERATION;
2702 }
2703 status_t status = NO_ERROR;
2704 if (mOutput != AUDIO_IO_HANDLE_NONE) {
2705 if (mDeviceCallback != 0) {
2706 ALOGW("%s callback already present!", __FUNCTION__);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002707 AudioSystem::removeAudioDeviceCallback(this, mOutput);
Eric Laurent296fb132015-05-01 11:38:42 -07002708 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002709 status = AudioSystem::addAudioDeviceCallback(this, mOutput);
Eric Laurent296fb132015-05-01 11:38:42 -07002710 }
2711 mDeviceCallback = callback;
2712 return status;
2713}
2714
2715status_t AudioTrack::removeAudioDeviceCallback(
2716 const sp<AudioSystem::AudioDeviceCallback>& callback)
2717{
2718 if (callback == 0) {
2719 ALOGW("%s removing NULL callback!", __FUNCTION__);
2720 return BAD_VALUE;
2721 }
2722 AutoMutex lock(mLock);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002723 if (mDeviceCallback.unsafe_get() != callback.get()) {
Eric Laurent296fb132015-05-01 11:38:42 -07002724 ALOGW("%s removing different callback!", __FUNCTION__);
2725 return INVALID_OPERATION;
2726 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002727 mDeviceCallback.clear();
Eric Laurent296fb132015-05-01 11:38:42 -07002728 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002729 AudioSystem::removeAudioDeviceCallback(this, mOutput);
Eric Laurent296fb132015-05-01 11:38:42 -07002730 }
Eric Laurent296fb132015-05-01 11:38:42 -07002731 return NO_ERROR;
2732}
2733
Eric Laurentad2e7b92017-09-14 20:06:42 -07002734
2735void AudioTrack::onAudioDeviceUpdate(audio_io_handle_t audioIo,
2736 audio_port_handle_t deviceId)
2737{
2738 sp<AudioSystem::AudioDeviceCallback> callback;
2739 {
2740 AutoMutex lock(mLock);
2741 if (audioIo != mOutput) {
2742 return;
2743 }
2744 callback = mDeviceCallback.promote();
2745 // only update device if the track is active as route changes due to other use cases are
2746 // irrelevant for this client
2747 if (mState == STATE_ACTIVE) {
2748 mRoutedDeviceId = deviceId;
2749 }
2750 }
2751 if (callback.get() != nullptr) {
2752 callback->onAudioDeviceUpdate(mOutput, mRoutedDeviceId);
2753 }
2754}
2755
Andy Hunge13f8a62016-03-30 14:20:42 -07002756status_t AudioTrack::pendingDuration(int32_t *msec, ExtendedTimestamp::Location location)
2757{
2758 if (msec == nullptr ||
2759 (location != ExtendedTimestamp::LOCATION_SERVER
2760 && location != ExtendedTimestamp::LOCATION_KERNEL)) {
2761 return BAD_VALUE;
2762 }
2763 AutoMutex lock(mLock);
2764 // inclusive of offloaded and direct tracks.
2765 //
2766 // It is possible, but not enabled, to allow duration computation for non-pcm
2767 // audio_has_proportional_frames() formats because currently they have
2768 // the drain rate equivalent to the pcm sample rate * framesize.
2769 if (!isPurePcmData_l()) {
2770 return INVALID_OPERATION;
2771 }
2772 ExtendedTimestamp ets;
2773 if (getTimestamp_l(&ets) == OK
2774 && ets.mTimeNs[location] > 0) {
2775 int64_t diff = ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT]
2776 - ets.mPosition[location];
2777 if (diff < 0) {
2778 *msec = 0;
2779 } else {
2780 // ms is the playback time by frames
2781 int64_t ms = (int64_t)((double)diff * 1000 /
2782 ((double)mSampleRate * mPlaybackRate.mSpeed));
2783 // clockdiff is the timestamp age (negative)
2784 int64_t clockdiff = (mState != STATE_ACTIVE) ? 0 :
2785 ets.mTimeNs[location]
2786 + ets.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_MONOTONIC]
2787 - systemTime(SYSTEM_TIME_MONOTONIC);
2788
2789 //ALOGV("ms: %lld clockdiff: %lld", (long long)ms, (long long)clockdiff);
2790 static const int NANOS_PER_MILLIS = 1000000;
2791 *msec = (int32_t)(ms + clockdiff / NANOS_PER_MILLIS);
2792 }
2793 return NO_ERROR;
2794 }
2795 if (location != ExtendedTimestamp::LOCATION_SERVER) {
2796 return INVALID_OPERATION; // LOCATION_KERNEL is not available
2797 }
2798 // use server position directly (offloaded and direct arrive here)
2799 updateAndGetPosition_l();
2800 int32_t diff = (Modulo<uint32_t>(mFramesWritten) - mPosition).signedValue();
2801 *msec = (diff <= 0) ? 0
2802 : (int32_t)((double)diff * 1000 / ((double)mSampleRate * mPlaybackRate.mSpeed));
2803 return NO_ERROR;
2804}
2805
Andy Hung65ffdfc2016-10-10 15:52:11 -07002806bool AudioTrack::hasStarted()
2807{
2808 AutoMutex lock(mLock);
2809 switch (mState) {
2810 case STATE_STOPPED:
2811 if (isOffloadedOrDirect_l()) {
2812 // check if we have started in the past to return true.
Andy Hungffa36952017-08-17 10:41:51 -07002813 return mStartFromZeroUs > 0;
Andy Hung65ffdfc2016-10-10 15:52:11 -07002814 }
2815 // A normal audio track may still be draining, so
2816 // check if stream has ended. This covers fasttrack position
2817 // instability and start/stop without any data written.
2818 if (mProxy->getStreamEndDone()) {
2819 return true;
2820 }
2821 // fall through
2822 case STATE_ACTIVE:
2823 case STATE_STOPPING:
2824 break;
2825 case STATE_PAUSED:
2826 case STATE_PAUSED_STOPPING:
2827 case STATE_FLUSHED:
2828 return false; // we're not active
2829 default:
2830 LOG_ALWAYS_FATAL("Invalid mState in hasStarted(): %d", mState);
2831 break;
2832 }
2833
2834 // wait indicates whether we need to wait for a timestamp.
2835 // This is conservatively figured - if we encounter an unexpected error
2836 // then we will not wait.
2837 bool wait = false;
2838 if (isOffloadedOrDirect_l()) {
2839 AudioTimestamp ts;
2840 status_t status = getTimestamp_l(ts);
2841 if (status == WOULD_BLOCK) {
2842 wait = true;
2843 } else if (status == OK) {
2844 wait = (ts.mPosition == 0 || ts.mPosition == mStartTs.mPosition);
2845 }
2846 ALOGV("hasStarted wait:%d ts:%u start position:%lld",
2847 (int)wait,
2848 ts.mPosition,
2849 (long long)mStartTs.mPosition);
2850 } else {
2851 int location = ExtendedTimestamp::LOCATION_SERVER; // for ALOG
2852 ExtendedTimestamp ets;
2853 status_t status = getTimestamp_l(&ets);
2854 if (status == WOULD_BLOCK) { // no SERVER or KERNEL frame info in ets
2855 wait = true;
2856 } else if (status == OK) {
2857 for (location = ExtendedTimestamp::LOCATION_KERNEL;
2858 location >= ExtendedTimestamp::LOCATION_SERVER; --location) {
2859 if (ets.mTimeNs[location] < 0 || mStartEts.mTimeNs[location] < 0) {
2860 continue;
2861 }
2862 wait = ets.mPosition[location] == 0
2863 || ets.mPosition[location] == mStartEts.mPosition[location];
2864 break;
2865 }
2866 }
2867 ALOGV("hasStarted wait:%d ets:%lld start position:%lld",
2868 (int)wait,
2869 (long long)ets.mPosition[location],
2870 (long long)mStartEts.mPosition[location]);
2871 }
2872 return !wait;
2873}
2874
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002875// =========================================================================
2876
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002877void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002878{
2879 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2880 if (audioTrack != 0) {
2881 AutoMutex lock(audioTrack->mLock);
2882 audioTrack->mProxy->binderDied();
2883 }
2884}
2885
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002886// =========================================================================
2887
2888AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002889 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2890 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002891{
2892}
2893
2894AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002895{
2896}
2897
2898bool AudioTrack::AudioTrackThread::threadLoop()
2899{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002900 {
2901 AutoMutex _l(mMyLock);
2902 if (mPaused) {
Glenn Kasten75f79032017-05-23 11:22:44 -07002903 // TODO check return value and handle or log
Glenn Kasten3acbd052012-02-28 10:39:56 -08002904 mMyCond.wait(mMyLock);
2905 // caller will check for exitPending()
2906 return true;
2907 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002908 if (mIgnoreNextPausedInt) {
2909 mIgnoreNextPausedInt = false;
2910 mPausedInt = false;
2911 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002912 if (mPausedInt) {
Glenn Kasten47d55172017-05-23 11:19:30 -07002913 // TODO use futex instead of condition, for event flag "or"
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002914 if (mPausedNs > 0) {
Glenn Kasten75f79032017-05-23 11:22:44 -07002915 // TODO check return value and handle or log
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002916 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2917 } else {
Glenn Kasten75f79032017-05-23 11:22:44 -07002918 // TODO check return value and handle or log
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002919 mMyCond.wait(mMyLock);
2920 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002921 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002922 return true;
2923 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002924 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002925 if (exitPending()) {
2926 return false;
2927 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002928 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002929 switch (ns) {
2930 case 0:
2931 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002932 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002933 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002934 return true;
2935 case NS_NEVER:
2936 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002937 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08002938 // Event driven: call wake() when callback notifications conditions change.
2939 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002940 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002941 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002942 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002943 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002944 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002945 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002946}
2947
Glenn Kasten3acbd052012-02-28 10:39:56 -08002948void AudioTrack::AudioTrackThread::requestExit()
2949{
2950 // must be in this order to avoid a race condition
2951 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002952 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002953}
2954
2955void AudioTrack::AudioTrackThread::pause()
2956{
2957 AutoMutex _l(mMyLock);
2958 mPaused = true;
2959}
2960
2961void AudioTrack::AudioTrackThread::resume()
2962{
2963 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002964 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002965 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002966 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002967 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002968 mMyCond.signal();
2969 }
2970}
2971
Andy Hung3c09c782014-12-29 18:39:32 -08002972void AudioTrack::AudioTrackThread::wake()
2973{
2974 AutoMutex _l(mMyLock);
Andy Hunga8d08902015-07-22 11:52:13 -07002975 if (!mPaused) {
2976 // wake() might be called while servicing a callback - ignore the next
2977 // pause time and call processAudioBuffer.
Andy Hung3c09c782014-12-29 18:39:32 -08002978 mIgnoreNextPausedInt = true;
Andy Hunga8d08902015-07-22 11:52:13 -07002979 if (mPausedInt && mPausedNs > 0) {
2980 // audio track is active and internally paused with timeout.
2981 mPausedInt = false;
2982 mMyCond.signal();
2983 }
Andy Hung3c09c782014-12-29 18:39:32 -08002984 }
2985}
2986
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002987void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2988{
2989 AutoMutex _l(mMyLock);
2990 mPausedInt = true;
2991 mPausedNs = ns;
2992}
2993
Glenn Kasten40bc9062015-03-20 09:09:33 -07002994} // namespace android