blob: 389aaccc37617e0f439f869c8576149d986658e8 [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 }
Glenn Kasten53cec222013-08-29 09:01:02 -0700197 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
198 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
Eric Laurentd1f69b02014-12-15 14:33:13 -0800338 // force direct flag if HW A/V sync requested
339 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
340 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
341 }
342
Glenn Kastenb7730382014-04-30 15:50:31 -0700343 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
344 if (audio_is_linear_pcm(format)) {
345 mFrameSize = channelCount * audio_bytes_per_sample(format);
346 } else {
347 mFrameSize = sizeof(uint8_t);
348 }
349 mFrameSizeAF = mFrameSize;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800350 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700351 ALOG_ASSERT(audio_is_linear_pcm(format));
352 mFrameSize = channelCount * audio_bytes_per_sample(format);
353 mFrameSizeAF = channelCount * audio_bytes_per_sample(
354 format == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : format);
355 // createTrack will return an error if PCM format is not supported by server,
356 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800357 }
358
Eric Laurent0d6db582014-11-12 18:39:44 -0800359 // sampling rate must be specified for direct outputs
360 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
361 return BAD_VALUE;
362 }
363 mSampleRate = sampleRate;
364
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800365 // Make copy of input parameter offloadInfo so that in the future:
366 // (a) createTrack_l doesn't need it as an input parameter
367 // (b) we can support re-creation of offloaded tracks
368 if (offloadInfo != NULL) {
369 mOffloadInfoCopy = *offloadInfo;
370 mOffloadInfo = &mOffloadInfoCopy;
371 } else {
372 mOffloadInfo = NULL;
373 }
374
Glenn Kasten66e46352014-01-16 17:44:23 -0800375 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
376 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800377 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800378 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800379 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700380 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800381 mNotificationFramesAct = 0;
Eric Laurentcaf7f482014-11-25 17:50:47 -0800382 if (sessionId == AUDIO_SESSION_ALLOCATE) {
383 mSessionId = AudioSystem::newAudioUniqueId();
384 } else {
385 mSessionId = sessionId;
386 }
Marco Nelissend457c972014-02-11 08:47:07 -0800387 int callingpid = IPCThreadState::self()->getCallingPid();
388 int mypid = getpid();
389 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800390 mClientUid = IPCThreadState::self()->getCallingUid();
391 } else {
392 mClientUid = uid;
393 }
Marco Nelissend457c972014-02-11 08:47:07 -0800394 if (pid == -1 || (callingpid != mypid)) {
395 mClientPid = callingpid;
396 } else {
397 mClientPid = pid;
398 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700399 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700400 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700401 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700402
Glenn Kastena997e7a2012-08-07 09:44:19 -0700403 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700404 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700405 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
406 }
407
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800408 // create the IAudioTrack
Eric Laurent0d6db582014-11-12 18:39:44 -0800409 status_t status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800410
Glenn Kastena997e7a2012-08-07 09:44:19 -0700411 if (status != NO_ERROR) {
412 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100413 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
414 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700415 mAudioTrackThread.clear();
416 }
417 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700418 }
419
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800420 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800421 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800422 mUserData = user;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800423 mLoopPeriod = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800424 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700425 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800426 mNewPosition = 0;
427 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700428 mServer = 0;
429 mPosition = 0;
430 mReleased = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700431 mStartUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800432 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800433 mSequence = 1;
434 mObservedSequence = mSequence;
435 mInUnderrun = false;
436
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800437 return NO_ERROR;
438}
439
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800440// -------------------------------------------------------------------------
441
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100442status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800443{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800444 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100445
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800446 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100447 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800448 }
449
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800450 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800451
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800452 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100453 if (previousState == STATE_PAUSED_STOPPING) {
454 mState = STATE_STOPPING;
455 } else {
456 mState = STATE_ACTIVE;
457 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700458 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800459 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
460 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700461 mPosition = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700462 // For offloaded tracks, we don't know if the hardware counters are really zero here,
463 // since the flush is asynchronous and stop may not fully drain.
464 // We save the time when the track is started to later verify whether
465 // the counters are realistic (i.e. start from zero after this time).
466 mStartUs = getNowUs();
467
Eric Laurentec9a0322013-08-28 10:23:01 -0700468 // force refresh of remaining frames by processAudioBuffer() as last
469 // write before stop could be partial.
470 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800471 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700472 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700473 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800474
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800475 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800476 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100477 if (previousState == STATE_STOPPING) {
478 mProxy->interrupt();
479 } else {
480 t->resume();
481 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800482 } else {
483 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
484 get_sched_policy(0, &mPreviousSchedulingGroup);
485 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
486 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800487
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800488 status_t status = NO_ERROR;
489 if (!(flags & CBLK_INVALID)) {
490 status = mAudioTrack->start();
491 if (status == DEAD_OBJECT) {
492 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800493 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800494 }
495 if (flags & CBLK_INVALID) {
496 status = restoreTrack_l("start");
497 }
498
499 if (status != NO_ERROR) {
500 ALOGE("start() status %d", status);
501 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800502 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100503 if (previousState != STATE_STOPPING) {
504 t->pause();
505 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800506 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700507 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700508 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800509 }
510 }
511
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100512 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800513}
514
515void AudioTrack::stop()
516{
517 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700518 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800519 return;
520 }
521
Glenn Kasten23a75452014-01-13 10:37:17 -0800522 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100523 mState = STATE_STOPPING;
524 } else {
525 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -0700526 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100527 }
528
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800529 mProxy->interrupt();
530 mAudioTrack->stop();
531 // the playback head position will reset to 0, so if a marker is set, we need
532 // to activate it again
533 mMarkerReached = false;
534#if 0
535 // Force flush if a shared buffer is used otherwise audioflinger
536 // will not stop before end of buffer is reached.
537 // It may be needed to make sure that we stop playback, likely in case looping is on.
538 if (mSharedBuffer != 0) {
539 flush_l();
540 }
541#endif
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100542
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800543 sp<AudioTrackThread> t = mAudioTrackThread;
544 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800545 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100546 t->pause();
547 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800548 } else {
549 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
550 set_sched_policy(0, mPreviousSchedulingGroup);
551 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800552}
553
554bool AudioTrack::stopped() const
555{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800556 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800557 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800558}
559
560void AudioTrack::flush()
561{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800562 if (mSharedBuffer != 0) {
563 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800564 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800565 AutoMutex lock(mLock);
566 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
567 return;
568 }
569 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800570}
571
Eric Laurent1703cdf2011-03-07 14:52:59 -0800572void AudioTrack::flush_l()
573{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800574 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700575
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700576 // clear playback marker and periodic update counter
577 mMarkerPosition = 0;
578 mMarkerReached = false;
579 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100580 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700581
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800582 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700583 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800584 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100585 mProxy->interrupt();
586 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800587 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800588 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800589}
590
591void AudioTrack::pause()
592{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800593 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100594 if (mState == STATE_ACTIVE) {
595 mState = STATE_PAUSED;
596 } else if (mState == STATE_STOPPING) {
597 mState = STATE_PAUSED_STOPPING;
598 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800599 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800600 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800601 mProxy->interrupt();
602 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800603
Marco Nelissen3a90f282014-03-10 11:21:43 -0700604 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700605 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700606 // An offload output can be re-used between two audio tracks having
607 // the same configuration. A timestamp query for a paused track
608 // while the other is running would return an incorrect time.
609 // To fix this, cache the playback position on a pause() and return
610 // this time when requested until the track is resumed.
611
612 // OffloadThread sends HAL pause in its threadLoop. Time saved
613 // here can be slightly off.
614
615 // TODO: check return code for getRenderPosition.
616
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800617 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800618 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
619 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
620 }
621 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800622}
623
Eric Laurentbe916aa2010-06-01 23:49:17 -0700624status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800625{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700626 // This duplicates a test by AudioTrack JNI, but that is not the only caller
627 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
628 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700629 return BAD_VALUE;
630 }
631
Eric Laurent1703cdf2011-03-07 14:52:59 -0800632 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800633 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
634 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800635
Glenn Kastenc56f3422014-03-21 17:53:17 -0700636 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700637
Glenn Kasten23a75452014-01-13 10:37:17 -0800638 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700639 mAudioTrack->signal();
640 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700641 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800642}
643
Glenn Kastenb1c09932012-02-27 16:21:04 -0800644status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800645{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800646 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700647}
648
Eric Laurent2beeb502010-07-16 07:43:46 -0700649status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700650{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700651 // This duplicates a test by AudioTrack JNI, but that is not the only caller
652 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700653 return BAD_VALUE;
654 }
655
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800656 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700657 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800658 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700659
660 return NO_ERROR;
661}
662
Glenn Kastena5224f32012-01-04 12:41:44 -0800663void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700664{
665 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800666 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700667 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800668}
669
Glenn Kasten3b16c762012-11-14 08:44:39 -0800670status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800671{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700672 if (mIsTimed || isOffloadedOrDirect()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800673 return INVALID_OPERATION;
674 }
675
Eric Laurent0d6db582014-11-12 18:39:44 -0800676 AutoMutex lock(mLock);
677 if (mOutput == AUDIO_IO_HANDLE_NONE) {
678 return NO_INIT;
679 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800680 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800681 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700682 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800683 }
Andy Hungcd044842014-08-07 11:04:34 -0700684 if (rate == 0 || rate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700685 return BAD_VALUE;
686 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800687
Glenn Kastene3aa6592012-12-04 12:22:46 -0800688 mSampleRate = rate;
689 mProxy->setSampleRate(rate);
690
Eric Laurent57326622009-07-07 07:10:45 -0700691 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800692}
693
Glenn Kastena5224f32012-01-04 12:41:44 -0800694uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800695{
John Grossman4ff14ba2012-02-08 16:37:41 -0800696 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800697 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800698 }
699
Eric Laurent1703cdf2011-03-07 14:52:59 -0800700 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700701
702 // sample rate can be updated during playback by the offloaded decoder so we need to
703 // query the HAL and update if needed.
704// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700705 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700706 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700707 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700708 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700709 if (status == NO_ERROR) {
710 mSampleRate = sampleRate;
711 }
712 }
713 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800714 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800715}
716
717status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
718{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700719 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800720 return INVALID_OPERATION;
721 }
722
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800723 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800724 ;
725 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
726 loopEnd - loopStart >= MIN_LOOP) {
727 ;
728 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800729 return BAD_VALUE;
730 }
731
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800732 AutoMutex lock(mLock);
733 // See setPosition() regarding setting parameters such as loop points or position while active
734 if (mState == STATE_ACTIVE) {
735 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700736 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800737 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800738 return NO_ERROR;
739}
740
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800741void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
742{
Andy Hung680b7952014-11-12 13:18:52 -0800743 // Setting the loop will reset next notification update period (like setPosition).
Glenn Kasten200092b2014-08-15 15:13:30 -0700744 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800745 mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0;
746 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
747}
748
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800749status_t AudioTrack::setMarkerPosition(uint32_t marker)
750{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700751 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700752 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700753 return INVALID_OPERATION;
754 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800755
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800756 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800757 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700758 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800759
760 return NO_ERROR;
761}
762
Glenn Kastena5224f32012-01-04 12:41:44 -0800763status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800764{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700765 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100766 return INVALID_OPERATION;
767 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700768 if (marker == NULL) {
769 return BAD_VALUE;
770 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800771
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800772 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800773 *marker = mMarkerPosition;
774
775 return NO_ERROR;
776}
777
778status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
779{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700780 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700781 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700782 return INVALID_OPERATION;
783 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800784
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800785 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700786 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800787 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800788
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800789 return NO_ERROR;
790}
791
Glenn Kastena5224f32012-01-04 12:41:44 -0800792status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800793{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700794 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100795 return INVALID_OPERATION;
796 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700797 if (updatePeriod == NULL) {
798 return BAD_VALUE;
799 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800800
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800801 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800802 *updatePeriod = mUpdatePeriod;
803
804 return NO_ERROR;
805}
806
807status_t AudioTrack::setPosition(uint32_t position)
808{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700809 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700810 return INVALID_OPERATION;
811 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800812 if (position > mFrameCount) {
813 return BAD_VALUE;
814 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800815
Eric Laurent1703cdf2011-03-07 14:52:59 -0800816 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800817 // Currently we require that the player is inactive before setting parameters such as position
818 // or loop points. Otherwise, there could be a race condition: the application could read the
819 // current position, compute a new position or loop parameters, and then set that position or
820 // loop parameters but it would do the "wrong" thing since the position has continued to advance
821 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
822 // to specify how it wants to handle such scenarios.
823 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700824 return INVALID_OPERATION;
825 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700826 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800827 mLoopPeriod = 0;
828 // FIXME Check whether loops and setting position are incompatible in old code.
829 // If we use setLoop for both purposes we lose the capability to set the position while looping.
830 mStaticProxy->setLoop(position, mFrameCount, 0);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700831
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800832 return NO_ERROR;
833}
834
Glenn Kasten200092b2014-08-15 15:13:30 -0700835status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800836{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700837 if (position == NULL) {
838 return BAD_VALUE;
839 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800840
Eric Laurent1703cdf2011-03-07 14:52:59 -0800841 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700842 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100843 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800844
Eric Laurentab5cdba2014-06-09 17:22:27 -0700845 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800846 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
847 *position = mPausedPosition;
848 return NO_ERROR;
849 }
850
Glenn Kasten142f5192014-03-25 17:44:59 -0700851 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100852 uint32_t halFrames;
853 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
854 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700855 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
856 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100857 *position = dspFrames;
858 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -0800859 if (mCblk->mFlags & CBLK_INVALID) {
860 restoreTrack_l("getPosition");
861 }
862
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100863 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700864 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
865 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100866 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800867 return NO_ERROR;
868}
869
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000870status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800871{
872 if (mSharedBuffer == 0 || mIsTimed) {
873 return INVALID_OPERATION;
874 }
875 if (position == NULL) {
876 return BAD_VALUE;
877 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800878
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800879 AutoMutex lock(mLock);
880 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800881 return NO_ERROR;
882}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800883
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800884status_t AudioTrack::reload()
885{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700886 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800887 return INVALID_OPERATION;
888 }
889
Eric Laurent1703cdf2011-03-07 14:52:59 -0800890 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800891 // See setPosition() regarding setting parameters such as loop points or position while active
892 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700893 return INVALID_OPERATION;
894 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800895 mNewPosition = mUpdatePeriod;
896 mLoopPeriod = 0;
897 // FIXME The new code cannot reload while keeping a loop specified.
898 // Need to check how the old code handled this, and whether it's a significant change.
899 mStaticProxy->setLoop(0, mFrameCount, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800900 return NO_ERROR;
901}
902
Glenn Kasten38e905b2014-01-13 10:21:48 -0800903audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700904{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800905 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100906 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800907}
908
Eric Laurentbe916aa2010-06-01 23:49:17 -0700909status_t AudioTrack::attachAuxEffect(int effectId)
910{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800911 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700912 status_t status = mAudioTrack->attachAuxEffect(effectId);
913 if (status == NO_ERROR) {
914 mAuxEffectId = effectId;
915 }
916 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700917}
918
Eric Laurente83b55d2014-11-14 10:06:21 -0800919audio_stream_type_t AudioTrack::streamType() const
920{
921 if (mStreamType == AUDIO_STREAM_DEFAULT) {
922 return audio_attributes_to_stream_type(&mAttributes);
923 }
924 return mStreamType;
925}
926
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800927// -------------------------------------------------------------------------
928
Eric Laurent1703cdf2011-03-07 14:52:59 -0800929// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -0700930status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800931{
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800932 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
933 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700934 ALOGE("Could not get audioflinger");
935 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800936 }
937
Eric Laurente83b55d2014-11-14 10:06:21 -0800938 audio_io_handle_t output;
939 audio_stream_type_t streamType = mStreamType;
940 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
941 status_t status = AudioSystem::getOutputForAttr(attr, &output,
942 (audio_session_t)mSessionId, &streamType,
943 mSampleRate, mFormat, mChannelMask,
944 mFlags, mOffloadInfo);
945
946
947 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700948 ALOGE("Could not get audio output for stream type %d, usage %d, sample rate %u, format %#x,"
949 " channel mask %#x, flags %#x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800950 streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800951 return BAD_VALUE;
952 }
953 {
954 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
955 // we must release it ourselves if anything goes wrong.
956
Glenn Kastence8828a2013-09-16 18:07:38 -0700957 // Not all of these values are needed under all conditions, but it is easier to get them all
958
Eric Laurentd1b449a2010-05-14 03:26:45 -0700959 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -0700960 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700961 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800962 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800963 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700964 }
965
Glenn Kastence8828a2013-09-16 18:07:38 -0700966 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700967 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -0700968 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700969 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800970 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700971 }
972
973 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700974 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -0700975 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700976 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800977 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700978 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800979 if (mSampleRate == 0) {
980 mSampleRate = afSampleRate;
981 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700982 // Client decides whether the track is TIMED (see below), but can only express a preference
983 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800984 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700985 // either of these use cases:
986 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -0800987 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -0800988 // use case 2: callback transfer mode
989 (mTransfer == TRANSFER_CALLBACK)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800990 // matching sample rate
991 (mSampleRate == afSampleRate))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800992 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -0700993 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -0800994 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700995 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700996 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700997
Glenn Kastence8828a2013-09-16 18:07:38 -0700998 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -0800999 // n = 1 fast track with single buffering; nBuffering is ignored
1000 // n = 2 fast track with double buffering
Glenn Kastence8828a2013-09-16 18:07:38 -07001001 // n = 2 normal track, no sample rate conversion
1002 // n = 3 normal track, with sample rate conversion
1003 // (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering)
1004 // n > 3 very high latency or very small notification interval; nBuffering is ignored
Glenn Kasten363fb752014-01-15 12:27:31 -08001005 const uint32_t nBuffering = (mSampleRate == afSampleRate) ? 2 : 3;
Glenn Kastence8828a2013-09-16 18:07:38 -07001006
Eric Laurentd1b449a2010-05-14 03:26:45 -07001007 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001008
Glenn Kasten363fb752014-01-15 12:27:31 -08001009 size_t frameCount = mReqFrameCount;
1010 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001011
Glenn Kasten363fb752014-01-15 12:27:31 -08001012 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001013 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001014 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001015 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001016 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001017 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001018 if (mNotificationFramesAct != frameCount) {
1019 mNotificationFramesAct = frameCount;
1020 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001021 } else if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001022
Glenn Kastena42ff002012-11-14 12:47:55 -08001023 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -07001024 // 8-bit data in shared memory is not currently supported by AudioFlinger
Glenn Kastenb7730382014-04-30 15:50:31 -07001025 size_t alignment = audio_bytes_per_sample(
1026 mFormat == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : mFormat);
1027 if (alignment & 1) {
1028 alignment = 1;
1029 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001030 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001031 // More than 2 channels does not require stronger alignment than stereo
1032 alignment <<= 1;
1033 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001034 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001035 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001036 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001037 status = BAD_VALUE;
1038 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001039 }
1040
1041 // When initializing a shared buffer AudioTrack via constructors,
1042 // there's no frameCount parameter.
1043 // But when initializing a shared buffer AudioTrack via set(),
1044 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kastenb7730382014-04-30 15:50:31 -07001045 frameCount = mSharedBuffer->size() / mFrameSizeAF;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001046
Glenn Kasten363fb752014-01-15 12:27:31 -08001047 } else if (!(mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001048
1049 // FIXME move these calculations and associated checks to server
Glenn Kastene0fa4672012-04-24 14:35:14 -07001050
Eric Laurentd1b449a2010-05-14 03:26:45 -07001051 // Ensure that buffer depth covers at least audio hardware latency
1052 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001053 ALOGV("afFrameCount=%zu, minBufCount=%d, afSampleRate=%u, afLatency=%d",
Glenn Kastenbb6f0a02013-06-03 15:00:29 -07001054 afFrameCount, minBufCount, afSampleRate, afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001055 if (minBufCount <= nBuffering) {
1056 minBufCount = nBuffering;
Glenn Kasten7c027242012-12-26 14:43:16 -08001057 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001058
Andy Hungcd044842014-08-07 11:04:34 -07001059 size_t minFrameCount = afFrameCount * minBufCount * uint64_t(mSampleRate) / afSampleRate;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001060 ALOGV("minFrameCount: %zu, afFrameCount=%zu, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -08001061 ", afLatency=%d",
Glenn Kasten363fb752014-01-15 12:27:31 -08001062 minFrameCount, afFrameCount, minBufCount, mSampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001063
1064 if (frameCount == 0) {
1065 frameCount = minFrameCount;
Glenn Kastence8828a2013-09-16 18:07:38 -07001066 } else if (frameCount < minFrameCount) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001067 // not ALOGW because it happens all the time when playing key clicks over A2DP
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001068 ALOGV("Minimum buffer size corrected from %zu to %zu",
Glenn Kastene0fa4672012-04-24 14:35:14 -07001069 frameCount, minFrameCount);
1070 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001071 }
Glenn Kastence8828a2013-09-16 18:07:38 -07001072 // Make sure that application is notified with sufficient margin before underrun
1073 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1074 mNotificationFramesAct = frameCount/nBuffering;
1075 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001076
Glenn Kastene0fa4672012-04-24 14:35:14 -07001077 } else {
1078 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -07001079 }
1080
Glenn Kastena075db42012-03-06 11:22:44 -08001081 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1082 if (mIsTimed) {
1083 trackFlags |= IAudioFlinger::TRACK_TIMED;
1084 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001085
1086 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001087 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001088 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001089 if (mAudioTrackThread != 0) {
1090 tid = mAudioTrackThread->getTid();
1091 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001092 }
1093
Glenn Kasten363fb752014-01-15 12:27:31 -08001094 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001095 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1096 }
1097
Eric Laurentab5cdba2014-06-09 17:22:27 -07001098 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1099 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1100 }
1101
Glenn Kasten74935e42013-12-19 08:56:45 -08001102 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1103 // but we will still need the original value also
Eric Laurente83b55d2014-11-14 10:06:21 -08001104 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001105 mSampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -07001106 // AudioFlinger only sees 16-bit PCM
Glenn Kastenc4b88a82014-04-30 16:54:30 -07001107 mFormat == AUDIO_FORMAT_PCM_8_BIT &&
1108 !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ?
Glenn Kasten363fb752014-01-15 12:27:31 -08001109 AUDIO_FORMAT_PCM_16_BIT : mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001110 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001111 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001112 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001113 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001114 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001115 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001116 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001117 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001118 &status);
1119
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001120 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001121 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001122 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001123 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001124 ALOG_ASSERT(track != 0);
1125
Glenn Kasten38e905b2014-01-13 10:21:48 -08001126 // AudioFlinger now owns the reference to the I/O handle,
1127 // so we are no longer responsible for releasing it.
1128
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001129 sp<IMemory> iMem = track->getCblk();
1130 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001131 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001132 return NO_INIT;
1133 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001134 void *iMemPointer = iMem->pointer();
1135 if (iMemPointer == NULL) {
1136 ALOGE("Could not get control block pointer");
1137 return NO_INIT;
1138 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001139 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001140 if (mAudioTrack != 0) {
1141 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
1142 mDeathNotifier.clear();
1143 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001144 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001145 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001146 IPCThreadState::self()->flushCommands();
1147
Glenn Kasten0cde0762014-01-16 15:06:36 -08001148 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001149 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001150 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001151 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1152 // In current design, AudioTrack client checks and ensures frame count validity before
1153 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1154 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001155 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001156 }
1157 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001158
Glenn Kastena07f17c2013-04-23 12:39:37 -07001159 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001160 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001161 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001162 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001163 mAwaitBoost = true;
Glenn Kasten363fb752014-01-15 12:27:31 -08001164 if (mSharedBuffer == 0) {
Glenn Kastenb5fed682013-12-03 09:06:43 -08001165 // Theoretically double-buffering is not required for fast tracks,
1166 // due to tighter scheduling. But in practice, to accommodate kernels with
1167 // scheduling jitter, and apps with computation jitter, we use double-buffering.
1168 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1169 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001170 }
1171 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001172 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001173 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001174 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001175 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1176 if (mSharedBuffer == 0) {
Glenn Kastence8828a2013-09-16 18:07:38 -07001177 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1178 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001179 }
1180 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001181 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001182 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001183 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001184 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1185 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1186 } else {
1187 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001188 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001189 // FIXME This is a warning, not an error, so don't return error status
1190 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001191 }
1192 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001193 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1194 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1195 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1196 } else {
1197 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1198 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1199 // FIXME This is a warning, not an error, so don't return error status
1200 //return NO_INIT;
1201 }
1202 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001203
Glenn Kasten38e905b2014-01-13 10:21:48 -08001204 // We retain a copy of the I/O handle, but don't own the reference
1205 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001206 mRefreshRemaining = true;
1207
1208 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1209 // is the value of pointer() for the shared buffer, otherwise buffers points
1210 // immediately after the control block. This address is for the mapping within client
1211 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1212 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001213 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001214 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001215 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001216 buffers = mSharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001217 }
1218
Eric Laurent2beeb502010-07-16 07:43:46 -07001219 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001220 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001221 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001222
Glenn Kastenb6037442012-11-14 13:42:25 -08001223 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001224 // If IAudioTrack is re-created, don't let the requested frameCount
1225 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001226 if (frameCount > mReqFrameCount) {
1227 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001228 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001229
1230 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001231 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001232 mStaticProxy.clear();
1233 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1234 } else {
1235 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1236 mProxy = mStaticProxy;
1237 }
seunghak.hanbe837c32014-11-22 15:22:35 +09001238
1239 mProxy->setVolumeLR(gain_minifloat_pack(
1240 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1241 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1242
Glenn Kastene3aa6592012-12-04 12:22:46 -08001243 mProxy->setSendLevel(mSendLevel);
1244 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001245 mProxy->setMinimum(mNotificationFramesAct);
1246
1247 mDeathNotifier = new DeathNotifier(this);
1248 mAudioTrack->asBinder()->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001249
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001250 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001251 }
1252
1253release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001254 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001255 if (status == NO_ERROR) {
1256 status = NO_INIT;
1257 }
1258 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001259}
1260
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001261status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1262{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001263 if (audioBuffer == NULL) {
1264 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001265 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001266 if (mTransfer != TRANSFER_OBTAIN) {
1267 audioBuffer->frameCount = 0;
1268 audioBuffer->size = 0;
1269 audioBuffer->raw = NULL;
1270 return INVALID_OPERATION;
1271 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001272
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001273 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001274 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001275 if (waitCount == -1) {
1276 requested = &ClientProxy::kForever;
1277 } else if (waitCount == 0) {
1278 requested = &ClientProxy::kNonBlocking;
1279 } else if (waitCount > 0) {
1280 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001281 timeout.tv_sec = ms / 1000;
1282 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1283 requested = &timeout;
1284 } else {
1285 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1286 requested = NULL;
1287 }
1288 return obtainBuffer(audioBuffer, requested);
1289}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001290
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001291status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1292 struct timespec *elapsed, size_t *nonContig)
1293{
1294 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1295 uint32_t oldSequence = 0;
1296 uint32_t newSequence;
1297
1298 Proxy::Buffer buffer;
1299 status_t status = NO_ERROR;
1300
1301 static const int32_t kMaxTries = 5;
1302 int32_t tryCounter = kMaxTries;
1303
1304 do {
1305 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1306 // keep them from going away if another thread re-creates the track during obtainBuffer()
1307 sp<AudioTrackClientProxy> proxy;
1308 sp<IMemory> iMem;
1309
1310 { // start of lock scope
1311 AutoMutex lock(mLock);
1312
1313 newSequence = mSequence;
1314 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1315 if (status == DEAD_OBJECT) {
1316 // re-create track, unless someone else has already done so
1317 if (newSequence == oldSequence) {
1318 status = restoreTrack_l("obtainBuffer");
1319 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001320 buffer.mFrameCount = 0;
1321 buffer.mRaw = NULL;
1322 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001323 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001324 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001325 }
1326 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001327 oldSequence = newSequence;
1328
1329 // Keep the extra references
1330 proxy = mProxy;
1331 iMem = mCblkMemory;
1332
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001333 if (mState == STATE_STOPPING) {
1334 status = -EINTR;
1335 buffer.mFrameCount = 0;
1336 buffer.mRaw = NULL;
1337 buffer.mNonContig = 0;
1338 break;
1339 }
1340
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001341 // Non-blocking if track is stopped or paused
1342 if (mState != STATE_ACTIVE) {
1343 requested = &ClientProxy::kNonBlocking;
1344 }
1345
1346 } // end of lock scope
1347
1348 buffer.mFrameCount = audioBuffer->frameCount;
1349 // FIXME starts the requested timeout and elapsed over from scratch
1350 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1351
1352 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1353
1354 audioBuffer->frameCount = buffer.mFrameCount;
1355 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1356 audioBuffer->raw = buffer.mRaw;
1357 if (nonContig != NULL) {
1358 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001359 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001360 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001361}
1362
1363void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1364{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001365 if (mTransfer == TRANSFER_SHARED) {
1366 return;
1367 }
1368
1369 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1370 if (stepCount == 0) {
1371 return;
1372 }
1373
1374 Proxy::Buffer buffer;
1375 buffer.mFrameCount = stepCount;
1376 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001377
Eric Laurent1703cdf2011-03-07 14:52:59 -08001378 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001379 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001380 mInUnderrun = false;
1381 mProxy->releaseBuffer(&buffer);
1382
1383 // restart track if it was disabled by audioflinger due to previous underrun
1384 if (mState == STATE_ACTIVE) {
1385 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001386 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001387 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001388 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001389 mAudioTrack->start();
1390 }
1391 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001392}
1393
1394// -------------------------------------------------------------------------
1395
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001396ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001397{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001398 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001399 return INVALID_OPERATION;
1400 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001401
Eric Laurentab5cdba2014-06-09 17:22:27 -07001402 if (isDirect()) {
1403 AutoMutex lock(mLock);
1404 int32_t flags = android_atomic_and(
1405 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1406 &mCblk->mFlags);
1407 if (flags & CBLK_INVALID) {
1408 return DEAD_OBJECT;
1409 }
1410 }
1411
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001412 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001413 // Sanity-check: user is most-likely passing an error code, and it would
1414 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001415 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001416 return BAD_VALUE;
1417 }
1418
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001419 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001420 Buffer audioBuffer;
1421
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001422 while (userSize >= mFrameSize) {
1423 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001424
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001425 status_t err = obtainBuffer(&audioBuffer,
1426 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001427 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001428 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001429 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001430 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001431 return ssize_t(err);
1432 }
1433
1434 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001435 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001436 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001437 toWrite = audioBuffer.size >> 1;
1438 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001439 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001440 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001441 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001442 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001443 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001444 userSize -= toWrite;
1445 written += toWrite;
1446
1447 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001448 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001449
1450 return written;
1451}
1452
1453// -------------------------------------------------------------------------
1454
John Grossman4ff14ba2012-02-08 16:37:41 -08001455TimedAudioTrack::TimedAudioTrack() {
1456 mIsTimed = true;
1457}
1458
1459status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1460{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001461 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001462 status_t result = UNKNOWN_ERROR;
1463
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001464#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001465 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1466 // while we are accessing the cblk
1467 sp<IAudioTrack> audioTrack = mAudioTrack;
1468 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001469#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001470
John Grossman4ff14ba2012-02-08 16:37:41 -08001471 // If the track is not invalid already, try to allocate a buffer. alloc
1472 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001473 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001474 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001475 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001476 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1477 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001478 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001479 }
1480 }
1481
1482 // If the track is invalid at this point, attempt to restore it. and try the
1483 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001484 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001485 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001486
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001487 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001488 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001489 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001490 }
1491
1492 return result;
1493}
1494
1495status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1496 int64_t pts)
1497{
Eric Laurentdf839842012-05-31 14:27:14 -07001498 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1499 {
1500 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001501 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001502 // restart track if it was disabled by audioflinger due to previous underrun
1503 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001504 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1505 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001506 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001507 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001508 mAudioTrack->start();
1509 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001510 }
Eric Laurentdf839842012-05-31 14:27:14 -07001511 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001512}
1513
1514status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1515 TargetTimeline target)
1516{
1517 return mAudioTrack->setMediaTimeTransform(xform, target);
1518}
1519
1520// -------------------------------------------------------------------------
1521
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001522nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001523{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001524 // Currently the AudioTrack thread is not created if there are no callbacks.
1525 // Would it ever make sense to run the thread, even without callbacks?
1526 // If so, then replace this by checks at each use for mCbf != NULL.
1527 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1528
Eric Laurent1703cdf2011-03-07 14:52:59 -08001529 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001530 if (mAwaitBoost) {
1531 mAwaitBoost = false;
1532 mLock.unlock();
1533 static const int32_t kMaxTries = 5;
1534 int32_t tryCounter = kMaxTries;
1535 uint32_t pollUs = 10000;
1536 do {
1537 int policy = sched_getscheduler(0);
1538 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1539 break;
1540 }
1541 usleep(pollUs);
1542 pollUs <<= 1;
1543 } while (tryCounter-- > 0);
1544 if (tryCounter < 0) {
1545 ALOGE("did not receive expected priority boost on time");
1546 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001547 // Run again immediately
1548 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001549 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001550
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001551 // Can only reference mCblk while locked
1552 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001553 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001554
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001555 // Check for track invalidation
1556 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001557 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1558 // AudioSystem cache. We should not exit here but after calling the callback so
1559 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001560 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001561 status_t status = restoreTrack_l("processAudioBuffer");
1562 mLock.unlock();
1563 // Run again immediately, but with a new IAudioTrack
1564 return 0;
1565 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001566 }
1567
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001568 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001569 bool active = mState == STATE_ACTIVE;
1570
1571 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1572 bool newUnderrun = false;
1573 if (flags & CBLK_UNDERRUN) {
1574#if 0
1575 // Currently in shared buffer mode, when the server reaches the end of buffer,
1576 // the track stays active in continuous underrun state. It's up to the application
1577 // to pause or stop the track, or set the position to a new offset within buffer.
1578 // This was some experimental code to auto-pause on underrun. Keeping it here
1579 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1580 if (mTransfer == TRANSFER_SHARED) {
1581 mState = STATE_PAUSED;
1582 active = false;
1583 }
1584#endif
1585 if (!mInUnderrun) {
1586 mInUnderrun = true;
1587 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001588 }
1589 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001590
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001591 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001592 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001593
1594 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001595 bool markerReached = false;
1596 size_t markerPosition = mMarkerPosition;
1597 // FIXME fails for wraparound, need 64 bits
1598 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1599 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001600 }
1601
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001602 // Determine number of new position callback(s) that will be needed, while locked
1603 size_t newPosCount = 0;
1604 size_t newPosition = mNewPosition;
1605 size_t updatePeriod = mUpdatePeriod;
1606 // FIXME fails for wraparound, need 64 bits
1607 if (updatePeriod > 0 && position >= newPosition) {
1608 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1609 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001610 }
1611
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001612 // Cache other fields that will be needed soon
1613 uint32_t loopPeriod = mLoopPeriod;
1614 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001615 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001616 if (mRefreshRemaining) {
1617 mRefreshRemaining = false;
1618 mRemainingFrames = notificationFrames;
1619 mRetryOnPartialBuffer = false;
1620 }
1621 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001622 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001623 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001624
1625 // These fields don't need to be cached, because they are assigned only by set():
1626 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1627 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1628
1629 mLock.unlock();
1630
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001631 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001632 struct timespec timeout;
1633 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1634 timeout.tv_nsec = 0;
1635
Glenn Kasten96f04882013-09-20 09:28:56 -07001636 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001637 switch (status) {
1638 case NO_ERROR:
1639 case DEAD_OBJECT:
1640 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001641 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001642 {
1643 AutoMutex lock(mLock);
1644 // The previously assigned value of waitStreamEnd is no longer valid,
1645 // since the mutex has been unlocked and either the callback handler
1646 // or another thread could have re-started the AudioTrack during that time.
1647 waitStreamEnd = mState == STATE_STOPPING;
1648 if (waitStreamEnd) {
1649 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001650 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001651 }
1652 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001653 if (waitStreamEnd && status != DEAD_OBJECT) {
1654 return NS_INACTIVE;
1655 }
1656 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001657 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001658 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001659 }
1660
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001661 // perform callbacks while unlocked
1662 if (newUnderrun) {
1663 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1664 }
1665 // FIXME we will miss loops if loop cycle was signaled several times since last call
1666 // to processAudioBuffer()
1667 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1668 mCbf(EVENT_LOOP_END, mUserData, NULL);
1669 }
1670 if (flags & CBLK_BUFFER_END) {
1671 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1672 }
1673 if (markerReached) {
1674 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1675 }
1676 while (newPosCount > 0) {
1677 size_t temp = newPosition;
1678 mCbf(EVENT_NEW_POS, mUserData, &temp);
1679 newPosition += updatePeriod;
1680 newPosCount--;
1681 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001682
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001683 if (mObservedSequence != sequence) {
1684 mObservedSequence = sequence;
1685 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001686 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001687 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001688 return NS_INACTIVE;
1689 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001690 }
1691
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001692 // if inactive, then don't run me again until re-started
1693 if (!active) {
1694 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001695 }
1696
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001697 // Compute the estimated time until the next timed event (position, markers, loops)
1698 // FIXME only for non-compressed audio
1699 uint32_t minFrames = ~0;
1700 if (!markerReached && position < markerPosition) {
1701 minFrames = markerPosition - position;
1702 }
1703 if (loopPeriod > 0 && loopPeriod < minFrames) {
1704 minFrames = loopPeriod;
1705 }
1706 if (updatePeriod > 0 && updatePeriod < minFrames) {
1707 minFrames = updatePeriod;
1708 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001709
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001710 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1711 static const uint32_t kPoll = 0;
1712 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1713 minFrames = kPoll * notificationFrames;
1714 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001715
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001716 // Convert frame units to time units
1717 nsecs_t ns = NS_WHENEVER;
1718 if (minFrames != (uint32_t) ~0) {
1719 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1720 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1721 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1722 }
1723
1724 // If not supplying data by EVENT_MORE_DATA, then we're done
1725 if (mTransfer != TRANSFER_CALLBACK) {
1726 return ns;
1727 }
1728
1729 struct timespec timeout;
1730 const struct timespec *requested = &ClientProxy::kForever;
1731 if (ns != NS_WHENEVER) {
1732 timeout.tv_sec = ns / 1000000000LL;
1733 timeout.tv_nsec = ns % 1000000000LL;
1734 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1735 requested = &timeout;
1736 }
1737
1738 while (mRemainingFrames > 0) {
1739
1740 Buffer audioBuffer;
1741 audioBuffer.frameCount = mRemainingFrames;
1742 size_t nonContig;
1743 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1744 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001745 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001746 requested = &ClientProxy::kNonBlocking;
1747 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001748 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001749 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001750 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001751 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1752 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001753 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001754 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001755 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1756 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001757 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001758
Eric Laurent42a6f422013-08-29 14:35:05 -07001759 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001760 mRetryOnPartialBuffer = false;
1761 if (avail < mRemainingFrames) {
1762 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1763 if (ns < 0 || myns < ns) {
1764 ns = myns;
1765 }
1766 return ns;
1767 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001768 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001769
1770 // Divide buffer size by 2 to take into account the expansion
1771 // due to 8 to 16 bit conversion: the callback must fill only half
1772 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001773 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001774 audioBuffer.size >>= 1;
1775 }
1776
1777 size_t reqSize = audioBuffer.size;
1778 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001779 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001780
1781 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001782 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001783 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1784 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001785 return NS_NEVER;
1786 }
1787
1788 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001789 // The callback is done filling buffers
1790 // Keep this thread going to handle timed events and
1791 // still try to get more data in intervals of WAIT_PERIOD_MS
1792 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001793 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001794 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001795
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001796 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001797 // 8 to 16 bit conversion, note that source and destination are the same address
1798 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001799 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001800 }
1801
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001802 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1803 audioBuffer.frameCount = releasedFrames;
1804 mRemainingFrames -= releasedFrames;
1805 if (misalignment >= releasedFrames) {
1806 misalignment -= releasedFrames;
1807 } else {
1808 misalignment = 0;
1809 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001810
1811 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001812
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001813 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1814 // if callback doesn't like to accept the full chunk
1815 if (writtenSize < reqSize) {
1816 continue;
1817 }
1818
1819 // There could be enough non-contiguous frames available to satisfy the remaining request
1820 if (mRemainingFrames <= nonContig) {
1821 continue;
1822 }
1823
1824#if 0
1825 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1826 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1827 // that total to a sum == notificationFrames.
1828 if (0 < misalignment && misalignment <= mRemainingFrames) {
1829 mRemainingFrames = misalignment;
1830 return (mRemainingFrames * 1100000000LL) / sampleRate;
1831 }
1832#endif
1833
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001834 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001835 mRemainingFrames = notificationFrames;
1836 mRetryOnPartialBuffer = true;
1837
1838 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1839 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001840}
1841
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001842status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001843{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001844 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001845 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001846 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001847 status_t result;
1848
Glenn Kastena47f3162012-11-07 10:13:08 -08001849 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08001850 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001851 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001852
Eric Laurentab5cdba2014-06-09 17:22:27 -07001853 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001854 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001855 return DEAD_OBJECT;
1856 }
1857
Glenn Kasten200092b2014-08-15 15:13:30 -07001858 // save the old static buffer position
1859 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
1860
1861 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001862 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001863 // It will also delete the strong references on previous IAudioTrack and IMemory.
1864 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
1865 result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001866
1867 // take the frames that will be lost by track recreation into account in saved position
Glenn Kasten200092b2014-08-15 15:13:30 -07001868 (void) updateAndGetPosition_l();
1869 mPosition = mReleased;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001870
Glenn Kastena47f3162012-11-07 10:13:08 -08001871 if (result == NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001872 // continue playback from last known position, but
1873 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1874 if (mStaticProxy != NULL) {
1875 mLoopPeriod = 0;
1876 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1877 }
1878 // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1879 // track destruction have been played? This is critical for SoundPool implementation
1880 // This must be broken, and needs to be tested/debugged.
1881#if 0
Glenn Kastena47f3162012-11-07 10:13:08 -08001882 // restore write index and set other indexes to reflect empty buffer status
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001883 if (!strcmp(from, "start")) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001884 // Make sure that a client relying on callback events indicating underrun or
1885 // the actual amount of audio frames played (e.g SoundPool) receives them.
1886 if (mSharedBuffer == 0) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001887 // restart playback even if buffer is not completely filled.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001888 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001889 }
1890 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001891#endif
1892 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001893 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001894 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001895 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001896 if (result != NO_ERROR) {
1897 ALOGW("restoreTrack_l() failed status %d", result);
1898 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001899 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001900 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001901
1902 return result;
1903}
1904
Glenn Kasten200092b2014-08-15 15:13:30 -07001905uint32_t AudioTrack::updateAndGetPosition_l()
1906{
1907 // This is the sole place to read server consumed frames
1908 uint32_t newServer = mProxy->getPosition();
1909 int32_t delta = newServer - mServer;
1910 mServer = newServer;
1911 // TODO There is controversy about whether there can be "negative jitter" in server position.
1912 // This should be investigated further, and if possible, it should be addressed.
1913 // A more definite failure mode is infrequent polling by client.
1914 // One could call (void)getPosition_l() in releaseBuffer(),
1915 // so mReleased and mPosition are always lock-step as best possible.
1916 // That should ensure delta never goes negative for infrequent polling
1917 // unless the server has more than 2^31 frames in its buffer,
1918 // in which case the use of uint32_t for these counters has bigger issues.
1919 if (delta < 0) {
1920 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
1921 delta = 0;
1922 }
1923 return mPosition += (uint32_t) delta;
1924}
1925
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001926status_t AudioTrack::setParameters(const String8& keyValuePairs)
1927{
1928 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001929 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001930}
1931
Glenn Kastence703742013-07-19 16:33:58 -07001932status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1933{
Glenn Kasten53cec222013-08-29 09:01:02 -07001934 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001935 // FIXME not implemented for fast tracks; should use proxy and SSQ
1936 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1937 return INVALID_OPERATION;
1938 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001939
1940 switch (mState) {
1941 case STATE_ACTIVE:
1942 case STATE_PAUSED:
1943 break; // handle below
1944 case STATE_FLUSHED:
1945 case STATE_STOPPED:
1946 return WOULD_BLOCK;
1947 case STATE_STOPPING:
1948 case STATE_PAUSED_STOPPING:
1949 if (!isOffloaded_l()) {
1950 return INVALID_OPERATION;
1951 }
1952 break; // offloaded tracks handled below
1953 default:
1954 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
1955 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07001956 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001957
Eric Laurent275e8e92014-11-30 15:14:47 -08001958 if (mCblk->mFlags & CBLK_INVALID) {
1959 restoreTrack_l("getTimestamp");
1960 }
1961
Glenn Kasten200092b2014-08-15 15:13:30 -07001962 // The presented frame count must always lag behind the consumed frame count.
1963 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07001964 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001965 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07001966 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001967 return status;
1968 }
1969 if (isOffloadedOrDirect_l()) {
1970 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
1971 // use cached paused position in case another offloaded track is running.
1972 timestamp.mPosition = mPausedPosition;
1973 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
1974 return NO_ERROR;
1975 }
1976
1977 // Check whether a pending flush or stop has completed, as those commands may
1978 // be asynchronous or return near finish.
1979 if (mStartUs != 0 && mSampleRate != 0) {
1980 static const int kTimeJitterUs = 100000; // 100 ms
1981 static const int k1SecUs = 1000000;
1982
1983 const int64_t timeNow = getNowUs();
1984
1985 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
1986 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
1987 if (timestampTimeUs < mStartUs) {
1988 return WOULD_BLOCK; // stale timestamp time, occurs before start.
1989 }
1990 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
1991 const int64_t deltaPositionByUs = timestamp.mPosition * 1000000LL / mSampleRate;
1992
1993 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
1994 // Verify that the counter can't count faster than the sample rate
1995 // since the start time. If greater, then that means we have failed
1996 // to completely flush or stop the previous playing track.
1997 ALOGW("incomplete flush or stop:"
1998 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
1999 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2000 timestamp.mPosition);
2001 return WOULD_BLOCK;
2002 }
2003 }
2004 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
2005 }
2006 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002007 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2008 (void) updateAndGetPosition_l();
2009 // Server consumed (mServer) and presented both use the same server time base,
2010 // and server consumed is always >= presented.
2011 // The delta between these represents the number of frames in the buffer pipeline.
2012 // If this delta between these is greater than the client position, it means that
2013 // actually presented is still stuck at the starting line (figuratively speaking),
2014 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
2015 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2016 return INVALID_OPERATION;
2017 }
2018 // Convert timestamp position from server time base to client time base.
2019 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2020 // But if we change it to 64-bit then this could fail.
2021 // If (mPosition - mServer) can be negative then should use:
2022 // (int32_t)(mPosition - mServer)
2023 timestamp.mPosition += mPosition - mServer;
2024 // Immediately after a call to getPosition_l(), mPosition and
2025 // mServer both represent the same frame position. mPosition is
2026 // in client's point of view, and mServer is in server's point of
2027 // view. So the difference between them is the "fudge factor"
2028 // between client and server views due to stop() and/or new
2029 // IAudioTrack. And timestamp.mPosition is initially in server's
2030 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002031 }
2032 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002033}
2034
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002035String8 AudioTrack::getParameters(const String8& keys)
2036{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002037 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002038 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002039 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002040 } else {
2041 return String8::empty();
2042 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002043}
2044
Glenn Kasten23a75452014-01-13 10:37:17 -08002045bool AudioTrack::isOffloaded() const
2046{
2047 AutoMutex lock(mLock);
2048 return isOffloaded_l();
2049}
2050
Eric Laurentab5cdba2014-06-09 17:22:27 -07002051bool AudioTrack::isDirect() const
2052{
2053 AutoMutex lock(mLock);
2054 return isDirect_l();
2055}
2056
2057bool AudioTrack::isOffloadedOrDirect() const
2058{
2059 AutoMutex lock(mLock);
2060 return isOffloadedOrDirect_l();
2061}
2062
2063
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002064status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002065{
2066
2067 const size_t SIZE = 256;
2068 char buffer[SIZE];
2069 String8 result;
2070
2071 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002072 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002073 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002074 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002075 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002076 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002077 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08002078 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002079 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002080 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002081 result.append(buffer);
2082 ::write(fd, result.string(), result.size());
2083 return NO_ERROR;
2084}
2085
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002086uint32_t AudioTrack::getUnderrunFrames() const
2087{
2088 AutoMutex lock(mLock);
2089 return mProxy->getUnderrunFrames();
2090}
2091
2092// =========================================================================
2093
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002094void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002095{
2096 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2097 if (audioTrack != 0) {
2098 AutoMutex lock(audioTrack->mLock);
2099 audioTrack->mProxy->binderDied();
2100 }
2101}
2102
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002103// =========================================================================
2104
2105AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002106 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2107 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002108{
2109}
2110
2111AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002112{
2113}
2114
2115bool AudioTrack::AudioTrackThread::threadLoop()
2116{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002117 {
2118 AutoMutex _l(mMyLock);
2119 if (mPaused) {
2120 mMyCond.wait(mMyLock);
2121 // caller will check for exitPending()
2122 return true;
2123 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002124 if (mIgnoreNextPausedInt) {
2125 mIgnoreNextPausedInt = false;
2126 mPausedInt = false;
2127 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002128 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002129 if (mPausedNs > 0) {
2130 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2131 } else {
2132 mMyCond.wait(mMyLock);
2133 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002134 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002135 return true;
2136 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002137 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002138 if (exitPending()) {
2139 return false;
2140 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002141 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002142 switch (ns) {
2143 case 0:
2144 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002145 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002146 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002147 return true;
2148 case NS_NEVER:
2149 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002150 case NS_WHENEVER:
2151 // FIXME increase poll interval, or make event-driven
2152 ns = 1000000000LL;
2153 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002154 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002155 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002156 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002157 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002158 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002159}
2160
Glenn Kasten3acbd052012-02-28 10:39:56 -08002161void AudioTrack::AudioTrackThread::requestExit()
2162{
2163 // must be in this order to avoid a race condition
2164 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002165 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002166}
2167
2168void AudioTrack::AudioTrackThread::pause()
2169{
2170 AutoMutex _l(mMyLock);
2171 mPaused = true;
2172}
2173
2174void AudioTrack::AudioTrackThread::resume()
2175{
2176 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002177 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002178 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002179 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002180 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002181 mMyCond.signal();
2182 }
2183}
2184
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002185void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2186{
2187 AutoMutex _l(mMyLock);
2188 mPausedInt = true;
2189 mPausedNs = ns;
2190}
2191
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002192}; // namespace android