blob: 6f09cbc63cc7156de172bdb35cb2dc11ae59b318 [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
36
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 Hung7f1bc8a2014-09-12 14:43:11 -070041static int64_t convertTimespecToUs(const struct timespec &tv)
42{
43 return tv.tv_sec * 1000000ll + tv.tv_nsec / 1000;
44}
45
46// current monotonic time in microseconds.
47static int64_t getNowUs()
48{
49 struct timespec tv;
50 (void) clock_gettime(CLOCK_MONOTONIC, &tv);
51 return convertTimespecToUs(tv);
52}
53
Chia-chi Yeh33005a92010-06-16 06:33:13 +080054// static
55status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080056 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080057 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080058 uint32_t sampleRate)
59{
Glenn Kastend65d73c2012-06-22 17:21:07 -070060 if (frameCount == NULL) {
61 return BAD_VALUE;
62 }
Glenn Kasten04cd0182012-06-25 11:49:27 -070063
Glenn Kastene0fa4672012-04-24 14:35:14 -070064 // FIXME merge with similar code in createTrack_l(), except we're missing
65 // some information here that is available in createTrack_l():
66 // audio_io_handle_t output
67 // audio_format_t format
68 // audio_channel_mask_t channelMask
69 // audio_output_flags_t flags
Glenn Kasten3b16c762012-11-14 08:44:39 -080070 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080071 status_t status;
72 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
73 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080074 ALOGE("Unable to query output sample rate for stream type %d; status %d",
75 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080076 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080077 }
Glenn Kastene33054e2012-11-14 12:54:39 -080078 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -080079 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
80 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080081 ALOGE("Unable to query output frame count for stream type %d; status %d",
82 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080083 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080084 }
85 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -080086 status = AudioSystem::getOutputLatency(&afLatency, streamType);
87 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080088 ALOGE("Unable to query output latency for stream type %d; status %d",
89 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080090 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080091 }
92
93 // Ensure that buffer depth covers at least audio hardware latency
94 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080095 if (minBufCount < 2) {
96 minBufCount = 2;
97 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +080098
99 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
Andy Hungcd044842014-08-07 11:04:34 -0700100 afFrameCount * minBufCount * uint64_t(sampleRate) / afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -0800101 // The formula above should always produce a non-zero value, but return an error
102 // in the unlikely event that it does not, as that's part of the API contract.
103 if (*frameCount == 0) {
104 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %d",
105 streamType, sampleRate);
106 return BAD_VALUE;
107 }
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700108 ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, minBufCount=%d, afSampleRate=%d, afLatency=%d",
Glenn Kasten3acbd052012-02-28 10:39:56 -0800109 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800110 return NO_ERROR;
111}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800112
113// ---------------------------------------------------------------------------
114
115AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700116 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800117 mIsTimed(false),
118 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800119 mPreviousSchedulingGroup(SP_DEFAULT),
120 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800121{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700122 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
123 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
124 mAttributes.flags = 0x0;
125 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800126}
127
128AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800129 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800130 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800131 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700132 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800133 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700134 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800135 callback_t cbf,
136 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800137 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800138 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000139 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800140 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800141 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700142 pid_t pid,
143 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700144 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800145 mIsTimed(false),
146 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800147 mPreviousSchedulingGroup(SP_DEFAULT),
148 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800149{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700150 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700151 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800152 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700153 offloadInfo, uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800154}
155
Andreas Huberc8139852012-01-18 10:51:55 -0800156AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800157 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800158 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800159 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700160 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800161 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700162 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800163 callback_t cbf,
164 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800165 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800166 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000167 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800168 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800169 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700170 pid_t pid,
171 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700172 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800173 mIsTimed(false),
174 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800175 mPreviousSchedulingGroup(SP_DEFAULT),
176 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800177{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700178 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800179 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800180 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700181 uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800182}
183
184AudioTrack::~AudioTrack()
185{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800186 if (mStatus == NO_ERROR) {
187 // Make sure that callback function exits in the case where
188 // it is looping on buffer full condition in obtainBuffer().
189 // Otherwise the callback thread will never exit.
190 stop();
191 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100192 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800193 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800194 mAudioTrackThread->requestExitAndWait();
195 mAudioTrackThread.clear();
196 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800197 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700198 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700199 mCblkMemory.clear();
200 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800201 IPCThreadState::self()->flushCommands();
Marco Nelissend457c972014-02-11 08:47:07 -0800202 ALOGV("~AudioTrack, releasing session id from %d on behalf of %d",
203 IPCThreadState::self()->getCallingPid(), mClientPid);
204 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800205 }
206}
207
208status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800209 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800210 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800211 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700212 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800213 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700214 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800215 callback_t cbf,
216 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800217 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800218 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700219 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800220 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000221 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800222 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800223 int uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700224 pid_t pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700225 const audio_attributes_t* pAttributes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800226{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800227 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten838b3d82014-02-27 15:30:41 -0800228 "flags #%x, notificationFrames %u, sessionId %d, transferType %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800229 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten86f04662014-02-24 15:13:05 -0800230 sessionId, transferType);
231
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800232 switch (transferType) {
233 case TRANSFER_DEFAULT:
234 if (sharedBuffer != 0) {
235 transferType = TRANSFER_SHARED;
236 } else if (cbf == NULL || threadCanCallJava) {
237 transferType = TRANSFER_SYNC;
238 } else {
239 transferType = TRANSFER_CALLBACK;
240 }
241 break;
242 case TRANSFER_CALLBACK:
243 if (cbf == NULL || sharedBuffer != 0) {
244 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
245 return BAD_VALUE;
246 }
247 break;
248 case TRANSFER_OBTAIN:
249 case TRANSFER_SYNC:
250 if (sharedBuffer != 0) {
251 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
252 return BAD_VALUE;
253 }
254 break;
255 case TRANSFER_SHARED:
256 if (sharedBuffer == 0) {
257 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
258 return BAD_VALUE;
259 }
260 break;
261 default:
262 ALOGE("Invalid transfer type %d", transferType);
263 return BAD_VALUE;
264 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800265 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800266 mTransfer = transferType;
267
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700268 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
269 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800270
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700271 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700272
Eric Laurent1703cdf2011-03-07 14:52:59 -0800273 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800274
Glenn Kasten53cec222013-08-29 09:01:02 -0700275 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700276 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000277 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800278 return INVALID_OPERATION;
279 }
280
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800281 // handle default values first.
Eric Laurente83b55d2014-11-14 10:06:21 -0800282 if (streamType == AUDIO_STREAM_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700283 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800284 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700285 if (pAttributes == NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800286 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700287 ALOGE("Invalid stream type %d", streamType);
288 return BAD_VALUE;
289 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700290 mStreamType = streamType;
Eric Laurente83b55d2014-11-14 10:06:21 -0800291
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700292 } else {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700293 // stream type shouldn't be looked at, this track has audio attributes
294 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700295 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
296 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800297 mStreamType = AUDIO_STREAM_DEFAULT;
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800298 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700299
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800300 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800301 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700302 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800303 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800304
305 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700306 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800307 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800308 return BAD_VALUE;
309 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800310 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700311
Glenn Kasten8ba90322013-10-30 11:29:27 -0700312 if (!audio_is_output_channel(channelMask)) {
313 ALOGE("Invalid channel mask %#x", channelMask);
314 return BAD_VALUE;
315 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800316 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700317 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800318 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700319
Glenn Kastene0fa4672012-04-24 14:35:14 -0700320 // AudioFlinger does not currently support 8-bit data in shared memory
321 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
322 ALOGE("8-bit data in shared memory is not supported");
323 return BAD_VALUE;
324 }
325
Eric Laurentc2f1f072009-07-17 12:17:14 -0700326 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100327 // or offload was requested
328 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
329 || !audio_is_linear_pcm(format)) {
330 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
331 ? "Offload request, forcing to Direct Output"
332 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700333 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800334 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700335 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700336 }
337
Glenn Kastenb7730382014-04-30 15:50:31 -0700338 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
339 if (audio_is_linear_pcm(format)) {
340 mFrameSize = channelCount * audio_bytes_per_sample(format);
341 } else {
342 mFrameSize = sizeof(uint8_t);
343 }
344 mFrameSizeAF = mFrameSize;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800345 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700346 ALOG_ASSERT(audio_is_linear_pcm(format));
347 mFrameSize = channelCount * audio_bytes_per_sample(format);
348 mFrameSizeAF = channelCount * audio_bytes_per_sample(
349 format == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : format);
350 // createTrack will return an error if PCM format is not supported by server,
351 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800352 }
353
Eric Laurent0d6db582014-11-12 18:39:44 -0800354 // sampling rate must be specified for direct outputs
355 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
356 return BAD_VALUE;
357 }
358 mSampleRate = sampleRate;
359
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800360 // Make copy of input parameter offloadInfo so that in the future:
361 // (a) createTrack_l doesn't need it as an input parameter
362 // (b) we can support re-creation of offloaded tracks
363 if (offloadInfo != NULL) {
364 mOffloadInfoCopy = *offloadInfo;
365 mOffloadInfo = &mOffloadInfoCopy;
366 } else {
367 mOffloadInfo = NULL;
368 }
369
Glenn Kasten66e46352014-01-16 17:44:23 -0800370 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
371 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800372 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800373 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800374 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700375 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800376 mNotificationFramesAct = 0;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700377 mSessionId = sessionId;
Marco Nelissend457c972014-02-11 08:47:07 -0800378 int callingpid = IPCThreadState::self()->getCallingPid();
379 int mypid = getpid();
380 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800381 mClientUid = IPCThreadState::self()->getCallingUid();
382 } else {
383 mClientUid = uid;
384 }
Marco Nelissend457c972014-02-11 08:47:07 -0800385 if (pid == -1 || (callingpid != mypid)) {
386 mClientPid = callingpid;
387 } else {
388 mClientPid = pid;
389 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700390 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700391 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700392 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700393
Glenn Kastena997e7a2012-08-07 09:44:19 -0700394 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700395 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700396 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
397 }
398
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800399 // create the IAudioTrack
Eric Laurent0d6db582014-11-12 18:39:44 -0800400 status_t status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800401
Glenn Kastena997e7a2012-08-07 09:44:19 -0700402 if (status != NO_ERROR) {
403 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100404 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
405 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700406 mAudioTrackThread.clear();
407 }
408 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700409 }
410
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800411 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800412 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800413 mUserData = user;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800414 mLoopPeriod = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800415 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700416 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800417 mNewPosition = 0;
418 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700419 mServer = 0;
420 mPosition = 0;
421 mReleased = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700422 mStartUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800423 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800424 mSequence = 1;
425 mObservedSequence = mSequence;
426 mInUnderrun = false;
427
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800428 return NO_ERROR;
429}
430
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800431// -------------------------------------------------------------------------
432
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100433status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800434{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800435 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100436
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800437 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100438 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800439 }
440
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800441 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800442
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800443 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100444 if (previousState == STATE_PAUSED_STOPPING) {
445 mState = STATE_STOPPING;
446 } else {
447 mState = STATE_ACTIVE;
448 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700449 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800450 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
451 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700452 mPosition = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700453 // For offloaded tracks, we don't know if the hardware counters are really zero here,
454 // since the flush is asynchronous and stop may not fully drain.
455 // We save the time when the track is started to later verify whether
456 // the counters are realistic (i.e. start from zero after this time).
457 mStartUs = getNowUs();
458
Eric Laurentec9a0322013-08-28 10:23:01 -0700459 // force refresh of remaining frames by processAudioBuffer() as last
460 // write before stop could be partial.
461 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800462 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700463 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700464 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800465
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800466 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800467 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100468 if (previousState == STATE_STOPPING) {
469 mProxy->interrupt();
470 } else {
471 t->resume();
472 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800473 } else {
474 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
475 get_sched_policy(0, &mPreviousSchedulingGroup);
476 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
477 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800478
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800479 status_t status = NO_ERROR;
480 if (!(flags & CBLK_INVALID)) {
481 status = mAudioTrack->start();
482 if (status == DEAD_OBJECT) {
483 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800484 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800485 }
486 if (flags & CBLK_INVALID) {
487 status = restoreTrack_l("start");
488 }
489
490 if (status != NO_ERROR) {
491 ALOGE("start() status %d", status);
492 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800493 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100494 if (previousState != STATE_STOPPING) {
495 t->pause();
496 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800497 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700498 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700499 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800500 }
501 }
502
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100503 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800504}
505
506void AudioTrack::stop()
507{
508 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700509 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800510 return;
511 }
512
Glenn Kasten23a75452014-01-13 10:37:17 -0800513 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100514 mState = STATE_STOPPING;
515 } else {
516 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -0700517 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100518 }
519
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800520 mProxy->interrupt();
521 mAudioTrack->stop();
522 // the playback head position will reset to 0, so if a marker is set, we need
523 // to activate it again
524 mMarkerReached = false;
525#if 0
526 // Force flush if a shared buffer is used otherwise audioflinger
527 // will not stop before end of buffer is reached.
528 // It may be needed to make sure that we stop playback, likely in case looping is on.
529 if (mSharedBuffer != 0) {
530 flush_l();
531 }
532#endif
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100533
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800534 sp<AudioTrackThread> t = mAudioTrackThread;
535 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800536 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100537 t->pause();
538 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800539 } else {
540 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
541 set_sched_policy(0, mPreviousSchedulingGroup);
542 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800543}
544
545bool AudioTrack::stopped() const
546{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800547 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800548 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800549}
550
551void AudioTrack::flush()
552{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800553 if (mSharedBuffer != 0) {
554 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800555 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800556 AutoMutex lock(mLock);
557 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
558 return;
559 }
560 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800561}
562
Eric Laurent1703cdf2011-03-07 14:52:59 -0800563void AudioTrack::flush_l()
564{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800565 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700566
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700567 // clear playback marker and periodic update counter
568 mMarkerPosition = 0;
569 mMarkerReached = false;
570 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100571 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700572
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800573 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700574 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800575 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100576 mProxy->interrupt();
577 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800578 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800579 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800580}
581
582void AudioTrack::pause()
583{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800584 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100585 if (mState == STATE_ACTIVE) {
586 mState = STATE_PAUSED;
587 } else if (mState == STATE_STOPPING) {
588 mState = STATE_PAUSED_STOPPING;
589 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800590 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800591 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800592 mProxy->interrupt();
593 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800594
Marco Nelissen3a90f282014-03-10 11:21:43 -0700595 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700596 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700597 // An offload output can be re-used between two audio tracks having
598 // the same configuration. A timestamp query for a paused track
599 // while the other is running would return an incorrect time.
600 // To fix this, cache the playback position on a pause() and return
601 // this time when requested until the track is resumed.
602
603 // OffloadThread sends HAL pause in its threadLoop. Time saved
604 // here can be slightly off.
605
606 // TODO: check return code for getRenderPosition.
607
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800608 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800609 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
610 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
611 }
612 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800613}
614
Eric Laurentbe916aa2010-06-01 23:49:17 -0700615status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800616{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700617 // This duplicates a test by AudioTrack JNI, but that is not the only caller
618 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
619 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700620 return BAD_VALUE;
621 }
622
Eric Laurent1703cdf2011-03-07 14:52:59 -0800623 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800624 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
625 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800626
Glenn Kastenc56f3422014-03-21 17:53:17 -0700627 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700628
Glenn Kasten23a75452014-01-13 10:37:17 -0800629 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700630 mAudioTrack->signal();
631 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700632 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800633}
634
Glenn Kastenb1c09932012-02-27 16:21:04 -0800635status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800636{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800637 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700638}
639
Eric Laurent2beeb502010-07-16 07:43:46 -0700640status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700641{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700642 // This duplicates a test by AudioTrack JNI, but that is not the only caller
643 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700644 return BAD_VALUE;
645 }
646
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800647 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700648 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800649 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700650
651 return NO_ERROR;
652}
653
Glenn Kastena5224f32012-01-04 12:41:44 -0800654void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700655{
656 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800657 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700658 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800659}
660
Glenn Kasten3b16c762012-11-14 08:44:39 -0800661status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800662{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700663 if (mIsTimed || isOffloadedOrDirect()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800664 return INVALID_OPERATION;
665 }
666
Eric Laurent0d6db582014-11-12 18:39:44 -0800667 AutoMutex lock(mLock);
668 if (mOutput == AUDIO_IO_HANDLE_NONE) {
669 return NO_INIT;
670 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800671 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800672 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700673 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800674 }
Andy Hungcd044842014-08-07 11:04:34 -0700675 if (rate == 0 || rate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700676 return BAD_VALUE;
677 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800678
Glenn Kastene3aa6592012-12-04 12:22:46 -0800679 mSampleRate = rate;
680 mProxy->setSampleRate(rate);
681
Eric Laurent57326622009-07-07 07:10:45 -0700682 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800683}
684
Glenn Kastena5224f32012-01-04 12:41:44 -0800685uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800686{
John Grossman4ff14ba2012-02-08 16:37:41 -0800687 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800688 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800689 }
690
Eric Laurent1703cdf2011-03-07 14:52:59 -0800691 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700692
693 // sample rate can be updated during playback by the offloaded decoder so we need to
694 // query the HAL and update if needed.
695// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700696 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700697 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700698 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700699 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700700 if (status == NO_ERROR) {
701 mSampleRate = sampleRate;
702 }
703 }
704 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800705 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800706}
707
708status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
709{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700710 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800711 return INVALID_OPERATION;
712 }
713
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800714 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800715 ;
716 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
717 loopEnd - loopStart >= MIN_LOOP) {
718 ;
719 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800720 return BAD_VALUE;
721 }
722
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800723 AutoMutex lock(mLock);
724 // See setPosition() regarding setting parameters such as loop points or position while active
725 if (mState == STATE_ACTIVE) {
726 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700727 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800728 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800729 return NO_ERROR;
730}
731
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800732void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
733{
Andy Hung680b7952014-11-12 13:18:52 -0800734 // Setting the loop will reset next notification update period (like setPosition).
Glenn Kasten200092b2014-08-15 15:13:30 -0700735 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800736 mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0;
737 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
738}
739
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800740status_t AudioTrack::setMarkerPosition(uint32_t marker)
741{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700742 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700743 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700744 return INVALID_OPERATION;
745 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800746
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800747 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800748 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700749 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800750
751 return NO_ERROR;
752}
753
Glenn Kastena5224f32012-01-04 12:41:44 -0800754status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800755{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700756 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100757 return INVALID_OPERATION;
758 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700759 if (marker == NULL) {
760 return BAD_VALUE;
761 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800762
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800763 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800764 *marker = mMarkerPosition;
765
766 return NO_ERROR;
767}
768
769status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
770{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700771 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700772 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700773 return INVALID_OPERATION;
774 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800775
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800776 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700777 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800778 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800779
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800780 return NO_ERROR;
781}
782
Glenn Kastena5224f32012-01-04 12:41:44 -0800783status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800784{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700785 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100786 return INVALID_OPERATION;
787 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700788 if (updatePeriod == NULL) {
789 return BAD_VALUE;
790 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800791
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800792 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800793 *updatePeriod = mUpdatePeriod;
794
795 return NO_ERROR;
796}
797
798status_t AudioTrack::setPosition(uint32_t position)
799{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700800 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700801 return INVALID_OPERATION;
802 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800803 if (position > mFrameCount) {
804 return BAD_VALUE;
805 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800806
Eric Laurent1703cdf2011-03-07 14:52:59 -0800807 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800808 // Currently we require that the player is inactive before setting parameters such as position
809 // or loop points. Otherwise, there could be a race condition: the application could read the
810 // current position, compute a new position or loop parameters, and then set that position or
811 // loop parameters but it would do the "wrong" thing since the position has continued to advance
812 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
813 // to specify how it wants to handle such scenarios.
814 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700815 return INVALID_OPERATION;
816 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700817 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800818 mLoopPeriod = 0;
819 // FIXME Check whether loops and setting position are incompatible in old code.
820 // If we use setLoop for both purposes we lose the capability to set the position while looping.
821 mStaticProxy->setLoop(position, mFrameCount, 0);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700822
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800823 return NO_ERROR;
824}
825
Glenn Kasten200092b2014-08-15 15:13:30 -0700826status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800827{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700828 if (position == NULL) {
829 return BAD_VALUE;
830 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800831
Eric Laurent1703cdf2011-03-07 14:52:59 -0800832 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700833 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100834 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800835
Eric Laurentab5cdba2014-06-09 17:22:27 -0700836 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800837 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
838 *position = mPausedPosition;
839 return NO_ERROR;
840 }
841
Glenn Kasten142f5192014-03-25 17:44:59 -0700842 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100843 uint32_t halFrames;
844 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
845 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700846 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
847 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100848 *position = dspFrames;
849 } else {
850 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700851 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
852 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100853 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800854 return NO_ERROR;
855}
856
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000857status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800858{
859 if (mSharedBuffer == 0 || mIsTimed) {
860 return INVALID_OPERATION;
861 }
862 if (position == NULL) {
863 return BAD_VALUE;
864 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800865
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800866 AutoMutex lock(mLock);
867 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800868 return NO_ERROR;
869}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800870
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800871status_t AudioTrack::reload()
872{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700873 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800874 return INVALID_OPERATION;
875 }
876
Eric Laurent1703cdf2011-03-07 14:52:59 -0800877 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800878 // See setPosition() regarding setting parameters such as loop points or position while active
879 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700880 return INVALID_OPERATION;
881 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800882 mNewPosition = mUpdatePeriod;
883 mLoopPeriod = 0;
884 // FIXME The new code cannot reload while keeping a loop specified.
885 // Need to check how the old code handled this, and whether it's a significant change.
886 mStaticProxy->setLoop(0, mFrameCount, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800887 return NO_ERROR;
888}
889
Glenn Kasten38e905b2014-01-13 10:21:48 -0800890audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700891{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800892 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100893 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800894}
895
Eric Laurentbe916aa2010-06-01 23:49:17 -0700896status_t AudioTrack::attachAuxEffect(int effectId)
897{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800898 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700899 status_t status = mAudioTrack->attachAuxEffect(effectId);
900 if (status == NO_ERROR) {
901 mAuxEffectId = effectId;
902 }
903 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700904}
905
Eric Laurente83b55d2014-11-14 10:06:21 -0800906audio_stream_type_t AudioTrack::streamType() const
907{
908 if (mStreamType == AUDIO_STREAM_DEFAULT) {
909 return audio_attributes_to_stream_type(&mAttributes);
910 }
911 return mStreamType;
912}
913
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800914// -------------------------------------------------------------------------
915
Eric Laurent1703cdf2011-03-07 14:52:59 -0800916// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -0700917status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800918{
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800919 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
920 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700921 ALOGE("Could not get audioflinger");
922 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800923 }
924
Eric Laurente83b55d2014-11-14 10:06:21 -0800925 audio_io_handle_t output;
926 audio_stream_type_t streamType = mStreamType;
927 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
928 status_t status = AudioSystem::getOutputForAttr(attr, &output,
929 (audio_session_t)mSessionId, &streamType,
930 mSampleRate, mFormat, mChannelMask,
931 mFlags, mOffloadInfo);
932
933
934 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700935 ALOGE("Could not get audio output for stream type %d, usage %d, sample rate %u, format %#x,"
936 " channel mask %#x, flags %#x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800937 streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800938 return BAD_VALUE;
939 }
940 {
941 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
942 // we must release it ourselves if anything goes wrong.
943
Glenn Kastence8828a2013-09-16 18:07:38 -0700944 // Not all of these values are needed under all conditions, but it is easier to get them all
945
Eric Laurentd1b449a2010-05-14 03:26:45 -0700946 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -0700947 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700948 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800949 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800950 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700951 }
952
Glenn Kastence8828a2013-09-16 18:07:38 -0700953 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700954 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -0700955 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700956 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800957 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700958 }
959
960 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700961 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -0700962 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700963 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800964 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700965 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800966 if (mSampleRate == 0) {
967 mSampleRate = afSampleRate;
968 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700969 // Client decides whether the track is TIMED (see below), but can only express a preference
970 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800971 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700972 // either of these use cases:
973 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -0800974 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -0800975 // use case 2: callback transfer mode
976 (mTransfer == TRANSFER_CALLBACK)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800977 // matching sample rate
978 (mSampleRate == afSampleRate))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800979 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -0700980 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -0800981 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700982 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700983 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700984
Glenn Kastence8828a2013-09-16 18:07:38 -0700985 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -0800986 // n = 1 fast track with single buffering; nBuffering is ignored
987 // n = 2 fast track with double buffering
Glenn Kastence8828a2013-09-16 18:07:38 -0700988 // n = 2 normal track, no sample rate conversion
989 // n = 3 normal track, with sample rate conversion
990 // (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering)
991 // n > 3 very high latency or very small notification interval; nBuffering is ignored
Glenn Kasten363fb752014-01-15 12:27:31 -0800992 const uint32_t nBuffering = (mSampleRate == afSampleRate) ? 2 : 3;
Glenn Kastence8828a2013-09-16 18:07:38 -0700993
Eric Laurentd1b449a2010-05-14 03:26:45 -0700994 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700995
Glenn Kasten363fb752014-01-15 12:27:31 -0800996 size_t frameCount = mReqFrameCount;
997 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700998
Glenn Kasten363fb752014-01-15 12:27:31 -0800999 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001000 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001001 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001002 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001003 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001004 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001005 if (mNotificationFramesAct != frameCount) {
1006 mNotificationFramesAct = frameCount;
1007 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001008 } else if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001009
Glenn Kastena42ff002012-11-14 12:47:55 -08001010 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -07001011 // 8-bit data in shared memory is not currently supported by AudioFlinger
Glenn Kastenb7730382014-04-30 15:50:31 -07001012 size_t alignment = audio_bytes_per_sample(
1013 mFormat == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : mFormat);
1014 if (alignment & 1) {
1015 alignment = 1;
1016 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001017 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001018 // More than 2 channels does not require stronger alignment than stereo
1019 alignment <<= 1;
1020 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001021 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001022 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001023 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001024 status = BAD_VALUE;
1025 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001026 }
1027
1028 // When initializing a shared buffer AudioTrack via constructors,
1029 // there's no frameCount parameter.
1030 // But when initializing a shared buffer AudioTrack via set(),
1031 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kastenb7730382014-04-30 15:50:31 -07001032 frameCount = mSharedBuffer->size() / mFrameSizeAF;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001033
Glenn Kasten363fb752014-01-15 12:27:31 -08001034 } else if (!(mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001035
1036 // FIXME move these calculations and associated checks to server
Glenn Kastene0fa4672012-04-24 14:35:14 -07001037
Eric Laurentd1b449a2010-05-14 03:26:45 -07001038 // Ensure that buffer depth covers at least audio hardware latency
1039 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001040 ALOGV("afFrameCount=%zu, minBufCount=%d, afSampleRate=%u, afLatency=%d",
Glenn Kastenbb6f0a02013-06-03 15:00:29 -07001041 afFrameCount, minBufCount, afSampleRate, afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001042 if (minBufCount <= nBuffering) {
1043 minBufCount = nBuffering;
Glenn Kasten7c027242012-12-26 14:43:16 -08001044 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001045
Andy Hungcd044842014-08-07 11:04:34 -07001046 size_t minFrameCount = afFrameCount * minBufCount * uint64_t(mSampleRate) / afSampleRate;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001047 ALOGV("minFrameCount: %zu, afFrameCount=%zu, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -08001048 ", afLatency=%d",
Glenn Kasten363fb752014-01-15 12:27:31 -08001049 minFrameCount, afFrameCount, minBufCount, mSampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001050
1051 if (frameCount == 0) {
1052 frameCount = minFrameCount;
Glenn Kastence8828a2013-09-16 18:07:38 -07001053 } else if (frameCount < minFrameCount) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001054 // not ALOGW because it happens all the time when playing key clicks over A2DP
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001055 ALOGV("Minimum buffer size corrected from %zu to %zu",
Glenn Kastene0fa4672012-04-24 14:35:14 -07001056 frameCount, minFrameCount);
1057 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001058 }
Glenn Kastence8828a2013-09-16 18:07:38 -07001059 // Make sure that application is notified with sufficient margin before underrun
1060 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1061 mNotificationFramesAct = frameCount/nBuffering;
1062 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001063
Glenn Kastene0fa4672012-04-24 14:35:14 -07001064 } else {
1065 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -07001066 }
1067
Glenn Kastena075db42012-03-06 11:22:44 -08001068 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1069 if (mIsTimed) {
1070 trackFlags |= IAudioFlinger::TRACK_TIMED;
1071 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001072
1073 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001074 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001075 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001076 if (mAudioTrackThread != 0) {
1077 tid = mAudioTrackThread->getTid();
1078 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001079 }
1080
Glenn Kasten363fb752014-01-15 12:27:31 -08001081 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001082 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1083 }
1084
Eric Laurentab5cdba2014-06-09 17:22:27 -07001085 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1086 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1087 }
1088
Glenn Kasten74935e42013-12-19 08:56:45 -08001089 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1090 // but we will still need the original value also
Eric Laurente83b55d2014-11-14 10:06:21 -08001091 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001092 mSampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -07001093 // AudioFlinger only sees 16-bit PCM
Glenn Kastenc4b88a82014-04-30 16:54:30 -07001094 mFormat == AUDIO_FORMAT_PCM_8_BIT &&
1095 !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ?
Glenn Kasten363fb752014-01-15 12:27:31 -08001096 AUDIO_FORMAT_PCM_16_BIT : mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001097 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001098 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001099 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001100 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001101 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001102 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001103 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001104 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001105 &status);
1106
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001107 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001108 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001109 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001110 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001111 ALOG_ASSERT(track != 0);
1112
Glenn Kasten38e905b2014-01-13 10:21:48 -08001113 // AudioFlinger now owns the reference to the I/O handle,
1114 // so we are no longer responsible for releasing it.
1115
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001116 sp<IMemory> iMem = track->getCblk();
1117 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001118 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001119 return NO_INIT;
1120 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001121 void *iMemPointer = iMem->pointer();
1122 if (iMemPointer == NULL) {
1123 ALOGE("Could not get control block pointer");
1124 return NO_INIT;
1125 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001126 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001127 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001128 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001129 mDeathNotifier.clear();
1130 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001131 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001132 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001133 IPCThreadState::self()->flushCommands();
1134
Glenn Kasten0cde0762014-01-16 15:06:36 -08001135 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001136 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001137 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001138 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1139 // In current design, AudioTrack client checks and ensures frame count validity before
1140 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1141 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001142 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001143 }
1144 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001145
Glenn Kastena07f17c2013-04-23 12:39:37 -07001146 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001147 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001148 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001149 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001150 mAwaitBoost = true;
Glenn Kasten363fb752014-01-15 12:27:31 -08001151 if (mSharedBuffer == 0) {
Glenn Kastenb5fed682013-12-03 09:06:43 -08001152 // Theoretically double-buffering is not required for fast tracks,
1153 // due to tighter scheduling. But in practice, to accommodate kernels with
1154 // scheduling jitter, and apps with computation jitter, we use double-buffering.
1155 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1156 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001157 }
1158 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001159 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001160 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001161 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001162 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1163 if (mSharedBuffer == 0) {
Glenn Kastence8828a2013-09-16 18:07:38 -07001164 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1165 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001166 }
1167 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001168 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001169 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001170 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001171 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1172 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1173 } else {
1174 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001175 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001176 // FIXME This is a warning, not an error, so don't return error status
1177 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001178 }
1179 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001180 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1181 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1182 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1183 } else {
1184 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1185 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1186 // FIXME This is a warning, not an error, so don't return error status
1187 //return NO_INIT;
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 Kasten9f80dd22012-12-18 15:57:32 -08001201 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001202 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001203 buffers = mSharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001204 }
1205
Eric Laurent2beeb502010-07-16 07:43:46 -07001206 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001207 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001208 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001209
Glenn Kastenb6037442012-11-14 13:42:25 -08001210 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001211 // If IAudioTrack is re-created, don't let the requested frameCount
1212 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001213 if (frameCount > mReqFrameCount) {
1214 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001215 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001216
1217 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001218 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001219 mStaticProxy.clear();
1220 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1221 } else {
1222 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1223 mProxy = mStaticProxy;
1224 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001225 mProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001226 mProxy->setSendLevel(mSendLevel);
1227 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001228 mProxy->setMinimum(mNotificationFramesAct);
1229
1230 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001231 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001232
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001233 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001234 }
1235
1236release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001237 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001238 if (status == NO_ERROR) {
1239 status = NO_INIT;
1240 }
1241 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001242}
1243
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001244status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1245{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001246 if (audioBuffer == NULL) {
1247 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001248 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001249 if (mTransfer != TRANSFER_OBTAIN) {
1250 audioBuffer->frameCount = 0;
1251 audioBuffer->size = 0;
1252 audioBuffer->raw = NULL;
1253 return INVALID_OPERATION;
1254 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001255
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001256 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001257 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001258 if (waitCount == -1) {
1259 requested = &ClientProxy::kForever;
1260 } else if (waitCount == 0) {
1261 requested = &ClientProxy::kNonBlocking;
1262 } else if (waitCount > 0) {
1263 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001264 timeout.tv_sec = ms / 1000;
1265 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1266 requested = &timeout;
1267 } else {
1268 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1269 requested = NULL;
1270 }
1271 return obtainBuffer(audioBuffer, requested);
1272}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001273
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001274status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1275 struct timespec *elapsed, size_t *nonContig)
1276{
1277 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1278 uint32_t oldSequence = 0;
1279 uint32_t newSequence;
1280
1281 Proxy::Buffer buffer;
1282 status_t status = NO_ERROR;
1283
1284 static const int32_t kMaxTries = 5;
1285 int32_t tryCounter = kMaxTries;
1286
1287 do {
1288 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1289 // keep them from going away if another thread re-creates the track during obtainBuffer()
1290 sp<AudioTrackClientProxy> proxy;
1291 sp<IMemory> iMem;
1292
1293 { // start of lock scope
1294 AutoMutex lock(mLock);
1295
1296 newSequence = mSequence;
1297 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1298 if (status == DEAD_OBJECT) {
1299 // re-create track, unless someone else has already done so
1300 if (newSequence == oldSequence) {
1301 status = restoreTrack_l("obtainBuffer");
1302 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001303 buffer.mFrameCount = 0;
1304 buffer.mRaw = NULL;
1305 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001306 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001307 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001308 }
1309 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001310 oldSequence = newSequence;
1311
1312 // Keep the extra references
1313 proxy = mProxy;
1314 iMem = mCblkMemory;
1315
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001316 if (mState == STATE_STOPPING) {
1317 status = -EINTR;
1318 buffer.mFrameCount = 0;
1319 buffer.mRaw = NULL;
1320 buffer.mNonContig = 0;
1321 break;
1322 }
1323
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001324 // Non-blocking if track is stopped or paused
1325 if (mState != STATE_ACTIVE) {
1326 requested = &ClientProxy::kNonBlocking;
1327 }
1328
1329 } // end of lock scope
1330
1331 buffer.mFrameCount = audioBuffer->frameCount;
1332 // FIXME starts the requested timeout and elapsed over from scratch
1333 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1334
1335 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1336
1337 audioBuffer->frameCount = buffer.mFrameCount;
1338 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1339 audioBuffer->raw = buffer.mRaw;
1340 if (nonContig != NULL) {
1341 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001342 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001343 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001344}
1345
1346void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1347{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001348 if (mTransfer == TRANSFER_SHARED) {
1349 return;
1350 }
1351
1352 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1353 if (stepCount == 0) {
1354 return;
1355 }
1356
1357 Proxy::Buffer buffer;
1358 buffer.mFrameCount = stepCount;
1359 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001360
Eric Laurent1703cdf2011-03-07 14:52:59 -08001361 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001362 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001363 mInUnderrun = false;
1364 mProxy->releaseBuffer(&buffer);
1365
1366 // restart track if it was disabled by audioflinger due to previous underrun
1367 if (mState == STATE_ACTIVE) {
1368 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001369 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001370 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001371 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001372 mAudioTrack->start();
1373 }
1374 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001375}
1376
1377// -------------------------------------------------------------------------
1378
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001379ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001380{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001381 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001382 return INVALID_OPERATION;
1383 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001384
Eric Laurentab5cdba2014-06-09 17:22:27 -07001385 if (isDirect()) {
1386 AutoMutex lock(mLock);
1387 int32_t flags = android_atomic_and(
1388 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1389 &mCblk->mFlags);
1390 if (flags & CBLK_INVALID) {
1391 return DEAD_OBJECT;
1392 }
1393 }
1394
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001395 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001396 // Sanity-check: user is most-likely passing an error code, and it would
1397 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001398 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001399 return BAD_VALUE;
1400 }
1401
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001402 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001403 Buffer audioBuffer;
1404
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001405 while (userSize >= mFrameSize) {
1406 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001407
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001408 status_t err = obtainBuffer(&audioBuffer,
1409 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001410 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001411 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001412 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001413 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001414 return ssize_t(err);
1415 }
1416
1417 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001418 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001419 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001420 toWrite = audioBuffer.size >> 1;
1421 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001422 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001423 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001424 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001425 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001426 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001427 userSize -= toWrite;
1428 written += toWrite;
1429
1430 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001431 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001432
1433 return written;
1434}
1435
1436// -------------------------------------------------------------------------
1437
John Grossman4ff14ba2012-02-08 16:37:41 -08001438TimedAudioTrack::TimedAudioTrack() {
1439 mIsTimed = true;
1440}
1441
1442status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1443{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001444 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001445 status_t result = UNKNOWN_ERROR;
1446
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001447#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001448 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1449 // while we are accessing the cblk
1450 sp<IAudioTrack> audioTrack = mAudioTrack;
1451 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001452#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001453
John Grossman4ff14ba2012-02-08 16:37:41 -08001454 // If the track is not invalid already, try to allocate a buffer. alloc
1455 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001456 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001457 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001458 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001459 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1460 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001461 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001462 }
1463 }
1464
1465 // If the track is invalid at this point, attempt to restore it. and try the
1466 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001467 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001468 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001469
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001470 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001471 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001472 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001473 }
1474
1475 return result;
1476}
1477
1478status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1479 int64_t pts)
1480{
Eric Laurentdf839842012-05-31 14:27:14 -07001481 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1482 {
1483 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001484 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001485 // restart track if it was disabled by audioflinger due to previous underrun
1486 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001487 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1488 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001489 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001490 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001491 mAudioTrack->start();
1492 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001493 }
Eric Laurentdf839842012-05-31 14:27:14 -07001494 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001495}
1496
1497status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1498 TargetTimeline target)
1499{
1500 return mAudioTrack->setMediaTimeTransform(xform, target);
1501}
1502
1503// -------------------------------------------------------------------------
1504
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001505nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001506{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001507 // Currently the AudioTrack thread is not created if there are no callbacks.
1508 // Would it ever make sense to run the thread, even without callbacks?
1509 // If so, then replace this by checks at each use for mCbf != NULL.
1510 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1511
Eric Laurent1703cdf2011-03-07 14:52:59 -08001512 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001513 if (mAwaitBoost) {
1514 mAwaitBoost = false;
1515 mLock.unlock();
1516 static const int32_t kMaxTries = 5;
1517 int32_t tryCounter = kMaxTries;
1518 uint32_t pollUs = 10000;
1519 do {
1520 int policy = sched_getscheduler(0);
1521 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1522 break;
1523 }
1524 usleep(pollUs);
1525 pollUs <<= 1;
1526 } while (tryCounter-- > 0);
1527 if (tryCounter < 0) {
1528 ALOGE("did not receive expected priority boost on time");
1529 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001530 // Run again immediately
1531 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001532 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001533
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001534 // Can only reference mCblk while locked
1535 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001536 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001537
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001538 // Check for track invalidation
1539 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001540 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1541 // AudioSystem cache. We should not exit here but after calling the callback so
1542 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001543 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001544 status_t status = restoreTrack_l("processAudioBuffer");
1545 mLock.unlock();
1546 // Run again immediately, but with a new IAudioTrack
1547 return 0;
1548 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001549 }
1550
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001551 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001552 bool active = mState == STATE_ACTIVE;
1553
1554 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1555 bool newUnderrun = false;
1556 if (flags & CBLK_UNDERRUN) {
1557#if 0
1558 // Currently in shared buffer mode, when the server reaches the end of buffer,
1559 // the track stays active in continuous underrun state. It's up to the application
1560 // to pause or stop the track, or set the position to a new offset within buffer.
1561 // This was some experimental code to auto-pause on underrun. Keeping it here
1562 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1563 if (mTransfer == TRANSFER_SHARED) {
1564 mState = STATE_PAUSED;
1565 active = false;
1566 }
1567#endif
1568 if (!mInUnderrun) {
1569 mInUnderrun = true;
1570 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001571 }
1572 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001573
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001574 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001575 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001576
1577 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001578 bool markerReached = false;
1579 size_t markerPosition = mMarkerPosition;
1580 // FIXME fails for wraparound, need 64 bits
1581 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1582 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001583 }
1584
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001585 // Determine number of new position callback(s) that will be needed, while locked
1586 size_t newPosCount = 0;
1587 size_t newPosition = mNewPosition;
1588 size_t updatePeriod = mUpdatePeriod;
1589 // FIXME fails for wraparound, need 64 bits
1590 if (updatePeriod > 0 && position >= newPosition) {
1591 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1592 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001593 }
1594
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001595 // Cache other fields that will be needed soon
1596 uint32_t loopPeriod = mLoopPeriod;
1597 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
1608 // These fields don't need to be cached, because they are assigned only by set():
1609 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1610 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1611
1612 mLock.unlock();
1613
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001614 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001615 struct timespec timeout;
1616 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1617 timeout.tv_nsec = 0;
1618
Glenn Kasten96f04882013-09-20 09:28:56 -07001619 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001620 switch (status) {
1621 case NO_ERROR:
1622 case DEAD_OBJECT:
1623 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001624 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001625 {
1626 AutoMutex lock(mLock);
1627 // The previously assigned value of waitStreamEnd is no longer valid,
1628 // since the mutex has been unlocked and either the callback handler
1629 // or another thread could have re-started the AudioTrack during that time.
1630 waitStreamEnd = mState == STATE_STOPPING;
1631 if (waitStreamEnd) {
1632 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001633 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001634 }
1635 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001636 if (waitStreamEnd && status != DEAD_OBJECT) {
1637 return NS_INACTIVE;
1638 }
1639 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001640 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001641 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001642 }
1643
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001644 // perform callbacks while unlocked
1645 if (newUnderrun) {
1646 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1647 }
1648 // FIXME we will miss loops if loop cycle was signaled several times since last call
1649 // to processAudioBuffer()
1650 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1651 mCbf(EVENT_LOOP_END, mUserData, NULL);
1652 }
1653 if (flags & CBLK_BUFFER_END) {
1654 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1655 }
1656 if (markerReached) {
1657 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1658 }
1659 while (newPosCount > 0) {
1660 size_t temp = newPosition;
1661 mCbf(EVENT_NEW_POS, mUserData, &temp);
1662 newPosition += updatePeriod;
1663 newPosCount--;
1664 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001665
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001666 if (mObservedSequence != sequence) {
1667 mObservedSequence = sequence;
1668 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001669 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001670 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001671 return NS_INACTIVE;
1672 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001673 }
1674
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001675 // if inactive, then don't run me again until re-started
1676 if (!active) {
1677 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001678 }
1679
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001680 // Compute the estimated time until the next timed event (position, markers, loops)
1681 // FIXME only for non-compressed audio
1682 uint32_t minFrames = ~0;
1683 if (!markerReached && position < markerPosition) {
1684 minFrames = markerPosition - position;
1685 }
1686 if (loopPeriod > 0 && loopPeriod < minFrames) {
1687 minFrames = loopPeriod;
1688 }
1689 if (updatePeriod > 0 && updatePeriod < minFrames) {
1690 minFrames = updatePeriod;
1691 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001692
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001693 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1694 static const uint32_t kPoll = 0;
1695 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1696 minFrames = kPoll * notificationFrames;
1697 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001698
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001699 // Convert frame units to time units
1700 nsecs_t ns = NS_WHENEVER;
1701 if (minFrames != (uint32_t) ~0) {
1702 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1703 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1704 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1705 }
1706
1707 // If not supplying data by EVENT_MORE_DATA, then we're done
1708 if (mTransfer != TRANSFER_CALLBACK) {
1709 return ns;
1710 }
1711
1712 struct timespec timeout;
1713 const struct timespec *requested = &ClientProxy::kForever;
1714 if (ns != NS_WHENEVER) {
1715 timeout.tv_sec = ns / 1000000000LL;
1716 timeout.tv_nsec = ns % 1000000000LL;
1717 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1718 requested = &timeout;
1719 }
1720
1721 while (mRemainingFrames > 0) {
1722
1723 Buffer audioBuffer;
1724 audioBuffer.frameCount = mRemainingFrames;
1725 size_t nonContig;
1726 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1727 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001728 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001729 requested = &ClientProxy::kNonBlocking;
1730 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001731 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001732 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001733 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001734 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1735 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001736 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001737 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001738 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1739 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001740 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001741
Eric Laurent42a6f422013-08-29 14:35:05 -07001742 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001743 mRetryOnPartialBuffer = false;
1744 if (avail < mRemainingFrames) {
1745 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1746 if (ns < 0 || myns < ns) {
1747 ns = myns;
1748 }
1749 return ns;
1750 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001751 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001752
1753 // Divide buffer size by 2 to take into account the expansion
1754 // due to 8 to 16 bit conversion: the callback must fill only half
1755 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001756 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001757 audioBuffer.size >>= 1;
1758 }
1759
1760 size_t reqSize = audioBuffer.size;
1761 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001762 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001763
1764 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001765 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001766 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1767 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001768 return NS_NEVER;
1769 }
1770
1771 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001772 // The callback is done filling buffers
1773 // Keep this thread going to handle timed events and
1774 // still try to get more data in intervals of WAIT_PERIOD_MS
1775 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001776 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001777 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001778
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001779 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001780 // 8 to 16 bit conversion, note that source and destination are the same address
1781 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001782 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001783 }
1784
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001785 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1786 audioBuffer.frameCount = releasedFrames;
1787 mRemainingFrames -= releasedFrames;
1788 if (misalignment >= releasedFrames) {
1789 misalignment -= releasedFrames;
1790 } else {
1791 misalignment = 0;
1792 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001793
1794 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001795
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001796 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1797 // if callback doesn't like to accept the full chunk
1798 if (writtenSize < reqSize) {
1799 continue;
1800 }
1801
1802 // There could be enough non-contiguous frames available to satisfy the remaining request
1803 if (mRemainingFrames <= nonContig) {
1804 continue;
1805 }
1806
1807#if 0
1808 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1809 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1810 // that total to a sum == notificationFrames.
1811 if (0 < misalignment && misalignment <= mRemainingFrames) {
1812 mRemainingFrames = misalignment;
1813 return (mRemainingFrames * 1100000000LL) / sampleRate;
1814 }
1815#endif
1816
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001817 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001818 mRemainingFrames = notificationFrames;
1819 mRetryOnPartialBuffer = true;
1820
1821 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1822 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001823}
1824
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001825status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001826{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001827 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001828 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001829 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001830 status_t result;
1831
Glenn Kastena47f3162012-11-07 10:13:08 -08001832 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08001833 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001834 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001835
Eric Laurentab5cdba2014-06-09 17:22:27 -07001836 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001837 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001838 return DEAD_OBJECT;
1839 }
1840
Glenn Kasten200092b2014-08-15 15:13:30 -07001841 // save the old static buffer position
1842 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
1843
1844 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001845 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001846 // It will also delete the strong references on previous IAudioTrack and IMemory.
1847 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
1848 result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001849
1850 // take the frames that will be lost by track recreation into account in saved position
Glenn Kasten200092b2014-08-15 15:13:30 -07001851 (void) updateAndGetPosition_l();
1852 mPosition = mReleased;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001853
Glenn Kastena47f3162012-11-07 10:13:08 -08001854 if (result == NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001855 // continue playback from last known position, but
1856 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1857 if (mStaticProxy != NULL) {
1858 mLoopPeriod = 0;
1859 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1860 }
1861 // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1862 // track destruction have been played? This is critical for SoundPool implementation
1863 // This must be broken, and needs to be tested/debugged.
1864#if 0
Glenn Kastena47f3162012-11-07 10:13:08 -08001865 // restore write index and set other indexes to reflect empty buffer status
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001866 if (!strcmp(from, "start")) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001867 // Make sure that a client relying on callback events indicating underrun or
1868 // the actual amount of audio frames played (e.g SoundPool) receives them.
1869 if (mSharedBuffer == 0) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001870 // restart playback even if buffer is not completely filled.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001871 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001872 }
1873 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001874#endif
1875 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001876 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001877 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001878 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001879 if (result != NO_ERROR) {
1880 ALOGW("restoreTrack_l() failed status %d", result);
1881 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001882 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001883 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001884
1885 return result;
1886}
1887
Glenn Kasten200092b2014-08-15 15:13:30 -07001888uint32_t AudioTrack::updateAndGetPosition_l()
1889{
1890 // This is the sole place to read server consumed frames
1891 uint32_t newServer = mProxy->getPosition();
1892 int32_t delta = newServer - mServer;
1893 mServer = newServer;
1894 // TODO There is controversy about whether there can be "negative jitter" in server position.
1895 // This should be investigated further, and if possible, it should be addressed.
1896 // A more definite failure mode is infrequent polling by client.
1897 // One could call (void)getPosition_l() in releaseBuffer(),
1898 // so mReleased and mPosition are always lock-step as best possible.
1899 // That should ensure delta never goes negative for infrequent polling
1900 // unless the server has more than 2^31 frames in its buffer,
1901 // in which case the use of uint32_t for these counters has bigger issues.
1902 if (delta < 0) {
1903 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
1904 delta = 0;
1905 }
1906 return mPosition += (uint32_t) delta;
1907}
1908
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001909status_t AudioTrack::setParameters(const String8& keyValuePairs)
1910{
1911 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001912 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001913}
1914
Glenn Kastence703742013-07-19 16:33:58 -07001915status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1916{
Glenn Kasten53cec222013-08-29 09:01:02 -07001917 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001918 // FIXME not implemented for fast tracks; should use proxy and SSQ
1919 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1920 return INVALID_OPERATION;
1921 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001922
1923 switch (mState) {
1924 case STATE_ACTIVE:
1925 case STATE_PAUSED:
1926 break; // handle below
1927 case STATE_FLUSHED:
1928 case STATE_STOPPED:
1929 return WOULD_BLOCK;
1930 case STATE_STOPPING:
1931 case STATE_PAUSED_STOPPING:
1932 if (!isOffloaded_l()) {
1933 return INVALID_OPERATION;
1934 }
1935 break; // offloaded tracks handled below
1936 default:
1937 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
1938 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07001939 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001940
Glenn Kasten200092b2014-08-15 15:13:30 -07001941 // The presented frame count must always lag behind the consumed frame count.
1942 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07001943 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001944 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07001945 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001946 return status;
1947 }
1948 if (isOffloadedOrDirect_l()) {
1949 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
1950 // use cached paused position in case another offloaded track is running.
1951 timestamp.mPosition = mPausedPosition;
1952 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
1953 return NO_ERROR;
1954 }
1955
1956 // Check whether a pending flush or stop has completed, as those commands may
1957 // be asynchronous or return near finish.
1958 if (mStartUs != 0 && mSampleRate != 0) {
1959 static const int kTimeJitterUs = 100000; // 100 ms
1960 static const int k1SecUs = 1000000;
1961
1962 const int64_t timeNow = getNowUs();
1963
1964 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
1965 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
1966 if (timestampTimeUs < mStartUs) {
1967 return WOULD_BLOCK; // stale timestamp time, occurs before start.
1968 }
1969 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
1970 const int64_t deltaPositionByUs = timestamp.mPosition * 1000000LL / mSampleRate;
1971
1972 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
1973 // Verify that the counter can't count faster than the sample rate
1974 // since the start time. If greater, then that means we have failed
1975 // to completely flush or stop the previous playing track.
1976 ALOGW("incomplete flush or stop:"
1977 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
1978 (long long)deltaTimeUs, (long long)deltaPositionByUs,
1979 timestamp.mPosition);
1980 return WOULD_BLOCK;
1981 }
1982 }
1983 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
1984 }
1985 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07001986 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
1987 (void) updateAndGetPosition_l();
1988 // Server consumed (mServer) and presented both use the same server time base,
1989 // and server consumed is always >= presented.
1990 // The delta between these represents the number of frames in the buffer pipeline.
1991 // If this delta between these is greater than the client position, it means that
1992 // actually presented is still stuck at the starting line (figuratively speaking),
1993 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
1994 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
1995 return INVALID_OPERATION;
1996 }
1997 // Convert timestamp position from server time base to client time base.
1998 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
1999 // But if we change it to 64-bit then this could fail.
2000 // If (mPosition - mServer) can be negative then should use:
2001 // (int32_t)(mPosition - mServer)
2002 timestamp.mPosition += mPosition - mServer;
2003 // Immediately after a call to getPosition_l(), mPosition and
2004 // mServer both represent the same frame position. mPosition is
2005 // in client's point of view, and mServer is in server's point of
2006 // view. So the difference between them is the "fudge factor"
2007 // between client and server views due to stop() and/or new
2008 // IAudioTrack. And timestamp.mPosition is initially in server's
2009 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002010 }
2011 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002012}
2013
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002014String8 AudioTrack::getParameters(const String8& keys)
2015{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002016 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002017 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002018 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002019 } else {
2020 return String8::empty();
2021 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002022}
2023
Glenn Kasten23a75452014-01-13 10:37:17 -08002024bool AudioTrack::isOffloaded() const
2025{
2026 AutoMutex lock(mLock);
2027 return isOffloaded_l();
2028}
2029
Eric Laurentab5cdba2014-06-09 17:22:27 -07002030bool AudioTrack::isDirect() const
2031{
2032 AutoMutex lock(mLock);
2033 return isDirect_l();
2034}
2035
2036bool AudioTrack::isOffloadedOrDirect() const
2037{
2038 AutoMutex lock(mLock);
2039 return isOffloadedOrDirect_l();
2040}
2041
2042
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002043status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002044{
2045
2046 const size_t SIZE = 256;
2047 char buffer[SIZE];
2048 String8 result;
2049
2050 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002051 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002052 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002053 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002054 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002055 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002056 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08002057 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002058 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002059 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002060 result.append(buffer);
2061 ::write(fd, result.string(), result.size());
2062 return NO_ERROR;
2063}
2064
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002065uint32_t AudioTrack::getUnderrunFrames() const
2066{
2067 AutoMutex lock(mLock);
2068 return mProxy->getUnderrunFrames();
2069}
2070
2071// =========================================================================
2072
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002073void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002074{
2075 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2076 if (audioTrack != 0) {
2077 AutoMutex lock(audioTrack->mLock);
2078 audioTrack->mProxy->binderDied();
2079 }
2080}
2081
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002082// =========================================================================
2083
2084AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002085 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2086 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002087{
2088}
2089
2090AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002091{
2092}
2093
2094bool AudioTrack::AudioTrackThread::threadLoop()
2095{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002096 {
2097 AutoMutex _l(mMyLock);
2098 if (mPaused) {
2099 mMyCond.wait(mMyLock);
2100 // caller will check for exitPending()
2101 return true;
2102 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002103 if (mIgnoreNextPausedInt) {
2104 mIgnoreNextPausedInt = false;
2105 mPausedInt = false;
2106 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002107 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002108 if (mPausedNs > 0) {
2109 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2110 } else {
2111 mMyCond.wait(mMyLock);
2112 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002113 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002114 return true;
2115 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002116 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002117 if (exitPending()) {
2118 return false;
2119 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002120 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002121 switch (ns) {
2122 case 0:
2123 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002124 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002125 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002126 return true;
2127 case NS_NEVER:
2128 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002129 case NS_WHENEVER:
2130 // FIXME increase poll interval, or make event-driven
2131 ns = 1000000000LL;
2132 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002133 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002134 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002135 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002136 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002137 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002138}
2139
Glenn Kasten3acbd052012-02-28 10:39:56 -08002140void AudioTrack::AudioTrackThread::requestExit()
2141{
2142 // must be in this order to avoid a race condition
2143 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002144 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002145}
2146
2147void AudioTrack::AudioTrackThread::pause()
2148{
2149 AutoMutex _l(mMyLock);
2150 mPaused = true;
2151}
2152
2153void AudioTrack::AudioTrackThread::resume()
2154{
2155 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002156 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002157 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002158 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002159 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002160 mMyCond.signal();
2161 }
2162}
2163
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002164void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2165{
2166 AutoMutex _l(mMyLock);
2167 mPausedInt = true;
2168 mPausedNs = ns;
2169}
2170
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002171}; // namespace android