blob: 356b321313dd0f28d0a7cd6b1aad9761cbb6707d [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
Andy Hung8edb8dc2015-03-26 19:13:55 -0700102// Must match similar computation in createTrack_l in Threads.cpp.
103// TODO: Move to a common library
104static size_t calculateMinFrameCount(
105 uint32_t afLatencyMs, uint32_t afFrameCount, uint32_t afSampleRate,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700106 uint32_t sampleRate, float speed /*, uint32_t notificationsPerBufferReq*/)
Andy Hung8edb8dc2015-03-26 19:13:55 -0700107{
108 // Ensure that buffer depth covers at least audio hardware latency
109 uint32_t minBufCount = afLatencyMs / ((1000 * afFrameCount) / afSampleRate);
110 if (minBufCount < 2) {
111 minBufCount = 2;
112 }
Glenn Kastenea38ee72016-04-18 11:08:01 -0700113#if 0
114 // The notificationsPerBufferReq parameter is not yet used for non-fast tracks,
115 // but keeping the code here to make it easier to add later.
116 if (minBufCount < notificationsPerBufferReq) {
117 minBufCount = notificationsPerBufferReq;
118 }
119#endif
Andy Hung8edb8dc2015-03-26 19:13:55 -0700120 ALOGV("calculateMinFrameCount afLatency %u afFrameCount %u afSampleRate %u "
Glenn Kastenea38ee72016-04-18 11:08:01 -0700121 "sampleRate %u speed %f minBufCount: %u" /*" notificationsPerBufferReq %u"*/,
122 afLatencyMs, afFrameCount, afSampleRate, sampleRate, speed, minBufCount
123 /*, notificationsPerBufferReq*/);
Andy Hung8edb8dc2015-03-26 19:13:55 -0700124 return minBufCount * sourceFramesNeededWithTimestretch(
125 sampleRate, afFrameCount, afSampleRate, speed);
126}
127
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800128// static
129status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -0800130 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800131 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800132 uint32_t sampleRate)
133{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700134 if (frameCount == NULL) {
135 return BAD_VALUE;
136 }
Glenn Kasten04cd0182012-06-25 11:49:27 -0700137
Andy Hung0e48d252015-01-26 11:43:15 -0800138 // FIXME handle in server, like createTrack_l(), possible missing info:
Glenn Kastene0fa4672012-04-24 14:35:14 -0700139 // audio_io_handle_t output
140 // audio_format_t format
141 // audio_channel_mask_t channelMask
Andy Hung0e48d252015-01-26 11:43:15 -0800142 // audio_output_flags_t flags (FAST)
Glenn Kasten3b16c762012-11-14 08:44:39 -0800143 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -0800144 status_t status;
145 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
146 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -0800147 ALOGE("Unable to query output sample rate for stream type %d; status %d",
148 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800149 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800150 }
Glenn Kastene33054e2012-11-14 12:54:39 -0800151 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -0800152 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
153 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -0800154 ALOGE("Unable to query output frame count for stream type %d; status %d",
155 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800156 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800157 }
158 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -0800159 status = AudioSystem::getOutputLatency(&afLatency, streamType);
160 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -0800161 ALOGE("Unable to query output latency for stream type %d; status %d",
162 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800163 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800164 }
165
Andy Hung8edb8dc2015-03-26 19:13:55 -0700166 // When called from createTrack, speed is 1.0f (normal speed).
167 // This is rechecked again on setting playback rate (TODO: on setting sample rate, too).
Glenn Kastenea38ee72016-04-18 11:08:01 -0700168 *frameCount = calculateMinFrameCount(afLatency, afFrameCount, afSampleRate, sampleRate, 1.0f
169 /*, 0 notificationsPerBufferReq*/);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800170
Andy Hung0e48d252015-01-26 11:43:15 -0800171 // The formula above should always produce a non-zero value under normal circumstances:
172 // AudioTrack.SAMPLE_RATE_HZ_MIN <= sampleRate <= AudioTrack.SAMPLE_RATE_HZ_MAX.
173 // 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 -0800174 if (*frameCount == 0) {
Andy Hung0e48d252015-01-26 11:43:15 -0800175 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %u",
Glenn Kasten66a04672014-01-08 08:53:44 -0800176 streamType, sampleRate);
177 return BAD_VALUE;
178 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700179 ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, afSampleRate=%u, afLatency=%u",
180 *frameCount, afFrameCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800181 return NO_ERROR;
182}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800183
184// ---------------------------------------------------------------------------
185
186AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700187 : mStatus(NO_INIT),
Haynes Mathew George9b3359f2016-03-23 19:09:10 -0700188 mState(STATE_STOPPED),
John Grossman4ff14ba2012-02-08 16:37:41 -0800189 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800190 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700191 mPausedPosition(0),
Eric Laurent20b9ef02016-12-05 11:03:16 -0800192 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
Eric Laurent9ae8c592017-06-22 17:17:09 -0700193 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
Eric Laurent20b9ef02016-12-05 11:03:16 -0800194 mPortId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800195{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700196 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
197 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
198 mAttributes.flags = 0x0;
199 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800200}
201
202AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800203 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800204 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800205 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700206 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800207 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700208 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800209 callback_t cbf,
210 void* user,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700211 int32_t notificationFrames,
Glenn Kastend848eb42016-03-08 13:42:11 -0800212 audio_session_t sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000213 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800214 const audio_offload_info_t *offloadInfo,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800215 uid_t uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700216 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700217 const audio_attributes_t* pAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -0700218 bool doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -0700219 float maxRequiredSpeed,
220 audio_port_handle_t selectedDeviceId)
Glenn Kasten87913512011-06-22 16:15:25 -0700221 : mStatus(NO_INIT),
Haynes Mathew George9b3359f2016-03-23 19:09:10 -0700222 mState(STATE_STOPPED),
John Grossman4ff14ba2012-02-08 16:37:41 -0800223 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800224 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700225 mPausedPosition(0),
Eric Laurent20b9ef02016-12-05 11:03:16 -0800226 mPortId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800227{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700228 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700229 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800230 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
jiabin156c6872017-10-06 09:47:15 -0700231 offloadInfo, uid, pid, pAttributes, doNotReconnect, maxRequiredSpeed, selectedDeviceId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800232}
233
Andreas Huberc8139852012-01-18 10:51:55 -0800234AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800235 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800236 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800237 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700238 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800239 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700240 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800241 callback_t cbf,
242 void* user,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700243 int32_t notificationFrames,
Glenn Kastend848eb42016-03-08 13:42:11 -0800244 audio_session_t sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000245 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800246 const audio_offload_info_t *offloadInfo,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800247 uid_t uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700248 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700249 const audio_attributes_t* pAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -0700250 bool doNotReconnect,
251 float maxRequiredSpeed)
Glenn Kasten87913512011-06-22 16:15:25 -0700252 : mStatus(NO_INIT),
Haynes Mathew George9b3359f2016-03-23 19:09:10 -0700253 mState(STATE_STOPPED),
John Grossman4ff14ba2012-02-08 16:37:41 -0800254 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800255 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700256 mPausedPosition(0),
Eric Laurent20b9ef02016-12-05 11:03:16 -0800257 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
258 mPortId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800259{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700260 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800261 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800262 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Andy Hungff874dc2016-04-11 16:49:09 -0700263 uid, pid, pAttributes, doNotReconnect, maxRequiredSpeed);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800264}
265
266AudioTrack::~AudioTrack()
267{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800268 if (mStatus == NO_ERROR) {
269 // Make sure that callback function exits in the case where
270 // it is looping on buffer full condition in obtainBuffer().
271 // Otherwise the callback thread will never exit.
272 stop();
273 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100274 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800275 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800276 mAudioTrackThread->requestExitAndWait();
277 mAudioTrackThread.clear();
278 }
Eric Laurent296fb132015-05-01 11:38:42 -0700279 // No lock here: worst case we remove a NULL callback which will be a nop
280 if (mDeviceCallback != 0 && mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700281 AudioSystem::removeAudioDeviceCallback(this, mOutput);
Eric Laurent296fb132015-05-01 11:38:42 -0700282 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800283 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700284 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700285 mCblkMemory.clear();
286 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800287 IPCThreadState::self()->flushCommands();
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700288 ALOGV("~AudioTrack, releasing session id %d from %d on behalf of %d",
289 mSessionId, IPCThreadState::self()->getCallingPid(), mClientPid);
Marco Nelissend457c972014-02-11 08:47:07 -0800290 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800291 }
292}
293
294status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800295 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800296 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800297 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700298 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800299 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700300 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800301 callback_t cbf,
302 void* user,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700303 int32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800304 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700305 bool threadCanCallJava,
Glenn Kastend848eb42016-03-08 13:42:11 -0800306 audio_session_t sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000307 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800308 const audio_offload_info_t *offloadInfo,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800309 uid_t uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700310 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700311 const audio_attributes_t* pAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -0700312 bool doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -0700313 float maxRequiredSpeed,
314 audio_port_handle_t selectedDeviceId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800315{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800316 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kastenea38ee72016-04-18 11:08:01 -0700317 "flags #%x, notificationFrames %d, sessionId %d, transferType %d, uid %d, pid %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800318 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700319 sessionId, transferType, uid, pid);
Glenn Kasten86f04662014-02-24 15:13:05 -0800320
Phil Burk33ff89b2015-11-30 11:16:01 -0800321 mThreadCanCallJava = threadCanCallJava;
jiabin156c6872017-10-06 09:47:15 -0700322 mSelectedDeviceId = selectedDeviceId;
Phil Burk33ff89b2015-11-30 11:16:01 -0800323
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800324 switch (transferType) {
325 case TRANSFER_DEFAULT:
326 if (sharedBuffer != 0) {
327 transferType = TRANSFER_SHARED;
328 } else if (cbf == NULL || threadCanCallJava) {
329 transferType = TRANSFER_SYNC;
330 } else {
331 transferType = TRANSFER_CALLBACK;
332 }
333 break;
334 case TRANSFER_CALLBACK:
335 if (cbf == NULL || sharedBuffer != 0) {
336 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
337 return BAD_VALUE;
338 }
339 break;
340 case TRANSFER_OBTAIN:
341 case TRANSFER_SYNC:
342 if (sharedBuffer != 0) {
343 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
344 return BAD_VALUE;
345 }
346 break;
347 case TRANSFER_SHARED:
348 if (sharedBuffer == 0) {
349 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
350 return BAD_VALUE;
351 }
352 break;
353 default:
354 ALOGE("Invalid transfer type %d", transferType);
355 return BAD_VALUE;
356 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800357 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800358 mTransfer = transferType;
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700359 mDoNotReconnect = doNotReconnect;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800360
Eric Laurent97c9f4f2015-08-11 18:04:14 -0700361 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %zu", sharedBuffer->pointer(),
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700362 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800363
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700364 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700365
Glenn Kasten53cec222013-08-29 09:01:02 -0700366 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700367 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000368 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800369 return INVALID_OPERATION;
370 }
371
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800372 // handle default values first.
Eric Laurente83b55d2014-11-14 10:06:21 -0800373 if (streamType == AUDIO_STREAM_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700374 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800375 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700376 if (pAttributes == NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800377 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700378 ALOGE("Invalid stream type %d", streamType);
379 return BAD_VALUE;
380 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700381 mStreamType = streamType;
Eric Laurente83b55d2014-11-14 10:06:21 -0800382
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700383 } else {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700384 // stream type shouldn't be looked at, this track has audio attributes
385 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700386 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
387 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800388 mStreamType = AUDIO_STREAM_DEFAULT;
Eric Laurentc6bd5db2015-03-09 16:29:33 -0700389 if ((mAttributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
390 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
391 }
Phil Burk33ff89b2015-11-30 11:16:01 -0800392 if ((mAttributes.flags & AUDIO_FLAG_LOW_LATENCY) != 0) {
393 flags = (audio_output_flags_t) (flags | AUDIO_OUTPUT_FLAG_FAST);
394 }
Andy Hungfff204c2017-01-12 19:09:55 -0800395 // check deep buffer after flags have been modified above
396 if (flags == AUDIO_OUTPUT_FLAG_NONE && (mAttributes.flags & AUDIO_FLAG_DEEP_BUFFER) != 0) {
397 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
398 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800399 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700400
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800401 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800402 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700403 format = AUDIO_FORMAT_PCM_16_BIT;
Phil Burkfdb3c072016-02-09 10:47:02 -0800404 } else if (format == AUDIO_FORMAT_IEC61937) { // HDMI pass-through?
405 mAttributes.flags |= AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800406 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800407
408 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700409 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800410 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800411 return BAD_VALUE;
412 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800413 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700414
Glenn Kasten8ba90322013-10-30 11:29:27 -0700415 if (!audio_is_output_channel(channelMask)) {
416 ALOGE("Invalid channel mask %#x", channelMask);
417 return BAD_VALUE;
418 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800419 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700420 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800421 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700422
Eric Laurentc2f1f072009-07-17 12:17:14 -0700423 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100424 // or offload was requested
425 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
426 || !audio_is_linear_pcm(format)) {
427 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
428 ? "Offload request, forcing to Direct Output"
429 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700430 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800431 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700432 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700433 }
434
Eric Laurentd1f69b02014-12-15 14:33:13 -0800435 // force direct flag if HW A/V sync requested
436 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
437 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
438 }
439
Glenn Kastenb7730382014-04-30 15:50:31 -0700440 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Phil Burkfdb3c072016-02-09 10:47:02 -0800441 if (audio_has_proportional_frames(format)) {
Glenn Kastenb7730382014-04-30 15:50:31 -0700442 mFrameSize = channelCount * audio_bytes_per_sample(format);
443 } else {
444 mFrameSize = sizeof(uint8_t);
445 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800446 } else {
Phil Burkfdb3c072016-02-09 10:47:02 -0800447 ALOG_ASSERT(audio_has_proportional_frames(format));
Glenn Kastenb7730382014-04-30 15:50:31 -0700448 mFrameSize = channelCount * audio_bytes_per_sample(format);
Glenn Kastenb7730382014-04-30 15:50:31 -0700449 // createTrack will return an error if PCM format is not supported by server,
450 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800451 }
452
Eric Laurent0d6db582014-11-12 18:39:44 -0800453 // sampling rate must be specified for direct outputs
454 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
455 return BAD_VALUE;
456 }
457 mSampleRate = sampleRate;
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700458 mOriginalSampleRate = sampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700459 mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT;
Andy Hungff874dc2016-04-11 16:49:09 -0700460 // 1.0 <= mMaxRequiredSpeed <= AUDIO_TIMESTRETCH_SPEED_MAX
461 mMaxRequiredSpeed = min(max(maxRequiredSpeed, 1.0f), AUDIO_TIMESTRETCH_SPEED_MAX);
Eric Laurent0d6db582014-11-12 18:39:44 -0800462
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800463 // Make copy of input parameter offloadInfo so that in the future:
464 // (a) createTrack_l doesn't need it as an input parameter
465 // (b) we can support re-creation of offloaded tracks
466 if (offloadInfo != NULL) {
467 mOffloadInfoCopy = *offloadInfo;
468 mOffloadInfo = &mOffloadInfoCopy;
469 } else {
470 mOffloadInfo = NULL;
Eric Laurent20b9ef02016-12-05 11:03:16 -0800471 memset(&mOffloadInfoCopy, 0, sizeof(audio_offload_info_t));
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800472 }
473
Glenn Kasten66e46352014-01-16 17:44:23 -0800474 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
475 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800476 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800477 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800478 mReqFrameCount = frameCount;
Glenn Kastenea38ee72016-04-18 11:08:01 -0700479 if (notificationFrames >= 0) {
480 mNotificationFramesReq = notificationFrames;
481 mNotificationsPerBufferReq = 0;
482 } else {
483 if (!(flags & AUDIO_OUTPUT_FLAG_FAST)) {
484 ALOGE("notificationFrames=%d not permitted for non-fast track",
485 notificationFrames);
486 return BAD_VALUE;
487 }
488 if (frameCount > 0) {
489 ALOGE("notificationFrames=%d not permitted with non-zero frameCount=%zu",
490 notificationFrames, frameCount);
491 return BAD_VALUE;
492 }
493 mNotificationFramesReq = 0;
494 const uint32_t minNotificationsPerBuffer = 1;
495 const uint32_t maxNotificationsPerBuffer = 8;
496 mNotificationsPerBufferReq = min(maxNotificationsPerBuffer,
497 max((uint32_t) -notificationFrames, minNotificationsPerBuffer));
498 ALOGW_IF(mNotificationsPerBufferReq != (uint32_t) -notificationFrames,
499 "notificationFrames=%d clamped to the range -%u to -%u",
500 notificationFrames, minNotificationsPerBuffer, maxNotificationsPerBuffer);
501 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800502 mNotificationFramesAct = 0;
Eric Laurentcaf7f482014-11-25 17:50:47 -0800503 if (sessionId == AUDIO_SESSION_ALLOCATE) {
Glenn Kastend848eb42016-03-08 13:42:11 -0800504 mSessionId = (audio_session_t) AudioSystem::newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentcaf7f482014-11-25 17:50:47 -0800505 } else {
506 mSessionId = sessionId;
507 }
Marco Nelissend457c972014-02-11 08:47:07 -0800508 int callingpid = IPCThreadState::self()->getCallingPid();
509 int mypid = getpid();
Andy Hung1f12a8a2016-11-07 16:10:30 -0800510 if (uid == AUDIO_UID_INVALID || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800511 mClientUid = IPCThreadState::self()->getCallingUid();
512 } else {
513 mClientUid = uid;
514 }
Marco Nelissend457c972014-02-11 08:47:07 -0800515 if (pid == -1 || (callingpid != mypid)) {
516 mClientPid = callingpid;
517 } else {
518 mClientPid = pid;
519 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700520 mAuxEffectId = 0;
Haynes Mathew Georgeae34ed22016-01-28 11:58:39 -0800521 mOrigFlags = mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700522 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700523
Glenn Kastena997e7a2012-08-07 09:44:19 -0700524 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700525 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700526 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
Glenn Kastenbfd31842015-03-20 09:01:44 -0700527 // thread begins in paused state, and will not reference us until start()
Glenn Kastena997e7a2012-08-07 09:44:19 -0700528 }
529
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800530 // create the IAudioTrack
Eric Laurent0d6db582014-11-12 18:39:44 -0800531 status_t status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800532
Glenn Kastena997e7a2012-08-07 09:44:19 -0700533 if (status != NO_ERROR) {
534 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100535 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
536 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700537 mAudioTrackThread.clear();
538 }
539 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700540 }
541
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800542 mStatus = NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800543 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800544 mLoopCount = 0;
545 mLoopStart = 0;
546 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800547 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800548 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700549 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800550 mNewPosition = 0;
551 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700552 mPosition = 0;
553 mReleased = 0;
Andy Hungffa36952017-08-17 10:41:51 -0700554 mStartNs = 0;
555 mStartFromZeroUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800556 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800557 mSequence = 1;
558 mObservedSequence = mSequence;
559 mInUnderrun = false;
Phil Burk1b420972015-04-22 10:52:21 -0700560 mPreviousTimestampValid = false;
Andy Hungc8e09c62015-06-03 23:43:36 -0700561 mTimestampStartupGlitchReported = false;
562 mRetrogradeMotionReported = false;
Andy Hungb01faa32016-04-27 12:51:32 -0700563 mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
Andy Hung65ffdfc2016-10-10 15:52:11 -0700564 mStartTs.mPosition = 0;
Phil Burk2812d9e2016-01-04 10:34:30 -0800565 mUnderrunCountOffset = 0;
Andy Hungea2b9c02016-02-12 17:06:53 -0800566 mFramesWritten = 0;
567 mFramesWrittenServerOffset = 0;
Andy Hungf20a4e92016-08-15 19:10:34 -0700568 mFramesWrittenAtRestore = -1; // -1 is a unique initializer.
Ivan Lozano8cf3a072017-08-09 09:01:33 -0700569 mVolumeHandler = new media::VolumeHandler();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800570 return NO_ERROR;
571}
572
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800573// -------------------------------------------------------------------------
574
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100575status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800576{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800577 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100578
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800579 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100580 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800581 }
582
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800583 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800584
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800585 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100586 if (previousState == STATE_PAUSED_STOPPING) {
587 mState = STATE_STOPPING;
588 } else {
589 mState = STATE_ACTIVE;
590 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700591 (void) updateAndGetPosition_l();
Andy Hung65ffdfc2016-10-10 15:52:11 -0700592
593 // save start timestamp
594 if (isOffloadedOrDirect_l()) {
595 if (getTimestamp_l(mStartTs) != OK) {
596 mStartTs.mPosition = 0;
597 }
598 } else {
599 if (getTimestamp_l(&mStartEts) != OK) {
600 mStartEts.clear();
601 }
602 }
Andy Hungffa36952017-08-17 10:41:51 -0700603 mStartNs = systemTime(); // save this for timestamp adjustment after starting.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800604 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
605 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700606 mPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -0700607 mPreviousTimestampValid = false;
Andy Hungc8e09c62015-06-03 23:43:36 -0700608 mTimestampStartupGlitchReported = false;
609 mRetrogradeMotionReported = false;
Andy Hungb01faa32016-04-27 12:51:32 -0700610 mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
Phil Burk1b420972015-04-22 10:52:21 -0700611
Andy Hung65ffdfc2016-10-10 15:52:11 -0700612 if (!isOffloadedOrDirect_l()
613 && mStartEts.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] > 0) {
Andy Hunge1e98462016-04-12 10:18:51 -0700614 // Server side has consumed something, but is it finished consuming?
615 // It is possible since flush and stop are asynchronous that the server
616 // is still active at this point.
617 ALOGV("start: server read:%lld cumulative flushed:%lld client written:%lld",
618 (long long)(mFramesWrittenServerOffset
Andy Hung65ffdfc2016-10-10 15:52:11 -0700619 + mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER]),
620 (long long)mStartEts.mFlushed,
Andy Hunge1e98462016-04-12 10:18:51 -0700621 (long long)mFramesWritten);
Andy Hungc4e60eb2017-09-06 11:14:57 -0700622 // mStartEts is already adjusted by mFramesWrittenServerOffset, so we delta adjust.
623 mFramesWrittenServerOffset -= mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung61be8412015-10-06 10:51:09 -0700624 }
Andy Hunge1e98462016-04-12 10:18:51 -0700625 mFramesWritten = 0;
626 mProxy->clearTimestamp(); // need new server push for valid timestamp
627 mMarkerReached = false;
Andy Hung61be8412015-10-06 10:51:09 -0700628
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700629 // For offloaded tracks, we don't know if the hardware counters are really zero here,
630 // since the flush is asynchronous and stop may not fully drain.
631 // We save the time when the track is started to later verify whether
632 // the counters are realistic (i.e. start from zero after this time).
Andy Hungffa36952017-08-17 10:41:51 -0700633 mStartFromZeroUs = mStartNs / 1000;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700634
Eric Laurentec9a0322013-08-28 10:23:01 -0700635 // force refresh of remaining frames by processAudioBuffer() as last
636 // write before stop could be partial.
637 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800638 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700639 mNewPosition = mPosition + mUpdatePeriod;
Andy Hung4be3b832016-10-13 17:51:43 -0700640 int32_t flags = android_atomic_and(~(CBLK_STREAM_END_DONE | CBLK_DISABLED), &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800641
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800642 status_t status = NO_ERROR;
643 if (!(flags & CBLK_INVALID)) {
644 status = mAudioTrack->start();
645 if (status == DEAD_OBJECT) {
646 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800647 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800648 }
649 if (flags & CBLK_INVALID) {
650 status = restoreTrack_l("start");
651 }
652
Andy Hung79629f02016-03-24 13:57:40 -0700653 // resume or pause the callback thread as needed.
654 sp<AudioTrackThread> t = mAudioTrackThread;
655 if (status == NO_ERROR) {
656 if (t != 0) {
657 if (previousState == STATE_STOPPING) {
658 mProxy->interrupt();
659 } else {
660 t->resume();
661 }
662 } else {
663 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
664 get_sched_policy(0, &mPreviousSchedulingGroup);
665 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
666 }
Andy Hung39399b62017-04-21 15:07:45 -0700667
668 // Start our local VolumeHandler for restoration purposes.
669 mVolumeHandler->setStarted();
Andy Hung79629f02016-03-24 13:57:40 -0700670 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800671 ALOGE("start() status %d", status);
672 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800673 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100674 if (previousState != STATE_STOPPING) {
675 t->pause();
676 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800677 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700678 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700679 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800680 }
681 }
682
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100683 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800684}
685
686void AudioTrack::stop()
687{
688 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700689 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800690 return;
691 }
692
Glenn Kasten23a75452014-01-13 10:37:17 -0800693 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100694 mState = STATE_STOPPING;
695 } else {
696 mState = STATE_STOPPED;
Andy Hung2148bf02016-11-28 19:01:02 -0800697 ALOGD_IF(mSharedBuffer == nullptr,
698 "stop() called with %u frames delivered", mReleased.value());
Andy Hungc2813e52014-10-16 17:54:34 -0700699 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100700 }
701
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800702 mProxy->interrupt();
703 mAudioTrack->stop();
Andy Hung61be8412015-10-06 10:51:09 -0700704
705 // Note: legacy handling - stop does not clear playback marker
706 // and periodic update counter, but flush does for streaming tracks.
Andy Hung9b461582014-12-01 17:56:29 -0800707
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800708 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800709 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800710 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
711 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800712 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100713
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800714 sp<AudioTrackThread> t = mAudioTrackThread;
715 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800716 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100717 t->pause();
718 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800719 } else {
720 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
721 set_sched_policy(0, mPreviousSchedulingGroup);
722 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800723}
724
725bool AudioTrack::stopped() const
726{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800727 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800728 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800729}
730
731void AudioTrack::flush()
732{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800733 if (mSharedBuffer != 0) {
734 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800735 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800736 AutoMutex lock(mLock);
737 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
738 return;
739 }
740 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800741}
742
Eric Laurent1703cdf2011-03-07 14:52:59 -0800743void AudioTrack::flush_l()
744{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800745 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700746
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700747 // clear playback marker and periodic update counter
748 mMarkerPosition = 0;
749 mMarkerReached = false;
750 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100751 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700752
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800753 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700754 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800755 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100756 mProxy->interrupt();
757 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800758 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800759 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800760}
761
762void AudioTrack::pause()
763{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800764 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100765 if (mState == STATE_ACTIVE) {
766 mState = STATE_PAUSED;
767 } else if (mState == STATE_STOPPING) {
768 mState = STATE_PAUSED_STOPPING;
769 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800770 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800771 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800772 mProxy->interrupt();
773 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800774
Marco Nelissen3a90f282014-03-10 11:21:43 -0700775 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700776 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700777 // An offload output can be re-used between two audio tracks having
778 // the same configuration. A timestamp query for a paused track
779 // while the other is running would return an incorrect time.
780 // To fix this, cache the playback position on a pause() and return
781 // this time when requested until the track is resumed.
782
783 // OffloadThread sends HAL pause in its threadLoop. Time saved
784 // here can be slightly off.
785
786 // TODO: check return code for getRenderPosition.
787
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800788 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800789 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
790 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
791 }
792 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800793}
794
Eric Laurentbe916aa2010-06-01 23:49:17 -0700795status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800796{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700797 // This duplicates a test by AudioTrack JNI, but that is not the only caller
798 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
799 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700800 return BAD_VALUE;
801 }
802
Eric Laurent1703cdf2011-03-07 14:52:59 -0800803 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800804 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
805 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800806
Glenn Kastenc56f3422014-03-21 17:53:17 -0700807 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700808
Glenn Kasten23a75452014-01-13 10:37:17 -0800809 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700810 mAudioTrack->signal();
811 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700812 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800813}
814
Glenn Kastenb1c09932012-02-27 16:21:04 -0800815status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800816{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800817 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700818}
819
Eric Laurent2beeb502010-07-16 07:43:46 -0700820status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700821{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700822 // This duplicates a test by AudioTrack JNI, but that is not the only caller
823 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700824 return BAD_VALUE;
825 }
826
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800827 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700828 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800829 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700830
831 return NO_ERROR;
832}
833
Glenn Kastena5224f32012-01-04 12:41:44 -0800834void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700835{
836 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800837 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700838 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800839}
840
Glenn Kasten3b16c762012-11-14 08:44:39 -0800841status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800842{
Andy Hung5cbb5782015-03-27 18:39:59 -0700843 AutoMutex lock(mLock);
844 if (rate == mSampleRate) {
845 return NO_ERROR;
846 }
Glenn Kastend79072e2016-01-06 08:41:20 -0800847 if (isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800848 return INVALID_OPERATION;
849 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800850 if (mOutput == AUDIO_IO_HANDLE_NONE) {
851 return NO_INIT;
852 }
Andy Hung5cbb5782015-03-27 18:39:59 -0700853 // NOTE: it is theoretically possible, but highly unlikely, that a device change
854 // could mean a previously allowed sampling rate is no longer allowed.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800855 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800856 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700857 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800858 }
Andy Hung26145642015-04-15 21:56:53 -0700859 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700860 const uint32_t effectiveSampleRate = adjustSampleRate(rate, mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -0700861 if (rate == 0 || effectiveSampleRate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700862 return BAD_VALUE;
863 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700864 // TODO: Should we also check if the buffer size is compatible?
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800865
Glenn Kastene3aa6592012-12-04 12:22:46 -0800866 mSampleRate = rate;
Andy Hung26145642015-04-15 21:56:53 -0700867 mProxy->setSampleRate(effectiveSampleRate);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800868
Eric Laurent57326622009-07-07 07:10:45 -0700869 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800870}
871
Glenn Kastena5224f32012-01-04 12:41:44 -0800872uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800873{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800874 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700875
876 // sample rate can be updated during playback by the offloaded decoder so we need to
877 // query the HAL and update if needed.
878// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700879 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700880 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700881 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700882 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700883 if (status == NO_ERROR) {
884 mSampleRate = sampleRate;
885 }
886 }
887 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800888 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800889}
890
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700891uint32_t AudioTrack::getOriginalSampleRate() const
892{
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700893 return mOriginalSampleRate;
894}
895
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700896status_t AudioTrack::setPlaybackRate(const AudioPlaybackRate &playbackRate)
Andy Hung8edb8dc2015-03-26 19:13:55 -0700897{
Andy Hung8edb8dc2015-03-26 19:13:55 -0700898 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700899 if (isAudioPlaybackRateEqual(playbackRate, mPlaybackRate)) {
Andy Hung8edb8dc2015-03-26 19:13:55 -0700900 return NO_ERROR;
901 }
Glenn Kastend79072e2016-01-06 08:41:20 -0800902 if (isOffloadedOrDirect_l()) {
Andy Hung8edb8dc2015-03-26 19:13:55 -0700903 return INVALID_OPERATION;
904 }
905 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
906 return INVALID_OPERATION;
907 }
Andy Hungff874dc2016-04-11 16:49:09 -0700908
909 ALOGV("setPlaybackRate (input): mSampleRate:%u mSpeed:%f mPitch:%f",
910 mSampleRate, playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -0700911 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700912 const uint32_t effectiveRate = adjustSampleRate(mSampleRate, playbackRate.mPitch);
913 const float effectiveSpeed = adjustSpeed(playbackRate.mSpeed, playbackRate.mPitch);
914 const float effectivePitch = adjustPitch(playbackRate.mPitch);
Ricardo Garcia6c7f0622015-04-30 18:39:16 -0700915 AudioPlaybackRate playbackRateTemp = playbackRate;
916 playbackRateTemp.mSpeed = effectiveSpeed;
917 playbackRateTemp.mPitch = effectivePitch;
918
Andy Hungff874dc2016-04-11 16:49:09 -0700919 ALOGV("setPlaybackRate (effective): mSampleRate:%u mSpeed:%f mPitch:%f",
920 effectiveRate, effectiveSpeed, effectivePitch);
921
Ricardo Garcia6c7f0622015-04-30 18:39:16 -0700922 if (!isAudioPlaybackRateValid(playbackRateTemp)) {
Kevin Rocard4e728d42017-04-06 18:00:40 -0700923 ALOGW("setPlaybackRate(%f, %f) failed (effective rate out of bounds)",
Andy Hungff874dc2016-04-11 16:49:09 -0700924 playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -0700925 return BAD_VALUE;
926 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700927 // Check if the buffer size is compatible.
Andy Hung26145642015-04-15 21:56:53 -0700928 if (!isSampleRateSpeedAllowed_l(effectiveRate, effectiveSpeed)) {
Kevin Rocard4e728d42017-04-06 18:00:40 -0700929 ALOGW("setPlaybackRate(%f, %f) failed (buffer size)",
Andy Hungff874dc2016-04-11 16:49:09 -0700930 playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung8edb8dc2015-03-26 19:13:55 -0700931 return BAD_VALUE;
932 }
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700933
Ricardo Garcia6c7f0622015-04-30 18:39:16 -0700934 // Check resampler ratios are within bounds
Glenn Kastend3bb6452016-12-05 18:14:37 -0800935 if ((uint64_t)effectiveRate > (uint64_t)mSampleRate *
936 (uint64_t)AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Kevin Rocard4e728d42017-04-06 18:00:40 -0700937 ALOGW("setPlaybackRate(%f, %f) failed. Resample rate exceeds max accepted value",
Ricardo Garcia6c7f0622015-04-30 18:39:16 -0700938 playbackRate.mSpeed, playbackRate.mPitch);
939 return BAD_VALUE;
940 }
941
Dan Austine34eae22015-10-27 16:14:52 -0700942 if ((uint64_t)effectiveRate * (uint64_t)AUDIO_RESAMPLER_UP_RATIO_MAX < (uint64_t)mSampleRate) {
Kevin Rocard4e728d42017-04-06 18:00:40 -0700943 ALOGW("setPlaybackRate(%f, %f) failed. Resample rate below min accepted value",
Ricardo Garcia6c7f0622015-04-30 18:39:16 -0700944 playbackRate.mSpeed, playbackRate.mPitch);
945 return BAD_VALUE;
946 }
947 mPlaybackRate = playbackRate;
948 //set effective rates
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700949 mProxy->setPlaybackRate(playbackRateTemp);
Andy Hung26145642015-04-15 21:56:53 -0700950 mProxy->setSampleRate(effectiveRate); // FIXME: not quite "atomic" with setPlaybackRate
Andy Hung8edb8dc2015-03-26 19:13:55 -0700951 return NO_ERROR;
952}
953
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700954const AudioPlaybackRate& AudioTrack::getPlaybackRate() const
Andy Hung8edb8dc2015-03-26 19:13:55 -0700955{
956 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700957 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700958}
959
Phil Burkc0adecb2016-01-08 12:44:11 -0800960ssize_t AudioTrack::getBufferSizeInFrames()
961{
962 AutoMutex lock(mLock);
963 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
964 return NO_INIT;
965 }
Phil Burke8972b02016-03-04 11:29:57 -0800966 return (ssize_t) mProxy->getBufferSizeInFrames();
Phil Burkc0adecb2016-01-08 12:44:11 -0800967}
968
Andy Hungf2c87b32016-04-07 19:49:29 -0700969status_t AudioTrack::getBufferDurationInUs(int64_t *duration)
970{
971 if (duration == nullptr) {
972 return BAD_VALUE;
973 }
974 AutoMutex lock(mLock);
975 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
976 return NO_INIT;
977 }
978 ssize_t bufferSizeInFrames = (ssize_t) mProxy->getBufferSizeInFrames();
979 if (bufferSizeInFrames < 0) {
980 return (status_t)bufferSizeInFrames;
981 }
982 *duration = (int64_t)((double)bufferSizeInFrames * 1000000
983 / ((double)mSampleRate * mPlaybackRate.mSpeed));
984 return NO_ERROR;
985}
986
Phil Burkc0adecb2016-01-08 12:44:11 -0800987ssize_t AudioTrack::setBufferSizeInFrames(size_t bufferSizeInFrames)
988{
989 AutoMutex lock(mLock);
990 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
991 return NO_INIT;
992 }
993 // Reject if timed track or compressed audio.
Glenn Kastend79072e2016-01-06 08:41:20 -0800994 if (!audio_is_linear_pcm(mFormat)) {
Phil Burkc0adecb2016-01-08 12:44:11 -0800995 return INVALID_OPERATION;
996 }
Phil Burke8972b02016-03-04 11:29:57 -0800997 return (ssize_t) mProxy->setBufferSizeInFrames((uint32_t) bufferSizeInFrames);
Phil Burkc0adecb2016-01-08 12:44:11 -0800998}
999
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001000status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
1001{
Glenn Kastend79072e2016-01-06 08:41:20 -08001002 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -08001003 return INVALID_OPERATION;
1004 }
1005
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001006 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001007 ;
1008 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
1009 loopEnd - loopStart >= MIN_LOOP) {
1010 ;
1011 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001012 return BAD_VALUE;
1013 }
1014
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001015 AutoMutex lock(mLock);
1016 // See setPosition() regarding setting parameters such as loop points or position while active
1017 if (mState == STATE_ACTIVE) {
1018 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001019 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001020 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001021 return NO_ERROR;
1022}
1023
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001024void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
1025{
Andy Hung4ede21d2014-12-12 15:37:34 -08001026 // We do not update the periodic notification point.
1027 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
1028 mLoopCount = loopCount;
1029 mLoopEnd = loopEnd;
1030 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -08001031 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001032 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -08001033
1034 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001035}
1036
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001037status_t AudioTrack::setMarkerPosition(uint32_t marker)
1038{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001039 // The only purpose of setting marker position 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);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001045 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -07001046 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -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::getMarkerPosition(uint32_t *marker) 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 (marker == 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);
Andy Hung90e8a972015-11-09 16:42:40 -08001065 mMarkerPosition.getValue(marker);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001066
1067 return NO_ERROR;
1068}
1069
1070status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
1071{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001072 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -07001073 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001074 return INVALID_OPERATION;
1075 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001076
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001077 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001078 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001079 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -08001080
Andy Hung3c09c782014-12-29 18:39:32 -08001081 sp<AudioTrackThread> t = mAudioTrackThread;
1082 if (t != 0) {
1083 t->wake();
1084 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001085 return NO_ERROR;
1086}
1087
Glenn Kastena5224f32012-01-04 12:41:44 -08001088status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001089{
Eric Laurentab5cdba2014-06-09 17:22:27 -07001090 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001091 return INVALID_OPERATION;
1092 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001093 if (updatePeriod == NULL) {
1094 return BAD_VALUE;
1095 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001096
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001097 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001098 *updatePeriod = mUpdatePeriod;
1099
1100 return NO_ERROR;
1101}
1102
1103status_t AudioTrack::setPosition(uint32_t position)
1104{
Glenn Kastend79072e2016-01-06 08:41:20 -08001105 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001106 return INVALID_OPERATION;
1107 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001108 if (position > mFrameCount) {
1109 return BAD_VALUE;
1110 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001111
Eric Laurent1703cdf2011-03-07 14:52:59 -08001112 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001113 // Currently we require that the player is inactive before setting parameters such as position
1114 // or loop points. Otherwise, there could be a race condition: the application could read the
1115 // current position, compute a new position or loop parameters, and then set that position or
1116 // loop parameters but it would do the "wrong" thing since the position has continued to advance
1117 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
1118 // to specify how it wants to handle such scenarios.
1119 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001120 return INVALID_OPERATION;
1121 }
Andy Hung9b461582014-12-01 17:56:29 -08001122 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -07001123 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -08001124 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -08001125
1126 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001127 return NO_ERROR;
1128}
1129
Glenn Kasten200092b2014-08-15 15:13:30 -07001130status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001131{
Glenn Kastend65d73c2012-06-22 17:21:07 -07001132 if (position == NULL) {
1133 return BAD_VALUE;
1134 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001135
Eric Laurent1703cdf2011-03-07 14:52:59 -08001136 AutoMutex lock(mLock);
Andy Hung7a490e72016-03-23 15:58:10 -07001137 // FIXME: offloaded and direct tracks call into the HAL for render positions
1138 // for compressed/synced data; however, we use proxy position for pure linear pcm data
1139 // as we do not know the capability of the HAL for pcm position support and standby.
1140 // There may be some latency differences between the HAL position and the proxy position.
1141 if (isOffloadedOrDirect_l() && !isPurePcmData_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001142 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001143
Eric Laurentab5cdba2014-06-09 17:22:27 -07001144 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -08001145 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
1146 *position = mPausedPosition;
1147 return NO_ERROR;
1148 }
1149
Glenn Kasten142f5192014-03-25 17:44:59 -07001150 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung1f1db832015-06-08 13:26:10 -07001151 uint32_t halFrames; // actually unused
1152 (void) AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
1153 // FIXME: on getRenderPosition() error, we return OK with frame position 0.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001154 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001155 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
1156 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001157 *position = dspFrames;
1158 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -08001159 if (mCblk->mFlags & CBLK_INVALID) {
Andy Hung1f1db832015-06-08 13:26:10 -07001160 (void) restoreTrack_l("getPosition");
1161 // FIXME: for compatibility with the Java API we ignore the restoreTrack_l()
1162 // error here (e.g. DEAD_OBJECT) and return OK with the last recorded server position.
Eric Laurent275e8e92014-11-30 15:14:47 -08001163 }
1164
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001165 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -07001166 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
Andy Hung90e8a972015-11-09 16:42:40 -08001167 0 : updateAndGetPosition_l().value();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001168 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001169 return NO_ERROR;
1170}
1171
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001172status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001173{
Glenn Kastend79072e2016-01-06 08:41:20 -08001174 if (mSharedBuffer == 0) {
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001175 return INVALID_OPERATION;
1176 }
1177 if (position == NULL) {
1178 return BAD_VALUE;
1179 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001180
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001181 AutoMutex lock(mLock);
1182 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001183 return NO_ERROR;
1184}
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001185
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001186status_t AudioTrack::reload()
1187{
Glenn Kastend79072e2016-01-06 08:41:20 -08001188 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -08001189 return INVALID_OPERATION;
1190 }
1191
Eric Laurent1703cdf2011-03-07 14:52:59 -08001192 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001193 // See setPosition() regarding setting parameters such as loop points or position while active
1194 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001195 return INVALID_OPERATION;
1196 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001197 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -08001198 (void) updateAndGetPosition_l();
1199 mPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -07001200 mPreviousTimestampValid = false;
Andy Hung53c3b5f2014-12-15 16:42:05 -08001201#if 0
Andy Hung9b461582014-12-01 17:56:29 -08001202 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -08001203 // of loop count. Historically we have not restored loop count, start, end,
1204 // but it makes sense if one desires to repeat playing a particular sound.
1205 if (mLoopCount != 0) {
1206 mLoopCountNotified = mLoopCount;
1207 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
1208 }
1209#endif
Andy Hung9b461582014-12-01 17:56:29 -08001210 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001211 return NO_ERROR;
1212}
1213
Glenn Kasten38e905b2014-01-13 10:21:48 -08001214audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -07001215{
Eric Laurent1703cdf2011-03-07 14:52:59 -08001216 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001217 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001218}
1219
Paul McLeanaa981192015-03-21 09:55:15 -07001220status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
1221 AutoMutex lock(mLock);
1222 if (mSelectedDeviceId != deviceId) {
1223 mSelectedDeviceId = deviceId;
Eric Laurentfb00fc72017-05-25 18:17:12 -07001224 if (mStatus == NO_ERROR) {
1225 android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
jiabin156c6872017-10-06 09:47:15 -07001226 mProxy->interrupt();
Eric Laurentfb00fc72017-05-25 18:17:12 -07001227 }
Paul McLeanaa981192015-03-21 09:55:15 -07001228 }
Eric Laurent493404d2015-04-21 15:07:36 -07001229 return NO_ERROR;
Paul McLeanaa981192015-03-21 09:55:15 -07001230}
1231
1232audio_port_handle_t AudioTrack::getOutputDevice() {
1233 AutoMutex lock(mLock);
1234 return mSelectedDeviceId;
1235}
1236
Eric Laurentad2e7b92017-09-14 20:06:42 -07001237// must be called with mLock held
1238void AudioTrack::updateRoutedDeviceId_l()
1239{
1240 // if the track is inactive, do not update actual device as the output stream maybe routed
1241 // to a device not relevant to this client because of other active use cases.
1242 if (mState != STATE_ACTIVE) {
1243 return;
1244 }
1245 if (mOutput != AUDIO_IO_HANDLE_NONE) {
1246 audio_port_handle_t deviceId = AudioSystem::getDeviceIdForIo(mOutput);
1247 if (deviceId != AUDIO_PORT_HANDLE_NONE) {
1248 mRoutedDeviceId = deviceId;
1249 }
1250 }
1251}
1252
Eric Laurent296fb132015-05-01 11:38:42 -07001253audio_port_handle_t AudioTrack::getRoutedDeviceId() {
1254 AutoMutex lock(mLock);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001255 updateRoutedDeviceId_l();
1256 return mRoutedDeviceId;
Eric Laurent296fb132015-05-01 11:38:42 -07001257}
1258
Eric Laurentbe916aa2010-06-01 23:49:17 -07001259status_t AudioTrack::attachAuxEffect(int effectId)
1260{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001261 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001262 status_t status = mAudioTrack->attachAuxEffect(effectId);
1263 if (status == NO_ERROR) {
1264 mAuxEffectId = effectId;
1265 }
1266 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -07001267}
1268
Eric Laurente83b55d2014-11-14 10:06:21 -08001269audio_stream_type_t AudioTrack::streamType() const
1270{
1271 if (mStreamType == AUDIO_STREAM_DEFAULT) {
1272 return audio_attributes_to_stream_type(&mAttributes);
1273 }
1274 return mStreamType;
1275}
1276
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001277uint32_t AudioTrack::latency()
1278{
1279 AutoMutex lock(mLock);
1280 updateLatency_l();
1281 return mLatency;
1282}
1283
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001284// -------------------------------------------------------------------------
1285
Eric Laurent1703cdf2011-03-07 14:52:59 -08001286// must be called with mLock held
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001287void AudioTrack::updateLatency_l()
1288{
1289 status_t status = AudioSystem::getLatency(mOutput, &mAfLatency);
1290 if (status != NO_ERROR) {
1291 ALOGW("getLatency(%d) failed status %d", mOutput, status);
1292 } else {
1293 // FIXME don't believe this lie
Andy Hung13969262017-09-11 17:24:21 -07001294 mLatency = mAfLatency + (1000LL * mFrameCount) / mSampleRate;
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001295 }
1296}
1297
Phil Burkadbb75a2017-06-16 12:19:42 -07001298// TODO Move this macro to a common header file for enum to string conversion in audio framework.
1299#define MEDIA_CASE_ENUM(name) case name: return #name
1300const char * AudioTrack::convertTransferToText(transfer_type transferType) {
1301 switch (transferType) {
1302 MEDIA_CASE_ENUM(TRANSFER_DEFAULT);
1303 MEDIA_CASE_ENUM(TRANSFER_CALLBACK);
1304 MEDIA_CASE_ENUM(TRANSFER_OBTAIN);
1305 MEDIA_CASE_ENUM(TRANSFER_SYNC);
1306 MEDIA_CASE_ENUM(TRANSFER_SHARED);
1307 default:
1308 return "UNRECOGNIZED";
1309 }
1310}
1311
Glenn Kasten200092b2014-08-15 15:13:30 -07001312status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001313{
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001314 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
1315 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001316 ALOGE("Could not get audioflinger");
1317 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001318 }
1319
Eric Laurente83b55d2014-11-14 10:06:21 -08001320 audio_io_handle_t output;
1321 audio_stream_type_t streamType = mStreamType;
1322 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001323 bool callbackAdded = false;
Eric Laurente83b55d2014-11-14 10:06:21 -08001324
Haynes Mathew Georgeae34ed22016-01-28 11:58:39 -08001325 // mFlags (not mOrigFlags) is modified depending on whether fast request is accepted.
1326 // After fast request is denied, we will request again if IAudioTrack is re-created.
1327
Paul McLeanaa981192015-03-21 09:55:15 -07001328 status_t status;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001329 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1330 config.sample_rate = mSampleRate;
1331 config.channel_mask = mChannelMask;
1332 config.format = mFormat;
1333 config.offload_info = mOffloadInfoCopy;
Eric Laurent9ae8c592017-06-22 17:17:09 -07001334 mRoutedDeviceId = mSelectedDeviceId;
Paul McLeanaa981192015-03-21 09:55:15 -07001335 status = AudioSystem::getOutputForAttr(attr, &output,
Glenn Kastend848eb42016-03-08 13:42:11 -08001336 mSessionId, &streamType, mClientUid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001337 &config,
Eric Laurent9ae8c592017-06-22 17:17:09 -07001338 mFlags, &mRoutedDeviceId, &mPortId);
Eric Laurente83b55d2014-11-14 10:06:21 -08001339
1340 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08001341 ALOGE("Could not get audio output for session %d, stream type %d, usage %d, sample rate %u,"
1342 " format %#x, channel mask %#x, flags %#x",
1343 mSessionId, streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask,
1344 mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001345 return BAD_VALUE;
1346 }
1347 {
1348 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
1349 // we must release it ourselves if anything goes wrong.
1350
Glenn Kastence8828a2013-09-16 18:07:38 -07001351 // Not all of these values are needed under all conditions, but it is easier to get them all
Andy Hung9f9e21e2015-05-31 21:45:36 -07001352 status = AudioSystem::getLatency(output, &mAfLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001353 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001354 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001355 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001356 }
Andy Hung9f9e21e2015-05-31 21:45:36 -07001357 ALOGV("createTrack_l() output %d afLatency %u", output, mAfLatency);
Eric Laurentd1b449a2010-05-14 03:26:45 -07001358
Andy Hung9f9e21e2015-05-31 21:45:36 -07001359 status = AudioSystem::getFrameCount(output, &mAfFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -07001360 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001361 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001362 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001363 }
1364
Glenn Kastenea38ee72016-04-18 11:08:01 -07001365 // TODO consider making this a member variable if there are other uses for it later
1366 size_t afFrameCountHAL;
1367 status = AudioSystem::getFrameCountHAL(output, &afFrameCountHAL);
1368 if (status != NO_ERROR) {
1369 ALOGE("getFrameCountHAL(output=%d) status %d", output, status);
1370 goto release;
1371 }
1372 ALOG_ASSERT(afFrameCountHAL > 0);
1373
Andy Hung9f9e21e2015-05-31 21:45:36 -07001374 status = AudioSystem::getSamplingRate(output, &mAfSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -07001375 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001376 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001377 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001378 }
Eric Laurent0d6db582014-11-12 18:39:44 -08001379 if (mSampleRate == 0) {
Andy Hung9f9e21e2015-05-31 21:45:36 -07001380 mSampleRate = mAfSampleRate;
1381 mOriginalSampleRate = mAfSampleRate;
Eric Laurent0d6db582014-11-12 18:39:44 -08001382 }
Glenn Kasten7fd04222016-02-02 12:38:16 -08001383
Glenn Kastend79072e2016-01-06 08:41:20 -08001384 // Client can only express a preference for FAST. Server will perform additional tests.
Phil Burk33ff89b2015-11-30 11:16:01 -08001385 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Phil Burkadbb75a2017-06-16 12:19:42 -07001386 // either of these use cases:
1387 // use case 1: shared buffer
1388 bool sharedBuffer = mSharedBuffer != 0;
1389 bool transferAllowed =
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001390 // use case 2: callback transfer mode
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001391 (mTransfer == TRANSFER_CALLBACK) ||
1392 // use case 3: obtain/release mode
Phil Burk33ff89b2015-11-30 11:16:01 -08001393 (mTransfer == TRANSFER_OBTAIN) ||
1394 // use case 4: synchronous write
1395 ((mTransfer == TRANSFER_SYNC) && mThreadCanCallJava);
Phil Burkadbb75a2017-06-16 12:19:42 -07001396
1397 bool useCaseAllowed = sharedBuffer || transferAllowed;
1398 if (!useCaseAllowed) {
Glenn Kasten9bf34d52017-10-24 14:26:23 -07001399 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client, not shared buffer and transfer = %s",
Phil Burkadbb75a2017-06-16 12:19:42 -07001400 convertTransferToText(mTransfer));
1401 }
1402
Phil Burk33ff89b2015-11-30 11:16:01 -08001403 // sample rates must also match
Phil Burkadbb75a2017-06-16 12:19:42 -07001404 bool sampleRateAllowed = mSampleRate == mAfSampleRate;
1405 if (!sampleRateAllowed) {
Glenn Kasten9bf34d52017-10-24 14:26:23 -07001406 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client, sample rate %u Hz but HAL needs %u Hz",
Phil Burkadbb75a2017-06-16 12:19:42 -07001407 mSampleRate, mAfSampleRate);
1408 }
1409
1410 bool fastAllowed = useCaseAllowed && sampleRateAllowed;
Phil Burk33ff89b2015-11-30 11:16:01 -08001411 if (!fastAllowed) {
Phil Burk33ff89b2015-11-30 11:16:01 -08001412 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1413 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001414 }
1415
Eric Laurentd1b449a2010-05-14 03:26:45 -07001416 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001417
Glenn Kasten363fb752014-01-15 12:27:31 -08001418 size_t frameCount = mReqFrameCount;
Phil Burkfdb3c072016-02-09 10:47:02 -08001419 if (!audio_has_proportional_frames(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001420
Glenn Kasten363fb752014-01-15 12:27:31 -08001421 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001422 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001423 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001424 } else if (frameCount == 0) {
Andy Hung9f9e21e2015-05-31 21:45:36 -07001425 frameCount = mAfFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001426 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001427 if (mNotificationFramesAct != frameCount) {
1428 mNotificationFramesAct = frameCount;
1429 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001430 } else if (mSharedBuffer != 0) {
Andy Hungabdb9902015-01-12 15:08:22 -08001431 // FIXME: Ensure client side memory buffers need
1432 // not have additional alignment beyond sample
1433 // (e.g. 16 bit stereo accessed as 32 bit frame).
1434 size_t alignment = audio_bytes_per_sample(mFormat);
Glenn Kastenb7730382014-04-30 15:50:31 -07001435 if (alignment & 1) {
Andy Hungabdb9902015-01-12 15:08:22 -08001436 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
Glenn Kastenb7730382014-04-30 15:50:31 -07001437 alignment = 1;
1438 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001439 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001440 // More than 2 channels does not require stronger alignment than stereo
1441 alignment <<= 1;
1442 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001443 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001444 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001445 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001446 status = BAD_VALUE;
1447 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001448 }
1449
1450 // When initializing a shared buffer AudioTrack via constructors,
1451 // there's no frameCount parameter.
1452 // But when initializing a shared buffer AudioTrack via set(),
1453 // there _is_ a frameCount parameter. We silently ignore it.
Andy Hungabdb9902015-01-12 15:08:22 -08001454 frameCount = mSharedBuffer->size() / mFrameSize;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001455 } else {
Glenn Kastenea38ee72016-04-18 11:08:01 -07001456 size_t minFrameCount = 0;
1457 // For fast tracks the frame count calculations and checks are mostly done by server,
1458 // but we try to respect the application's request for notifications per buffer.
1459 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1460 if (mNotificationsPerBufferReq > 0) {
1461 // Avoid possible arithmetic overflow during multiplication.
1462 // mNotificationsPerBuffer is clamped to a small integer earlier, so it is unlikely.
1463 if (mNotificationsPerBufferReq > SIZE_MAX / afFrameCountHAL) {
1464 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
1465 mNotificationsPerBufferReq, afFrameCountHAL);
1466 } else {
1467 minFrameCount = afFrameCountHAL * mNotificationsPerBufferReq;
1468 }
1469 }
1470 } else {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001471 // for normal tracks precompute the frame count based on speed.
Andy Hungff874dc2016-04-11 16:49:09 -07001472 const float speed = !isPurePcmData_l() || isOffloadedOrDirect_l() ? 1.0f :
1473 max(mMaxRequiredSpeed, mPlaybackRate.mSpeed);
Glenn Kastenea38ee72016-04-18 11:08:01 -07001474 minFrameCount = calculateMinFrameCount(
Andy Hung9f9e21e2015-05-31 21:45:36 -07001475 mAfLatency, mAfFrameCount, mAfSampleRate, mSampleRate,
Glenn Kastenea38ee72016-04-18 11:08:01 -07001476 speed /*, 0 mNotificationsPerBufferReq*/);
1477 }
1478 if (frameCount < minFrameCount) {
1479 frameCount = minFrameCount;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001480 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001481 }
1482
Eric Laurent05067782016-06-01 18:27:28 -07001483 audio_output_flags_t flags = mFlags;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001484
1485 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001486 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten47d55172017-05-23 11:19:30 -07001487 // It is currently meaningless to request SCHED_FIFO for a Java thread. Even if the
1488 // application-level code follows all non-blocking design rules, the language runtime
1489 // doesn't also follow those rules, so the thread will not benefit overall.
Phil Burk33ff89b2015-11-30 11:16:01 -08001490 if (mAudioTrackThread != 0 && !mThreadCanCallJava) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08001491 tid = mAudioTrackThread->getTid();
1492 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001493 }
1494
Glenn Kasten74935e42013-12-19 08:56:45 -08001495 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1496 // but we will still need the original value also
Glenn Kastend848eb42016-03-08 13:42:11 -08001497 audio_session_t originalSessionId = mSessionId;
Eric Laurente83b55d2014-11-14 10:06:21 -08001498 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001499 mSampleRate,
Andy Hungabdb9902015-01-12 15:08:22 -08001500 mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001501 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001502 &temp,
Eric Laurent05067782016-06-01 18:27:28 -07001503 &flags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001504 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001505 output,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001506 mClientPid,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001507 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001508 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001509 mClientUid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001510 &status,
1511 mPortId);
Glenn Kasten138d6f92015-03-20 10:54:51 -07001512 ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
1513 "session ID changed from %d to %d", originalSessionId, mSessionId);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001514
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001515 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001516 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001517 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001518 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001519 ALOG_ASSERT(track != 0);
1520
Glenn Kasten38e905b2014-01-13 10:21:48 -08001521 // AudioFlinger now owns the reference to the I/O handle,
1522 // so we are no longer responsible for releasing it.
1523
Glenn Kasten7fd04222016-02-02 12:38:16 -08001524 // FIXME compare to AudioRecord
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001525 sp<IMemory> iMem = track->getCblk();
1526 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001527 ALOGE("Could not get control block");
Eric Laurentad2e7b92017-09-14 20:06:42 -07001528 status = NO_INIT;
1529 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001530 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001531 void *iMemPointer = iMem->pointer();
1532 if (iMemPointer == NULL) {
1533 ALOGE("Could not get control block pointer");
Eric Laurentad2e7b92017-09-14 20:06:42 -07001534 status = NO_INIT;
1535 goto release;
Glenn Kasten0cde0762014-01-16 15:06:36 -08001536 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001537 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001538 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001539 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001540 mDeathNotifier.clear();
1541 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001542 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001543 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001544 IPCThreadState::self()->flushCommands();
1545
Glenn Kasten0cde0762014-01-16 15:06:36 -08001546 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001547 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001548 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001549 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1550 // In current design, AudioTrack client checks and ensures frame count validity before
1551 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1552 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001553 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001554 }
1555 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001556
Glenn Kastena07f17c2013-04-23 12:39:37 -07001557 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001558 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent05067782016-06-01 18:27:28 -07001559 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten6d8018f2017-02-21 13:05:56 -08001560 ALOGI("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu -> %zu", frameCount, temp);
Phil Burk33ff89b2015-11-30 11:16:01 -08001561 if (!mThreadCanCallJava) {
1562 mAwaitBoost = true;
1563 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001564 } else {
Glenn Kasten6d8018f2017-02-21 13:05:56 -08001565 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu -> %zu", frameCount,
1566 temp);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001567 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001568 }
Eric Laurent05067782016-06-01 18:27:28 -07001569 mFlags = flags;
Glenn Kasten7fd04222016-02-02 12:38:16 -08001570
1571 // Make sure that application is notified with sufficient margin before underrun.
Glenn Kastenea38ee72016-04-18 11:08:01 -07001572 // The client can divide the AudioTrack buffer into sub-buffers,
1573 // and expresses its desire to server as the notification frame count.
Andy Hung0e48d252015-01-26 11:43:15 -08001574 if (mSharedBuffer == 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kastenea38ee72016-04-18 11:08:01 -07001575 size_t maxNotificationFrames;
Eric Laurent05067782016-06-01 18:27:28 -07001576 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastenea38ee72016-04-18 11:08:01 -07001577 // notify every HAL buffer, regardless of the size of the track buffer
1578 maxNotificationFrames = afFrameCountHAL;
1579 } else {
Glenn Kastenaebe9dc2016-05-02 14:38:21 -07001580 // For normal tracks, use at least double-buffering if no sample rate conversion,
1581 // or at least triple-buffering if there is sample rate conversion
1582 const int nBuffering = mOriginalSampleRate == mAfSampleRate ? 2 : 3;
Glenn Kastenea38ee72016-04-18 11:08:01 -07001583 maxNotificationFrames = frameCount / nBuffering;
Glenn Kasten9bf34d52017-10-24 14:26:23 -07001584 // If client requested a fast track but this was denied, then use the smaller maximum.
1585 // FMS_20 is the minimum task wakeup period in ms for which CFS operates reliably.
1586#define FMS_20 20 // FIXME share a common declaration with the same symbol in Threads.cpp
1587 if (mOrigFlags & AUDIO_OUTPUT_FLAG_FAST) {
1588 size_t maxNotificationFramesFastDenied = FMS_20 * mSampleRate / 1000;
1589 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
1590 maxNotificationFrames = maxNotificationFramesFastDenied;
1591 }
1592 }
Glenn Kasten7fd04222016-02-02 12:38:16 -08001593 }
1594 if (mNotificationFramesAct == 0 || mNotificationFramesAct > maxNotificationFrames) {
Glenn Kastenea38ee72016-04-18 11:08:01 -07001595 if (mNotificationFramesAct == 0) {
1596 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
1597 maxNotificationFrames, frameCount);
1598 } else {
1599 ALOGW("Client adjusted notificationFrames from %u to %zu for frameCount %zu",
Glenn Kasten7fd04222016-02-02 12:38:16 -08001600 mNotificationFramesAct, maxNotificationFrames, frameCount);
Glenn Kastenea38ee72016-04-18 11:08:01 -07001601 }
Glenn Kasten7fd04222016-02-02 12:38:16 -08001602 mNotificationFramesAct = (uint32_t) maxNotificationFrames;
Andy Hung0e48d252015-01-26 11:43:15 -08001603 }
1604 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001605
Eric Laurentad2e7b92017-09-14 20:06:42 -07001606 //mOutput != output includes the case where mOutput == AUDIO_IO_HANDLE_NONE for first creation
1607 if (mDeviceCallback != 0 && mOutput != output) {
1608 if (mOutput != AUDIO_IO_HANDLE_NONE) {
1609 AudioSystem::removeAudioDeviceCallback(this, mOutput);
1610 }
1611 AudioSystem::addAudioDeviceCallback(this, output);
1612 callbackAdded = true;
1613 }
1614
Glenn Kasten38e905b2014-01-13 10:21:48 -08001615 // We retain a copy of the I/O handle, but don't own the reference
1616 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001617 mRefreshRemaining = true;
1618
1619 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1620 // is the value of pointer() for the shared buffer, otherwise buffers points
1621 // immediately after the control block. This address is for the mapping within client
1622 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1623 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001624 if (mSharedBuffer == 0) {
Glenn Kasten138d6f92015-03-20 10:54:51 -07001625 buffers = cblk + 1;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001626 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001627 buffers = mSharedBuffer->pointer();
Glenn Kasten138d6f92015-03-20 10:54:51 -07001628 if (buffers == NULL) {
1629 ALOGE("Could not get buffer pointer");
Eric Laurentad2e7b92017-09-14 20:06:42 -07001630 status = NO_INIT;
1631 goto release;
Glenn Kasten138d6f92015-03-20 10:54:51 -07001632 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001633 }
1634
Eric Laurent2beeb502010-07-16 07:43:46 -07001635 mAudioTrack->attachAuxEffect(mAuxEffectId);
Andreas Gampe0b86e572017-06-07 18:56:27 -07001636 mFrameCount = frameCount;
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001637 updateLatency_l(); // this refetches mAfLatency and sets mLatency
Glenn Kasten5f631512014-02-24 15:16:07 -08001638
Glenn Kasten093000f2012-05-03 09:35:36 -07001639 // If IAudioTrack is re-created, don't let the requested frameCount
1640 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001641 if (frameCount > mReqFrameCount) {
1642 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001643 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001644
Andy Hungd7bd69e2015-07-24 07:52:41 -07001645 // reset server position to 0 as we have new cblk.
1646 mServer = 0;
1647
Glenn Kastene3aa6592012-12-04 12:22:46 -08001648 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001649 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001650 mStaticProxy.clear();
Andy Hungabdb9902015-01-12 15:08:22 -08001651 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001652 } else {
Andy Hungabdb9902015-01-12 15:08:22 -08001653 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001654 mProxy = mStaticProxy;
1655 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001656
1657 mProxy->setVolumeLR(gain_minifloat_pack(
1658 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1659 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1660
Glenn Kastene3aa6592012-12-04 12:22:46 -08001661 mProxy->setSendLevel(mSendLevel);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001662 const uint32_t effectiveSampleRate = adjustSampleRate(mSampleRate, mPlaybackRate.mPitch);
1663 const float effectiveSpeed = adjustSpeed(mPlaybackRate.mSpeed, mPlaybackRate.mPitch);
1664 const float effectivePitch = adjustPitch(mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001665 mProxy->setSampleRate(effectiveSampleRate);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001666
1667 AudioPlaybackRate playbackRateTemp = mPlaybackRate;
1668 playbackRateTemp.mSpeed = effectiveSpeed;
1669 playbackRateTemp.mPitch = effectivePitch;
1670 mProxy->setPlaybackRate(playbackRateTemp);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001671 mProxy->setMinimum(mNotificationFramesAct);
1672
1673 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001674 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001675
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001676 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001677 }
1678
1679release:
Glenn Kastend848eb42016-03-08 13:42:11 -08001680 AudioSystem::releaseOutput(output, streamType, mSessionId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001681 if (callbackAdded) {
1682 // note: mOutput is always valid is callbackAdded is true
1683 AudioSystem::removeAudioDeviceCallback(this, mOutput);
1684 }
Glenn Kasten38e905b2014-01-13 10:21:48 -08001685 if (status == NO_ERROR) {
1686 status = NO_INIT;
1687 }
1688 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001689}
1690
Glenn Kastenb46f3942015-03-09 12:00:30 -07001691status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001692{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001693 if (audioBuffer == NULL) {
Glenn Kasten551b5352015-03-20 11:30:28 -07001694 if (nonContig != NULL) {
1695 *nonContig = 0;
1696 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001697 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001698 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001699 if (mTransfer != TRANSFER_OBTAIN) {
1700 audioBuffer->frameCount = 0;
1701 audioBuffer->size = 0;
1702 audioBuffer->raw = NULL;
Glenn Kasten551b5352015-03-20 11:30:28 -07001703 if (nonContig != NULL) {
1704 *nonContig = 0;
1705 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001706 return INVALID_OPERATION;
1707 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001708
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001709 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001710 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001711 if (waitCount == -1) {
1712 requested = &ClientProxy::kForever;
1713 } else if (waitCount == 0) {
1714 requested = &ClientProxy::kNonBlocking;
1715 } else if (waitCount > 0) {
1716 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001717 timeout.tv_sec = ms / 1000;
1718 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1719 requested = &timeout;
1720 } else {
1721 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1722 requested = NULL;
1723 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001724 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001725}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001726
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001727status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1728 struct timespec *elapsed, size_t *nonContig)
1729{
1730 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1731 uint32_t oldSequence = 0;
1732 uint32_t newSequence;
1733
1734 Proxy::Buffer buffer;
1735 status_t status = NO_ERROR;
1736
1737 static const int32_t kMaxTries = 5;
1738 int32_t tryCounter = kMaxTries;
1739
1740 do {
1741 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1742 // keep them from going away if another thread re-creates the track during obtainBuffer()
1743 sp<AudioTrackClientProxy> proxy;
1744 sp<IMemory> iMem;
1745
1746 { // start of lock scope
1747 AutoMutex lock(mLock);
1748
1749 newSequence = mSequence;
1750 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1751 if (status == DEAD_OBJECT) {
1752 // re-create track, unless someone else has already done so
1753 if (newSequence == oldSequence) {
1754 status = restoreTrack_l("obtainBuffer");
1755 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001756 buffer.mFrameCount = 0;
1757 buffer.mRaw = NULL;
1758 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001759 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001760 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001761 }
1762 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001763 oldSequence = newSequence;
1764
Eric Laurent4d231dc2016-03-11 18:38:23 -08001765 if (status == NOT_ENOUGH_DATA) {
1766 restartIfDisabled();
1767 }
1768
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001769 // Keep the extra references
1770 proxy = mProxy;
1771 iMem = mCblkMemory;
1772
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001773 if (mState == STATE_STOPPING) {
1774 status = -EINTR;
1775 buffer.mFrameCount = 0;
1776 buffer.mRaw = NULL;
1777 buffer.mNonContig = 0;
1778 break;
1779 }
1780
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001781 // Non-blocking if track is stopped or paused
1782 if (mState != STATE_ACTIVE) {
1783 requested = &ClientProxy::kNonBlocking;
1784 }
1785
1786 } // end of lock scope
1787
1788 buffer.mFrameCount = audioBuffer->frameCount;
1789 // FIXME starts the requested timeout and elapsed over from scratch
1790 status = proxy->obtainBuffer(&buffer, requested, elapsed);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001791 } while (((status == DEAD_OBJECT) || (status == NOT_ENOUGH_DATA)) && (tryCounter-- > 0));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001792
1793 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001794 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001795 audioBuffer->raw = buffer.mRaw;
1796 if (nonContig != NULL) {
1797 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001798 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001799 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001800}
1801
Glenn Kasten54a8a452015-03-09 12:03:00 -07001802void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001803{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001804 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001805 if (mTransfer == TRANSFER_SHARED) {
1806 return;
1807 }
1808
Andy Hungabdb9902015-01-12 15:08:22 -08001809 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001810 if (stepCount == 0) {
1811 return;
1812 }
1813
1814 Proxy::Buffer buffer;
1815 buffer.mFrameCount = stepCount;
1816 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001817
Eric Laurent1703cdf2011-03-07 14:52:59 -08001818 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001819 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001820 mInUnderrun = false;
1821 mProxy->releaseBuffer(&buffer);
1822
1823 // restart track if it was disabled by audioflinger due to previous underrun
Eric Laurent4d231dc2016-03-11 18:38:23 -08001824 restartIfDisabled();
1825}
1826
1827void AudioTrack::restartIfDisabled()
1828{
1829 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1830 if ((mState == STATE_ACTIVE) && (flags & CBLK_DISABLED)) {
1831 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
1832 // FIXME ignoring status
1833 mAudioTrack->start();
Eric Laurentdf839842012-05-31 14:27:14 -07001834 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001835}
1836
1837// -------------------------------------------------------------------------
1838
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001839ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001840{
Glenn Kastend79072e2016-01-06 08:41:20 -08001841 if (mTransfer != TRANSFER_SYNC) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001842 return INVALID_OPERATION;
1843 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001844
Eric Laurentab5cdba2014-06-09 17:22:27 -07001845 if (isDirect()) {
1846 AutoMutex lock(mLock);
1847 int32_t flags = android_atomic_and(
1848 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1849 &mCblk->mFlags);
1850 if (flags & CBLK_INVALID) {
1851 return DEAD_OBJECT;
1852 }
1853 }
1854
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001855 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001856 // Sanity-check: user is most-likely passing an error code, and it would
1857 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001858 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001859 return BAD_VALUE;
1860 }
1861
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001862 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001863 Buffer audioBuffer;
1864
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001865 while (userSize >= mFrameSize) {
1866 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001867
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001868 status_t err = obtainBuffer(&audioBuffer,
1869 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001870 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001871 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001872 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001873 }
Glenn Kasten0a2f1512016-07-22 08:06:37 -07001874 if (err == TIMED_OUT || err == -EINTR) {
1875 err = WOULD_BLOCK;
1876 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001877 return ssize_t(err);
1878 }
1879
Glenn Kastenae4b8792015-03-20 09:04:21 -07001880 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08001881 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001882 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001883 userSize -= toWrite;
1884 written += toWrite;
1885
1886 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001887 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001888
Andy Hungea2b9c02016-02-12 17:06:53 -08001889 if (written > 0) {
1890 mFramesWritten += written / mFrameSize;
1891 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001892 return written;
1893}
1894
1895// -------------------------------------------------------------------------
1896
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001897nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001898{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001899 // Currently the AudioTrack thread is not created if there are no callbacks.
1900 // Would it ever make sense to run the thread, even without callbacks?
1901 // If so, then replace this by checks at each use for mCbf != NULL.
1902 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1903
Eric Laurent1703cdf2011-03-07 14:52:59 -08001904 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001905 if (mAwaitBoost) {
1906 mAwaitBoost = false;
1907 mLock.unlock();
1908 static const int32_t kMaxTries = 5;
1909 int32_t tryCounter = kMaxTries;
1910 uint32_t pollUs = 10000;
1911 do {
Glenn Kasten8255ba72016-08-23 13:54:23 -07001912 int policy = sched_getscheduler(0) & ~SCHED_RESET_ON_FORK;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001913 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1914 break;
1915 }
1916 usleep(pollUs);
1917 pollUs <<= 1;
1918 } while (tryCounter-- > 0);
1919 if (tryCounter < 0) {
1920 ALOGE("did not receive expected priority boost on time");
1921 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001922 // Run again immediately
1923 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001924 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001925
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001926 // Can only reference mCblk while locked
1927 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001928 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001929
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001930 // Check for track invalidation
1931 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001932 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1933 // AudioSystem cache. We should not exit here but after calling the callback so
1934 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001935 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Lajos Molnarf1063e22015-04-17 15:19:42 -07001936 status_t status __unused = restoreTrack_l("processAudioBuffer");
1937 // FIXME unused status
Andy Hung53c3b5f2014-12-15 16:42:05 -08001938 // after restoration, continue below to make sure that the loop and buffer events
1939 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001940 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001941 }
1942
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001943 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001944 bool active = mState == STATE_ACTIVE;
1945
1946 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1947 bool newUnderrun = false;
1948 if (flags & CBLK_UNDERRUN) {
1949#if 0
1950 // Currently in shared buffer mode, when the server reaches the end of buffer,
1951 // the track stays active in continuous underrun state. It's up to the application
1952 // to pause or stop the track, or set the position to a new offset within buffer.
1953 // This was some experimental code to auto-pause on underrun. Keeping it here
1954 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1955 if (mTransfer == TRANSFER_SHARED) {
1956 mState = STATE_PAUSED;
1957 active = false;
1958 }
1959#endif
1960 if (!mInUnderrun) {
1961 mInUnderrun = true;
1962 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001963 }
1964 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001965
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001966 // Get current position of server
Andy Hung90e8a972015-11-09 16:42:40 -08001967 Modulo<uint32_t> position(updateAndGetPosition_l());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001968
1969 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001970 bool markerReached = false;
Andy Hung90e8a972015-11-09 16:42:40 -08001971 Modulo<uint32_t> markerPosition(mMarkerPosition);
1972 // uses 32 bit wraparound for comparison with position.
1973 if (!mMarkerReached && markerPosition.value() > 0 && position >= markerPosition) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001974 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001975 }
1976
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001977 // Determine number of new position callback(s) that will be needed, while locked
1978 size_t newPosCount = 0;
Andy Hung90e8a972015-11-09 16:42:40 -08001979 Modulo<uint32_t> newPosition(mNewPosition);
1980 uint32_t updatePeriod = mUpdatePeriod;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001981 // FIXME fails for wraparound, need 64 bits
1982 if (updatePeriod > 0 && position >= newPosition) {
Andy Hung90e8a972015-11-09 16:42:40 -08001983 newPosCount = ((position - newPosition).value() / updatePeriod) + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001984 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001985 }
1986
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001987 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001988 uint32_t sampleRate = mSampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001989 float speed = mPlaybackRate.mSpeed;
Andy Hunga7f03352015-05-31 21:54:49 -07001990 const uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001991 if (mRefreshRemaining) {
1992 mRefreshRemaining = false;
1993 mRemainingFrames = notificationFrames;
1994 mRetryOnPartialBuffer = false;
1995 }
1996 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001997 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001998 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001999
Andy Hung53c3b5f2014-12-15 16:42:05 -08002000 // Determine the number of new loop callback(s) that will be needed, while locked.
2001 int loopCountNotifications = 0;
2002 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
2003
2004 if (mLoopCount > 0) {
2005 int loopCount;
2006 size_t bufferPosition;
2007 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
2008 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
2009 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
2010 mLoopCountNotified = loopCount; // discard any excess notifications
2011 } else if (mLoopCount < 0) {
2012 // FIXME: We're not accurate with notification count and position with infinite looping
2013 // since loopCount from server side will always return -1 (we could decrement it).
2014 size_t bufferPosition = mStaticProxy->getBufferPosition();
2015 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
2016 loopPeriod = mLoopEnd - bufferPosition;
2017 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
2018 size_t bufferPosition = mStaticProxy->getBufferPosition();
2019 loopPeriod = mFrameCount - bufferPosition;
2020 }
2021
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002022 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08002023 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002024 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
2025
2026 mLock.unlock();
2027
Andy Hunga7f03352015-05-31 21:54:49 -07002028 // get anchor time to account for callbacks.
2029 const nsecs_t timeBeforeCallbacks = systemTime();
2030
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002031 if (waitStreamEnd) {
Andy Hunga7f03352015-05-31 21:54:49 -07002032 // FIXME: Instead of blocking in proxy->waitStreamEndDone(), Callback thread
2033 // should wait on proxy futex and handle CBLK_STREAM_END_DONE within this function
2034 // (and make sure we don't callback for more data while we're stopping).
2035 // This helps with position, marker notifications, and track invalidation.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002036 struct timespec timeout;
2037 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
2038 timeout.tv_nsec = 0;
2039
Glenn Kasten96f04882013-09-20 09:28:56 -07002040 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002041 switch (status) {
2042 case NO_ERROR:
2043 case DEAD_OBJECT:
2044 case TIMED_OUT:
Andy Hung39609a02015-09-03 16:38:38 -07002045 if (status != DEAD_OBJECT) {
2046 // for DEAD_OBJECT, we do not send a EVENT_STREAM_END after stop();
2047 // instead, the application should handle the EVENT_NEW_IAUDIOTRACK.
2048 mCbf(EVENT_STREAM_END, mUserData, NULL);
2049 }
Glenn Kasten96f04882013-09-20 09:28:56 -07002050 {
2051 AutoMutex lock(mLock);
2052 // The previously assigned value of waitStreamEnd is no longer valid,
2053 // since the mutex has been unlocked and either the callback handler
2054 // or another thread could have re-started the AudioTrack during that time.
2055 waitStreamEnd = mState == STATE_STOPPING;
2056 if (waitStreamEnd) {
2057 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07002058 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002059 }
2060 }
Glenn Kasten96f04882013-09-20 09:28:56 -07002061 if (waitStreamEnd && status != DEAD_OBJECT) {
2062 return NS_INACTIVE;
2063 }
2064 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002065 }
Glenn Kasten96f04882013-09-20 09:28:56 -07002066 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002067 }
2068
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002069 // perform callbacks while unlocked
2070 if (newUnderrun) {
2071 mCbf(EVENT_UNDERRUN, mUserData, NULL);
2072 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08002073 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002074 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002075 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002076 }
2077 if (flags & CBLK_BUFFER_END) {
2078 mCbf(EVENT_BUFFER_END, mUserData, NULL);
2079 }
2080 if (markerReached) {
2081 mCbf(EVENT_MARKER, mUserData, &markerPosition);
2082 }
2083 while (newPosCount > 0) {
Andy Hung90e8a972015-11-09 16:42:40 -08002084 size_t temp = newPosition.value(); // FIXME size_t != uint32_t
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002085 mCbf(EVENT_NEW_POS, mUserData, &temp);
2086 newPosition += updatePeriod;
2087 newPosCount--;
2088 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002089
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002090 if (mObservedSequence != sequence) {
2091 mObservedSequence = sequence;
2092 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002093 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07002094 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002095 return NS_INACTIVE;
2096 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002097 }
2098
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002099 // if inactive, then don't run me again until re-started
2100 if (!active) {
2101 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07002102 }
2103
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002104 // Compute the estimated time until the next timed event (position, markers, loops)
2105 // FIXME only for non-compressed audio
2106 uint32_t minFrames = ~0;
2107 if (!markerReached && position < markerPosition) {
Andy Hung90e8a972015-11-09 16:42:40 -08002108 minFrames = (markerPosition - position).value();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002109 }
2110 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08002111 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002112 minFrames = loopPeriod;
2113 }
Andy Hung2d85f092015-01-07 12:45:13 -08002114 if (updatePeriod > 0) {
Andy Hung90e8a972015-11-09 16:42:40 -08002115 minFrames = min(minFrames, (newPosition - position).value());
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002116 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002117
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002118 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
2119 static const uint32_t kPoll = 0;
2120 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
2121 minFrames = kPoll * notificationFrames;
2122 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07002123
Andy Hunga7f03352015-05-31 21:54:49 -07002124 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
2125 static const nsecs_t kWaitPeriodNs = WAIT_PERIOD_MS * 1000000LL;
2126 const nsecs_t timeAfterCallbacks = systemTime();
2127
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002128 // Convert frame units to time units
2129 nsecs_t ns = NS_WHENEVER;
2130 if (minFrames != (uint32_t) ~0) {
jiabinc7bb8322017-09-06 18:20:11 -07002131 // AudioFlinger consumption of client data may be irregular when coming out of device
2132 // standby since the kernel buffers require filling. This is throttled to no more than 2x
2133 // the expected rate in the MixerThread. Hence, we reduce the estimated time to wait by one
2134 // half (but no more than half a second) to improve callback accuracy during these temporary
2135 // data surges.
2136 const nsecs_t estimatedNs = framesToNanoseconds(minFrames, sampleRate, speed);
2137 constexpr nsecs_t maxThrottleCompensationNs = 500000000LL;
2138 ns = estimatedNs - min(estimatedNs / 2, maxThrottleCompensationNs) + kWaitPeriodNs;
Andy Hunga7f03352015-05-31 21:54:49 -07002139 ns -= (timeAfterCallbacks - timeBeforeCallbacks); // account for callback time
2140 // TODO: Should we warn if the callback time is too long?
2141 if (ns < 0) ns = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002142 }
2143
2144 // If not supplying data by EVENT_MORE_DATA, then we're done
2145 if (mTransfer != TRANSFER_CALLBACK) {
2146 return ns;
2147 }
2148
Andy Hunga7f03352015-05-31 21:54:49 -07002149 // EVENT_MORE_DATA callback handling.
2150 // Timing for linear pcm audio data formats can be derived directly from the
2151 // buffer fill level.
2152 // Timing for compressed data is not directly available from the buffer fill level,
2153 // rather indirectly from waiting for blocking mode callbacks or waiting for obtain()
2154 // to return a certain fill level.
2155
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002156 struct timespec timeout;
2157 const struct timespec *requested = &ClientProxy::kForever;
2158 if (ns != NS_WHENEVER) {
2159 timeout.tv_sec = ns / 1000000000LL;
2160 timeout.tv_nsec = ns % 1000000000LL;
2161 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
2162 requested = &timeout;
2163 }
2164
Andy Hungea2b9c02016-02-12 17:06:53 -08002165 size_t writtenFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002166 while (mRemainingFrames > 0) {
2167
2168 Buffer audioBuffer;
2169 audioBuffer.frameCount = mRemainingFrames;
2170 size_t nonContig;
2171 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
2172 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002173 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002174 requested = &ClientProxy::kNonBlocking;
2175 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002176 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002177 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002178 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002179 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
2180 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten606fbc12015-10-22 15:28:15 -07002181 // FIXME bug 25195759
2182 return 1000000;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002183 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002184 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
2185 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002186 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002187
Phil Burkfdb3c072016-02-09 10:47:02 -08002188 if (mRetryOnPartialBuffer && audio_has_proportional_frames(mFormat)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002189 mRetryOnPartialBuffer = false;
2190 if (avail < mRemainingFrames) {
Andy Hunga7f03352015-05-31 21:54:49 -07002191 if (ns > 0) { // account for obtain time
2192 const nsecs_t timeNow = systemTime();
2193 ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2194 }
2195 nsecs_t myns = framesToNanoseconds(mRemainingFrames - avail, sampleRate, speed);
2196 if (ns < 0 /* NS_WHENEVER */ || myns < ns) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002197 ns = myns;
2198 }
2199 return ns;
2200 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07002201 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002202
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002203 size_t reqSize = audioBuffer.size;
2204 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002205 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002206
2207 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002208 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002209 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
2210 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002211 return NS_NEVER;
2212 }
2213
2214 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08002215 // The callback is done filling buffers
2216 // Keep this thread going to handle timed events and
2217 // still try to get more data in intervals of WAIT_PERIOD_MS
2218 // but don't just loop and block the CPU, so wait
Andy Hunga7f03352015-05-31 21:54:49 -07002219
2220 // mCbf(EVENT_MORE_DATA, ...) might either
2221 // (1) Block until it can fill the buffer, returning 0 size on EOS.
2222 // (2) Block until it can fill the buffer, returning 0 data (silence) on EOS.
2223 // (3) Return 0 size when no data is available, does not wait for more data.
2224 //
2225 // (1) and (2) occurs with AudioPlayer/AwesomePlayer; (3) occurs with NuPlayer.
2226 // We try to compute the wait time to avoid a tight sleep-wait cycle,
2227 // especially for case (3).
2228 //
2229 // The decision to support (1) and (2) affect the sizing of mRemainingFrames
2230 // and this loop; whereas for case (3) we could simply check once with the full
2231 // buffer size and skip the loop entirely.
2232
2233 nsecs_t myns;
Phil Burkfdb3c072016-02-09 10:47:02 -08002234 if (audio_has_proportional_frames(mFormat)) {
Andy Hunga7f03352015-05-31 21:54:49 -07002235 // time to wait based on buffer occupancy
2236 const nsecs_t datans = mRemainingFrames <= avail ? 0 :
2237 framesToNanoseconds(mRemainingFrames - avail, sampleRate, speed);
2238 // audio flinger thread buffer size (TODO: adjust for fast tracks)
Glenn Kastenea38ee72016-04-18 11:08:01 -07002239 // FIXME: use mAfFrameCountHAL instead of mAfFrameCount below for fast tracks.
Andy Hunga7f03352015-05-31 21:54:49 -07002240 const nsecs_t afns = framesToNanoseconds(mAfFrameCount, mAfSampleRate, speed);
2241 // add a half the AudioFlinger buffer time to avoid soaking CPU if datans is 0.
2242 myns = datans + (afns / 2);
2243 } else {
2244 // FIXME: This could ping quite a bit if the buffer isn't full.
2245 // Note that when mState is stopping we waitStreamEnd, so it never gets here.
2246 myns = kWaitPeriodNs;
2247 }
2248 if (ns > 0) { // account for obtain and callback time
2249 const nsecs_t timeNow = systemTime();
2250 ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2251 }
2252 if (ns < 0 /* NS_WHENEVER */ || myns < ns) {
2253 ns = myns;
2254 }
2255 return ns;
Glenn Kastend65d73c2012-06-22 17:21:07 -07002256 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002257
Glenn Kasten138d6f92015-03-20 10:54:51 -07002258 size_t releasedFrames = writtenSize / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002259 audioBuffer.frameCount = releasedFrames;
2260 mRemainingFrames -= releasedFrames;
2261 if (misalignment >= releasedFrames) {
2262 misalignment -= releasedFrames;
2263 } else {
2264 misalignment = 0;
2265 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002266
2267 releaseBuffer(&audioBuffer);
Andy Hungea2b9c02016-02-12 17:06:53 -08002268 writtenFrames += releasedFrames;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002269
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002270 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
2271 // if callback doesn't like to accept the full chunk
2272 if (writtenSize < reqSize) {
2273 continue;
2274 }
2275
2276 // There could be enough non-contiguous frames available to satisfy the remaining request
2277 if (mRemainingFrames <= nonContig) {
2278 continue;
2279 }
2280
2281#if 0
2282 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
2283 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
2284 // that total to a sum == notificationFrames.
2285 if (0 < misalignment && misalignment <= mRemainingFrames) {
2286 mRemainingFrames = misalignment;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002287 return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002288 }
2289#endif
2290
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002291 }
Andy Hungea2b9c02016-02-12 17:06:53 -08002292 if (writtenFrames > 0) {
2293 AutoMutex lock(mLock);
2294 mFramesWritten += writtenFrames;
2295 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002296 mRemainingFrames = notificationFrames;
2297 mRetryOnPartialBuffer = true;
2298
2299 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
2300 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002301}
2302
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002303status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08002304{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002305 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07002306 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002307 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002308
Glenn Kastena47f3162012-11-07 10:13:08 -08002309 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08002310 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08002311 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07002312
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002313 if (isOffloadedOrDirect_l() || mDoNotReconnect) {
Andy Hung1f1db832015-06-08 13:26:10 -07002314 // FIXME re-creation of offloaded and direct tracks is not yet implemented;
2315 // reconsider enabling for linear PCM encodings when position can be preserved.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002316 return DEAD_OBJECT;
2317 }
2318
Phil Burk2812d9e2016-01-04 10:34:30 -08002319 // Save so we can return count since creation.
2320 mUnderrunCountOffset = getUnderrunCount_l();
2321
Glenn Kasten200092b2014-08-15 15:13:30 -07002322 // save the old static buffer position
Andy Hungf20a4e92016-08-15 19:10:34 -07002323 uint32_t staticPosition = 0;
Andy Hung4ede21d2014-12-12 15:37:34 -08002324 size_t bufferPosition = 0;
2325 int loopCount = 0;
2326 if (mStaticProxy != 0) {
2327 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
Andy Hungf20a4e92016-08-15 19:10:34 -07002328 staticPosition = mStaticProxy->getPosition().unsignedValue();
Andy Hung4ede21d2014-12-12 15:37:34 -08002329 }
Glenn Kasten200092b2014-08-15 15:13:30 -07002330
Haynes Mathew Georgeae34ed22016-01-28 11:58:39 -08002331 mFlags = mOrigFlags;
2332
Glenn Kasten200092b2014-08-15 15:13:30 -07002333 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08002334 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07002335 // It will also delete the strong references on previous IAudioTrack and IMemory.
2336 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Glenn Kastenae4b8792015-03-20 09:04:21 -07002337 status_t result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07002338
Glenn Kastena47f3162012-11-07 10:13:08 -08002339 if (result == NO_ERROR) {
Andy Hungd7bd69e2015-07-24 07:52:41 -07002340 // take the frames that will be lost by track recreation into account in saved position
2341 // For streaming tracks, this is the amount we obtained from the user/client
2342 // (not the number actually consumed at the server - those are already lost).
2343 if (mStaticProxy == 0) {
2344 mPosition = mReleased;
2345 }
Andy Hung4ede21d2014-12-12 15:37:34 -08002346 // Continue playback from last known position and restore loop.
2347 if (mStaticProxy != 0) {
2348 if (loopCount != 0) {
2349 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
2350 mLoopStart, mLoopEnd, loopCount);
2351 } else {
2352 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002353 if (bufferPosition == mFrameCount) {
2354 ALOGD("restoring track at end of static buffer");
2355 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002356 }
2357 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002358 // restore volume handler
Andy Hung39399b62017-04-21 15:07:45 -07002359 mVolumeHandler->forall([this](const VolumeShaper &shaper) -> VolumeShaper::Status {
2360 sp<VolumeShaper::Operation> operationToEnd =
2361 new VolumeShaper::Operation(shaper.mOperation);
Andy Hung4ef88d72017-02-21 19:47:53 -08002362 // TODO: Ideally we would restore to the exact xOffset position
2363 // as returned by getVolumeShaperState(), but we don't have that
2364 // information when restoring at the client unless we periodically poll
2365 // the server or create shared memory state.
2366 //
Andy Hung39399b62017-04-21 15:07:45 -07002367 // For now, we simply advance to the end of the VolumeShaper effect
2368 // if it has been started.
2369 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002370 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002371 }
2372 return mAudioTrack->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002373 });
2374
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002375 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08002376 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08002377 }
Andy Hungf20a4e92016-08-15 19:10:34 -07002378 // server resets to zero so we offset
2379 mFramesWrittenServerOffset =
2380 mStaticProxy.get() != nullptr ? staticPosition : mFramesWritten;
2381 mFramesWrittenAtRestore = mFramesWrittenServerOffset;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002382 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002383 if (result != NO_ERROR) {
2384 ALOGW("restoreTrack_l() failed status %d", result);
2385 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07002386 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002387 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002388
2389 return result;
2390}
2391
Andy Hung90e8a972015-11-09 16:42:40 -08002392Modulo<uint32_t> AudioTrack::updateAndGetPosition_l()
Glenn Kasten200092b2014-08-15 15:13:30 -07002393{
2394 // This is the sole place to read server consumed frames
Andy Hung90e8a972015-11-09 16:42:40 -08002395 Modulo<uint32_t> newServer(mProxy->getPosition());
2396 const int32_t delta = (newServer - mServer).signedValue();
Glenn Kasten200092b2014-08-15 15:13:30 -07002397 // TODO There is controversy about whether there can be "negative jitter" in server position.
2398 // This should be investigated further, and if possible, it should be addressed.
2399 // A more definite failure mode is infrequent polling by client.
2400 // One could call (void)getPosition_l() in releaseBuffer(),
2401 // so mReleased and mPosition are always lock-step as best possible.
2402 // That should ensure delta never goes negative for infrequent polling
2403 // unless the server has more than 2^31 frames in its buffer,
2404 // in which case the use of uint32_t for these counters has bigger issues.
Andy Hung90e8a972015-11-09 16:42:40 -08002405 ALOGE_IF(delta < 0,
2406 "detected illegal retrograde motion by the server: mServer advanced by %d",
2407 delta);
Chad Brubaker039c27a2015-09-23 15:17:29 -07002408 mServer = newServer;
Andy Hung90e8a972015-11-09 16:42:40 -08002409 if (delta > 0) { // avoid retrograde
2410 mPosition += delta;
2411 }
2412 return mPosition;
Glenn Kasten200092b2014-08-15 15:13:30 -07002413}
2414
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002415bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed)
Andy Hung8edb8dc2015-03-26 19:13:55 -07002416{
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002417 updateLatency_l();
Andy Hung8edb8dc2015-03-26 19:13:55 -07002418 // applicable for mixing tracks only (not offloaded or direct)
2419 if (mStaticProxy != 0) {
2420 return true; // static tracks do not have issues with buffer sizing.
2421 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07002422 const size_t minFrameCount =
Glenn Kastenea38ee72016-04-18 11:08:01 -07002423 calculateMinFrameCount(mAfLatency, mAfFrameCount, mAfSampleRate, sampleRate, speed
2424 /*, 0 mNotificationsPerBufferReq*/);
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002425 const bool allowed = mFrameCount >= minFrameCount;
2426 ALOGD_IF(!allowed,
2427 "isSampleRateSpeedAllowed_l denied "
2428 "mAfLatency:%u mAfFrameCount:%zu mAfSampleRate:%u sampleRate:%u speed:%f "
2429 "mFrameCount:%zu < minFrameCount:%zu",
2430 mAfLatency, mAfFrameCount, mAfSampleRate, sampleRate, speed,
Andy Hung8edb8dc2015-03-26 19:13:55 -07002431 mFrameCount, minFrameCount);
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002432 return allowed;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002433}
2434
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002435status_t AudioTrack::setParameters(const String8& keyValuePairs)
2436{
2437 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07002438 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002439}
2440
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002441VolumeShaper::Status AudioTrack::applyVolumeShaper(
2442 const sp<VolumeShaper::Configuration>& configuration,
2443 const sp<VolumeShaper::Operation>& operation)
2444{
2445 AutoMutex lock(mLock);
Andy Hung4ef88d72017-02-21 19:47:53 -08002446 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002447 VolumeShaper::Status status = mAudioTrack->applyVolumeShaper(configuration, operation);
Andy Hung39399b62017-04-21 15:07:45 -07002448
2449 if (status == DEAD_OBJECT) {
2450 if (restoreTrack_l("applyVolumeShaper") == OK) {
2451 status = mAudioTrack->applyVolumeShaper(configuration, operation);
2452 }
2453 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002454 if (status >= 0) {
2455 // save VolumeShaper for restore
2456 mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung39399b62017-04-21 15:07:45 -07002457 if (mState == STATE_ACTIVE || mState == STATE_STOPPING) {
2458 mVolumeHandler->setStarted();
2459 }
2460 } else {
2461 // warn only if not an expected restore failure.
2462 ALOGW_IF(!((isOffloadedOrDirect_l() || mDoNotReconnect) && status == DEAD_OBJECT),
2463 "applyVolumeShaper failed: %d", status);
Andy Hung4ef88d72017-02-21 19:47:53 -08002464 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002465 return status;
2466}
2467
2468sp<VolumeShaper::State> AudioTrack::getVolumeShaperState(int id)
2469{
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002470 AutoMutex lock(mLock);
Andy Hung39399b62017-04-21 15:07:45 -07002471 sp<VolumeShaper::State> state = mAudioTrack->getVolumeShaperState(id);
2472 if (state.get() == nullptr && (mCblk->mFlags & CBLK_INVALID) != 0) {
2473 if (restoreTrack_l("getVolumeShaperState") == OK) {
2474 state = mAudioTrack->getVolumeShaperState(id);
2475 }
2476 }
2477 return state;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002478}
2479
Andy Hungea2b9c02016-02-12 17:06:53 -08002480status_t AudioTrack::getTimestamp(ExtendedTimestamp *timestamp)
2481{
2482 if (timestamp == nullptr) {
2483 return BAD_VALUE;
2484 }
2485 AutoMutex lock(mLock);
Andy Hunge13f8a62016-03-30 14:20:42 -07002486 return getTimestamp_l(timestamp);
2487}
2488
2489status_t AudioTrack::getTimestamp_l(ExtendedTimestamp *timestamp)
2490{
Andy Hungea2b9c02016-02-12 17:06:53 -08002491 if (mCblk->mFlags & CBLK_INVALID) {
2492 const status_t status = restoreTrack_l("getTimestampExtended");
2493 if (status != OK) {
2494 // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
2495 // recommending that the track be recreated.
2496 return DEAD_OBJECT;
2497 }
2498 }
2499 // check for offloaded/direct here in case restoring somehow changed those flags.
2500 if (isOffloadedOrDirect_l()) {
2501 return INVALID_OPERATION; // not supported
2502 }
2503 status_t status = mProxy->getTimestamp(timestamp);
Andy Hunge1e98462016-04-12 10:18:51 -07002504 LOG_ALWAYS_FATAL_IF(status != OK, "status %d not allowed from proxy getTimestamp", status);
Andy Hungea2b9c02016-02-12 17:06:53 -08002505 bool found = false;
Andy Hunge1e98462016-04-12 10:18:51 -07002506 timestamp->mPosition[ExtendedTimestamp::LOCATION_CLIENT] = mFramesWritten;
2507 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_CLIENT] = 0;
2508 // server side frame offset in case AudioTrack has been restored.
2509 for (int i = ExtendedTimestamp::LOCATION_SERVER;
2510 i < ExtendedTimestamp::LOCATION_MAX; ++i) {
2511 if (timestamp->mTimeNs[i] >= 0) {
2512 // apply server offset (frames flushed is ignored
2513 // so we don't report the jump when the flush occurs).
2514 timestamp->mPosition[i] += mFramesWrittenServerOffset;
2515 found = true;
Andy Hungea2b9c02016-02-12 17:06:53 -08002516 }
2517 }
2518 return found ? OK : WOULD_BLOCK;
2519}
2520
Glenn Kastence703742013-07-19 16:33:58 -07002521status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
2522{
Glenn Kasten53cec222013-08-29 09:01:02 -07002523 AutoMutex lock(mLock);
Andy Hung65ffdfc2016-10-10 15:52:11 -07002524 return getTimestamp_l(timestamp);
2525}
Phil Burk1b420972015-04-22 10:52:21 -07002526
Andy Hung65ffdfc2016-10-10 15:52:11 -07002527status_t AudioTrack::getTimestamp_l(AudioTimestamp& timestamp)
2528{
Phil Burk1b420972015-04-22 10:52:21 -07002529 bool previousTimestampValid = mPreviousTimestampValid;
2530 // Set false here to cover all the error return cases.
2531 mPreviousTimestampValid = false;
2532
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002533 switch (mState) {
2534 case STATE_ACTIVE:
2535 case STATE_PAUSED:
2536 break; // handle below
2537 case STATE_FLUSHED:
2538 case STATE_STOPPED:
2539 return WOULD_BLOCK;
2540 case STATE_STOPPING:
2541 case STATE_PAUSED_STOPPING:
2542 if (!isOffloaded_l()) {
2543 return INVALID_OPERATION;
2544 }
2545 break; // offloaded tracks handled below
2546 default:
2547 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
2548 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07002549 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002550
Eric Laurent275e8e92014-11-30 15:14:47 -08002551 if (mCblk->mFlags & CBLK_INVALID) {
Andy Hung6653c932015-06-08 13:27:48 -07002552 const status_t status = restoreTrack_l("getTimestamp");
2553 if (status != OK) {
2554 // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
2555 // recommending that the track be recreated.
2556 return DEAD_OBJECT;
2557 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002558 }
2559
Glenn Kasten200092b2014-08-15 15:13:30 -07002560 // The presented frame count must always lag behind the consumed frame count.
2561 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Andy Hung6ae58432016-02-16 18:32:24 -08002562
2563 status_t status;
Andy Hung818e7a32016-02-16 18:08:07 -08002564 if (isOffloadedOrDirect_l()) {
Andy Hung6ae58432016-02-16 18:32:24 -08002565 // use Binder to get timestamp
2566 status = mAudioTrack->getTimestamp(timestamp);
2567 } else {
2568 // read timestamp from shared memory
2569 ExtendedTimestamp ets;
2570 status = mProxy->getTimestamp(&ets);
2571 if (status == OK) {
Andy Hungb01faa32016-04-27 12:51:32 -07002572 ExtendedTimestamp::Location location;
2573 status = ets.getBestTimestamp(&timestamp, &location);
2574
2575 if (status == OK) {
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002576 updateLatency_l();
Andy Hungb01faa32016-04-27 12:51:32 -07002577 // It is possible that the best location has moved from the kernel to the server.
2578 // In this case we adjust the position from the previous computed latency.
2579 if (location == ExtendedTimestamp::LOCATION_SERVER) {
2580 ALOGW_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_KERNEL,
2581 "getTimestamp() location moved from kernel to server");
Andy Hung07eee802016-06-21 16:47:16 -07002582 // check that the last kernel OK time info exists and the positions
2583 // are valid (if they predate the current track, the positions may
2584 // be zero or negative).
Andy Hungb01faa32016-04-27 12:51:32 -07002585 const int64_t frames =
Andy Hung6d7b1192016-05-07 22:59:48 -07002586 (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
Andy Hung07eee802016-06-21 16:47:16 -07002587 ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0 ||
2588 ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] <= 0 ||
2589 ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] <= 0)
Andy Hung6d7b1192016-05-07 22:59:48 -07002590 ?
2591 int64_t((double)mAfLatency * mSampleRate * mPlaybackRate.mSpeed
2592 / 1000)
2593 :
2594 (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
2595 - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK]);
2596 ALOGV("frame adjustment:%lld timestamp:%s",
2597 (long long)frames, ets.toString().c_str());
Andy Hungb01faa32016-04-27 12:51:32 -07002598 if (frames >= ets.mPosition[location]) {
2599 timestamp.mPosition = 0;
2600 } else {
2601 timestamp.mPosition = (uint32_t)(ets.mPosition[location] - frames);
2602 }
Andy Hung69488c42016-05-16 18:43:33 -07002603 } else if (location == ExtendedTimestamp::LOCATION_KERNEL) {
2604 ALOGV_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_SERVER,
2605 "getTimestamp() location moved from server to kernel");
Andy Hungb01faa32016-04-27 12:51:32 -07002606 }
Andy Hung5d313802016-10-10 15:09:39 -07002607
2608 // We update the timestamp time even when paused.
2609 if (mState == STATE_PAUSED /* not needed: STATE_PAUSED_STOPPING */) {
2610 const int64_t now = systemTime();
Andy Hung2b01f002017-07-05 12:01:36 -07002611 const int64_t at = audio_utils_ns_from_timespec(&timestamp.mTime);
Andy Hung5d313802016-10-10 15:09:39 -07002612 const int64_t lag =
2613 (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
2614 ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0)
2615 ? int64_t(mAfLatency * 1000000LL)
2616 : (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
2617 - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK])
2618 * NANOS_PER_SECOND / mSampleRate;
2619 const int64_t limit = now - lag; // no earlier than this limit
2620 if (at < limit) {
2621 ALOGV("timestamp pause lag:%lld adjusting from %lld to %lld",
2622 (long long)lag, (long long)at, (long long)limit);
Andy Hungffa36952017-08-17 10:41:51 -07002623 timestamp.mTime = convertNsToTimespec(limit);
Andy Hung5d313802016-10-10 15:09:39 -07002624 }
2625 }
Andy Hungb01faa32016-04-27 12:51:32 -07002626 mPreviousLocation = location;
2627 } else {
2628 // right after AudioTrack is started, one may not find a timestamp
2629 ALOGV("getBestTimestamp did not find timestamp");
2630 }
Andy Hung6ae58432016-02-16 18:32:24 -08002631 }
2632 if (status == INVALID_OPERATION) {
Andy Hungf20a4e92016-08-15 19:10:34 -07002633 // INVALID_OPERATION occurs when no timestamp has been issued by the server;
2634 // other failures are signaled by a negative time.
2635 // If we come out of FLUSHED or STOPPED where the position is known
2636 // to be zero we convert this to WOULD_BLOCK (with the implicit meaning of
2637 // "zero" for NuPlayer). We don't convert for track restoration as position
2638 // does not reset.
2639 ALOGV("timestamp server offset:%lld restore frames:%lld",
2640 (long long)mFramesWrittenServerOffset, (long long)mFramesWrittenAtRestore);
2641 if (mFramesWrittenServerOffset != mFramesWrittenAtRestore) {
2642 status = WOULD_BLOCK;
2643 }
Andy Hung6ae58432016-02-16 18:32:24 -08002644 }
2645 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002646 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07002647 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002648 return status;
2649 }
2650 if (isOffloadedOrDirect_l()) {
2651 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
2652 // use cached paused position in case another offloaded track is running.
2653 timestamp.mPosition = mPausedPosition;
2654 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
Andy Hung5d313802016-10-10 15:09:39 -07002655 // TODO: adjust for delay
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002656 return NO_ERROR;
2657 }
2658
2659 // Check whether a pending flush or stop has completed, as those commands may
Andy Hungc8e09c62015-06-03 23:43:36 -07002660 // be asynchronous or return near finish or exhibit glitchy behavior.
2661 //
2662 // Originally this showed up as the first timestamp being a continuation of
2663 // the previous song under gapless playback.
2664 // However, we sometimes see zero timestamps, then a glitch of
2665 // the previous song's position, and then correct timestamps afterwards.
Andy Hungffa36952017-08-17 10:41:51 -07002666 if (mStartFromZeroUs != 0 && mSampleRate != 0) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002667 static const int kTimeJitterUs = 100000; // 100 ms
2668 static const int k1SecUs = 1000000;
2669
2670 const int64_t timeNow = getNowUs();
2671
Andy Hungffa36952017-08-17 10:41:51 -07002672 if (timeNow < mStartFromZeroUs + k1SecUs) { // within first second of starting
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002673 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
Andy Hungffa36952017-08-17 10:41:51 -07002674 if (timestampTimeUs < mStartFromZeroUs) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002675 return WOULD_BLOCK; // stale timestamp time, occurs before start.
2676 }
Andy Hungffa36952017-08-17 10:41:51 -07002677 const int64_t deltaTimeUs = timestampTimeUs - mStartFromZeroUs;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002678 const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002679 / ((double)mSampleRate * mPlaybackRate.mSpeed);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002680
2681 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2682 // Verify that the counter can't count faster than the sample rate
Andy Hungc8e09c62015-06-03 23:43:36 -07002683 // since the start time. If greater, then that means we may have failed
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002684 // to completely flush or stop the previous playing track.
Andy Hungc8e09c62015-06-03 23:43:36 -07002685 ALOGW_IF(!mTimestampStartupGlitchReported,
2686 "getTimestamp startup glitch detected"
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002687 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2688 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2689 timestamp.mPosition);
Andy Hungc8e09c62015-06-03 23:43:36 -07002690 mTimestampStartupGlitchReported = true;
2691 if (previousTimestampValid
2692 && mPreviousTimestamp.mPosition == 0 /* should be true if valid */) {
2693 timestamp = mPreviousTimestamp;
2694 mPreviousTimestampValid = true;
2695 return NO_ERROR;
2696 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002697 return WOULD_BLOCK;
2698 }
Andy Hungc8e09c62015-06-03 23:43:36 -07002699 if (deltaPositionByUs != 0) {
Andy Hungffa36952017-08-17 10:41:51 -07002700 mStartFromZeroUs = 0; // don't check again, we got valid nonzero position.
Andy Hungc8e09c62015-06-03 23:43:36 -07002701 }
2702 } else {
Andy Hungffa36952017-08-17 10:41:51 -07002703 mStartFromZeroUs = 0; // don't check again, start time expired.
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002704 }
Andy Hungc8e09c62015-06-03 23:43:36 -07002705 mTimestampStartupGlitchReported = false;
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002706 }
2707 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002708 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2709 (void) updateAndGetPosition_l();
2710 // Server consumed (mServer) and presented both use the same server time base,
2711 // and server consumed is always >= presented.
2712 // The delta between these represents the number of frames in the buffer pipeline.
2713 // If this delta between these is greater than the client position, it means that
2714 // actually presented is still stuck at the starting line (figuratively speaking),
2715 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
Andy Hung90e8a972015-11-09 16:42:40 -08002716 // Note: We explicitly use non-Modulo comparison here - potential wrap issue when
2717 // mPosition exceeds 32 bits.
2718 // TODO Remove when timestamp is updated to contain pipeline status info.
2719 const int32_t pipelineDepthInFrames = (mServer - timestamp.mPosition).signedValue();
2720 if (pipelineDepthInFrames > 0 /* should be true, but we check anyways */
2721 && (uint32_t)pipelineDepthInFrames > mPosition.value()) {
Glenn Kasten200092b2014-08-15 15:13:30 -07002722 return INVALID_OPERATION;
2723 }
2724 // Convert timestamp position from server time base to client time base.
2725 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2726 // But if we change it to 64-bit then this could fail.
Andy Hung90e8a972015-11-09 16:42:40 -08002727 // Use Modulo computation here.
2728 timestamp.mPosition = (mPosition - mServer + timestamp.mPosition).value();
Glenn Kasten200092b2014-08-15 15:13:30 -07002729 // Immediately after a call to getPosition_l(), mPosition and
2730 // mServer both represent the same frame position. mPosition is
2731 // in client's point of view, and mServer is in server's point of
2732 // view. So the difference between them is the "fudge factor"
2733 // between client and server views due to stop() and/or new
2734 // IAudioTrack. And timestamp.mPosition is initially in server's
2735 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002736 }
Phil Burk1b420972015-04-22 10:52:21 -07002737
2738 // Prevent retrograde motion in timestamp.
2739 // This is sometimes caused by erratic reports of the available space in the ALSA drivers.
2740 if (status == NO_ERROR) {
Andy Hungffa36952017-08-17 10:41:51 -07002741 // previousTimestampValid is set to false when starting after a stop or flush.
Phil Burk1b420972015-04-22 10:52:21 -07002742 if (previousTimestampValid) {
Andy Hung2b01f002017-07-05 12:01:36 -07002743 const int64_t previousTimeNanos =
2744 audio_utils_ns_from_timespec(&mPreviousTimestamp.mTime);
Andy Hungffa36952017-08-17 10:41:51 -07002745 int64_t currentTimeNanos = audio_utils_ns_from_timespec(&timestamp.mTime);
2746
2747 // Fix stale time when checking timestamp right after start().
2748 //
2749 // For offload compatibility, use a default lag value here.
2750 // Any time discrepancy between this update and the pause timestamp is handled
2751 // by the retrograde check afterwards.
2752 const int64_t lagNs = int64_t(mAfLatency * 1000000LL);
2753 const int64_t limitNs = mStartNs - lagNs;
2754 if (currentTimeNanos < limitNs) {
2755 ALOGD("correcting timestamp time for pause, "
2756 "currentTimeNanos: %lld < limitNs: %lld < mStartNs: %lld",
2757 (long long)currentTimeNanos, (long long)limitNs, (long long)mStartNs);
2758 timestamp.mTime = convertNsToTimespec(limitNs);
2759 currentTimeNanos = limitNs;
2760 }
2761
2762 // retrograde check
Phil Burk1b420972015-04-22 10:52:21 -07002763 if (currentTimeNanos < previousTimeNanos) {
Andy Hung5d313802016-10-10 15:09:39 -07002764 ALOGW("retrograde timestamp time corrected, %lld < %lld",
2765 (long long)currentTimeNanos, (long long)previousTimeNanos);
2766 timestamp.mTime = mPreviousTimestamp.mTime;
Andy Hungffa36952017-08-17 10:41:51 -07002767 // currentTimeNanos not used below.
Phil Burk1b420972015-04-22 10:52:21 -07002768 }
2769
2770 // Looking at signed delta will work even when the timestamps
2771 // are wrapping around.
Andy Hung90e8a972015-11-09 16:42:40 -08002772 int32_t deltaPosition = (Modulo<uint32_t>(timestamp.mPosition)
2773 - mPreviousTimestamp.mPosition).signedValue();
Phil Burk4c5a3672015-04-30 16:18:53 -07002774 if (deltaPosition < 0) {
2775 // Only report once per position instead of spamming the log.
2776 if (!mRetrogradeMotionReported) {
2777 ALOGW("retrograde timestamp position corrected, %d = %u - %u",
2778 deltaPosition,
2779 timestamp.mPosition,
2780 mPreviousTimestamp.mPosition);
2781 mRetrogradeMotionReported = true;
2782 }
2783 } else {
2784 mRetrogradeMotionReported = false;
2785 }
Andy Hung5d313802016-10-10 15:09:39 -07002786 if (deltaPosition < 0) {
2787 timestamp.mPosition = mPreviousTimestamp.mPosition;
2788 deltaPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -07002789 }
Andy Hung5d313802016-10-10 15:09:39 -07002790#if 0
2791 // Uncomment this to verify audio timestamp rate.
2792 const int64_t deltaTime =
Andy Hung2b01f002017-07-05 12:01:36 -07002793 audio_utils_ns_from_timespec(&timestamp.mTime) - previousTimeNanos;
Andy Hung5d313802016-10-10 15:09:39 -07002794 if (deltaTime != 0) {
2795 const int64_t computedSampleRate =
2796 deltaPosition * (long long)NANOS_PER_SECOND / deltaTime;
2797 ALOGD("computedSampleRate:%u sampleRate:%u",
2798 (unsigned)computedSampleRate, mSampleRate);
2799 }
2800#endif
Phil Burk1b420972015-04-22 10:52:21 -07002801 }
2802 mPreviousTimestamp = timestamp;
2803 mPreviousTimestampValid = true;
2804 }
2805
Glenn Kastenfe346c72013-08-30 13:28:22 -07002806 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002807}
2808
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002809String8 AudioTrack::getParameters(const String8& keys)
2810{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002811 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002812 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002813 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002814 } else {
2815 return String8::empty();
2816 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002817}
2818
Glenn Kasten23a75452014-01-13 10:37:17 -08002819bool AudioTrack::isOffloaded() const
2820{
2821 AutoMutex lock(mLock);
2822 return isOffloaded_l();
2823}
2824
Eric Laurentab5cdba2014-06-09 17:22:27 -07002825bool AudioTrack::isDirect() const
2826{
2827 AutoMutex lock(mLock);
2828 return isDirect_l();
2829}
2830
2831bool AudioTrack::isOffloadedOrDirect() const
2832{
2833 AutoMutex lock(mLock);
2834 return isOffloadedOrDirect_l();
2835}
2836
2837
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002838status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002839{
2840
2841 const size_t SIZE = 256;
2842 char buffer[SIZE];
2843 String8 result;
2844
2845 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002846 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002847 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002848 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002849 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002850 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002851 result.append(buffer);
Andy Hung8edb8dc2015-03-26 19:13:55 -07002852 snprintf(buffer, 255, " sample rate(%u), speed(%f), status(%d)\n",
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002853 mSampleRate, mPlaybackRate.mSpeed, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002854 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002855 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002856 result.append(buffer);
2857 ::write(fd, result.string(), result.size());
2858 return NO_ERROR;
2859}
2860
Phil Burk2812d9e2016-01-04 10:34:30 -08002861uint32_t AudioTrack::getUnderrunCount() const
2862{
2863 AutoMutex lock(mLock);
2864 return getUnderrunCount_l();
2865}
2866
2867uint32_t AudioTrack::getUnderrunCount_l() const
2868{
2869 return mProxy->getUnderrunCount() + mUnderrunCountOffset;
2870}
2871
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002872uint32_t AudioTrack::getUnderrunFrames() const
2873{
2874 AutoMutex lock(mLock);
2875 return mProxy->getUnderrunFrames();
2876}
2877
Eric Laurent296fb132015-05-01 11:38:42 -07002878status_t AudioTrack::addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback)
2879{
2880 if (callback == 0) {
2881 ALOGW("%s adding NULL callback!", __FUNCTION__);
2882 return BAD_VALUE;
2883 }
2884 AutoMutex lock(mLock);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002885 if (mDeviceCallback.unsafe_get() == callback.get()) {
Eric Laurent296fb132015-05-01 11:38:42 -07002886 ALOGW("%s adding same callback!", __FUNCTION__);
2887 return INVALID_OPERATION;
2888 }
2889 status_t status = NO_ERROR;
2890 if (mOutput != AUDIO_IO_HANDLE_NONE) {
2891 if (mDeviceCallback != 0) {
2892 ALOGW("%s callback already present!", __FUNCTION__);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002893 AudioSystem::removeAudioDeviceCallback(this, mOutput);
Eric Laurent296fb132015-05-01 11:38:42 -07002894 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002895 status = AudioSystem::addAudioDeviceCallback(this, mOutput);
Eric Laurent296fb132015-05-01 11:38:42 -07002896 }
2897 mDeviceCallback = callback;
2898 return status;
2899}
2900
2901status_t AudioTrack::removeAudioDeviceCallback(
2902 const sp<AudioSystem::AudioDeviceCallback>& callback)
2903{
2904 if (callback == 0) {
2905 ALOGW("%s removing NULL callback!", __FUNCTION__);
2906 return BAD_VALUE;
2907 }
2908 AutoMutex lock(mLock);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002909 if (mDeviceCallback.unsafe_get() != callback.get()) {
Eric Laurent296fb132015-05-01 11:38:42 -07002910 ALOGW("%s removing different callback!", __FUNCTION__);
2911 return INVALID_OPERATION;
2912 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002913 mDeviceCallback.clear();
Eric Laurent296fb132015-05-01 11:38:42 -07002914 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002915 AudioSystem::removeAudioDeviceCallback(this, mOutput);
Eric Laurent296fb132015-05-01 11:38:42 -07002916 }
Eric Laurent296fb132015-05-01 11:38:42 -07002917 return NO_ERROR;
2918}
2919
Eric Laurentad2e7b92017-09-14 20:06:42 -07002920
2921void AudioTrack::onAudioDeviceUpdate(audio_io_handle_t audioIo,
2922 audio_port_handle_t deviceId)
2923{
2924 sp<AudioSystem::AudioDeviceCallback> callback;
2925 {
2926 AutoMutex lock(mLock);
2927 if (audioIo != mOutput) {
2928 return;
2929 }
2930 callback = mDeviceCallback.promote();
2931 // only update device if the track is active as route changes due to other use cases are
2932 // irrelevant for this client
2933 if (mState == STATE_ACTIVE) {
2934 mRoutedDeviceId = deviceId;
2935 }
2936 }
2937 if (callback.get() != nullptr) {
2938 callback->onAudioDeviceUpdate(mOutput, mRoutedDeviceId);
2939 }
2940}
2941
Andy Hunge13f8a62016-03-30 14:20:42 -07002942status_t AudioTrack::pendingDuration(int32_t *msec, ExtendedTimestamp::Location location)
2943{
2944 if (msec == nullptr ||
2945 (location != ExtendedTimestamp::LOCATION_SERVER
2946 && location != ExtendedTimestamp::LOCATION_KERNEL)) {
2947 return BAD_VALUE;
2948 }
2949 AutoMutex lock(mLock);
2950 // inclusive of offloaded and direct tracks.
2951 //
2952 // It is possible, but not enabled, to allow duration computation for non-pcm
2953 // audio_has_proportional_frames() formats because currently they have
2954 // the drain rate equivalent to the pcm sample rate * framesize.
2955 if (!isPurePcmData_l()) {
2956 return INVALID_OPERATION;
2957 }
2958 ExtendedTimestamp ets;
2959 if (getTimestamp_l(&ets) == OK
2960 && ets.mTimeNs[location] > 0) {
2961 int64_t diff = ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT]
2962 - ets.mPosition[location];
2963 if (diff < 0) {
2964 *msec = 0;
2965 } else {
2966 // ms is the playback time by frames
2967 int64_t ms = (int64_t)((double)diff * 1000 /
2968 ((double)mSampleRate * mPlaybackRate.mSpeed));
2969 // clockdiff is the timestamp age (negative)
2970 int64_t clockdiff = (mState != STATE_ACTIVE) ? 0 :
2971 ets.mTimeNs[location]
2972 + ets.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_MONOTONIC]
2973 - systemTime(SYSTEM_TIME_MONOTONIC);
2974
2975 //ALOGV("ms: %lld clockdiff: %lld", (long long)ms, (long long)clockdiff);
2976 static const int NANOS_PER_MILLIS = 1000000;
2977 *msec = (int32_t)(ms + clockdiff / NANOS_PER_MILLIS);
2978 }
2979 return NO_ERROR;
2980 }
2981 if (location != ExtendedTimestamp::LOCATION_SERVER) {
2982 return INVALID_OPERATION; // LOCATION_KERNEL is not available
2983 }
2984 // use server position directly (offloaded and direct arrive here)
2985 updateAndGetPosition_l();
2986 int32_t diff = (Modulo<uint32_t>(mFramesWritten) - mPosition).signedValue();
2987 *msec = (diff <= 0) ? 0
2988 : (int32_t)((double)diff * 1000 / ((double)mSampleRate * mPlaybackRate.mSpeed));
2989 return NO_ERROR;
2990}
2991
Andy Hung65ffdfc2016-10-10 15:52:11 -07002992bool AudioTrack::hasStarted()
2993{
2994 AutoMutex lock(mLock);
2995 switch (mState) {
2996 case STATE_STOPPED:
2997 if (isOffloadedOrDirect_l()) {
2998 // check if we have started in the past to return true.
Andy Hungffa36952017-08-17 10:41:51 -07002999 return mStartFromZeroUs > 0;
Andy Hung65ffdfc2016-10-10 15:52:11 -07003000 }
3001 // A normal audio track may still be draining, so
3002 // check if stream has ended. This covers fasttrack position
3003 // instability and start/stop without any data written.
3004 if (mProxy->getStreamEndDone()) {
3005 return true;
3006 }
3007 // fall through
3008 case STATE_ACTIVE:
3009 case STATE_STOPPING:
3010 break;
3011 case STATE_PAUSED:
3012 case STATE_PAUSED_STOPPING:
3013 case STATE_FLUSHED:
3014 return false; // we're not active
3015 default:
3016 LOG_ALWAYS_FATAL("Invalid mState in hasStarted(): %d", mState);
3017 break;
3018 }
3019
3020 // wait indicates whether we need to wait for a timestamp.
3021 // This is conservatively figured - if we encounter an unexpected error
3022 // then we will not wait.
3023 bool wait = false;
3024 if (isOffloadedOrDirect_l()) {
3025 AudioTimestamp ts;
3026 status_t status = getTimestamp_l(ts);
3027 if (status == WOULD_BLOCK) {
3028 wait = true;
3029 } else if (status == OK) {
3030 wait = (ts.mPosition == 0 || ts.mPosition == mStartTs.mPosition);
3031 }
3032 ALOGV("hasStarted wait:%d ts:%u start position:%lld",
3033 (int)wait,
3034 ts.mPosition,
3035 (long long)mStartTs.mPosition);
3036 } else {
3037 int location = ExtendedTimestamp::LOCATION_SERVER; // for ALOG
3038 ExtendedTimestamp ets;
3039 status_t status = getTimestamp_l(&ets);
3040 if (status == WOULD_BLOCK) { // no SERVER or KERNEL frame info in ets
3041 wait = true;
3042 } else if (status == OK) {
3043 for (location = ExtendedTimestamp::LOCATION_KERNEL;
3044 location >= ExtendedTimestamp::LOCATION_SERVER; --location) {
3045 if (ets.mTimeNs[location] < 0 || mStartEts.mTimeNs[location] < 0) {
3046 continue;
3047 }
3048 wait = ets.mPosition[location] == 0
3049 || ets.mPosition[location] == mStartEts.mPosition[location];
3050 break;
3051 }
3052 }
3053 ALOGV("hasStarted wait:%d ets:%lld start position:%lld",
3054 (int)wait,
3055 (long long)ets.mPosition[location],
3056 (long long)mStartEts.mPosition[location]);
3057 }
3058 return !wait;
3059}
3060
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003061// =========================================================================
3062
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08003063void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003064{
3065 sp<AudioTrack> audioTrack = mAudioTrack.promote();
3066 if (audioTrack != 0) {
3067 AutoMutex lock(audioTrack->mLock);
3068 audioTrack->mProxy->binderDied();
3069 }
3070}
3071
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003072// =========================================================================
3073
3074AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07003075 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
3076 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08003077{
3078}
3079
3080AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003081{
3082}
3083
3084bool AudioTrack::AudioTrackThread::threadLoop()
3085{
Glenn Kasten3acbd052012-02-28 10:39:56 -08003086 {
3087 AutoMutex _l(mMyLock);
3088 if (mPaused) {
Glenn Kasten75f79032017-05-23 11:22:44 -07003089 // TODO check return value and handle or log
Glenn Kasten3acbd052012-02-28 10:39:56 -08003090 mMyCond.wait(mMyLock);
3091 // caller will check for exitPending()
3092 return true;
3093 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07003094 if (mIgnoreNextPausedInt) {
3095 mIgnoreNextPausedInt = false;
3096 mPausedInt = false;
3097 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003098 if (mPausedInt) {
Glenn Kasten47d55172017-05-23 11:19:30 -07003099 // TODO use futex instead of condition, for event flag "or"
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003100 if (mPausedNs > 0) {
Glenn Kasten75f79032017-05-23 11:22:44 -07003101 // TODO check return value and handle or log
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003102 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
3103 } else {
Glenn Kasten75f79032017-05-23 11:22:44 -07003104 // TODO check return value and handle or log
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003105 mMyCond.wait(mMyLock);
3106 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07003107 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003108 return true;
3109 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08003110 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07003111 if (exitPending()) {
3112 return false;
3113 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08003114 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003115 switch (ns) {
3116 case 0:
3117 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003118 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003119 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003120 return true;
3121 case NS_NEVER:
3122 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003123 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08003124 // Event driven: call wake() when callback notifications conditions change.
3125 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003126 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003127 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07003128 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003129 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003130 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07003131 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003132}
3133
Glenn Kasten3acbd052012-02-28 10:39:56 -08003134void AudioTrack::AudioTrackThread::requestExit()
3135{
3136 // must be in this order to avoid a race condition
3137 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07003138 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08003139}
3140
3141void AudioTrack::AudioTrackThread::pause()
3142{
3143 AutoMutex _l(mMyLock);
3144 mPaused = true;
3145}
3146
3147void AudioTrack::AudioTrackThread::resume()
3148{
3149 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07003150 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07003151 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08003152 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07003153 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08003154 mMyCond.signal();
3155 }
3156}
3157
Andy Hung3c09c782014-12-29 18:39:32 -08003158void AudioTrack::AudioTrackThread::wake()
3159{
3160 AutoMutex _l(mMyLock);
Andy Hunga8d08902015-07-22 11:52:13 -07003161 if (!mPaused) {
3162 // wake() might be called while servicing a callback - ignore the next
3163 // pause time and call processAudioBuffer.
Andy Hung3c09c782014-12-29 18:39:32 -08003164 mIgnoreNextPausedInt = true;
Andy Hunga8d08902015-07-22 11:52:13 -07003165 if (mPausedInt && mPausedNs > 0) {
3166 // audio track is active and internally paused with timeout.
3167 mPausedInt = false;
3168 mMyCond.signal();
3169 }
Andy Hung3c09c782014-12-29 18:39:32 -08003170 }
3171}
3172
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003173void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
3174{
3175 AutoMutex _l(mMyLock);
3176 mPausedInt = true;
3177 mPausedNs = ns;
3178}
3179
Glenn Kasten40bc9062015-03-20 09:09:33 -07003180} // namespace android