blob: ff7da837f8262a762d1107456881ec60d4ab90cf [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>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080032
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010033#define WAIT_PERIOD_MS 10
34#define WAIT_STREAM_END_TIMEOUT_SEC 120
35
Glenn Kasten511754b2012-01-11 09:52:19 -080036
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080037namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080038// ---------------------------------------------------------------------------
39
40// static
41status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080042 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080043 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080044 uint32_t sampleRate)
45{
Glenn Kastend65d73c2012-06-22 17:21:07 -070046 if (frameCount == NULL) {
47 return BAD_VALUE;
48 }
Glenn Kasten04cd0182012-06-25 11:49:27 -070049
Glenn Kastene0fa4672012-04-24 14:35:14 -070050 // FIXME merge with similar code in createTrack_l(), except we're missing
51 // some information here that is available in createTrack_l():
52 // audio_io_handle_t output
53 // audio_format_t format
54 // audio_channel_mask_t channelMask
55 // audio_output_flags_t flags
Glenn Kasten3b16c762012-11-14 08:44:39 -080056 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080057 status_t status;
58 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
59 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080060 ALOGE("Unable to query output sample rate for stream type %d; status %d",
61 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080062 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080063 }
Glenn Kastene33054e2012-11-14 12:54:39 -080064 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -080065 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
66 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080067 ALOGE("Unable to query output frame count for stream type %d; status %d",
68 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080069 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080070 }
71 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -080072 status = AudioSystem::getOutputLatency(&afLatency, streamType);
73 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080074 ALOGE("Unable to query output latency 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 }
78
79 // Ensure that buffer depth covers at least audio hardware latency
80 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080081 if (minBufCount < 2) {
82 minBufCount = 2;
83 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +080084
85 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
Andy Hungcd044842014-08-07 11:04:34 -070086 afFrameCount * minBufCount * uint64_t(sampleRate) / afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080087 // The formula above should always produce a non-zero value, but return an error
88 // in the unlikely event that it does not, as that's part of the API contract.
89 if (*frameCount == 0) {
90 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %d",
91 streamType, sampleRate);
92 return BAD_VALUE;
93 }
Mark Salyzyn34fb2962014-06-18 16:30:56 -070094 ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, minBufCount=%d, afSampleRate=%d, afLatency=%d",
Glenn Kasten3acbd052012-02-28 10:39:56 -080095 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +080096 return NO_ERROR;
97}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080098
99// ---------------------------------------------------------------------------
100
101AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700102 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800103 mIsTimed(false),
104 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800105 mPreviousSchedulingGroup(SP_DEFAULT),
106 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800107{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700108 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
109 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
110 mAttributes.flags = 0x0;
111 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800112}
113
114AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800115 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800116 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800117 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700118 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800119 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700120 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800121 callback_t cbf,
122 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800123 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800124 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000125 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800126 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800127 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700128 pid_t pid,
129 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700130 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800131 mIsTimed(false),
132 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800133 mPreviousSchedulingGroup(SP_DEFAULT),
134 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800135{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700136 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700137 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800138 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700139 offloadInfo, uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800140}
141
Andreas Huberc8139852012-01-18 10:51:55 -0800142AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800143 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800144 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800145 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700146 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800147 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700148 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800149 callback_t cbf,
150 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800151 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800152 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000153 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800154 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800155 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700156 pid_t pid,
157 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700158 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800159 mIsTimed(false),
160 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800161 mPreviousSchedulingGroup(SP_DEFAULT),
162 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800163{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700164 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800165 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800166 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700167 uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800168}
169
170AudioTrack::~AudioTrack()
171{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800172 if (mStatus == NO_ERROR) {
173 // Make sure that callback function exits in the case where
174 // it is looping on buffer full condition in obtainBuffer().
175 // Otherwise the callback thread will never exit.
176 stop();
177 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100178 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800179 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800180 mAudioTrackThread->requestExitAndWait();
181 mAudioTrackThread.clear();
182 }
Glenn Kasten53cec222013-08-29 09:01:02 -0700183 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
184 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700185 mCblkMemory.clear();
186 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800187 IPCThreadState::self()->flushCommands();
Marco Nelissend457c972014-02-11 08:47:07 -0800188 ALOGV("~AudioTrack, releasing session id from %d on behalf of %d",
189 IPCThreadState::self()->getCallingPid(), mClientPid);
190 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800191 }
192}
193
194status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800195 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800196 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800197 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700198 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800199 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700200 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800201 callback_t cbf,
202 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800203 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800204 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700205 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800206 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000207 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800208 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800209 int uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700210 pid_t pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700211 const audio_attributes_t* pAttributes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800212{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800213 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten838b3d82014-02-27 15:30:41 -0800214 "flags #%x, notificationFrames %u, sessionId %d, transferType %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800215 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten86f04662014-02-24 15:13:05 -0800216 sessionId, transferType);
217
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800218 switch (transferType) {
219 case TRANSFER_DEFAULT:
220 if (sharedBuffer != 0) {
221 transferType = TRANSFER_SHARED;
222 } else if (cbf == NULL || threadCanCallJava) {
223 transferType = TRANSFER_SYNC;
224 } else {
225 transferType = TRANSFER_CALLBACK;
226 }
227 break;
228 case TRANSFER_CALLBACK:
229 if (cbf == NULL || sharedBuffer != 0) {
230 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
231 return BAD_VALUE;
232 }
233 break;
234 case TRANSFER_OBTAIN:
235 case TRANSFER_SYNC:
236 if (sharedBuffer != 0) {
237 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
238 return BAD_VALUE;
239 }
240 break;
241 case TRANSFER_SHARED:
242 if (sharedBuffer == 0) {
243 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
244 return BAD_VALUE;
245 }
246 break;
247 default:
248 ALOGE("Invalid transfer type %d", transferType);
249 return BAD_VALUE;
250 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800251 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800252 mTransfer = transferType;
253
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700254 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
255 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800256
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700257 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700258
Eric Laurent1703cdf2011-03-07 14:52:59 -0800259 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800260
Glenn Kasten53cec222013-08-29 09:01:02 -0700261 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700262 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000263 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800264 return INVALID_OPERATION;
265 }
266
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800267 // handle default values first.
Dima Zavinfce7a472011-04-19 22:30:36 -0700268 if (streamType == AUDIO_STREAM_DEFAULT) {
269 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800270 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700271
272 if (pAttributes == NULL) {
273 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
274 ALOGE("Invalid stream type %d", streamType);
275 return BAD_VALUE;
276 }
277 setAttributesFromStreamType(streamType);
278 mStreamType = streamType;
279 } else {
280 if (!isValidAttributes(pAttributes)) {
281 ALOGE("Invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
282 pAttributes->usage, pAttributes->content_type, pAttributes->flags,
283 pAttributes->tags);
284 }
285 // stream type shouldn't be looked at, this track has audio attributes
286 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
287 setStreamTypeFromAttributes(mAttributes);
288 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
289 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800290 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700291
Glenn Kastenb1bef512014-01-13 10:25:53 -0800292 status_t status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800293 if (sampleRate == 0) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700294 status = AudioSystem::getOutputSamplingRateForAttr(&sampleRate, &mAttributes);
Glenn Kastenb1bef512014-01-13 10:25:53 -0800295 if (status != NO_ERROR) {
296 ALOGE("Could not get output sample rate for stream type %d; status %d",
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700297 mStreamType, status);
Glenn Kastenb1bef512014-01-13 10:25:53 -0800298 return status;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700299 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800300 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800301 mSampleRate = sampleRate;
Glenn Kastenea7939a2012-03-14 12:56:26 -0700302
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800303 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800304 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700305 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800306 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800307
308 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700309 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800310 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800311 return BAD_VALUE;
312 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800313 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700314
Glenn Kasten8ba90322013-10-30 11:29:27 -0700315 if (!audio_is_output_channel(channelMask)) {
316 ALOGE("Invalid channel mask %#x", channelMask);
317 return BAD_VALUE;
318 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800319 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700320 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800321 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700322
Glenn Kastene0fa4672012-04-24 14:35:14 -0700323 // AudioFlinger does not currently support 8-bit data in shared memory
324 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
325 ALOGE("8-bit data in shared memory is not supported");
326 return BAD_VALUE;
327 }
328
Eric Laurentc2f1f072009-07-17 12:17:14 -0700329 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100330 // or offload was requested
331 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
332 || !audio_is_linear_pcm(format)) {
333 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
334 ? "Offload request, forcing to Direct Output"
335 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700336 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800337 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700338 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700339 }
Eric Laurent1948eb32012-04-13 16:50:19 -0700340 // only allow deep buffering for music stream type
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700341 if (mStreamType != AUDIO_STREAM_MUSIC) {
Eric Laurent1948eb32012-04-13 16:50:19 -0700342 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
343 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700344
Glenn Kastenb7730382014-04-30 15:50:31 -0700345 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
346 if (audio_is_linear_pcm(format)) {
347 mFrameSize = channelCount * audio_bytes_per_sample(format);
348 } else {
349 mFrameSize = sizeof(uint8_t);
350 }
351 mFrameSizeAF = mFrameSize;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800352 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700353 ALOG_ASSERT(audio_is_linear_pcm(format));
354 mFrameSize = channelCount * audio_bytes_per_sample(format);
355 mFrameSizeAF = channelCount * audio_bytes_per_sample(
356 format == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : format);
357 // createTrack will return an error if PCM format is not supported by server,
358 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800359 }
360
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800361 // Make copy of input parameter offloadInfo so that in the future:
362 // (a) createTrack_l doesn't need it as an input parameter
363 // (b) we can support re-creation of offloaded tracks
364 if (offloadInfo != NULL) {
365 mOffloadInfoCopy = *offloadInfo;
366 mOffloadInfo = &mOffloadInfoCopy;
367 } else {
368 mOffloadInfo = NULL;
369 }
370
Glenn Kasten66e46352014-01-16 17:44:23 -0800371 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
372 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800373 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800374 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800375 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700376 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800377 mNotificationFramesAct = 0;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700378 mSessionId = sessionId;
Marco Nelissend457c972014-02-11 08:47:07 -0800379 int callingpid = IPCThreadState::self()->getCallingPid();
380 int mypid = getpid();
381 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800382 mClientUid = IPCThreadState::self()->getCallingUid();
383 } else {
384 mClientUid = uid;
385 }
Marco Nelissend457c972014-02-11 08:47:07 -0800386 if (pid == -1 || (callingpid != mypid)) {
387 mClientPid = callingpid;
388 } else {
389 mClientPid = pid;
390 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700391 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700392 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700393 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700394
Glenn Kastena997e7a2012-08-07 09:44:19 -0700395 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700396 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700397 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
398 }
399
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800400 // create the IAudioTrack
Glenn Kasten200092b2014-08-15 15:13:30 -0700401 status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800402
Glenn Kastena997e7a2012-08-07 09:44:19 -0700403 if (status != NO_ERROR) {
404 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100405 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
406 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700407 mAudioTrackThread.clear();
408 }
409 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700410 }
411
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800412 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800413 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800414 mUserData = user;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800415 mLoopPeriod = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800416 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700417 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800418 mNewPosition = 0;
419 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700420 mServer = 0;
421 mPosition = 0;
422 mReleased = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800423 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800424 mSequence = 1;
425 mObservedSequence = mSequence;
426 mInUnderrun = false;
427
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800428 return NO_ERROR;
429}
430
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800431// -------------------------------------------------------------------------
432
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100433status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800434{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800435 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100436
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800437 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100438 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800439 }
440
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800441 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800442
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800443 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100444 if (previousState == STATE_PAUSED_STOPPING) {
445 mState = STATE_STOPPING;
446 } else {
447 mState = STATE_ACTIVE;
448 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700449 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800450 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
451 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700452 mPosition = 0;
453 mReleased = 0;
Eric Laurentec9a0322013-08-28 10:23:01 -0700454 // force refresh of remaining frames by processAudioBuffer() as last
455 // write before stop could be partial.
456 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800457 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700458 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700459 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800460
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800461 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800462 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100463 if (previousState == STATE_STOPPING) {
464 mProxy->interrupt();
465 } else {
466 t->resume();
467 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800468 } else {
469 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
470 get_sched_policy(0, &mPreviousSchedulingGroup);
471 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
472 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800473
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800474 status_t status = NO_ERROR;
475 if (!(flags & CBLK_INVALID)) {
476 status = mAudioTrack->start();
477 if (status == DEAD_OBJECT) {
478 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800479 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800480 }
481 if (flags & CBLK_INVALID) {
482 status = restoreTrack_l("start");
483 }
484
485 if (status != NO_ERROR) {
486 ALOGE("start() status %d", status);
487 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800488 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100489 if (previousState != STATE_STOPPING) {
490 t->pause();
491 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800492 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700493 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700494 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800495 }
496 }
497
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100498 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800499}
500
501void AudioTrack::stop()
502{
503 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700504 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800505 return;
506 }
507
Glenn Kasten23a75452014-01-13 10:37:17 -0800508 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100509 mState = STATE_STOPPING;
510 } else {
511 mState = STATE_STOPPED;
512 }
513
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800514 mProxy->interrupt();
515 mAudioTrack->stop();
516 // the playback head position will reset to 0, so if a marker is set, we need
517 // to activate it again
518 mMarkerReached = false;
519#if 0
520 // Force flush if a shared buffer is used otherwise audioflinger
521 // will not stop before end of buffer is reached.
522 // It may be needed to make sure that we stop playback, likely in case looping is on.
523 if (mSharedBuffer != 0) {
524 flush_l();
525 }
526#endif
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100527
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800528 sp<AudioTrackThread> t = mAudioTrackThread;
529 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800530 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100531 t->pause();
532 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800533 } else {
534 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
535 set_sched_policy(0, mPreviousSchedulingGroup);
536 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800537}
538
539bool AudioTrack::stopped() const
540{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800541 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800542 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800543}
544
545void AudioTrack::flush()
546{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800547 if (mSharedBuffer != 0) {
548 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800549 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800550 AutoMutex lock(mLock);
551 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
552 return;
553 }
554 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800555}
556
Eric Laurent1703cdf2011-03-07 14:52:59 -0800557void AudioTrack::flush_l()
558{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800559 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700560
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700561 // clear playback marker and periodic update counter
562 mMarkerPosition = 0;
563 mMarkerReached = false;
564 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100565 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700566
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800567 mState = STATE_FLUSHED;
Glenn Kasten23a75452014-01-13 10:37:17 -0800568 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100569 mProxy->interrupt();
570 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800571 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800572 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800573}
574
575void AudioTrack::pause()
576{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800577 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100578 if (mState == STATE_ACTIVE) {
579 mState = STATE_PAUSED;
580 } else if (mState == STATE_STOPPING) {
581 mState = STATE_PAUSED_STOPPING;
582 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800583 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800584 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800585 mProxy->interrupt();
586 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800587
Marco Nelissen3a90f282014-03-10 11:21:43 -0700588 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700589 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800590 uint32_t halFrames;
591 // OffloadThread sends HAL pause in its threadLoop.. time saved
592 // here can be slightly off
593 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
594 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
595 }
596 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800597}
598
Eric Laurentbe916aa2010-06-01 23:49:17 -0700599status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800600{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700601 // This duplicates a test by AudioTrack JNI, but that is not the only caller
602 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
603 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700604 return BAD_VALUE;
605 }
606
Eric Laurent1703cdf2011-03-07 14:52:59 -0800607 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800608 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
609 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800610
Glenn Kastenc56f3422014-03-21 17:53:17 -0700611 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700612
Glenn Kasten23a75452014-01-13 10:37:17 -0800613 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700614 mAudioTrack->signal();
615 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700616 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800617}
618
Glenn Kastenb1c09932012-02-27 16:21:04 -0800619status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800620{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800621 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700622}
623
Eric Laurent2beeb502010-07-16 07:43:46 -0700624status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700625{
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(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700628 return BAD_VALUE;
629 }
630
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800631 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700632 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800633 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700634
635 return NO_ERROR;
636}
637
Glenn Kastena5224f32012-01-04 12:41:44 -0800638void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700639{
640 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800641 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700642 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800643}
644
Glenn Kasten3b16c762012-11-14 08:44:39 -0800645status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800646{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700647 if (mIsTimed || isOffloadedOrDirect()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800648 return INVALID_OPERATION;
649 }
650
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800651 uint32_t afSamplingRate;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700652 if (AudioSystem::getOutputSamplingRateForAttr(&afSamplingRate, &mAttributes) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700653 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800654 }
Andy Hungcd044842014-08-07 11:04:34 -0700655 if (rate == 0 || rate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700656 return BAD_VALUE;
657 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800658
Eric Laurent1703cdf2011-03-07 14:52:59 -0800659 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800660 mSampleRate = rate;
661 mProxy->setSampleRate(rate);
662
Eric Laurent57326622009-07-07 07:10:45 -0700663 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800664}
665
Glenn Kastena5224f32012-01-04 12:41:44 -0800666uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800667{
John Grossman4ff14ba2012-02-08 16:37:41 -0800668 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800669 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800670 }
671
Eric Laurent1703cdf2011-03-07 14:52:59 -0800672 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700673
674 // sample rate can be updated during playback by the offloaded decoder so we need to
675 // query the HAL and update if needed.
676// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700677 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700678 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700679 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700680 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700681 if (status == NO_ERROR) {
682 mSampleRate = sampleRate;
683 }
684 }
685 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800686 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800687}
688
689status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
690{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700691 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800692 return INVALID_OPERATION;
693 }
694
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800695 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800696 ;
697 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
698 loopEnd - loopStart >= MIN_LOOP) {
699 ;
700 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800701 return BAD_VALUE;
702 }
703
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800704 AutoMutex lock(mLock);
705 // See setPosition() regarding setting parameters such as loop points or position while active
706 if (mState == STATE_ACTIVE) {
707 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700708 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800709 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800710 return NO_ERROR;
711}
712
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800713void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
714{
715 // FIXME If setting a loop also sets position to start of loop, then
716 // this is correct. Otherwise it should be removed.
Glenn Kasten200092b2014-08-15 15:13:30 -0700717 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800718 mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0;
719 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
720}
721
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800722status_t AudioTrack::setMarkerPosition(uint32_t marker)
723{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700724 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700725 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700726 return INVALID_OPERATION;
727 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800728
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800729 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800730 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700731 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800732
733 return NO_ERROR;
734}
735
Glenn Kastena5224f32012-01-04 12:41:44 -0800736status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800737{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700738 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100739 return INVALID_OPERATION;
740 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700741 if (marker == NULL) {
742 return BAD_VALUE;
743 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800744
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800745 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800746 *marker = mMarkerPosition;
747
748 return NO_ERROR;
749}
750
751status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
752{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700753 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700754 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700755 return INVALID_OPERATION;
756 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800757
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800758 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700759 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800760 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800761
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800762 return NO_ERROR;
763}
764
Glenn Kastena5224f32012-01-04 12:41:44 -0800765status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800766{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700767 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100768 return INVALID_OPERATION;
769 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700770 if (updatePeriod == NULL) {
771 return BAD_VALUE;
772 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800773
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800774 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800775 *updatePeriod = mUpdatePeriod;
776
777 return NO_ERROR;
778}
779
780status_t AudioTrack::setPosition(uint32_t position)
781{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700782 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700783 return INVALID_OPERATION;
784 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800785 if (position > mFrameCount) {
786 return BAD_VALUE;
787 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800788
Eric Laurent1703cdf2011-03-07 14:52:59 -0800789 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800790 // Currently we require that the player is inactive before setting parameters such as position
791 // or loop points. Otherwise, there could be a race condition: the application could read the
792 // current position, compute a new position or loop parameters, and then set that position or
793 // loop parameters but it would do the "wrong" thing since the position has continued to advance
794 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
795 // to specify how it wants to handle such scenarios.
796 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700797 return INVALID_OPERATION;
798 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700799 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800800 mLoopPeriod = 0;
801 // FIXME Check whether loops and setting position are incompatible in old code.
802 // If we use setLoop for both purposes we lose the capability to set the position while looping.
803 mStaticProxy->setLoop(position, mFrameCount, 0);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700804
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800805 return NO_ERROR;
806}
807
Glenn Kasten200092b2014-08-15 15:13:30 -0700808status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800809{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700810 if (position == NULL) {
811 return BAD_VALUE;
812 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800813
Eric Laurent1703cdf2011-03-07 14:52:59 -0800814 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700815 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100816 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800817
Eric Laurentab5cdba2014-06-09 17:22:27 -0700818 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800819 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
820 *position = mPausedPosition;
821 return NO_ERROR;
822 }
823
Glenn Kasten142f5192014-03-25 17:44:59 -0700824 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100825 uint32_t halFrames;
826 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
827 }
828 *position = dspFrames;
829 } else {
830 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700831 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
832 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100833 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800834 return NO_ERROR;
835}
836
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000837status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800838{
839 if (mSharedBuffer == 0 || mIsTimed) {
840 return INVALID_OPERATION;
841 }
842 if (position == NULL) {
843 return BAD_VALUE;
844 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800845
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800846 AutoMutex lock(mLock);
847 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800848 return NO_ERROR;
849}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800850
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800851status_t AudioTrack::reload()
852{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700853 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800854 return INVALID_OPERATION;
855 }
856
Eric Laurent1703cdf2011-03-07 14:52:59 -0800857 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800858 // See setPosition() regarding setting parameters such as loop points or position while active
859 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700860 return INVALID_OPERATION;
861 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800862 mNewPosition = mUpdatePeriod;
863 mLoopPeriod = 0;
864 // FIXME The new code cannot reload while keeping a loop specified.
865 // Need to check how the old code handled this, and whether it's a significant change.
866 mStaticProxy->setLoop(0, mFrameCount, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800867 return NO_ERROR;
868}
869
Glenn Kasten38e905b2014-01-13 10:21:48 -0800870audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700871{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800872 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100873 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800874}
875
Eric Laurentbe916aa2010-06-01 23:49:17 -0700876status_t AudioTrack::attachAuxEffect(int effectId)
877{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800878 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700879 status_t status = mAudioTrack->attachAuxEffect(effectId);
880 if (status == NO_ERROR) {
881 mAuxEffectId = effectId;
882 }
883 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700884}
885
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800886// -------------------------------------------------------------------------
887
Eric Laurent1703cdf2011-03-07 14:52:59 -0800888// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -0700889status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800890{
891 status_t status;
892 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
893 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700894 ALOGE("Could not get audioflinger");
895 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800896 }
897
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700898 audio_io_handle_t output = AudioSystem::getOutputForAttr(&mAttributes, mSampleRate, mFormat,
Glenn Kasten38e905b2014-01-13 10:21:48 -0800899 mChannelMask, mFlags, mOffloadInfo);
Glenn Kasten142f5192014-03-25 17:44:59 -0700900 if (output == AUDIO_IO_HANDLE_NONE) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700901 ALOGE("Could not get audio output for stream type %d, usage %d, sample rate %u, format %#x,"
902 " channel mask %#x, flags %#x",
903 mStreamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800904 return BAD_VALUE;
905 }
906 {
907 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
908 // we must release it ourselves if anything goes wrong.
909
Glenn Kastence8828a2013-09-16 18:07:38 -0700910 // Not all of these values are needed under all conditions, but it is easier to get them all
911
Eric Laurentd1b449a2010-05-14 03:26:45 -0700912 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -0700913 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700914 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800915 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800916 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700917 }
918
Glenn Kastence8828a2013-09-16 18:07:38 -0700919 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700920 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -0700921 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700922 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800923 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700924 }
925
926 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700927 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -0700928 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700929 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800930 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700931 }
932
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700933 // Client decides whether the track is TIMED (see below), but can only express a preference
934 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800935 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700936 // either of these use cases:
937 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -0800938 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -0800939 // use case 2: callback transfer mode
940 (mTransfer == TRANSFER_CALLBACK)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800941 // matching sample rate
942 (mSampleRate == afSampleRate))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800943 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -0700944 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -0800945 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700946 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700947 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700948
Glenn Kastence8828a2013-09-16 18:07:38 -0700949 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -0800950 // n = 1 fast track with single buffering; nBuffering is ignored
951 // n = 2 fast track with double buffering
Glenn Kastence8828a2013-09-16 18:07:38 -0700952 // n = 2 normal track, no sample rate conversion
953 // n = 3 normal track, with sample rate conversion
954 // (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering)
955 // n > 3 very high latency or very small notification interval; nBuffering is ignored
Glenn Kasten363fb752014-01-15 12:27:31 -0800956 const uint32_t nBuffering = (mSampleRate == afSampleRate) ? 2 : 3;
Glenn Kastence8828a2013-09-16 18:07:38 -0700957
Eric Laurentd1b449a2010-05-14 03:26:45 -0700958 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700959
Glenn Kasten363fb752014-01-15 12:27:31 -0800960 size_t frameCount = mReqFrameCount;
961 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700962
Glenn Kasten363fb752014-01-15 12:27:31 -0800963 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700964 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -0800965 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -0700966 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700967 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700968 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100969 if (mNotificationFramesAct != frameCount) {
970 mNotificationFramesAct = frameCount;
971 }
Glenn Kasten363fb752014-01-15 12:27:31 -0800972 } else if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700973
Glenn Kastena42ff002012-11-14 12:47:55 -0800974 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -0700975 // 8-bit data in shared memory is not currently supported by AudioFlinger
Glenn Kastenb7730382014-04-30 15:50:31 -0700976 size_t alignment = audio_bytes_per_sample(
977 mFormat == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : mFormat);
978 if (alignment & 1) {
979 alignment = 1;
980 }
Glenn Kastena42ff002012-11-14 12:47:55 -0800981 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700982 // More than 2 channels does not require stronger alignment than stereo
983 alignment <<= 1;
984 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000985 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -0800986 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -0800987 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800988 status = BAD_VALUE;
989 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700990 }
991
992 // When initializing a shared buffer AudioTrack via constructors,
993 // there's no frameCount parameter.
994 // But when initializing a shared buffer AudioTrack via set(),
995 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kastenb7730382014-04-30 15:50:31 -0700996 frameCount = mSharedBuffer->size() / mFrameSizeAF;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700997
Glenn Kasten363fb752014-01-15 12:27:31 -0800998 } else if (!(mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700999
1000 // FIXME move these calculations and associated checks to server
Glenn Kastene0fa4672012-04-24 14:35:14 -07001001
Eric Laurentd1b449a2010-05-14 03:26:45 -07001002 // Ensure that buffer depth covers at least audio hardware latency
1003 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001004 ALOGV("afFrameCount=%zu, minBufCount=%d, afSampleRate=%u, afLatency=%d",
Glenn Kastenbb6f0a02013-06-03 15:00:29 -07001005 afFrameCount, minBufCount, afSampleRate, afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001006 if (minBufCount <= nBuffering) {
1007 minBufCount = nBuffering;
Glenn Kasten7c027242012-12-26 14:43:16 -08001008 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001009
Andy Hungcd044842014-08-07 11:04:34 -07001010 size_t minFrameCount = afFrameCount * minBufCount * uint64_t(mSampleRate) / afSampleRate;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001011 ALOGV("minFrameCount: %zu, afFrameCount=%zu, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -08001012 ", afLatency=%d",
Glenn Kasten363fb752014-01-15 12:27:31 -08001013 minFrameCount, afFrameCount, minBufCount, mSampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001014
1015 if (frameCount == 0) {
1016 frameCount = minFrameCount;
Glenn Kastence8828a2013-09-16 18:07:38 -07001017 } else if (frameCount < minFrameCount) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001018 // not ALOGW because it happens all the time when playing key clicks over A2DP
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001019 ALOGV("Minimum buffer size corrected from %zu to %zu",
Glenn Kastene0fa4672012-04-24 14:35:14 -07001020 frameCount, minFrameCount);
1021 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001022 }
Glenn Kastence8828a2013-09-16 18:07:38 -07001023 // Make sure that application is notified with sufficient margin before underrun
1024 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1025 mNotificationFramesAct = frameCount/nBuffering;
1026 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001027
Glenn Kastene0fa4672012-04-24 14:35:14 -07001028 } else {
1029 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -07001030 }
1031
Glenn Kastena075db42012-03-06 11:22:44 -08001032 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1033 if (mIsTimed) {
1034 trackFlags |= IAudioFlinger::TRACK_TIMED;
1035 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001036
1037 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001038 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001039 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001040 if (mAudioTrackThread != 0) {
1041 tid = mAudioTrackThread->getTid();
1042 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001043 }
1044
Glenn Kasten363fb752014-01-15 12:27:31 -08001045 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001046 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1047 }
1048
Eric Laurentab5cdba2014-06-09 17:22:27 -07001049 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1050 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1051 }
1052
Glenn Kasten74935e42013-12-19 08:56:45 -08001053 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1054 // but we will still need the original value also
Glenn Kasten363fb752014-01-15 12:27:31 -08001055 sp<IAudioTrack> track = audioFlinger->createTrack(mStreamType,
1056 mSampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -07001057 // AudioFlinger only sees 16-bit PCM
Glenn Kastenc4b88a82014-04-30 16:54:30 -07001058 mFormat == AUDIO_FORMAT_PCM_8_BIT &&
1059 !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ?
Glenn Kasten363fb752014-01-15 12:27:31 -08001060 AUDIO_FORMAT_PCM_16_BIT : mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001061 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001062 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001063 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001064 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001065 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001066 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001067 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001068 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001069 &status);
1070
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001071 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001072 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001073 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001074 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001075 ALOG_ASSERT(track != 0);
1076
Glenn Kasten38e905b2014-01-13 10:21:48 -08001077 // AudioFlinger now owns the reference to the I/O handle,
1078 // so we are no longer responsible for releasing it.
1079
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001080 sp<IMemory> iMem = track->getCblk();
1081 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001082 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001083 return NO_INIT;
1084 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001085 void *iMemPointer = iMem->pointer();
1086 if (iMemPointer == NULL) {
1087 ALOGE("Could not get control block pointer");
1088 return NO_INIT;
1089 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001090 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001091 if (mAudioTrack != 0) {
1092 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
1093 mDeathNotifier.clear();
1094 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001095 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001096 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001097 IPCThreadState::self()->flushCommands();
1098
Glenn Kasten0cde0762014-01-16 15:06:36 -08001099 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001100 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001101 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001102 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1103 // In current design, AudioTrack client checks and ensures frame count validity before
1104 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1105 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001106 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001107 }
1108 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001109
Glenn Kastena07f17c2013-04-23 12:39:37 -07001110 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001111 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001112 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001113 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001114 mAwaitBoost = true;
Glenn Kasten363fb752014-01-15 12:27:31 -08001115 if (mSharedBuffer == 0) {
Glenn Kastenb5fed682013-12-03 09:06:43 -08001116 // Theoretically double-buffering is not required for fast tracks,
1117 // due to tighter scheduling. But in practice, to accommodate kernels with
1118 // scheduling jitter, and apps with computation jitter, we use double-buffering.
1119 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1120 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001121 }
1122 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001123 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001124 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001125 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001126 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1127 if (mSharedBuffer == 0) {
Glenn Kastence8828a2013-09-16 18:07:38 -07001128 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1129 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001130 }
1131 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001132 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001133 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001134 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001135 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1136 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1137 } else {
1138 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001139 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001140 // FIXME This is a warning, not an error, so don't return error status
1141 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001142 }
1143 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001144 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1145 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1146 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1147 } else {
1148 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1149 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1150 // FIXME This is a warning, not an error, so don't return error status
1151 //return NO_INIT;
1152 }
1153 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001154
Glenn Kasten38e905b2014-01-13 10:21:48 -08001155 // We retain a copy of the I/O handle, but don't own the reference
1156 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001157 mRefreshRemaining = true;
1158
1159 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1160 // is the value of pointer() for the shared buffer, otherwise buffers points
1161 // immediately after the control block. This address is for the mapping within client
1162 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1163 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001164 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001165 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001166 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001167 buffers = mSharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001168 }
1169
Eric Laurent2beeb502010-07-16 07:43:46 -07001170 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001171 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001172 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001173
Glenn Kastenb6037442012-11-14 13:42:25 -08001174 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001175 // If IAudioTrack is re-created, don't let the requested frameCount
1176 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001177 if (frameCount > mReqFrameCount) {
1178 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001179 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001180
1181 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001182 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001183 mStaticProxy.clear();
1184 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1185 } else {
1186 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1187 mProxy = mStaticProxy;
1188 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001189 mProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001190 mProxy->setSendLevel(mSendLevel);
1191 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001192 mProxy->setMinimum(mNotificationFramesAct);
1193
1194 mDeathNotifier = new DeathNotifier(this);
1195 mAudioTrack->asBinder()->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001196
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001197 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001198 }
1199
1200release:
1201 AudioSystem::releaseOutput(output);
1202 if (status == NO_ERROR) {
1203 status = NO_INIT;
1204 }
1205 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001206}
1207
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001208status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1209{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001210 if (audioBuffer == NULL) {
1211 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001212 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001213 if (mTransfer != TRANSFER_OBTAIN) {
1214 audioBuffer->frameCount = 0;
1215 audioBuffer->size = 0;
1216 audioBuffer->raw = NULL;
1217 return INVALID_OPERATION;
1218 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001219
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001220 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001221 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001222 if (waitCount == -1) {
1223 requested = &ClientProxy::kForever;
1224 } else if (waitCount == 0) {
1225 requested = &ClientProxy::kNonBlocking;
1226 } else if (waitCount > 0) {
1227 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001228 timeout.tv_sec = ms / 1000;
1229 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1230 requested = &timeout;
1231 } else {
1232 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1233 requested = NULL;
1234 }
1235 return obtainBuffer(audioBuffer, requested);
1236}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001237
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001238status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1239 struct timespec *elapsed, size_t *nonContig)
1240{
1241 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1242 uint32_t oldSequence = 0;
1243 uint32_t newSequence;
1244
1245 Proxy::Buffer buffer;
1246 status_t status = NO_ERROR;
1247
1248 static const int32_t kMaxTries = 5;
1249 int32_t tryCounter = kMaxTries;
1250
1251 do {
1252 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1253 // keep them from going away if another thread re-creates the track during obtainBuffer()
1254 sp<AudioTrackClientProxy> proxy;
1255 sp<IMemory> iMem;
1256
1257 { // start of lock scope
1258 AutoMutex lock(mLock);
1259
1260 newSequence = mSequence;
1261 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1262 if (status == DEAD_OBJECT) {
1263 // re-create track, unless someone else has already done so
1264 if (newSequence == oldSequence) {
1265 status = restoreTrack_l("obtainBuffer");
1266 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001267 buffer.mFrameCount = 0;
1268 buffer.mRaw = NULL;
1269 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001270 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001271 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001272 }
1273 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001274 oldSequence = newSequence;
1275
1276 // Keep the extra references
1277 proxy = mProxy;
1278 iMem = mCblkMemory;
1279
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001280 if (mState == STATE_STOPPING) {
1281 status = -EINTR;
1282 buffer.mFrameCount = 0;
1283 buffer.mRaw = NULL;
1284 buffer.mNonContig = 0;
1285 break;
1286 }
1287
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001288 // Non-blocking if track is stopped or paused
1289 if (mState != STATE_ACTIVE) {
1290 requested = &ClientProxy::kNonBlocking;
1291 }
1292
1293 } // end of lock scope
1294
1295 buffer.mFrameCount = audioBuffer->frameCount;
1296 // FIXME starts the requested timeout and elapsed over from scratch
1297 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1298
1299 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1300
1301 audioBuffer->frameCount = buffer.mFrameCount;
1302 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1303 audioBuffer->raw = buffer.mRaw;
1304 if (nonContig != NULL) {
1305 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001306 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001307 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001308}
1309
1310void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1311{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001312 if (mTransfer == TRANSFER_SHARED) {
1313 return;
1314 }
1315
1316 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1317 if (stepCount == 0) {
1318 return;
1319 }
1320
1321 Proxy::Buffer buffer;
1322 buffer.mFrameCount = stepCount;
1323 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001324
Eric Laurent1703cdf2011-03-07 14:52:59 -08001325 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001326 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001327 mInUnderrun = false;
1328 mProxy->releaseBuffer(&buffer);
1329
1330 // restart track if it was disabled by audioflinger due to previous underrun
1331 if (mState == STATE_ACTIVE) {
1332 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001333 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001334 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001335 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001336 mAudioTrack->start();
1337 }
1338 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001339}
1340
1341// -------------------------------------------------------------------------
1342
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001343ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001344{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001345 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001346 return INVALID_OPERATION;
1347 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001348
Eric Laurentab5cdba2014-06-09 17:22:27 -07001349 if (isDirect()) {
1350 AutoMutex lock(mLock);
1351 int32_t flags = android_atomic_and(
1352 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1353 &mCblk->mFlags);
1354 if (flags & CBLK_INVALID) {
1355 return DEAD_OBJECT;
1356 }
1357 }
1358
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001359 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001360 // Sanity-check: user is most-likely passing an error code, and it would
1361 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001362 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001363 return BAD_VALUE;
1364 }
1365
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001366 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001367 Buffer audioBuffer;
1368
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001369 while (userSize >= mFrameSize) {
1370 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001371
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001372 status_t err = obtainBuffer(&audioBuffer,
1373 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001374 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001375 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001376 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001377 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001378 return ssize_t(err);
1379 }
1380
1381 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001382 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001383 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001384 toWrite = audioBuffer.size >> 1;
1385 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001386 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001387 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001388 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001389 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001390 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001391 userSize -= toWrite;
1392 written += toWrite;
1393
1394 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001395 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001396
1397 return written;
1398}
1399
1400// -------------------------------------------------------------------------
1401
John Grossman4ff14ba2012-02-08 16:37:41 -08001402TimedAudioTrack::TimedAudioTrack() {
1403 mIsTimed = true;
1404}
1405
1406status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1407{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001408 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001409 status_t result = UNKNOWN_ERROR;
1410
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001411#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001412 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1413 // while we are accessing the cblk
1414 sp<IAudioTrack> audioTrack = mAudioTrack;
1415 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001416#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001417
John Grossman4ff14ba2012-02-08 16:37:41 -08001418 // If the track is not invalid already, try to allocate a buffer. alloc
1419 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001420 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001421 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001422 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001423 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1424 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001425 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001426 }
1427 }
1428
1429 // If the track is invalid at this point, attempt to restore it. and try the
1430 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001431 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001432 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001433
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001434 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001435 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001436 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001437 }
1438
1439 return result;
1440}
1441
1442status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1443 int64_t pts)
1444{
Eric Laurentdf839842012-05-31 14:27:14 -07001445 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1446 {
1447 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001448 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001449 // restart track if it was disabled by audioflinger due to previous underrun
1450 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001451 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1452 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001453 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001454 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001455 mAudioTrack->start();
1456 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001457 }
Eric Laurentdf839842012-05-31 14:27:14 -07001458 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001459}
1460
1461status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1462 TargetTimeline target)
1463{
1464 return mAudioTrack->setMediaTimeTransform(xform, target);
1465}
1466
1467// -------------------------------------------------------------------------
1468
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001469nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001470{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001471 // Currently the AudioTrack thread is not created if there are no callbacks.
1472 // Would it ever make sense to run the thread, even without callbacks?
1473 // If so, then replace this by checks at each use for mCbf != NULL.
1474 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1475
Eric Laurent1703cdf2011-03-07 14:52:59 -08001476 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001477 if (mAwaitBoost) {
1478 mAwaitBoost = false;
1479 mLock.unlock();
1480 static const int32_t kMaxTries = 5;
1481 int32_t tryCounter = kMaxTries;
1482 uint32_t pollUs = 10000;
1483 do {
1484 int policy = sched_getscheduler(0);
1485 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1486 break;
1487 }
1488 usleep(pollUs);
1489 pollUs <<= 1;
1490 } while (tryCounter-- > 0);
1491 if (tryCounter < 0) {
1492 ALOGE("did not receive expected priority boost on time");
1493 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001494 // Run again immediately
1495 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001496 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001497
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001498 // Can only reference mCblk while locked
1499 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001500 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001501
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001502 // Check for track invalidation
1503 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001504 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1505 // AudioSystem cache. We should not exit here but after calling the callback so
1506 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001507 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001508 status_t status = restoreTrack_l("processAudioBuffer");
1509 mLock.unlock();
1510 // Run again immediately, but with a new IAudioTrack
1511 return 0;
1512 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001513 }
1514
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001515 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001516 bool active = mState == STATE_ACTIVE;
1517
1518 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1519 bool newUnderrun = false;
1520 if (flags & CBLK_UNDERRUN) {
1521#if 0
1522 // Currently in shared buffer mode, when the server reaches the end of buffer,
1523 // the track stays active in continuous underrun state. It's up to the application
1524 // to pause or stop the track, or set the position to a new offset within buffer.
1525 // This was some experimental code to auto-pause on underrun. Keeping it here
1526 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1527 if (mTransfer == TRANSFER_SHARED) {
1528 mState = STATE_PAUSED;
1529 active = false;
1530 }
1531#endif
1532 if (!mInUnderrun) {
1533 mInUnderrun = true;
1534 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001535 }
1536 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001537
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001538 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001539 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001540
1541 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001542 bool markerReached = false;
1543 size_t markerPosition = mMarkerPosition;
1544 // FIXME fails for wraparound, need 64 bits
1545 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1546 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001547 }
1548
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001549 // Determine number of new position callback(s) that will be needed, while locked
1550 size_t newPosCount = 0;
1551 size_t newPosition = mNewPosition;
1552 size_t updatePeriod = mUpdatePeriod;
1553 // FIXME fails for wraparound, need 64 bits
1554 if (updatePeriod > 0 && position >= newPosition) {
1555 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1556 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001557 }
1558
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001559 // Cache other fields that will be needed soon
1560 uint32_t loopPeriod = mLoopPeriod;
1561 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001562 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001563 if (mRefreshRemaining) {
1564 mRefreshRemaining = false;
1565 mRemainingFrames = notificationFrames;
1566 mRetryOnPartialBuffer = false;
1567 }
1568 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001569 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001570 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001571
1572 // These fields don't need to be cached, because they are assigned only by set():
1573 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1574 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1575
1576 mLock.unlock();
1577
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001578 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001579 struct timespec timeout;
1580 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1581 timeout.tv_nsec = 0;
1582
Glenn Kasten96f04882013-09-20 09:28:56 -07001583 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001584 switch (status) {
1585 case NO_ERROR:
1586 case DEAD_OBJECT:
1587 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001588 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001589 {
1590 AutoMutex lock(mLock);
1591 // The previously assigned value of waitStreamEnd is no longer valid,
1592 // since the mutex has been unlocked and either the callback handler
1593 // or another thread could have re-started the AudioTrack during that time.
1594 waitStreamEnd = mState == STATE_STOPPING;
1595 if (waitStreamEnd) {
1596 mState = STATE_STOPPED;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001597 }
1598 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001599 if (waitStreamEnd && status != DEAD_OBJECT) {
1600 return NS_INACTIVE;
1601 }
1602 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001603 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001604 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001605 }
1606
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001607 // perform callbacks while unlocked
1608 if (newUnderrun) {
1609 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1610 }
1611 // FIXME we will miss loops if loop cycle was signaled several times since last call
1612 // to processAudioBuffer()
1613 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1614 mCbf(EVENT_LOOP_END, mUserData, NULL);
1615 }
1616 if (flags & CBLK_BUFFER_END) {
1617 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1618 }
1619 if (markerReached) {
1620 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1621 }
1622 while (newPosCount > 0) {
1623 size_t temp = newPosition;
1624 mCbf(EVENT_NEW_POS, mUserData, &temp);
1625 newPosition += updatePeriod;
1626 newPosCount--;
1627 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001628
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001629 if (mObservedSequence != sequence) {
1630 mObservedSequence = sequence;
1631 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001632 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001633 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001634 return NS_INACTIVE;
1635 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001636 }
1637
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001638 // if inactive, then don't run me again until re-started
1639 if (!active) {
1640 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001641 }
1642
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001643 // Compute the estimated time until the next timed event (position, markers, loops)
1644 // FIXME only for non-compressed audio
1645 uint32_t minFrames = ~0;
1646 if (!markerReached && position < markerPosition) {
1647 minFrames = markerPosition - position;
1648 }
1649 if (loopPeriod > 0 && loopPeriod < minFrames) {
1650 minFrames = loopPeriod;
1651 }
1652 if (updatePeriod > 0 && updatePeriod < minFrames) {
1653 minFrames = updatePeriod;
1654 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001655
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001656 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1657 static const uint32_t kPoll = 0;
1658 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1659 minFrames = kPoll * notificationFrames;
1660 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001661
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001662 // Convert frame units to time units
1663 nsecs_t ns = NS_WHENEVER;
1664 if (minFrames != (uint32_t) ~0) {
1665 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1666 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1667 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1668 }
1669
1670 // If not supplying data by EVENT_MORE_DATA, then we're done
1671 if (mTransfer != TRANSFER_CALLBACK) {
1672 return ns;
1673 }
1674
1675 struct timespec timeout;
1676 const struct timespec *requested = &ClientProxy::kForever;
1677 if (ns != NS_WHENEVER) {
1678 timeout.tv_sec = ns / 1000000000LL;
1679 timeout.tv_nsec = ns % 1000000000LL;
1680 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1681 requested = &timeout;
1682 }
1683
1684 while (mRemainingFrames > 0) {
1685
1686 Buffer audioBuffer;
1687 audioBuffer.frameCount = mRemainingFrames;
1688 size_t nonContig;
1689 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1690 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001691 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001692 requested = &ClientProxy::kNonBlocking;
1693 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001694 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001695 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001696 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001697 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1698 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001699 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001700 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001701 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1702 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001703 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001704
Eric Laurent42a6f422013-08-29 14:35:05 -07001705 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001706 mRetryOnPartialBuffer = false;
1707 if (avail < mRemainingFrames) {
1708 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1709 if (ns < 0 || myns < ns) {
1710 ns = myns;
1711 }
1712 return ns;
1713 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001714 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001715
1716 // Divide buffer size by 2 to take into account the expansion
1717 // due to 8 to 16 bit conversion: the callback must fill only half
1718 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001719 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001720 audioBuffer.size >>= 1;
1721 }
1722
1723 size_t reqSize = audioBuffer.size;
1724 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001725 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001726
1727 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001728 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001729 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1730 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001731 return NS_NEVER;
1732 }
1733
1734 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001735 // The callback is done filling buffers
1736 // Keep this thread going to handle timed events and
1737 // still try to get more data in intervals of WAIT_PERIOD_MS
1738 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001739 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001740 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001741
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001742 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001743 // 8 to 16 bit conversion, note that source and destination are the same address
1744 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001745 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001746 }
1747
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001748 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1749 audioBuffer.frameCount = releasedFrames;
1750 mRemainingFrames -= releasedFrames;
1751 if (misalignment >= releasedFrames) {
1752 misalignment -= releasedFrames;
1753 } else {
1754 misalignment = 0;
1755 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001756
1757 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001758
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001759 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1760 // if callback doesn't like to accept the full chunk
1761 if (writtenSize < reqSize) {
1762 continue;
1763 }
1764
1765 // There could be enough non-contiguous frames available to satisfy the remaining request
1766 if (mRemainingFrames <= nonContig) {
1767 continue;
1768 }
1769
1770#if 0
1771 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1772 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1773 // that total to a sum == notificationFrames.
1774 if (0 < misalignment && misalignment <= mRemainingFrames) {
1775 mRemainingFrames = misalignment;
1776 return (mRemainingFrames * 1100000000LL) / sampleRate;
1777 }
1778#endif
1779
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001780 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001781 mRemainingFrames = notificationFrames;
1782 mRetryOnPartialBuffer = true;
1783
1784 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1785 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001786}
1787
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001788status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001789{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001790 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001791 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001792 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001793 status_t result;
1794
Glenn Kastena47f3162012-11-07 10:13:08 -08001795 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kasten38e905b2014-01-13 10:21:48 -08001796 // output parameters in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001797 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001798
Eric Laurentab5cdba2014-06-09 17:22:27 -07001799 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001800 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001801 return DEAD_OBJECT;
1802 }
1803
Glenn Kasten200092b2014-08-15 15:13:30 -07001804 // save the old static buffer position
1805 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
1806
1807 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001808 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001809 // It will also delete the strong references on previous IAudioTrack and IMemory.
1810 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
1811 result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001812
1813 // take the frames that will be lost by track recreation into account in saved position
Glenn Kasten200092b2014-08-15 15:13:30 -07001814 (void) updateAndGetPosition_l();
1815 mPosition = mReleased;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001816
Glenn Kastena47f3162012-11-07 10:13:08 -08001817 if (result == NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001818 // continue playback from last known position, but
1819 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1820 if (mStaticProxy != NULL) {
1821 mLoopPeriod = 0;
1822 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1823 }
1824 // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1825 // track destruction have been played? This is critical for SoundPool implementation
1826 // This must be broken, and needs to be tested/debugged.
1827#if 0
Glenn Kastena47f3162012-11-07 10:13:08 -08001828 // restore write index and set other indexes to reflect empty buffer status
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001829 if (!strcmp(from, "start")) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001830 // Make sure that a client relying on callback events indicating underrun or
1831 // the actual amount of audio frames played (e.g SoundPool) receives them.
1832 if (mSharedBuffer == 0) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001833 // restart playback even if buffer is not completely filled.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001834 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001835 }
1836 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001837#endif
1838 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001839 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001840 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001841 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001842 if (result != NO_ERROR) {
1843 ALOGW("restoreTrack_l() failed status %d", result);
1844 mState = STATE_STOPPED;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001845 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001846
1847 return result;
1848}
1849
Glenn Kasten200092b2014-08-15 15:13:30 -07001850uint32_t AudioTrack::updateAndGetPosition_l()
1851{
1852 // This is the sole place to read server consumed frames
1853 uint32_t newServer = mProxy->getPosition();
1854 int32_t delta = newServer - mServer;
1855 mServer = newServer;
1856 // TODO There is controversy about whether there can be "negative jitter" in server position.
1857 // This should be investigated further, and if possible, it should be addressed.
1858 // A more definite failure mode is infrequent polling by client.
1859 // One could call (void)getPosition_l() in releaseBuffer(),
1860 // so mReleased and mPosition are always lock-step as best possible.
1861 // That should ensure delta never goes negative for infrequent polling
1862 // unless the server has more than 2^31 frames in its buffer,
1863 // in which case the use of uint32_t for these counters has bigger issues.
1864 if (delta < 0) {
1865 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
1866 delta = 0;
1867 }
1868 return mPosition += (uint32_t) delta;
1869}
1870
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001871status_t AudioTrack::setParameters(const String8& keyValuePairs)
1872{
1873 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001874 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001875}
1876
Glenn Kastence703742013-07-19 16:33:58 -07001877status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1878{
Glenn Kasten53cec222013-08-29 09:01:02 -07001879 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001880 // FIXME not implemented for fast tracks; should use proxy and SSQ
1881 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1882 return INVALID_OPERATION;
1883 }
1884 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
1885 return INVALID_OPERATION;
1886 }
Glenn Kasten200092b2014-08-15 15:13:30 -07001887 // The presented frame count must always lag behind the consumed frame count.
1888 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07001889 status_t status = mAudioTrack->getTimestamp(timestamp);
1890 if (status == NO_ERROR) {
Glenn Kasten200092b2014-08-15 15:13:30 -07001891 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
1892 (void) updateAndGetPosition_l();
1893 // Server consumed (mServer) and presented both use the same server time base,
1894 // and server consumed is always >= presented.
1895 // The delta between these represents the number of frames in the buffer pipeline.
1896 // If this delta between these is greater than the client position, it means that
1897 // actually presented is still stuck at the starting line (figuratively speaking),
1898 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
1899 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
1900 return INVALID_OPERATION;
1901 }
1902 // Convert timestamp position from server time base to client time base.
1903 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
1904 // But if we change it to 64-bit then this could fail.
1905 // If (mPosition - mServer) can be negative then should use:
1906 // (int32_t)(mPosition - mServer)
1907 timestamp.mPosition += mPosition - mServer;
1908 // Immediately after a call to getPosition_l(), mPosition and
1909 // mServer both represent the same frame position. mPosition is
1910 // in client's point of view, and mServer is in server's point of
1911 // view. So the difference between them is the "fudge factor"
1912 // between client and server views due to stop() and/or new
1913 // IAudioTrack. And timestamp.mPosition is initially in server's
1914 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07001915 }
1916 return status;
Glenn Kastence703742013-07-19 16:33:58 -07001917}
1918
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001919String8 AudioTrack::getParameters(const String8& keys)
1920{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08001921 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07001922 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08001923 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001924 } else {
1925 return String8::empty();
1926 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001927}
1928
Glenn Kasten23a75452014-01-13 10:37:17 -08001929bool AudioTrack::isOffloaded() const
1930{
1931 AutoMutex lock(mLock);
1932 return isOffloaded_l();
1933}
1934
Eric Laurentab5cdba2014-06-09 17:22:27 -07001935bool AudioTrack::isDirect() const
1936{
1937 AutoMutex lock(mLock);
1938 return isDirect_l();
1939}
1940
1941bool AudioTrack::isOffloadedOrDirect() const
1942{
1943 AutoMutex lock(mLock);
1944 return isOffloadedOrDirect_l();
1945}
1946
1947
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001948status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001949{
1950
1951 const size_t SIZE = 256;
1952 char buffer[SIZE];
1953 String8 result;
1954
1955 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001956 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07001957 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001958 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001959 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001960 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001961 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001962 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001963 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001964 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001965 result.append(buffer);
1966 ::write(fd, result.string(), result.size());
1967 return NO_ERROR;
1968}
1969
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001970uint32_t AudioTrack::getUnderrunFrames() const
1971{
1972 AutoMutex lock(mLock);
1973 return mProxy->getUnderrunFrames();
1974}
1975
Jean-Michel Trivifaabb512014-06-11 16:55:06 -07001976void AudioTrack::setAttributesFromStreamType(audio_stream_type_t streamType) {
1977 mAttributes.flags = 0x0;
1978
1979 switch(streamType) {
1980 case AUDIO_STREAM_DEFAULT:
1981 case AUDIO_STREAM_MUSIC:
1982 mAttributes.content_type = AUDIO_CONTENT_TYPE_MUSIC;
1983 mAttributes.usage = AUDIO_USAGE_MEDIA;
1984 break;
1985 case AUDIO_STREAM_VOICE_CALL:
1986 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1987 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION;
1988 break;
1989 case AUDIO_STREAM_ENFORCED_AUDIBLE:
1990 mAttributes.flags |= AUDIO_FLAG_AUDIBILITY_ENFORCED;
1991 // intended fall through, attributes in common with STREAM_SYSTEM
1992 case AUDIO_STREAM_SYSTEM:
1993 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1994 mAttributes.usage = AUDIO_USAGE_ASSISTANCE_SONIFICATION;
1995 break;
1996 case AUDIO_STREAM_RING:
1997 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1998 mAttributes.usage = AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE;
1999 break;
2000 case AUDIO_STREAM_ALARM:
2001 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
2002 mAttributes.usage = AUDIO_USAGE_ALARM;
2003 break;
2004 case AUDIO_STREAM_NOTIFICATION:
2005 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
2006 mAttributes.usage = AUDIO_USAGE_NOTIFICATION;
2007 break;
2008 case AUDIO_STREAM_BLUETOOTH_SCO:
2009 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
2010 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION;
2011 mAttributes.flags |= AUDIO_FLAG_SCO;
2012 break;
2013 case AUDIO_STREAM_DTMF:
2014 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
2015 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING;
2016 break;
2017 case AUDIO_STREAM_TTS:
2018 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
2019 mAttributes.usage = AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY;
2020 break;
2021 default:
2022 ALOGE("invalid stream type %d when converting to attributes", streamType);
2023 }
2024}
2025
2026void AudioTrack::setStreamTypeFromAttributes(audio_attributes_t& aa) {
2027 // flags to stream type mapping
2028 if ((aa.flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
2029 mStreamType = AUDIO_STREAM_ENFORCED_AUDIBLE;
2030 return;
2031 }
2032 if ((aa.flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
2033 mStreamType = AUDIO_STREAM_BLUETOOTH_SCO;
2034 return;
2035 }
2036
2037 // usage to stream type mapping
2038 switch (aa.usage) {
2039 case AUDIO_USAGE_MEDIA:
2040 case AUDIO_USAGE_GAME:
2041 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
2042 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
2043 mStreamType = AUDIO_STREAM_MUSIC;
2044 return;
2045 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
2046 mStreamType = AUDIO_STREAM_SYSTEM;
2047 return;
2048 case AUDIO_USAGE_VOICE_COMMUNICATION:
2049 mStreamType = AUDIO_STREAM_VOICE_CALL;
2050 return;
2051
2052 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
2053 mStreamType = AUDIO_STREAM_DTMF;
2054 return;
2055
2056 case AUDIO_USAGE_ALARM:
2057 mStreamType = AUDIO_STREAM_ALARM;
2058 return;
2059 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
2060 mStreamType = AUDIO_STREAM_RING;
2061 return;
2062
2063 case AUDIO_USAGE_NOTIFICATION:
2064 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
2065 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
2066 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
2067 case AUDIO_USAGE_NOTIFICATION_EVENT:
2068 mStreamType = AUDIO_STREAM_NOTIFICATION;
2069 return;
2070
2071 case AUDIO_USAGE_UNKNOWN:
2072 default:
2073 mStreamType = AUDIO_STREAM_MUSIC;
2074 }
2075}
2076
2077bool AudioTrack::isValidAttributes(const audio_attributes_t *paa) {
2078 // has flags that map to a strategy?
2079 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO)) != 0) {
2080 return true;
2081 }
2082
2083 // has known usage?
2084 switch (paa->usage) {
2085 case AUDIO_USAGE_UNKNOWN:
2086 case AUDIO_USAGE_MEDIA:
2087 case AUDIO_USAGE_VOICE_COMMUNICATION:
2088 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
2089 case AUDIO_USAGE_ALARM:
2090 case AUDIO_USAGE_NOTIFICATION:
2091 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
2092 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
2093 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
2094 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
2095 case AUDIO_USAGE_NOTIFICATION_EVENT:
2096 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
2097 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
2098 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
2099 case AUDIO_USAGE_GAME:
2100 break;
2101 default:
2102 return false;
2103 }
2104 return true;
2105}
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002106// =========================================================================
2107
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002108void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002109{
2110 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2111 if (audioTrack != 0) {
2112 AutoMutex lock(audioTrack->mLock);
2113 audioTrack->mProxy->binderDied();
2114 }
2115}
2116
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002117// =========================================================================
2118
2119AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002120 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2121 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002122{
2123}
2124
2125AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002126{
2127}
2128
2129bool AudioTrack::AudioTrackThread::threadLoop()
2130{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002131 {
2132 AutoMutex _l(mMyLock);
2133 if (mPaused) {
2134 mMyCond.wait(mMyLock);
2135 // caller will check for exitPending()
2136 return true;
2137 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002138 if (mIgnoreNextPausedInt) {
2139 mIgnoreNextPausedInt = false;
2140 mPausedInt = false;
2141 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002142 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002143 if (mPausedNs > 0) {
2144 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2145 } else {
2146 mMyCond.wait(mMyLock);
2147 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002148 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002149 return true;
2150 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002151 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002152 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002153 switch (ns) {
2154 case 0:
2155 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002156 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002157 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002158 return true;
2159 case NS_NEVER:
2160 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002161 case NS_WHENEVER:
2162 // FIXME increase poll interval, or make event-driven
2163 ns = 1000000000LL;
2164 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002165 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002166 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002167 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002168 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002169 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002170}
2171
Glenn Kasten3acbd052012-02-28 10:39:56 -08002172void AudioTrack::AudioTrackThread::requestExit()
2173{
2174 // must be in this order to avoid a race condition
2175 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002176 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002177}
2178
2179void AudioTrack::AudioTrackThread::pause()
2180{
2181 AutoMutex _l(mMyLock);
2182 mPaused = true;
2183}
2184
2185void AudioTrack::AudioTrackThread::resume()
2186{
2187 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002188 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002189 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002190 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002191 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002192 mMyCond.signal();
2193 }
2194}
2195
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002196void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2197{
2198 AutoMutex _l(mMyLock);
2199 mPausedInt = true;
2200 mPausedNs = ns;
2201}
2202
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002203}; // namespace android