blob: 8fd52781daa6ff608427422b0e20ec44827bddbe [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
Glenn Kasten9f80dd22012-12-18 15:57:32 -080025#include <audio_utils/primitives.h>
26#include <binder/IPCThreadState.h>
27#include <media/AudioTrack.h>
28#include <utils/Log.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080029#include <private/media/AudioTrackShared.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/IAudioFlinger.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080031#include <media/AudioPolicyHelper.h>
Andy Hungcd044842014-08-07 11:04:34 -070032#include <media/AudioResamplerPublic.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080033
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010034#define WAIT_PERIOD_MS 10
35#define WAIT_STREAM_END_TIMEOUT_SEC 120
Andy Hung53c3b5f2014-12-15 16:42:05 -080036static const int kMaxLoopCountNotifications = 32;
Glenn Kasten511754b2012-01-11 09:52:19 -080037
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080038namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080039// ---------------------------------------------------------------------------
40
Andy Hung4ede21d2014-12-12 15:37:34 -080041template <typename T>
42const T &min(const T &x, const T &y) {
43 return x < y ? x : y;
44}
45
Andy Hung7f1bc8a2014-09-12 14:43:11 -070046static int64_t convertTimespecToUs(const struct timespec &tv)
47{
48 return tv.tv_sec * 1000000ll + tv.tv_nsec / 1000;
49}
50
51// current monotonic time in microseconds.
52static int64_t getNowUs()
53{
54 struct timespec tv;
55 (void) clock_gettime(CLOCK_MONOTONIC, &tv);
56 return convertTimespecToUs(tv);
57}
58
Chia-chi Yeh33005a92010-06-16 06:33:13 +080059// static
60status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080061 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080062 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080063 uint32_t sampleRate)
64{
Glenn Kastend65d73c2012-06-22 17:21:07 -070065 if (frameCount == NULL) {
66 return BAD_VALUE;
67 }
Glenn Kasten04cd0182012-06-25 11:49:27 -070068
Andy Hung0e48d252015-01-26 11:43:15 -080069 // FIXME handle in server, like createTrack_l(), possible missing info:
Glenn Kastene0fa4672012-04-24 14:35:14 -070070 // audio_io_handle_t output
71 // audio_format_t format
72 // audio_channel_mask_t channelMask
Andy Hung0e48d252015-01-26 11:43:15 -080073 // audio_output_flags_t flags (FAST)
Glenn Kasten3b16c762012-11-14 08:44:39 -080074 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080075 status_t status;
76 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
77 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080078 ALOGE("Unable to query output sample rate for stream type %d; status %d",
79 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080080 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080081 }
Glenn Kastene33054e2012-11-14 12:54:39 -080082 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -080083 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
84 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080085 ALOGE("Unable to query output frame count for stream type %d; status %d",
86 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080087 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080088 }
89 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -080090 status = AudioSystem::getOutputLatency(&afLatency, streamType);
91 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080092 ALOGE("Unable to query output latency for stream type %d; status %d",
93 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080094 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080095 }
96
97 // Ensure that buffer depth covers at least audio hardware latency
98 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080099 if (minBufCount < 2) {
100 minBufCount = 2;
101 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800102
Andy Hung0e48d252015-01-26 11:43:15 -0800103 *frameCount = minBufCount * sourceFramesNeeded(sampleRate, afFrameCount, afSampleRate);
104 // The formula above should always produce a non-zero value under normal circumstances:
105 // AudioTrack.SAMPLE_RATE_HZ_MIN <= sampleRate <= AudioTrack.SAMPLE_RATE_HZ_MAX.
106 // 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 -0800107 if (*frameCount == 0) {
Andy Hung0e48d252015-01-26 11:43:15 -0800108 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %u",
Glenn Kasten66a04672014-01-08 08:53:44 -0800109 streamType, sampleRate);
110 return BAD_VALUE;
111 }
Andy Hung0e48d252015-01-26 11:43:15 -0800112 ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, minBufCount=%u, afSampleRate=%u, afLatency=%u",
Glenn Kasten3acbd052012-02-28 10:39:56 -0800113 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800114 return NO_ERROR;
115}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800116
117// ---------------------------------------------------------------------------
118
119AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700120 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800121 mIsTimed(false),
122 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800123 mPreviousSchedulingGroup(SP_DEFAULT),
124 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800125{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700126 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
127 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
128 mAttributes.flags = 0x0;
129 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800130}
131
132AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800133 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800134 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800135 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700136 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800137 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700138 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800139 callback_t cbf,
140 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800141 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800142 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000143 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800144 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800145 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700146 pid_t pid,
147 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700148 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800149 mIsTimed(false),
150 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800151 mPreviousSchedulingGroup(SP_DEFAULT),
152 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800153{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700154 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700155 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800156 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700157 offloadInfo, uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800158}
159
Andreas Huberc8139852012-01-18 10:51:55 -0800160AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800161 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800162 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800163 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700164 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800165 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700166 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800167 callback_t cbf,
168 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800169 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800170 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000171 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800172 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800173 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700174 pid_t pid,
175 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700176 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800177 mIsTimed(false),
178 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800179 mPreviousSchedulingGroup(SP_DEFAULT),
180 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800181{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700182 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800183 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800184 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700185 uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800186}
187
188AudioTrack::~AudioTrack()
189{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800190 if (mStatus == NO_ERROR) {
191 // Make sure that callback function exits in the case where
192 // it is looping on buffer full condition in obtainBuffer().
193 // Otherwise the callback thread will never exit.
194 stop();
195 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100196 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800197 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800198 mAudioTrackThread->requestExitAndWait();
199 mAudioTrackThread.clear();
200 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800201 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700202 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700203 mCblkMemory.clear();
204 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800205 IPCThreadState::self()->flushCommands();
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700206 ALOGV("~AudioTrack, releasing session id %d from %d on behalf of %d",
207 mSessionId, IPCThreadState::self()->getCallingPid(), mClientPid);
Marco Nelissend457c972014-02-11 08:47:07 -0800208 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800209 }
210}
211
212status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800213 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800214 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800215 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700216 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800217 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700218 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800219 callback_t cbf,
220 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800221 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800222 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700223 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800224 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000225 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800226 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800227 int uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700228 pid_t pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700229 const audio_attributes_t* pAttributes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800230{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800231 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700232 "flags #%x, notificationFrames %u, sessionId %d, transferType %d, uid %d, pid %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800233 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700234 sessionId, transferType, uid, pid);
Glenn Kasten86f04662014-02-24 15:13:05 -0800235
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800236 switch (transferType) {
237 case TRANSFER_DEFAULT:
238 if (sharedBuffer != 0) {
239 transferType = TRANSFER_SHARED;
240 } else if (cbf == NULL || threadCanCallJava) {
241 transferType = TRANSFER_SYNC;
242 } else {
243 transferType = TRANSFER_CALLBACK;
244 }
245 break;
246 case TRANSFER_CALLBACK:
247 if (cbf == NULL || sharedBuffer != 0) {
248 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
249 return BAD_VALUE;
250 }
251 break;
252 case TRANSFER_OBTAIN:
253 case TRANSFER_SYNC:
254 if (sharedBuffer != 0) {
255 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
256 return BAD_VALUE;
257 }
258 break;
259 case TRANSFER_SHARED:
260 if (sharedBuffer == 0) {
261 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
262 return BAD_VALUE;
263 }
264 break;
265 default:
266 ALOGE("Invalid transfer type %d", transferType);
267 return BAD_VALUE;
268 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800269 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800270 mTransfer = transferType;
271
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700272 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
273 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800274
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700275 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700276
Eric Laurent1703cdf2011-03-07 14:52:59 -0800277 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800278
Glenn Kasten53cec222013-08-29 09:01:02 -0700279 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700280 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000281 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800282 return INVALID_OPERATION;
283 }
284
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800285 // handle default values first.
Eric Laurente83b55d2014-11-14 10:06:21 -0800286 if (streamType == AUDIO_STREAM_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700287 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800288 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700289 if (pAttributes == NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800290 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700291 ALOGE("Invalid stream type %d", streamType);
292 return BAD_VALUE;
293 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700294 mStreamType = streamType;
Eric Laurente83b55d2014-11-14 10:06:21 -0800295
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700296 } else {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700297 // stream type shouldn't be looked at, this track has audio attributes
298 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700299 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
300 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800301 mStreamType = AUDIO_STREAM_DEFAULT;
Eric Laurentc6bd5db2015-03-09 16:29:33 -0700302 if ((mAttributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
303 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
304 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800305 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700306
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800307 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800308 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700309 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800310 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800311
312 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700313 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800314 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800315 return BAD_VALUE;
316 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800317 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700318
Glenn Kasten8ba90322013-10-30 11:29:27 -0700319 if (!audio_is_output_channel(channelMask)) {
320 ALOGE("Invalid channel mask %#x", channelMask);
321 return BAD_VALUE;
322 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800323 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700324 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800325 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700326
Eric Laurentc2f1f072009-07-17 12:17:14 -0700327 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100328 // or offload was requested
329 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
330 || !audio_is_linear_pcm(format)) {
331 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
332 ? "Offload request, forcing to Direct Output"
333 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700334 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800335 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700336 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700337 }
338
Eric Laurentd1f69b02014-12-15 14:33:13 -0800339 // force direct flag if HW A/V sync requested
340 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
341 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
342 }
343
Glenn Kastenb7730382014-04-30 15:50:31 -0700344 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
345 if (audio_is_linear_pcm(format)) {
346 mFrameSize = channelCount * audio_bytes_per_sample(format);
347 } else {
348 mFrameSize = sizeof(uint8_t);
349 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800350 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700351 ALOG_ASSERT(audio_is_linear_pcm(format));
352 mFrameSize = channelCount * audio_bytes_per_sample(format);
Glenn Kastenb7730382014-04-30 15:50:31 -0700353 // createTrack will return an error if PCM format is not supported by server,
354 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800355 }
356
Eric Laurent0d6db582014-11-12 18:39:44 -0800357 // sampling rate must be specified for direct outputs
358 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
359 return BAD_VALUE;
360 }
361 mSampleRate = sampleRate;
362
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800363 // Make copy of input parameter offloadInfo so that in the future:
364 // (a) createTrack_l doesn't need it as an input parameter
365 // (b) we can support re-creation of offloaded tracks
366 if (offloadInfo != NULL) {
367 mOffloadInfoCopy = *offloadInfo;
368 mOffloadInfo = &mOffloadInfoCopy;
369 } else {
370 mOffloadInfo = NULL;
371 }
372
Glenn Kasten66e46352014-01-16 17:44:23 -0800373 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
374 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800375 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800376 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800377 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700378 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800379 mNotificationFramesAct = 0;
Eric Laurentcaf7f482014-11-25 17:50:47 -0800380 if (sessionId == AUDIO_SESSION_ALLOCATE) {
381 mSessionId = AudioSystem::newAudioUniqueId();
382 } else {
383 mSessionId = sessionId;
384 }
Marco Nelissend457c972014-02-11 08:47:07 -0800385 int callingpid = IPCThreadState::self()->getCallingPid();
386 int mypid = getpid();
387 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800388 mClientUid = IPCThreadState::self()->getCallingUid();
389 } else {
390 mClientUid = uid;
391 }
Marco Nelissend457c972014-02-11 08:47:07 -0800392 if (pid == -1 || (callingpid != mypid)) {
393 mClientPid = callingpid;
394 } else {
395 mClientPid = pid;
396 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700397 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700398 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700399 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700400
Glenn Kastena997e7a2012-08-07 09:44:19 -0700401 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700402 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700403 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
404 }
405
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800406 // create the IAudioTrack
Eric Laurent0d6db582014-11-12 18:39:44 -0800407 status_t status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800408
Glenn Kastena997e7a2012-08-07 09:44:19 -0700409 if (status != NO_ERROR) {
410 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100411 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
412 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700413 mAudioTrackThread.clear();
414 }
415 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700416 }
417
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800418 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800419 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800420 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800421 mLoopCount = 0;
422 mLoopStart = 0;
423 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800424 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800425 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700426 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800427 mNewPosition = 0;
428 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700429 mServer = 0;
430 mPosition = 0;
431 mReleased = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700432 mStartUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800433 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800434 mSequence = 1;
435 mObservedSequence = mSequence;
436 mInUnderrun = false;
437
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800438 return NO_ERROR;
439}
440
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800441// -------------------------------------------------------------------------
442
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100443status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800444{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800445 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100446
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800447 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100448 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800449 }
450
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800451 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800452
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800453 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100454 if (previousState == STATE_PAUSED_STOPPING) {
455 mState = STATE_STOPPING;
456 } else {
457 mState = STATE_ACTIVE;
458 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700459 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800460 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
461 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700462 mPosition = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700463 // For offloaded tracks, we don't know if the hardware counters are really zero here,
464 // since the flush is asynchronous and stop may not fully drain.
465 // We save the time when the track is started to later verify whether
466 // the counters are realistic (i.e. start from zero after this time).
467 mStartUs = getNowUs();
468
Eric Laurentec9a0322013-08-28 10:23:01 -0700469 // force refresh of remaining frames by processAudioBuffer() as last
470 // write before stop could be partial.
471 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800472 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700473 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700474 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800475
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800476 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800477 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100478 if (previousState == STATE_STOPPING) {
479 mProxy->interrupt();
480 } else {
481 t->resume();
482 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800483 } else {
484 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
485 get_sched_policy(0, &mPreviousSchedulingGroup);
486 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
487 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800488
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800489 status_t status = NO_ERROR;
490 if (!(flags & CBLK_INVALID)) {
491 status = mAudioTrack->start();
492 if (status == DEAD_OBJECT) {
493 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800494 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800495 }
496 if (flags & CBLK_INVALID) {
497 status = restoreTrack_l("start");
498 }
499
500 if (status != NO_ERROR) {
501 ALOGE("start() status %d", status);
502 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800503 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100504 if (previousState != STATE_STOPPING) {
505 t->pause();
506 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800507 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700508 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700509 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800510 }
511 }
512
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100513 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800514}
515
516void AudioTrack::stop()
517{
518 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700519 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800520 return;
521 }
522
Glenn Kasten23a75452014-01-13 10:37:17 -0800523 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100524 mState = STATE_STOPPING;
525 } else {
526 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -0700527 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100528 }
529
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800530 mProxy->interrupt();
531 mAudioTrack->stop();
532 // the playback head position will reset to 0, so if a marker is set, we need
533 // to activate it again
534 mMarkerReached = false;
Andy Hung9b461582014-12-01 17:56:29 -0800535
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800536 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800537 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800538 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
539 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800540 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100541
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800542 sp<AudioTrackThread> t = mAudioTrackThread;
543 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800544 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100545 t->pause();
546 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800547 } else {
548 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
549 set_sched_policy(0, mPreviousSchedulingGroup);
550 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800551}
552
553bool AudioTrack::stopped() const
554{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800555 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800556 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800557}
558
559void AudioTrack::flush()
560{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800561 if (mSharedBuffer != 0) {
562 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800563 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800564 AutoMutex lock(mLock);
565 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
566 return;
567 }
568 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800569}
570
Eric Laurent1703cdf2011-03-07 14:52:59 -0800571void AudioTrack::flush_l()
572{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800573 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700574
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700575 // clear playback marker and periodic update counter
576 mMarkerPosition = 0;
577 mMarkerReached = false;
578 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100579 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700580
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800581 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700582 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800583 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100584 mProxy->interrupt();
585 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800586 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800587 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800588}
589
590void AudioTrack::pause()
591{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800592 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100593 if (mState == STATE_ACTIVE) {
594 mState = STATE_PAUSED;
595 } else if (mState == STATE_STOPPING) {
596 mState = STATE_PAUSED_STOPPING;
597 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800598 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800599 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800600 mProxy->interrupt();
601 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800602
Marco Nelissen3a90f282014-03-10 11:21:43 -0700603 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700604 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700605 // An offload output can be re-used between two audio tracks having
606 // the same configuration. A timestamp query for a paused track
607 // while the other is running would return an incorrect time.
608 // To fix this, cache the playback position on a pause() and return
609 // this time when requested until the track is resumed.
610
611 // OffloadThread sends HAL pause in its threadLoop. Time saved
612 // here can be slightly off.
613
614 // TODO: check return code for getRenderPosition.
615
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800616 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800617 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
618 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
619 }
620 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800621}
622
Eric Laurentbe916aa2010-06-01 23:49:17 -0700623status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800624{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700625 // This duplicates a test by AudioTrack JNI, but that is not the only caller
626 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
627 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700628 return BAD_VALUE;
629 }
630
Eric Laurent1703cdf2011-03-07 14:52:59 -0800631 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800632 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
633 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800634
Glenn Kastenc56f3422014-03-21 17:53:17 -0700635 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700636
Glenn Kasten23a75452014-01-13 10:37:17 -0800637 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700638 mAudioTrack->signal();
639 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700640 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800641}
642
Glenn Kastenb1c09932012-02-27 16:21:04 -0800643status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800644{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800645 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700646}
647
Eric Laurent2beeb502010-07-16 07:43:46 -0700648status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700649{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700650 // This duplicates a test by AudioTrack JNI, but that is not the only caller
651 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700652 return BAD_VALUE;
653 }
654
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800655 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700656 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800657 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700658
659 return NO_ERROR;
660}
661
Glenn Kastena5224f32012-01-04 12:41:44 -0800662void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700663{
664 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800665 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700666 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800667}
668
Glenn Kasten3b16c762012-11-14 08:44:39 -0800669status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800670{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700671 if (mIsTimed || isOffloadedOrDirect()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800672 return INVALID_OPERATION;
673 }
674
Eric Laurent0d6db582014-11-12 18:39:44 -0800675 AutoMutex lock(mLock);
676 if (mOutput == AUDIO_IO_HANDLE_NONE) {
677 return NO_INIT;
678 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800679 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800680 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700681 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800682 }
Andy Hungcd044842014-08-07 11:04:34 -0700683 if (rate == 0 || rate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700684 return BAD_VALUE;
685 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800686
Glenn Kastene3aa6592012-12-04 12:22:46 -0800687 mSampleRate = rate;
688 mProxy->setSampleRate(rate);
689
Eric Laurent57326622009-07-07 07:10:45 -0700690 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800691}
692
Glenn Kastena5224f32012-01-04 12:41:44 -0800693uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800694{
John Grossman4ff14ba2012-02-08 16:37:41 -0800695 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800696 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800697 }
698
Eric Laurent1703cdf2011-03-07 14:52:59 -0800699 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700700
701 // sample rate can be updated during playback by the offloaded decoder so we need to
702 // query the HAL and update if needed.
703// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700704 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700705 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700706 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700707 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700708 if (status == NO_ERROR) {
709 mSampleRate = sampleRate;
710 }
711 }
712 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800713 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800714}
715
716status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
717{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700718 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800719 return INVALID_OPERATION;
720 }
721
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800722 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800723 ;
724 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
725 loopEnd - loopStart >= MIN_LOOP) {
726 ;
727 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800728 return BAD_VALUE;
729 }
730
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800731 AutoMutex lock(mLock);
732 // See setPosition() regarding setting parameters such as loop points or position while active
733 if (mState == STATE_ACTIVE) {
734 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700735 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800736 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800737 return NO_ERROR;
738}
739
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800740void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
741{
Andy Hung4ede21d2014-12-12 15:37:34 -0800742 // We do not update the periodic notification point.
743 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
744 mLoopCount = loopCount;
745 mLoopEnd = loopEnd;
746 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800747 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800748 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -0800749
750 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800751}
752
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800753status_t AudioTrack::setMarkerPosition(uint32_t marker)
754{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700755 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700756 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700757 return INVALID_OPERATION;
758 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800759
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800760 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800761 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700762 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800763
Andy Hung3c09c782014-12-29 18:39:32 -0800764 sp<AudioTrackThread> t = mAudioTrackThread;
765 if (t != 0) {
766 t->wake();
767 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800768 return NO_ERROR;
769}
770
Glenn Kastena5224f32012-01-04 12:41:44 -0800771status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800772{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700773 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100774 return INVALID_OPERATION;
775 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700776 if (marker == NULL) {
777 return BAD_VALUE;
778 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800779
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800780 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800781 *marker = mMarkerPosition;
782
783 return NO_ERROR;
784}
785
786status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
787{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700788 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700789 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700790 return INVALID_OPERATION;
791 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800792
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800793 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700794 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800795 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800796
Andy Hung3c09c782014-12-29 18:39:32 -0800797 sp<AudioTrackThread> t = mAudioTrackThread;
798 if (t != 0) {
799 t->wake();
800 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800801 return NO_ERROR;
802}
803
Glenn Kastena5224f32012-01-04 12:41:44 -0800804status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800805{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700806 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100807 return INVALID_OPERATION;
808 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700809 if (updatePeriod == NULL) {
810 return BAD_VALUE;
811 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800812
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800813 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800814 *updatePeriod = mUpdatePeriod;
815
816 return NO_ERROR;
817}
818
819status_t AudioTrack::setPosition(uint32_t position)
820{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700821 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700822 return INVALID_OPERATION;
823 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800824 if (position > mFrameCount) {
825 return BAD_VALUE;
826 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800827
Eric Laurent1703cdf2011-03-07 14:52:59 -0800828 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800829 // Currently we require that the player is inactive before setting parameters such as position
830 // or loop points. Otherwise, there could be a race condition: the application could read the
831 // current position, compute a new position or loop parameters, and then set that position or
832 // loop parameters but it would do the "wrong" thing since the position has continued to advance
833 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
834 // to specify how it wants to handle such scenarios.
835 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700836 return INVALID_OPERATION;
837 }
Andy Hung9b461582014-12-01 17:56:29 -0800838 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -0700839 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800840 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -0800841
842 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800843 return NO_ERROR;
844}
845
Glenn Kasten200092b2014-08-15 15:13:30 -0700846status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800847{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700848 if (position == NULL) {
849 return BAD_VALUE;
850 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800851
Eric Laurent1703cdf2011-03-07 14:52:59 -0800852 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700853 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100854 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800855
Eric Laurentab5cdba2014-06-09 17:22:27 -0700856 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800857 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
858 *position = mPausedPosition;
859 return NO_ERROR;
860 }
861
Glenn Kasten142f5192014-03-25 17:44:59 -0700862 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100863 uint32_t halFrames;
864 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
865 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700866 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
867 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100868 *position = dspFrames;
869 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -0800870 if (mCblk->mFlags & CBLK_INVALID) {
871 restoreTrack_l("getPosition");
872 }
873
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100874 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700875 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
876 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100877 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800878 return NO_ERROR;
879}
880
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000881status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800882{
883 if (mSharedBuffer == 0 || mIsTimed) {
884 return INVALID_OPERATION;
885 }
886 if (position == NULL) {
887 return BAD_VALUE;
888 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800889
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800890 AutoMutex lock(mLock);
891 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800892 return NO_ERROR;
893}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800894
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800895status_t AudioTrack::reload()
896{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700897 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800898 return INVALID_OPERATION;
899 }
900
Eric Laurent1703cdf2011-03-07 14:52:59 -0800901 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800902 // See setPosition() regarding setting parameters such as loop points or position while active
903 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700904 return INVALID_OPERATION;
905 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800906 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800907 (void) updateAndGetPosition_l();
908 mPosition = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800909#if 0
Andy Hung9b461582014-12-01 17:56:29 -0800910 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -0800911 // of loop count. Historically we have not restored loop count, start, end,
912 // but it makes sense if one desires to repeat playing a particular sound.
913 if (mLoopCount != 0) {
914 mLoopCountNotified = mLoopCount;
915 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
916 }
917#endif
Andy Hung9b461582014-12-01 17:56:29 -0800918 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800919 return NO_ERROR;
920}
921
Glenn Kasten38e905b2014-01-13 10:21:48 -0800922audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700923{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800924 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100925 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800926}
927
Eric Laurentbe916aa2010-06-01 23:49:17 -0700928status_t AudioTrack::attachAuxEffect(int effectId)
929{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800930 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700931 status_t status = mAudioTrack->attachAuxEffect(effectId);
932 if (status == NO_ERROR) {
933 mAuxEffectId = effectId;
934 }
935 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700936}
937
Eric Laurente83b55d2014-11-14 10:06:21 -0800938audio_stream_type_t AudioTrack::streamType() const
939{
940 if (mStreamType == AUDIO_STREAM_DEFAULT) {
941 return audio_attributes_to_stream_type(&mAttributes);
942 }
943 return mStreamType;
944}
945
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800946// -------------------------------------------------------------------------
947
Eric Laurent1703cdf2011-03-07 14:52:59 -0800948// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -0700949status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800950{
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800951 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
952 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700953 ALOGE("Could not get audioflinger");
954 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800955 }
956
Eric Laurente83b55d2014-11-14 10:06:21 -0800957 audio_io_handle_t output;
958 audio_stream_type_t streamType = mStreamType;
959 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
960 status_t status = AudioSystem::getOutputForAttr(attr, &output,
961 (audio_session_t)mSessionId, &streamType,
962 mSampleRate, mFormat, mChannelMask,
963 mFlags, mOffloadInfo);
964
965
966 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700967 ALOGE("Could not get audio output for session %d, stream type %d, usage %d, sample rate %u, format %#x,"
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700968 " channel mask %#x, flags %#x",
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700969 mSessionId, streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800970 return BAD_VALUE;
971 }
972 {
973 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
974 // we must release it ourselves if anything goes wrong.
975
Glenn Kastence8828a2013-09-16 18:07:38 -0700976 // Not all of these values are needed under all conditions, but it is easier to get them all
977
Eric Laurentd1b449a2010-05-14 03:26:45 -0700978 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -0700979 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700980 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800981 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800982 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700983 }
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700984 ALOGV("createTrack_l() output %d afLatency %u", output, afLatency);
Eric Laurentd1b449a2010-05-14 03:26:45 -0700985
Glenn Kastence8828a2013-09-16 18:07:38 -0700986 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700987 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -0700988 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700989 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800990 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700991 }
992
993 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700994 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -0700995 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700996 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800997 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700998 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800999 if (mSampleRate == 0) {
1000 mSampleRate = afSampleRate;
1001 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001002 // Client decides whether the track is TIMED (see below), but can only express a preference
1003 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001004 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001005 // either of these use cases:
1006 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -08001007 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001008 // use case 2: callback transfer mode
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001009 (mTransfer == TRANSFER_CALLBACK) ||
1010 // use case 3: obtain/release mode
1011 (mTransfer == TRANSFER_OBTAIN)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001012 // matching sample rate
1013 (mSampleRate == afSampleRate))) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001014 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client; transfer %d, track %u Hz, output %u Hz",
1015 mTransfer, mSampleRate, afSampleRate);
Glenn Kasten093000f2012-05-03 09:35:36 -07001016 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001017 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001018 }
1019
Glenn Kastence8828a2013-09-16 18:07:38 -07001020 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -08001021 // n = 1 fast track with single buffering; nBuffering is ignored
1022 // n = 2 fast track with double buffering
Andy Hung0e48d252015-01-26 11:43:15 -08001023 // n = 2 normal track, (including those with sample rate conversion)
1024 // n >= 3 very high latency or very small notification interval (unused).
1025 const uint32_t nBuffering = 2;
Glenn Kastence8828a2013-09-16 18:07:38 -07001026
Eric Laurentd1b449a2010-05-14 03:26:45 -07001027 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001028
Glenn Kasten363fb752014-01-15 12:27:31 -08001029 size_t frameCount = mReqFrameCount;
1030 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001031
Glenn Kasten363fb752014-01-15 12:27:31 -08001032 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001033 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001034 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001035 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001036 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001037 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001038 if (mNotificationFramesAct != frameCount) {
1039 mNotificationFramesAct = frameCount;
1040 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001041 } else if (mSharedBuffer != 0) {
Andy Hungabdb9902015-01-12 15:08:22 -08001042 // FIXME: Ensure client side memory buffers need
1043 // not have additional alignment beyond sample
1044 // (e.g. 16 bit stereo accessed as 32 bit frame).
1045 size_t alignment = audio_bytes_per_sample(mFormat);
Glenn Kastenb7730382014-04-30 15:50:31 -07001046 if (alignment & 1) {
Andy Hungabdb9902015-01-12 15:08:22 -08001047 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
Glenn Kastenb7730382014-04-30 15:50:31 -07001048 alignment = 1;
1049 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001050 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001051 // More than 2 channels does not require stronger alignment than stereo
1052 alignment <<= 1;
1053 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001054 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001055 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001056 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001057 status = BAD_VALUE;
1058 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001059 }
1060
1061 // When initializing a shared buffer AudioTrack via constructors,
1062 // there's no frameCount parameter.
1063 // But when initializing a shared buffer AudioTrack via set(),
1064 // there _is_ a frameCount parameter. We silently ignore it.
Andy Hungabdb9902015-01-12 15:08:22 -08001065 frameCount = mSharedBuffer->size() / mFrameSize;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001066 } else {
Andy Hung0e48d252015-01-26 11:43:15 -08001067 // For fast and normal streaming tracks,
1068 // the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -07001069 }
1070
Glenn Kastena075db42012-03-06 11:22:44 -08001071 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1072 if (mIsTimed) {
1073 trackFlags |= IAudioFlinger::TRACK_TIMED;
1074 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001075
1076 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001077 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001078 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001079 if (mAudioTrackThread != 0) {
1080 tid = mAudioTrackThread->getTid();
1081 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001082 }
1083
Glenn Kasten363fb752014-01-15 12:27:31 -08001084 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001085 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1086 }
1087
Eric Laurentab5cdba2014-06-09 17:22:27 -07001088 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1089 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1090 }
1091
Glenn Kasten74935e42013-12-19 08:56:45 -08001092 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1093 // but we will still need the original value also
Glenn Kasten138d6f92015-03-20 10:54:51 -07001094 int originalSessionId = mSessionId;
Eric Laurente83b55d2014-11-14 10:06:21 -08001095 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001096 mSampleRate,
Andy Hungabdb9902015-01-12 15:08:22 -08001097 mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001098 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001099 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001100 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001101 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001102 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001103 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001104 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001105 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001106 &status);
Glenn Kasten138d6f92015-03-20 10:54:51 -07001107 ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
1108 "session ID changed from %d to %d", originalSessionId, mSessionId);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001109
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001110 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001111 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001112 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001113 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001114 ALOG_ASSERT(track != 0);
1115
Glenn Kasten38e905b2014-01-13 10:21:48 -08001116 // AudioFlinger now owns the reference to the I/O handle,
1117 // so we are no longer responsible for releasing it.
1118
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001119 sp<IMemory> iMem = track->getCblk();
1120 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001121 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001122 return NO_INIT;
1123 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001124 void *iMemPointer = iMem->pointer();
1125 if (iMemPointer == NULL) {
1126 ALOGE("Could not get control block pointer");
1127 return NO_INIT;
1128 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001129 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001130 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001131 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001132 mDeathNotifier.clear();
1133 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001134 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001135 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001136 IPCThreadState::self()->flushCommands();
1137
Glenn Kasten0cde0762014-01-16 15:06:36 -08001138 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001139 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001140 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001141 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1142 // In current design, AudioTrack client checks and ensures frame count validity before
1143 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1144 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001145 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001146 }
1147 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001148
Glenn Kastena07f17c2013-04-23 12:39:37 -07001149 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001150 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001151 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001152 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001153 mAwaitBoost = true;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001154 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001155 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001156 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001157 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001158 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001159 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001160 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001161 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1162 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1163 } else {
1164 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001165 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001166 // FIXME This is a warning, not an error, so don't return error status
1167 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001168 }
1169 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001170 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1171 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1172 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1173 } else {
1174 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1175 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1176 // FIXME This is a warning, not an error, so don't return error status
1177 //return NO_INIT;
1178 }
1179 }
Andy Hung0e48d252015-01-26 11:43:15 -08001180 // Make sure that application is notified with sufficient margin before underrun
1181 if (mSharedBuffer == 0 && audio_is_linear_pcm(mFormat)) {
1182 // Theoretically double-buffering is not required for fast tracks,
1183 // due to tighter scheduling. But in practice, to accommodate kernels with
1184 // scheduling jitter, and apps with computation jitter, we use double-buffering
1185 // for fast tracks just like normal streaming tracks.
1186 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount / nBuffering) {
1187 mNotificationFramesAct = frameCount / nBuffering;
1188 }
1189 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001190
Glenn Kasten38e905b2014-01-13 10:21:48 -08001191 // We retain a copy of the I/O handle, but don't own the reference
1192 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001193 mRefreshRemaining = true;
1194
1195 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1196 // is the value of pointer() for the shared buffer, otherwise buffers points
1197 // immediately after the control block. This address is for the mapping within client
1198 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1199 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001200 if (mSharedBuffer == 0) {
Glenn Kasten138d6f92015-03-20 10:54:51 -07001201 buffers = cblk + 1;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001202 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001203 buffers = mSharedBuffer->pointer();
Glenn Kasten138d6f92015-03-20 10:54:51 -07001204 if (buffers == NULL) {
1205 ALOGE("Could not get buffer pointer");
1206 return NO_INIT;
1207 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001208 }
1209
Eric Laurent2beeb502010-07-16 07:43:46 -07001210 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001211 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001212 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001213
Glenn Kastenb6037442012-11-14 13:42:25 -08001214 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001215 // If IAudioTrack is re-created, don't let the requested frameCount
1216 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001217 if (frameCount > mReqFrameCount) {
1218 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001219 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001220
1221 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001222 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001223 mStaticProxy.clear();
Andy Hungabdb9902015-01-12 15:08:22 -08001224 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001225 } else {
Andy Hungabdb9902015-01-12 15:08:22 -08001226 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001227 mProxy = mStaticProxy;
1228 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001229
1230 mProxy->setVolumeLR(gain_minifloat_pack(
1231 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1232 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1233
Glenn Kastene3aa6592012-12-04 12:22:46 -08001234 mProxy->setSendLevel(mSendLevel);
1235 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001236 mProxy->setMinimum(mNotificationFramesAct);
1237
1238 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001239 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001240
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001241 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001242 }
1243
1244release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001245 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001246 if (status == NO_ERROR) {
1247 status = NO_INIT;
1248 }
1249 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001250}
1251
Glenn Kastenb46f3942015-03-09 12:00:30 -07001252status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001253{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001254 if (audioBuffer == NULL) {
1255 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001256 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001257 if (mTransfer != TRANSFER_OBTAIN) {
1258 audioBuffer->frameCount = 0;
1259 audioBuffer->size = 0;
1260 audioBuffer->raw = NULL;
1261 return INVALID_OPERATION;
1262 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001263
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001264 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001265 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001266 if (waitCount == -1) {
1267 requested = &ClientProxy::kForever;
1268 } else if (waitCount == 0) {
1269 requested = &ClientProxy::kNonBlocking;
1270 } else if (waitCount > 0) {
1271 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001272 timeout.tv_sec = ms / 1000;
1273 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1274 requested = &timeout;
1275 } else {
1276 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1277 requested = NULL;
1278 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001279 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001280}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001281
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001282status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1283 struct timespec *elapsed, size_t *nonContig)
1284{
1285 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1286 uint32_t oldSequence = 0;
1287 uint32_t newSequence;
1288
1289 Proxy::Buffer buffer;
1290 status_t status = NO_ERROR;
1291
1292 static const int32_t kMaxTries = 5;
1293 int32_t tryCounter = kMaxTries;
1294
1295 do {
1296 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1297 // keep them from going away if another thread re-creates the track during obtainBuffer()
1298 sp<AudioTrackClientProxy> proxy;
1299 sp<IMemory> iMem;
1300
1301 { // start of lock scope
1302 AutoMutex lock(mLock);
1303
1304 newSequence = mSequence;
1305 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1306 if (status == DEAD_OBJECT) {
1307 // re-create track, unless someone else has already done so
1308 if (newSequence == oldSequence) {
1309 status = restoreTrack_l("obtainBuffer");
1310 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001311 buffer.mFrameCount = 0;
1312 buffer.mRaw = NULL;
1313 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001314 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001315 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001316 }
1317 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001318 oldSequence = newSequence;
1319
1320 // Keep the extra references
1321 proxy = mProxy;
1322 iMem = mCblkMemory;
1323
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001324 if (mState == STATE_STOPPING) {
1325 status = -EINTR;
1326 buffer.mFrameCount = 0;
1327 buffer.mRaw = NULL;
1328 buffer.mNonContig = 0;
1329 break;
1330 }
1331
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001332 // Non-blocking if track is stopped or paused
1333 if (mState != STATE_ACTIVE) {
1334 requested = &ClientProxy::kNonBlocking;
1335 }
1336
1337 } // end of lock scope
1338
1339 buffer.mFrameCount = audioBuffer->frameCount;
1340 // FIXME starts the requested timeout and elapsed over from scratch
1341 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1342
1343 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1344
1345 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001346 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001347 audioBuffer->raw = buffer.mRaw;
1348 if (nonContig != NULL) {
1349 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001350 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001351 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001352}
1353
Glenn Kasten54a8a452015-03-09 12:03:00 -07001354void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001355{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001356 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001357 if (mTransfer == TRANSFER_SHARED) {
1358 return;
1359 }
1360
Andy Hungabdb9902015-01-12 15:08:22 -08001361 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001362 if (stepCount == 0) {
1363 return;
1364 }
1365
1366 Proxy::Buffer buffer;
1367 buffer.mFrameCount = stepCount;
1368 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001369
Eric Laurent1703cdf2011-03-07 14:52:59 -08001370 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001371 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001372 mInUnderrun = false;
1373 mProxy->releaseBuffer(&buffer);
1374
1375 // restart track if it was disabled by audioflinger due to previous underrun
1376 if (mState == STATE_ACTIVE) {
1377 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001378 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001379 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001380 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001381 mAudioTrack->start();
1382 }
1383 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001384}
1385
1386// -------------------------------------------------------------------------
1387
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001388ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001389{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001390 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001391 return INVALID_OPERATION;
1392 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001393
Eric Laurentab5cdba2014-06-09 17:22:27 -07001394 if (isDirect()) {
1395 AutoMutex lock(mLock);
1396 int32_t flags = android_atomic_and(
1397 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1398 &mCblk->mFlags);
1399 if (flags & CBLK_INVALID) {
1400 return DEAD_OBJECT;
1401 }
1402 }
1403
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001404 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001405 // Sanity-check: user is most-likely passing an error code, and it would
1406 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001407 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001408 return BAD_VALUE;
1409 }
1410
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001411 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001412 Buffer audioBuffer;
1413
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001414 while (userSize >= mFrameSize) {
1415 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001416
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001417 status_t err = obtainBuffer(&audioBuffer,
1418 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001419 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001420 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001421 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001422 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001423 return ssize_t(err);
1424 }
1425
Glenn Kastenae4b8792015-03-20 09:04:21 -07001426 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08001427 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001428 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001429 userSize -= toWrite;
1430 written += toWrite;
1431
1432 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001433 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001434
1435 return written;
1436}
1437
1438// -------------------------------------------------------------------------
1439
John Grossman4ff14ba2012-02-08 16:37:41 -08001440TimedAudioTrack::TimedAudioTrack() {
1441 mIsTimed = true;
1442}
1443
1444status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1445{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001446 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001447 status_t result = UNKNOWN_ERROR;
1448
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001449#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001450 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1451 // while we are accessing the cblk
1452 sp<IAudioTrack> audioTrack = mAudioTrack;
1453 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001454#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001455
John Grossman4ff14ba2012-02-08 16:37:41 -08001456 // If the track is not invalid already, try to allocate a buffer. alloc
1457 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001458 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001459 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001460 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001461 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1462 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001463 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001464 }
1465 }
1466
1467 // If the track is invalid at this point, attempt to restore it. and try the
1468 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001469 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001470 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001471
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001472 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001473 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001474 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001475 }
1476
1477 return result;
1478}
1479
1480status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1481 int64_t pts)
1482{
Eric Laurentdf839842012-05-31 14:27:14 -07001483 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1484 {
1485 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001486 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001487 // restart track if it was disabled by audioflinger due to previous underrun
1488 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001489 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1490 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001491 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001492 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001493 mAudioTrack->start();
1494 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001495 }
Eric Laurentdf839842012-05-31 14:27:14 -07001496 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001497}
1498
1499status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1500 TargetTimeline target)
1501{
1502 return mAudioTrack->setMediaTimeTransform(xform, target);
1503}
1504
1505// -------------------------------------------------------------------------
1506
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001507nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001508{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001509 // Currently the AudioTrack thread is not created if there are no callbacks.
1510 // Would it ever make sense to run the thread, even without callbacks?
1511 // If so, then replace this by checks at each use for mCbf != NULL.
1512 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1513
Eric Laurent1703cdf2011-03-07 14:52:59 -08001514 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001515 if (mAwaitBoost) {
1516 mAwaitBoost = false;
1517 mLock.unlock();
1518 static const int32_t kMaxTries = 5;
1519 int32_t tryCounter = kMaxTries;
1520 uint32_t pollUs = 10000;
1521 do {
1522 int policy = sched_getscheduler(0);
1523 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1524 break;
1525 }
1526 usleep(pollUs);
1527 pollUs <<= 1;
1528 } while (tryCounter-- > 0);
1529 if (tryCounter < 0) {
1530 ALOGE("did not receive expected priority boost on time");
1531 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001532 // Run again immediately
1533 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001534 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001535
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001536 // Can only reference mCblk while locked
1537 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001538 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001539
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001540 // Check for track invalidation
1541 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001542 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1543 // AudioSystem cache. We should not exit here but after calling the callback so
1544 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001545 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001546 status_t status = restoreTrack_l("processAudioBuffer");
Andy Hung53c3b5f2014-12-15 16:42:05 -08001547 // after restoration, continue below to make sure that the loop and buffer events
1548 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001549 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001550 }
1551
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001552 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001553 bool active = mState == STATE_ACTIVE;
1554
1555 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1556 bool newUnderrun = false;
1557 if (flags & CBLK_UNDERRUN) {
1558#if 0
1559 // Currently in shared buffer mode, when the server reaches the end of buffer,
1560 // the track stays active in continuous underrun state. It's up to the application
1561 // to pause or stop the track, or set the position to a new offset within buffer.
1562 // This was some experimental code to auto-pause on underrun. Keeping it here
1563 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1564 if (mTransfer == TRANSFER_SHARED) {
1565 mState = STATE_PAUSED;
1566 active = false;
1567 }
1568#endif
1569 if (!mInUnderrun) {
1570 mInUnderrun = true;
1571 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001572 }
1573 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001574
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001575 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001576 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001577
1578 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001579 bool markerReached = false;
1580 size_t markerPosition = mMarkerPosition;
1581 // FIXME fails for wraparound, need 64 bits
1582 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1583 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001584 }
1585
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001586 // Determine number of new position callback(s) that will be needed, while locked
1587 size_t newPosCount = 0;
1588 size_t newPosition = mNewPosition;
1589 size_t updatePeriod = mUpdatePeriod;
1590 // FIXME fails for wraparound, need 64 bits
1591 if (updatePeriod > 0 && position >= newPosition) {
1592 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1593 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001594 }
1595
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001596 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001597 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001598 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001599 if (mRefreshRemaining) {
1600 mRefreshRemaining = false;
1601 mRemainingFrames = notificationFrames;
1602 mRetryOnPartialBuffer = false;
1603 }
1604 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001605 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001606 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001607
Andy Hung53c3b5f2014-12-15 16:42:05 -08001608 // Determine the number of new loop callback(s) that will be needed, while locked.
1609 int loopCountNotifications = 0;
1610 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1611
1612 if (mLoopCount > 0) {
1613 int loopCount;
1614 size_t bufferPosition;
1615 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1616 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1617 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1618 mLoopCountNotified = loopCount; // discard any excess notifications
1619 } else if (mLoopCount < 0) {
1620 // FIXME: We're not accurate with notification count and position with infinite looping
1621 // since loopCount from server side will always return -1 (we could decrement it).
1622 size_t bufferPosition = mStaticProxy->getBufferPosition();
1623 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1624 loopPeriod = mLoopEnd - bufferPosition;
1625 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1626 size_t bufferPosition = mStaticProxy->getBufferPosition();
1627 loopPeriod = mFrameCount - bufferPosition;
1628 }
1629
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001630 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08001631 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001632 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1633
1634 mLock.unlock();
1635
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001636 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001637 struct timespec timeout;
1638 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1639 timeout.tv_nsec = 0;
1640
Glenn Kasten96f04882013-09-20 09:28:56 -07001641 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001642 switch (status) {
1643 case NO_ERROR:
1644 case DEAD_OBJECT:
1645 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001646 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001647 {
1648 AutoMutex lock(mLock);
1649 // The previously assigned value of waitStreamEnd is no longer valid,
1650 // since the mutex has been unlocked and either the callback handler
1651 // or another thread could have re-started the AudioTrack during that time.
1652 waitStreamEnd = mState == STATE_STOPPING;
1653 if (waitStreamEnd) {
1654 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001655 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001656 }
1657 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001658 if (waitStreamEnd && status != DEAD_OBJECT) {
1659 return NS_INACTIVE;
1660 }
1661 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001662 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001663 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001664 }
1665
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001666 // perform callbacks while unlocked
1667 if (newUnderrun) {
1668 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1669 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001670 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001671 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001672 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001673 }
1674 if (flags & CBLK_BUFFER_END) {
1675 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1676 }
1677 if (markerReached) {
1678 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1679 }
1680 while (newPosCount > 0) {
1681 size_t temp = newPosition;
1682 mCbf(EVENT_NEW_POS, mUserData, &temp);
1683 newPosition += updatePeriod;
1684 newPosCount--;
1685 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001686
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001687 if (mObservedSequence != sequence) {
1688 mObservedSequence = sequence;
1689 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001690 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001691 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001692 return NS_INACTIVE;
1693 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001694 }
1695
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001696 // if inactive, then don't run me again until re-started
1697 if (!active) {
1698 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001699 }
1700
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001701 // Compute the estimated time until the next timed event (position, markers, loops)
1702 // FIXME only for non-compressed audio
1703 uint32_t minFrames = ~0;
1704 if (!markerReached && position < markerPosition) {
1705 minFrames = markerPosition - position;
1706 }
1707 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08001708 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001709 minFrames = loopPeriod;
1710 }
Andy Hung2d85f092015-01-07 12:45:13 -08001711 if (updatePeriod > 0) {
1712 minFrames = min(minFrames, uint32_t(newPosition - position));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001713 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001714
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001715 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1716 static const uint32_t kPoll = 0;
1717 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1718 minFrames = kPoll * notificationFrames;
1719 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001720
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001721 // Convert frame units to time units
1722 nsecs_t ns = NS_WHENEVER;
1723 if (minFrames != (uint32_t) ~0) {
1724 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1725 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1726 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1727 }
1728
1729 // If not supplying data by EVENT_MORE_DATA, then we're done
1730 if (mTransfer != TRANSFER_CALLBACK) {
1731 return ns;
1732 }
1733
1734 struct timespec timeout;
1735 const struct timespec *requested = &ClientProxy::kForever;
1736 if (ns != NS_WHENEVER) {
1737 timeout.tv_sec = ns / 1000000000LL;
1738 timeout.tv_nsec = ns % 1000000000LL;
1739 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1740 requested = &timeout;
1741 }
1742
1743 while (mRemainingFrames > 0) {
1744
1745 Buffer audioBuffer;
1746 audioBuffer.frameCount = mRemainingFrames;
1747 size_t nonContig;
1748 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1749 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001750 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001751 requested = &ClientProxy::kNonBlocking;
1752 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001753 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001754 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001755 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001756 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1757 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001758 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001759 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001760 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1761 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001762 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001763
Eric Laurent42a6f422013-08-29 14:35:05 -07001764 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001765 mRetryOnPartialBuffer = false;
1766 if (avail < mRemainingFrames) {
1767 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1768 if (ns < 0 || myns < ns) {
1769 ns = myns;
1770 }
1771 return ns;
1772 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001773 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001774
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001775 size_t reqSize = audioBuffer.size;
1776 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001777 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001778
1779 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001780 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001781 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1782 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001783 return NS_NEVER;
1784 }
1785
1786 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001787 // The callback is done filling buffers
1788 // Keep this thread going to handle timed events and
1789 // still try to get more data in intervals of WAIT_PERIOD_MS
1790 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001791 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001792 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001793
Glenn Kasten138d6f92015-03-20 10:54:51 -07001794 size_t releasedFrames = writtenSize / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001795 audioBuffer.frameCount = releasedFrames;
1796 mRemainingFrames -= releasedFrames;
1797 if (misalignment >= releasedFrames) {
1798 misalignment -= releasedFrames;
1799 } else {
1800 misalignment = 0;
1801 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001802
1803 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001804
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001805 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1806 // if callback doesn't like to accept the full chunk
1807 if (writtenSize < reqSize) {
1808 continue;
1809 }
1810
1811 // There could be enough non-contiguous frames available to satisfy the remaining request
1812 if (mRemainingFrames <= nonContig) {
1813 continue;
1814 }
1815
1816#if 0
1817 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1818 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1819 // that total to a sum == notificationFrames.
1820 if (0 < misalignment && misalignment <= mRemainingFrames) {
1821 mRemainingFrames = misalignment;
1822 return (mRemainingFrames * 1100000000LL) / sampleRate;
1823 }
1824#endif
1825
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001826 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001827 mRemainingFrames = notificationFrames;
1828 mRetryOnPartialBuffer = true;
1829
1830 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1831 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001832}
1833
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001834status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001835{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001836 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001837 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001838 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001839
Glenn Kastena47f3162012-11-07 10:13:08 -08001840 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08001841 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001842 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001843
Eric Laurentab5cdba2014-06-09 17:22:27 -07001844 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001845 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001846 return DEAD_OBJECT;
1847 }
1848
Glenn Kasten200092b2014-08-15 15:13:30 -07001849 // save the old static buffer position
Andy Hung4ede21d2014-12-12 15:37:34 -08001850 size_t bufferPosition = 0;
1851 int loopCount = 0;
1852 if (mStaticProxy != 0) {
1853 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1854 }
Glenn Kasten200092b2014-08-15 15:13:30 -07001855
1856 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001857 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001858 // It will also delete the strong references on previous IAudioTrack and IMemory.
1859 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Glenn Kastenae4b8792015-03-20 09:04:21 -07001860 status_t result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001861
1862 // take the frames that will be lost by track recreation into account in saved position
Andy Hung9b461582014-12-01 17:56:29 -08001863 // For streaming tracks, this is the amount we obtained from the user/client
1864 // (not the number actually consumed at the server - those are already lost).
Glenn Kasten200092b2014-08-15 15:13:30 -07001865 (void) updateAndGetPosition_l();
Andy Hung7ccdaad2015-03-20 00:38:32 -07001866 if (mStaticProxy == 0) {
Andy Hung9b461582014-12-01 17:56:29 -08001867 mPosition = mReleased;
1868 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001869
Glenn Kastena47f3162012-11-07 10:13:08 -08001870 if (result == NO_ERROR) {
Andy Hung4ede21d2014-12-12 15:37:34 -08001871 // Continue playback from last known position and restore loop.
1872 if (mStaticProxy != 0) {
1873 if (loopCount != 0) {
1874 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
1875 mLoopStart, mLoopEnd, loopCount);
1876 } else {
1877 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001878 if (bufferPosition == mFrameCount) {
1879 ALOGD("restoring track at end of static buffer");
1880 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001881 }
1882 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001883 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001884 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001885 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001886 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001887 if (result != NO_ERROR) {
1888 ALOGW("restoreTrack_l() failed status %d", result);
1889 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001890 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001891 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001892
1893 return result;
1894}
1895
Glenn Kasten200092b2014-08-15 15:13:30 -07001896uint32_t AudioTrack::updateAndGetPosition_l()
1897{
1898 // This is the sole place to read server consumed frames
1899 uint32_t newServer = mProxy->getPosition();
1900 int32_t delta = newServer - mServer;
1901 mServer = newServer;
1902 // TODO There is controversy about whether there can be "negative jitter" in server position.
1903 // This should be investigated further, and if possible, it should be addressed.
1904 // A more definite failure mode is infrequent polling by client.
1905 // One could call (void)getPosition_l() in releaseBuffer(),
1906 // so mReleased and mPosition are always lock-step as best possible.
1907 // That should ensure delta never goes negative for infrequent polling
1908 // unless the server has more than 2^31 frames in its buffer,
1909 // in which case the use of uint32_t for these counters has bigger issues.
1910 if (delta < 0) {
1911 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
1912 delta = 0;
1913 }
1914 return mPosition += (uint32_t) delta;
1915}
1916
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001917status_t AudioTrack::setParameters(const String8& keyValuePairs)
1918{
1919 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001920 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001921}
1922
Glenn Kastence703742013-07-19 16:33:58 -07001923status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1924{
Glenn Kasten53cec222013-08-29 09:01:02 -07001925 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001926 // FIXME not implemented for fast tracks; should use proxy and SSQ
1927 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1928 return INVALID_OPERATION;
1929 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001930
1931 switch (mState) {
1932 case STATE_ACTIVE:
1933 case STATE_PAUSED:
1934 break; // handle below
1935 case STATE_FLUSHED:
1936 case STATE_STOPPED:
1937 return WOULD_BLOCK;
1938 case STATE_STOPPING:
1939 case STATE_PAUSED_STOPPING:
1940 if (!isOffloaded_l()) {
1941 return INVALID_OPERATION;
1942 }
1943 break; // offloaded tracks handled below
1944 default:
1945 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
1946 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07001947 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001948
Eric Laurent275e8e92014-11-30 15:14:47 -08001949 if (mCblk->mFlags & CBLK_INVALID) {
1950 restoreTrack_l("getTimestamp");
1951 }
1952
Glenn Kasten200092b2014-08-15 15:13:30 -07001953 // The presented frame count must always lag behind the consumed frame count.
1954 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07001955 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001956 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07001957 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001958 return status;
1959 }
1960 if (isOffloadedOrDirect_l()) {
1961 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
1962 // use cached paused position in case another offloaded track is running.
1963 timestamp.mPosition = mPausedPosition;
1964 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
1965 return NO_ERROR;
1966 }
1967
1968 // Check whether a pending flush or stop has completed, as those commands may
1969 // be asynchronous or return near finish.
1970 if (mStartUs != 0 && mSampleRate != 0) {
1971 static const int kTimeJitterUs = 100000; // 100 ms
1972 static const int k1SecUs = 1000000;
1973
1974 const int64_t timeNow = getNowUs();
1975
1976 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
1977 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
1978 if (timestampTimeUs < mStartUs) {
1979 return WOULD_BLOCK; // stale timestamp time, occurs before start.
1980 }
1981 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
1982 const int64_t deltaPositionByUs = timestamp.mPosition * 1000000LL / mSampleRate;
1983
1984 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
1985 // Verify that the counter can't count faster than the sample rate
1986 // since the start time. If greater, then that means we have failed
1987 // to completely flush or stop the previous playing track.
1988 ALOGW("incomplete flush or stop:"
1989 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
1990 (long long)deltaTimeUs, (long long)deltaPositionByUs,
1991 timestamp.mPosition);
1992 return WOULD_BLOCK;
1993 }
1994 }
1995 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
1996 }
1997 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07001998 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
1999 (void) updateAndGetPosition_l();
2000 // Server consumed (mServer) and presented both use the same server time base,
2001 // and server consumed is always >= presented.
2002 // The delta between these represents the number of frames in the buffer pipeline.
2003 // If this delta between these is greater than the client position, it means that
2004 // actually presented is still stuck at the starting line (figuratively speaking),
2005 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
2006 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2007 return INVALID_OPERATION;
2008 }
2009 // Convert timestamp position from server time base to client time base.
2010 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2011 // But if we change it to 64-bit then this could fail.
2012 // If (mPosition - mServer) can be negative then should use:
2013 // (int32_t)(mPosition - mServer)
2014 timestamp.mPosition += mPosition - mServer;
2015 // Immediately after a call to getPosition_l(), mPosition and
2016 // mServer both represent the same frame position. mPosition is
2017 // in client's point of view, and mServer is in server's point of
2018 // view. So the difference between them is the "fudge factor"
2019 // between client and server views due to stop() and/or new
2020 // IAudioTrack. And timestamp.mPosition is initially in server's
2021 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002022 }
2023 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002024}
2025
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002026String8 AudioTrack::getParameters(const String8& keys)
2027{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002028 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002029 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002030 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002031 } else {
2032 return String8::empty();
2033 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002034}
2035
Glenn Kasten23a75452014-01-13 10:37:17 -08002036bool AudioTrack::isOffloaded() const
2037{
2038 AutoMutex lock(mLock);
2039 return isOffloaded_l();
2040}
2041
Eric Laurentab5cdba2014-06-09 17:22:27 -07002042bool AudioTrack::isDirect() const
2043{
2044 AutoMutex lock(mLock);
2045 return isDirect_l();
2046}
2047
2048bool AudioTrack::isOffloadedOrDirect() const
2049{
2050 AutoMutex lock(mLock);
2051 return isOffloadedOrDirect_l();
2052}
2053
2054
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002055status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002056{
2057
2058 const size_t SIZE = 256;
2059 char buffer[SIZE];
2060 String8 result;
2061
2062 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002063 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002064 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002065 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002066 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002067 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002068 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08002069 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002070 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002071 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002072 result.append(buffer);
2073 ::write(fd, result.string(), result.size());
2074 return NO_ERROR;
2075}
2076
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002077uint32_t AudioTrack::getUnderrunFrames() const
2078{
2079 AutoMutex lock(mLock);
2080 return mProxy->getUnderrunFrames();
2081}
2082
2083// =========================================================================
2084
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002085void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002086{
2087 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2088 if (audioTrack != 0) {
2089 AutoMutex lock(audioTrack->mLock);
2090 audioTrack->mProxy->binderDied();
2091 }
2092}
2093
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002094// =========================================================================
2095
2096AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002097 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2098 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002099{
2100}
2101
2102AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002103{
2104}
2105
2106bool AudioTrack::AudioTrackThread::threadLoop()
2107{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002108 {
2109 AutoMutex _l(mMyLock);
2110 if (mPaused) {
2111 mMyCond.wait(mMyLock);
2112 // caller will check for exitPending()
2113 return true;
2114 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002115 if (mIgnoreNextPausedInt) {
2116 mIgnoreNextPausedInt = false;
2117 mPausedInt = false;
2118 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002119 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002120 if (mPausedNs > 0) {
2121 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2122 } else {
2123 mMyCond.wait(mMyLock);
2124 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002125 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002126 return true;
2127 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002128 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002129 if (exitPending()) {
2130 return false;
2131 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002132 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002133 switch (ns) {
2134 case 0:
2135 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002136 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002137 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002138 return true;
2139 case NS_NEVER:
2140 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002141 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08002142 // Event driven: call wake() when callback notifications conditions change.
2143 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002144 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002145 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002146 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002147 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002148 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002149 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002150}
2151
Glenn Kasten3acbd052012-02-28 10:39:56 -08002152void AudioTrack::AudioTrackThread::requestExit()
2153{
2154 // must be in this order to avoid a race condition
2155 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002156 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002157}
2158
2159void AudioTrack::AudioTrackThread::pause()
2160{
2161 AutoMutex _l(mMyLock);
2162 mPaused = true;
2163}
2164
2165void AudioTrack::AudioTrackThread::resume()
2166{
2167 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002168 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002169 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002170 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002171 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002172 mMyCond.signal();
2173 }
2174}
2175
Andy Hung3c09c782014-12-29 18:39:32 -08002176void AudioTrack::AudioTrackThread::wake()
2177{
2178 AutoMutex _l(mMyLock);
2179 if (!mPaused && mPausedInt && mPausedNs > 0) {
2180 // audio track is active and internally paused with timeout.
2181 mIgnoreNextPausedInt = true;
2182 mPausedInt = false;
2183 mMyCond.signal();
2184 }
2185}
2186
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002187void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2188{
2189 AutoMutex _l(mMyLock);
2190 mPausedInt = true;
2191 mPausedNs = ns;
2192}
2193
Glenn Kasten40bc9062015-03-20 09:09:33 -07002194} // namespace android