blob: 77419f0387b2697d63c3c14ca5b321425a1b1deb [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
18
19//#define LOG_NDEBUG 0
20#define LOG_TAG "AudioTrack"
21
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>
Glenn Kasten9f80dd22012-12-18 15:57:32 -080024#include <audio_utils/primitives.h>
25#include <binder/IPCThreadState.h>
26#include <media/AudioTrack.h>
27#include <utils/Log.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080028#include <private/media/AudioTrackShared.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070029#include <media/IAudioFlinger.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080030
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010031#define WAIT_PERIOD_MS 10
32#define WAIT_STREAM_END_TIMEOUT_SEC 120
33
Glenn Kasten511754b2012-01-11 09:52:19 -080034
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080035namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080036// ---------------------------------------------------------------------------
37
38// static
39status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080040 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080041 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080042 uint32_t sampleRate)
43{
Glenn Kastend65d73c2012-06-22 17:21:07 -070044 if (frameCount == NULL) {
45 return BAD_VALUE;
46 }
Glenn Kasten04cd0182012-06-25 11:49:27 -070047
Glenn Kastene0fa4672012-04-24 14:35:14 -070048 // FIXME merge with similar code in createTrack_l(), except we're missing
49 // some information here that is available in createTrack_l():
50 // audio_io_handle_t output
51 // audio_format_t format
52 // audio_channel_mask_t channelMask
53 // audio_output_flags_t flags
Glenn Kasten3b16c762012-11-14 08:44:39 -080054 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080055 status_t status;
56 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
57 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080058 ALOGE("Unable to query output sample rate for stream type %d; status %d",
59 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080060 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080061 }
Glenn Kastene33054e2012-11-14 12:54:39 -080062 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -080063 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
64 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080065 ALOGE("Unable to query output frame count for stream type %d; status %d",
66 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080067 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080068 }
69 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -080070 status = AudioSystem::getOutputLatency(&afLatency, streamType);
71 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080072 ALOGE("Unable to query output latency for stream type %d; status %d",
73 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080074 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080075 }
76
77 // Ensure that buffer depth covers at least audio hardware latency
78 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080079 if (minBufCount < 2) {
80 minBufCount = 2;
81 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +080082
83 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
Glenn Kastene53b9ea2012-03-12 16:29:55 -070084 afFrameCount * minBufCount * sampleRate / afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080085 // The formula above should always produce a non-zero value, but return an error
86 // in the unlikely event that it does not, as that's part of the API contract.
87 if (*frameCount == 0) {
88 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %d",
89 streamType, sampleRate);
90 return BAD_VALUE;
91 }
Glenn Kasten3acbd052012-02-28 10:39:56 -080092 ALOGV("getMinFrameCount=%d: afFrameCount=%d, minBufCount=%d, afSampleRate=%d, afLatency=%d",
93 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +080094 return NO_ERROR;
95}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080096
97// ---------------------------------------------------------------------------
98
99AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700100 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800101 mIsTimed(false),
102 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800103 mPreviousSchedulingGroup(SP_DEFAULT),
104 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800105{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700106 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
107 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
108 mAttributes.flags = 0x0;
109 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800110}
111
112AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800113 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800114 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800115 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700116 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800117 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700118 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800119 callback_t cbf,
120 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800121 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800122 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000123 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800124 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800125 int uid,
126 pid_t pid)
Glenn Kasten87913512011-06-22 16:15:25 -0700127 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800128 mIsTimed(false),
129 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800130 mPreviousSchedulingGroup(SP_DEFAULT),
131 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800132{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700133 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700134 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800135 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700136 offloadInfo, uid, pid, NULL /*no audio attributes*/);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800137}
138
Andreas Huberc8139852012-01-18 10:51:55 -0800139AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800140 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800141 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800142 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700143 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800144 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700145 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800146 callback_t cbf,
147 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800148 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800149 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000150 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800151 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800152 int uid,
153 pid_t pid)
Glenn Kasten87913512011-06-22 16:15:25 -0700154 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800155 mIsTimed(false),
156 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800157 mPreviousSchedulingGroup(SP_DEFAULT),
158 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800159{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700160 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800161 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800162 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700163 uid, pid, NULL /*no audio attributes*/);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800164}
165
166AudioTrack::~AudioTrack()
167{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800168 if (mStatus == NO_ERROR) {
169 // Make sure that callback function exits in the case where
170 // it is looping on buffer full condition in obtainBuffer().
171 // Otherwise the callback thread will never exit.
172 stop();
173 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100174 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800175 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800176 mAudioTrackThread->requestExitAndWait();
177 mAudioTrackThread.clear();
178 }
Glenn Kasten53cec222013-08-29 09:01:02 -0700179 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
180 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700181 mCblkMemory.clear();
182 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800183 IPCThreadState::self()->flushCommands();
Marco Nelissend457c972014-02-11 08:47:07 -0800184 ALOGV("~AudioTrack, releasing session id from %d on behalf of %d",
185 IPCThreadState::self()->getCallingPid(), mClientPid);
186 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800187 }
188}
189
190status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800191 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800192 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800193 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700194 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800195 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700196 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800197 callback_t cbf,
198 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800199 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800200 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700201 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800202 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000203 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800204 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800205 int uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700206 pid_t pid,
207 audio_attributes_t* pAttributes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800208{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800209 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten838b3d82014-02-27 15:30:41 -0800210 "flags #%x, notificationFrames %u, sessionId %d, transferType %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800211 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten86f04662014-02-24 15:13:05 -0800212 sessionId, transferType);
213
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800214 switch (transferType) {
215 case TRANSFER_DEFAULT:
216 if (sharedBuffer != 0) {
217 transferType = TRANSFER_SHARED;
218 } else if (cbf == NULL || threadCanCallJava) {
219 transferType = TRANSFER_SYNC;
220 } else {
221 transferType = TRANSFER_CALLBACK;
222 }
223 break;
224 case TRANSFER_CALLBACK:
225 if (cbf == NULL || sharedBuffer != 0) {
226 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
227 return BAD_VALUE;
228 }
229 break;
230 case TRANSFER_OBTAIN:
231 case TRANSFER_SYNC:
232 if (sharedBuffer != 0) {
233 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
234 return BAD_VALUE;
235 }
236 break;
237 case TRANSFER_SHARED:
238 if (sharedBuffer == 0) {
239 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
240 return BAD_VALUE;
241 }
242 break;
243 default:
244 ALOGE("Invalid transfer type %d", transferType);
245 return BAD_VALUE;
246 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800247 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800248 mTransfer = transferType;
249
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700250 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
251 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800252
Glenn Kastene33054e2012-11-14 12:54:39 -0800253 ALOGV("set() streamType %d frameCount %u flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700254
Eric Laurent1703cdf2011-03-07 14:52:59 -0800255 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800256
Glenn Kasten53cec222013-08-29 09:01:02 -0700257 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700258 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000259 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800260 return INVALID_OPERATION;
261 }
262
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800263 // handle default values first.
Dima Zavinfce7a472011-04-19 22:30:36 -0700264 if (streamType == AUDIO_STREAM_DEFAULT) {
265 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800266 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700267
268 if (pAttributes == NULL) {
269 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
270 ALOGE("Invalid stream type %d", streamType);
271 return BAD_VALUE;
272 }
273 setAttributesFromStreamType(streamType);
274 mStreamType = streamType;
275 } else {
276 if (!isValidAttributes(pAttributes)) {
277 ALOGE("Invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
278 pAttributes->usage, pAttributes->content_type, pAttributes->flags,
279 pAttributes->tags);
280 }
281 // stream type shouldn't be looked at, this track has audio attributes
282 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
283 setStreamTypeFromAttributes(mAttributes);
284 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
285 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800286 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700287
Glenn Kastenb1bef512014-01-13 10:25:53 -0800288 status_t status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800289 if (sampleRate == 0) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700290 status = AudioSystem::getOutputSamplingRateForAttr(&sampleRate, &mAttributes);
Glenn Kastenb1bef512014-01-13 10:25:53 -0800291 if (status != NO_ERROR) {
292 ALOGE("Could not get output sample rate for stream type %d; status %d",
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700293 mStreamType, status);
Glenn Kastenb1bef512014-01-13 10:25:53 -0800294 return status;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700295 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800296 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800297 mSampleRate = sampleRate;
Glenn Kastenea7939a2012-03-14 12:56:26 -0700298
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800299 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800300 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700301 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800302 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800303
304 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700305 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800306 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800307 return BAD_VALUE;
308 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800309 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700310
Glenn Kasten8ba90322013-10-30 11:29:27 -0700311 if (!audio_is_output_channel(channelMask)) {
312 ALOGE("Invalid channel mask %#x", channelMask);
313 return BAD_VALUE;
314 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800315 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700316 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800317 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700318
Glenn Kastene0fa4672012-04-24 14:35:14 -0700319 // AudioFlinger does not currently support 8-bit data in shared memory
320 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
321 ALOGE("8-bit data in shared memory is not supported");
322 return BAD_VALUE;
323 }
324
Eric Laurentc2f1f072009-07-17 12:17:14 -0700325 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100326 // or offload was requested
327 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
328 || !audio_is_linear_pcm(format)) {
329 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
330 ? "Offload request, forcing to Direct Output"
331 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700332 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800333 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700334 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700335 }
Eric Laurent1948eb32012-04-13 16:50:19 -0700336 // only allow deep buffering for music stream type
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700337 if (mStreamType != AUDIO_STREAM_MUSIC) {
Eric Laurent1948eb32012-04-13 16:50:19 -0700338 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
339 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700340
Glenn Kastenb7730382014-04-30 15:50:31 -0700341 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
342 if (audio_is_linear_pcm(format)) {
343 mFrameSize = channelCount * audio_bytes_per_sample(format);
344 } else {
345 mFrameSize = sizeof(uint8_t);
346 }
347 mFrameSizeAF = mFrameSize;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800348 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700349 ALOG_ASSERT(audio_is_linear_pcm(format));
350 mFrameSize = channelCount * audio_bytes_per_sample(format);
351 mFrameSizeAF = channelCount * audio_bytes_per_sample(
352 format == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : format);
353 // createTrack will return an error if PCM format is not supported by server,
354 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800355 }
356
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800357 // Make copy of input parameter offloadInfo so that in the future:
358 // (a) createTrack_l doesn't need it as an input parameter
359 // (b) we can support re-creation of offloaded tracks
360 if (offloadInfo != NULL) {
361 mOffloadInfoCopy = *offloadInfo;
362 mOffloadInfo = &mOffloadInfoCopy;
363 } else {
364 mOffloadInfo = NULL;
365 }
366
Glenn Kasten66e46352014-01-16 17:44:23 -0800367 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
368 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800369 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800370 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800371 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700372 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800373 mNotificationFramesAct = 0;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700374 mSessionId = sessionId;
Marco Nelissend457c972014-02-11 08:47:07 -0800375 int callingpid = IPCThreadState::self()->getCallingPid();
376 int mypid = getpid();
377 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800378 mClientUid = IPCThreadState::self()->getCallingUid();
379 } else {
380 mClientUid = uid;
381 }
Marco Nelissend457c972014-02-11 08:47:07 -0800382 if (pid == -1 || (callingpid != mypid)) {
383 mClientPid = callingpid;
384 } else {
385 mClientPid = pid;
386 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700387 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700388 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700389 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700390
Glenn Kastena997e7a2012-08-07 09:44:19 -0700391 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700392 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700393 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
394 }
395
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800396 // create the IAudioTrack
Glenn Kasten363fb752014-01-15 12:27:31 -0800397 status = createTrack_l(0 /*epoch*/);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800398
Glenn Kastena997e7a2012-08-07 09:44:19 -0700399 if (status != NO_ERROR) {
400 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100401 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
402 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700403 mAudioTrackThread.clear();
404 }
405 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700406 }
407
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800408 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800409 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800410 mUserData = user;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800411 mLoopPeriod = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800412 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700413 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800414 mNewPosition = 0;
415 mUpdatePeriod = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800416 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800417 mSequence = 1;
418 mObservedSequence = mSequence;
419 mInUnderrun = false;
420
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800421 return NO_ERROR;
422}
423
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800424// -------------------------------------------------------------------------
425
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100426status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800427{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800428 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100429
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800430 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100431 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800432 }
433
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800434 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800435
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800436 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100437 if (previousState == STATE_PAUSED_STOPPING) {
438 mState = STATE_STOPPING;
439 } else {
440 mState = STATE_ACTIVE;
441 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800442 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
443 // reset current position as seen by client to 0
444 mProxy->setEpoch(mProxy->getEpoch() - mProxy->getPosition());
Eric Laurentec9a0322013-08-28 10:23:01 -0700445 // force refresh of remaining frames by processAudioBuffer() as last
446 // write before stop could be partial.
447 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800448 }
449 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700450 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800451
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800452 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800453 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100454 if (previousState == STATE_STOPPING) {
455 mProxy->interrupt();
456 } else {
457 t->resume();
458 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800459 } else {
460 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
461 get_sched_policy(0, &mPreviousSchedulingGroup);
462 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
463 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800464
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800465 status_t status = NO_ERROR;
466 if (!(flags & CBLK_INVALID)) {
467 status = mAudioTrack->start();
468 if (status == DEAD_OBJECT) {
469 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800470 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800471 }
472 if (flags & CBLK_INVALID) {
473 status = restoreTrack_l("start");
474 }
475
476 if (status != NO_ERROR) {
477 ALOGE("start() status %d", status);
478 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800479 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100480 if (previousState != STATE_STOPPING) {
481 t->pause();
482 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800483 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700484 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700485 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800486 }
487 }
488
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100489 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800490}
491
492void AudioTrack::stop()
493{
494 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700495 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800496 return;
497 }
498
Glenn Kasten23a75452014-01-13 10:37:17 -0800499 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100500 mState = STATE_STOPPING;
501 } else {
502 mState = STATE_STOPPED;
503 }
504
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800505 mProxy->interrupt();
506 mAudioTrack->stop();
507 // the playback head position will reset to 0, so if a marker is set, we need
508 // to activate it again
509 mMarkerReached = false;
510#if 0
511 // Force flush if a shared buffer is used otherwise audioflinger
512 // will not stop before end of buffer is reached.
513 // It may be needed to make sure that we stop playback, likely in case looping is on.
514 if (mSharedBuffer != 0) {
515 flush_l();
516 }
517#endif
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100518
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800519 sp<AudioTrackThread> t = mAudioTrackThread;
520 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800521 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100522 t->pause();
523 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800524 } else {
525 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
526 set_sched_policy(0, mPreviousSchedulingGroup);
527 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800528}
529
530bool AudioTrack::stopped() const
531{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800532 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800533 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800534}
535
536void AudioTrack::flush()
537{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800538 if (mSharedBuffer != 0) {
539 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800540 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800541 AutoMutex lock(mLock);
542 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
543 return;
544 }
545 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800546}
547
Eric Laurent1703cdf2011-03-07 14:52:59 -0800548void AudioTrack::flush_l()
549{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800550 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700551
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700552 // clear playback marker and periodic update counter
553 mMarkerPosition = 0;
554 mMarkerReached = false;
555 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100556 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700557
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800558 mState = STATE_FLUSHED;
Glenn Kasten23a75452014-01-13 10:37:17 -0800559 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100560 mProxy->interrupt();
561 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800562 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800563 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800564}
565
566void AudioTrack::pause()
567{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800568 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100569 if (mState == STATE_ACTIVE) {
570 mState = STATE_PAUSED;
571 } else if (mState == STATE_STOPPING) {
572 mState = STATE_PAUSED_STOPPING;
573 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800574 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800575 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800576 mProxy->interrupt();
577 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800578
Marco Nelissen3a90f282014-03-10 11:21:43 -0700579 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700580 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800581 uint32_t halFrames;
582 // OffloadThread sends HAL pause in its threadLoop.. time saved
583 // here can be slightly off
584 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
585 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
586 }
587 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800588}
589
Eric Laurentbe916aa2010-06-01 23:49:17 -0700590status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800591{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700592 // This duplicates a test by AudioTrack JNI, but that is not the only caller
593 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
594 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700595 return BAD_VALUE;
596 }
597
Eric Laurent1703cdf2011-03-07 14:52:59 -0800598 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800599 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
600 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800601
Glenn Kastenc56f3422014-03-21 17:53:17 -0700602 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700603
Glenn Kasten23a75452014-01-13 10:37:17 -0800604 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700605 mAudioTrack->signal();
606 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700607 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800608}
609
Glenn Kastenb1c09932012-02-27 16:21:04 -0800610status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800611{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800612 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700613}
614
Eric Laurent2beeb502010-07-16 07:43:46 -0700615status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700616{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700617 // This duplicates a test by AudioTrack JNI, but that is not the only caller
618 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700619 return BAD_VALUE;
620 }
621
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800622 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700623 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800624 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700625
626 return NO_ERROR;
627}
628
Glenn Kastena5224f32012-01-04 12:41:44 -0800629void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700630{
631 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800632 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700633 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800634}
635
Glenn Kasten3b16c762012-11-14 08:44:39 -0800636status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800637{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100638 if (mIsTimed || isOffloaded()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800639 return INVALID_OPERATION;
640 }
641
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800642 uint32_t afSamplingRate;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700643 if (AudioSystem::getOutputSamplingRateForAttr(&afSamplingRate, &mAttributes) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700644 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800645 }
646 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Glenn Kastend65d73c2012-06-22 17:21:07 -0700647 if (rate == 0 || rate > afSamplingRate*2 ) {
648 return BAD_VALUE;
649 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800650
Eric Laurent1703cdf2011-03-07 14:52:59 -0800651 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800652 mSampleRate = rate;
653 mProxy->setSampleRate(rate);
654
Eric Laurent57326622009-07-07 07:10:45 -0700655 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800656}
657
Glenn Kastena5224f32012-01-04 12:41:44 -0800658uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800659{
John Grossman4ff14ba2012-02-08 16:37:41 -0800660 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800661 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800662 }
663
Eric Laurent1703cdf2011-03-07 14:52:59 -0800664 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700665
666 // sample rate can be updated during playback by the offloaded decoder so we need to
667 // query the HAL and update if needed.
668// FIXME use Proxy return channel to update the rate from server and avoid polling here
Glenn Kasten23a75452014-01-13 10:37:17 -0800669 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700670 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700671 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700672 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700673 if (status == NO_ERROR) {
674 mSampleRate = sampleRate;
675 }
676 }
677 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800678 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800679}
680
681status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
682{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100683 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800684 return INVALID_OPERATION;
685 }
686
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800687 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800688 ;
689 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
690 loopEnd - loopStart >= MIN_LOOP) {
691 ;
692 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800693 return BAD_VALUE;
694 }
695
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800696 AutoMutex lock(mLock);
697 // See setPosition() regarding setting parameters such as loop points or position while active
698 if (mState == STATE_ACTIVE) {
699 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700700 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800701 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800702 return NO_ERROR;
703}
704
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800705void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
706{
707 // FIXME If setting a loop also sets position to start of loop, then
708 // this is correct. Otherwise it should be removed.
709 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
710 mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0;
711 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
712}
713
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800714status_t AudioTrack::setMarkerPosition(uint32_t marker)
715{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700716 // The only purpose of setting marker position is to get a callback
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100717 if (mCbf == NULL || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700718 return INVALID_OPERATION;
719 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800720
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800721 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800722 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700723 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800724
725 return NO_ERROR;
726}
727
Glenn Kastena5224f32012-01-04 12:41:44 -0800728status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800729{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100730 if (isOffloaded()) {
731 return INVALID_OPERATION;
732 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700733 if (marker == NULL) {
734 return BAD_VALUE;
735 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800736
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800737 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800738 *marker = mMarkerPosition;
739
740 return NO_ERROR;
741}
742
743status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
744{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700745 // The only purpose of setting position update period is to get a callback
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100746 if (mCbf == NULL || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700747 return INVALID_OPERATION;
748 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800749
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800750 AutoMutex lock(mLock);
751 mNewPosition = mProxy->getPosition() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800752 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800753
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800754 return NO_ERROR;
755}
756
Glenn Kastena5224f32012-01-04 12:41:44 -0800757status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800758{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100759 if (isOffloaded()) {
760 return INVALID_OPERATION;
761 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700762 if (updatePeriod == NULL) {
763 return BAD_VALUE;
764 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800765
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800766 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800767 *updatePeriod = mUpdatePeriod;
768
769 return NO_ERROR;
770}
771
772status_t AudioTrack::setPosition(uint32_t position)
773{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100774 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700775 return INVALID_OPERATION;
776 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800777 if (position > mFrameCount) {
778 return BAD_VALUE;
779 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800780
Eric Laurent1703cdf2011-03-07 14:52:59 -0800781 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800782 // Currently we require that the player is inactive before setting parameters such as position
783 // or loop points. Otherwise, there could be a race condition: the application could read the
784 // current position, compute a new position or loop parameters, and then set that position or
785 // loop parameters but it would do the "wrong" thing since the position has continued to advance
786 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
787 // to specify how it wants to handle such scenarios.
788 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700789 return INVALID_OPERATION;
790 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800791 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
792 mLoopPeriod = 0;
793 // FIXME Check whether loops and setting position are incompatible in old code.
794 // If we use setLoop for both purposes we lose the capability to set the position while looping.
795 mStaticProxy->setLoop(position, mFrameCount, 0);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700796
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800797 return NO_ERROR;
798}
799
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800800status_t AudioTrack::getPosition(uint32_t *position) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800801{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700802 if (position == NULL) {
803 return BAD_VALUE;
804 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800805
Eric Laurent1703cdf2011-03-07 14:52:59 -0800806 AutoMutex lock(mLock);
Glenn Kasten23a75452014-01-13 10:37:17 -0800807 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100808 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800809
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800810 if ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING)) {
811 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
812 *position = mPausedPosition;
813 return NO_ERROR;
814 }
815
Glenn Kasten142f5192014-03-25 17:44:59 -0700816 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100817 uint32_t halFrames;
818 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
819 }
820 *position = dspFrames;
821 } else {
822 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
823 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ? 0 :
824 mProxy->getPosition();
825 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800826 return NO_ERROR;
827}
828
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000829status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800830{
831 if (mSharedBuffer == 0 || mIsTimed) {
832 return INVALID_OPERATION;
833 }
834 if (position == NULL) {
835 return BAD_VALUE;
836 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800837
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800838 AutoMutex lock(mLock);
839 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800840 return NO_ERROR;
841}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800842
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800843status_t AudioTrack::reload()
844{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100845 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800846 return INVALID_OPERATION;
847 }
848
Eric Laurent1703cdf2011-03-07 14:52:59 -0800849 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800850 // See setPosition() regarding setting parameters such as loop points or position while active
851 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700852 return INVALID_OPERATION;
853 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800854 mNewPosition = mUpdatePeriod;
855 mLoopPeriod = 0;
856 // FIXME The new code cannot reload while keeping a loop specified.
857 // Need to check how the old code handled this, and whether it's a significant change.
858 mStaticProxy->setLoop(0, mFrameCount, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800859 return NO_ERROR;
860}
861
Glenn Kasten38e905b2014-01-13 10:21:48 -0800862audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700863{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800864 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100865 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800866}
867
Eric Laurentbe916aa2010-06-01 23:49:17 -0700868status_t AudioTrack::attachAuxEffect(int effectId)
869{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800870 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700871 status_t status = mAudioTrack->attachAuxEffect(effectId);
872 if (status == NO_ERROR) {
873 mAuxEffectId = effectId;
874 }
875 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700876}
877
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800878// -------------------------------------------------------------------------
879
Eric Laurent1703cdf2011-03-07 14:52:59 -0800880// must be called with mLock held
Glenn Kasten363fb752014-01-15 12:27:31 -0800881status_t AudioTrack::createTrack_l(size_t epoch)
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800882{
883 status_t status;
884 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
885 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700886 ALOGE("Could not get audioflinger");
887 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800888 }
889
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700890 audio_io_handle_t output = AudioSystem::getOutputForAttr(&mAttributes, mSampleRate, mFormat,
Glenn Kasten38e905b2014-01-13 10:21:48 -0800891 mChannelMask, mFlags, mOffloadInfo);
Glenn Kasten142f5192014-03-25 17:44:59 -0700892 if (output == AUDIO_IO_HANDLE_NONE) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700893 ALOGE("Could not get audio output for stream type %d, usage %d, sample rate %u, format %#x,"
894 " channel mask %#x, flags %#x",
895 mStreamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800896 return BAD_VALUE;
897 }
898 {
899 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
900 // we must release it ourselves if anything goes wrong.
901
Glenn Kastence8828a2013-09-16 18:07:38 -0700902 // Not all of these values are needed under all conditions, but it is easier to get them all
903
Eric Laurentd1b449a2010-05-14 03:26:45 -0700904 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -0700905 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700906 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800907 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800908 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700909 }
910
Glenn Kastence8828a2013-09-16 18:07:38 -0700911 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700912 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -0700913 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700914 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800915 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700916 }
917
918 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700919 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -0700920 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700921 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800922 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700923 }
924
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700925 // Client decides whether the track is TIMED (see below), but can only express a preference
926 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800927 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700928 // either of these use cases:
929 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -0800930 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -0800931 // use case 2: callback transfer mode
932 (mTransfer == TRANSFER_CALLBACK)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800933 // matching sample rate
934 (mSampleRate == afSampleRate))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800935 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -0700936 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -0800937 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700938 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700939 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700940
Glenn Kastence8828a2013-09-16 18:07:38 -0700941 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -0800942 // n = 1 fast track with single buffering; nBuffering is ignored
943 // n = 2 fast track with double buffering
Glenn Kastence8828a2013-09-16 18:07:38 -0700944 // n = 2 normal track, no sample rate conversion
945 // n = 3 normal track, with sample rate conversion
946 // (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering)
947 // n > 3 very high latency or very small notification interval; nBuffering is ignored
Glenn Kasten363fb752014-01-15 12:27:31 -0800948 const uint32_t nBuffering = (mSampleRate == afSampleRate) ? 2 : 3;
Glenn Kastence8828a2013-09-16 18:07:38 -0700949
Eric Laurentd1b449a2010-05-14 03:26:45 -0700950 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700951
Glenn Kasten363fb752014-01-15 12:27:31 -0800952 size_t frameCount = mReqFrameCount;
953 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700954
Glenn Kasten363fb752014-01-15 12:27:31 -0800955 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700956 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -0800957 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -0700958 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700959 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700960 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100961 if (mNotificationFramesAct != frameCount) {
962 mNotificationFramesAct = frameCount;
963 }
Glenn Kasten363fb752014-01-15 12:27:31 -0800964 } else if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700965
Glenn Kastena42ff002012-11-14 12:47:55 -0800966 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -0700967 // 8-bit data in shared memory is not currently supported by AudioFlinger
Glenn Kastenb7730382014-04-30 15:50:31 -0700968 size_t alignment = audio_bytes_per_sample(
969 mFormat == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : mFormat);
970 if (alignment & 1) {
971 alignment = 1;
972 }
Glenn Kastena42ff002012-11-14 12:47:55 -0800973 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700974 // More than 2 channels does not require stronger alignment than stereo
975 alignment <<= 1;
976 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000977 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -0800978 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -0800979 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800980 status = BAD_VALUE;
981 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700982 }
983
984 // When initializing a shared buffer AudioTrack via constructors,
985 // there's no frameCount parameter.
986 // But when initializing a shared buffer AudioTrack via set(),
987 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kastenb7730382014-04-30 15:50:31 -0700988 frameCount = mSharedBuffer->size() / mFrameSizeAF;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700989
Glenn Kasten363fb752014-01-15 12:27:31 -0800990 } else if (!(mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700991
992 // FIXME move these calculations and associated checks to server
Glenn Kastene0fa4672012-04-24 14:35:14 -0700993
Eric Laurentd1b449a2010-05-14 03:26:45 -0700994 // Ensure that buffer depth covers at least audio hardware latency
995 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Glenn Kastenbb6f0a02013-06-03 15:00:29 -0700996 ALOGV("afFrameCount=%d, minBufCount=%d, afSampleRate=%u, afLatency=%d",
997 afFrameCount, minBufCount, afSampleRate, afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700998 if (minBufCount <= nBuffering) {
999 minBufCount = nBuffering;
Glenn Kasten7c027242012-12-26 14:43:16 -08001000 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001001
Glenn Kasten363fb752014-01-15 12:27:31 -08001002 size_t minFrameCount = (afFrameCount*mSampleRate*minBufCount)/afSampleRate;
Glenn Kastene33054e2012-11-14 12:54:39 -08001003 ALOGV("minFrameCount: %u, afFrameCount=%d, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -08001004 ", afLatency=%d",
Glenn Kasten363fb752014-01-15 12:27:31 -08001005 minFrameCount, afFrameCount, minBufCount, mSampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001006
1007 if (frameCount == 0) {
1008 frameCount = minFrameCount;
Glenn Kastence8828a2013-09-16 18:07:38 -07001009 } else if (frameCount < minFrameCount) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001010 // not ALOGW because it happens all the time when playing key clicks over A2DP
1011 ALOGV("Minimum buffer size corrected from %d to %d",
1012 frameCount, minFrameCount);
1013 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001014 }
Glenn Kastence8828a2013-09-16 18:07:38 -07001015 // Make sure that application is notified with sufficient margin before underrun
1016 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1017 mNotificationFramesAct = frameCount/nBuffering;
1018 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001019
Glenn Kastene0fa4672012-04-24 14:35:14 -07001020 } else {
1021 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -07001022 }
1023
Glenn Kastena075db42012-03-06 11:22:44 -08001024 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1025 if (mIsTimed) {
1026 trackFlags |= IAudioFlinger::TRACK_TIMED;
1027 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001028
1029 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001030 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001031 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001032 if (mAudioTrackThread != 0) {
1033 tid = mAudioTrackThread->getTid();
1034 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001035 }
1036
Glenn Kasten363fb752014-01-15 12:27:31 -08001037 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001038 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1039 }
1040
Glenn Kasten74935e42013-12-19 08:56:45 -08001041 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1042 // but we will still need the original value also
Glenn Kasten363fb752014-01-15 12:27:31 -08001043 sp<IAudioTrack> track = audioFlinger->createTrack(mStreamType,
1044 mSampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -07001045 // AudioFlinger only sees 16-bit PCM
Glenn Kastenc4b88a82014-04-30 16:54:30 -07001046 mFormat == AUDIO_FORMAT_PCM_8_BIT &&
1047 !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ?
Glenn Kasten363fb752014-01-15 12:27:31 -08001048 AUDIO_FORMAT_PCM_16_BIT : mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001049 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001050 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001051 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001052 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001053 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001054 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001055 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001056 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001057 &status);
1058
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001059 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001060 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001061 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001062 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001063 ALOG_ASSERT(track != 0);
1064
Glenn Kasten38e905b2014-01-13 10:21:48 -08001065 // AudioFlinger now owns the reference to the I/O handle,
1066 // so we are no longer responsible for releasing it.
1067
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001068 sp<IMemory> iMem = track->getCblk();
1069 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001070 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001071 return NO_INIT;
1072 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001073 void *iMemPointer = iMem->pointer();
1074 if (iMemPointer == NULL) {
1075 ALOGE("Could not get control block pointer");
1076 return NO_INIT;
1077 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001078 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001079 if (mAudioTrack != 0) {
1080 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
1081 mDeathNotifier.clear();
1082 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001083 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001084 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001085 IPCThreadState::self()->flushCommands();
1086
Glenn Kasten0cde0762014-01-16 15:06:36 -08001087 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001088 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001089 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001090 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1091 // In current design, AudioTrack client checks and ensures frame count validity before
1092 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1093 // for fast track as it uses a special method of assigning frame count.
1094 ALOGW("Requested frameCount %u but received frameCount %u", frameCount, temp);
1095 }
1096 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001097
Glenn Kastena07f17c2013-04-23 12:39:37 -07001098 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001099 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001100 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Glenn Kastenb6037442012-11-14 13:42:25 -08001101 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %u", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001102 mAwaitBoost = true;
Glenn Kasten363fb752014-01-15 12:27:31 -08001103 if (mSharedBuffer == 0) {
Glenn Kastenb5fed682013-12-03 09:06:43 -08001104 // Theoretically double-buffering is not required for fast tracks,
1105 // due to tighter scheduling. But in practice, to accommodate kernels with
1106 // scheduling jitter, and apps with computation jitter, we use double-buffering.
1107 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1108 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001109 }
1110 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001111 } else {
Glenn Kastenb6037442012-11-14 13:42:25 -08001112 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %u", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001113 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001114 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1115 if (mSharedBuffer == 0) {
Glenn Kastence8828a2013-09-16 18:07:38 -07001116 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1117 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001118 }
1119 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001120 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001121 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001122 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001123 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1124 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1125 } else {
1126 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001127 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001128 // FIXME This is a warning, not an error, so don't return error status
1129 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001130 }
1131 }
1132
Glenn Kasten38e905b2014-01-13 10:21:48 -08001133 // We retain a copy of the I/O handle, but don't own the reference
1134 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001135 mRefreshRemaining = true;
1136
1137 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1138 // is the value of pointer() for the shared buffer, otherwise buffers points
1139 // immediately after the control block. This address is for the mapping within client
1140 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1141 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001142 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001143 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001144 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001145 buffers = mSharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001146 }
1147
Eric Laurent2beeb502010-07-16 07:43:46 -07001148 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001149 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001150 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001151
Glenn Kastenb6037442012-11-14 13:42:25 -08001152 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001153 // If IAudioTrack is re-created, don't let the requested frameCount
1154 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001155 if (frameCount > mReqFrameCount) {
1156 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001157 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001158
1159 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001160 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001161 mStaticProxy.clear();
1162 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1163 } else {
1164 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1165 mProxy = mStaticProxy;
1166 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001167 mProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001168 mProxy->setSendLevel(mSendLevel);
1169 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001170 mProxy->setEpoch(epoch);
1171 mProxy->setMinimum(mNotificationFramesAct);
1172
1173 mDeathNotifier = new DeathNotifier(this);
1174 mAudioTrack->asBinder()->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001175
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001176 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001177 }
1178
1179release:
1180 AudioSystem::releaseOutput(output);
1181 if (status == NO_ERROR) {
1182 status = NO_INIT;
1183 }
1184 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001185}
1186
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001187status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1188{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001189 if (audioBuffer == NULL) {
1190 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001191 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001192 if (mTransfer != TRANSFER_OBTAIN) {
1193 audioBuffer->frameCount = 0;
1194 audioBuffer->size = 0;
1195 audioBuffer->raw = NULL;
1196 return INVALID_OPERATION;
1197 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001198
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001199 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001200 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001201 if (waitCount == -1) {
1202 requested = &ClientProxy::kForever;
1203 } else if (waitCount == 0) {
1204 requested = &ClientProxy::kNonBlocking;
1205 } else if (waitCount > 0) {
1206 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001207 timeout.tv_sec = ms / 1000;
1208 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1209 requested = &timeout;
1210 } else {
1211 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1212 requested = NULL;
1213 }
1214 return obtainBuffer(audioBuffer, requested);
1215}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001216
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001217status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1218 struct timespec *elapsed, size_t *nonContig)
1219{
1220 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1221 uint32_t oldSequence = 0;
1222 uint32_t newSequence;
1223
1224 Proxy::Buffer buffer;
1225 status_t status = NO_ERROR;
1226
1227 static const int32_t kMaxTries = 5;
1228 int32_t tryCounter = kMaxTries;
1229
1230 do {
1231 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1232 // keep them from going away if another thread re-creates the track during obtainBuffer()
1233 sp<AudioTrackClientProxy> proxy;
1234 sp<IMemory> iMem;
1235
1236 { // start of lock scope
1237 AutoMutex lock(mLock);
1238
1239 newSequence = mSequence;
1240 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1241 if (status == DEAD_OBJECT) {
1242 // re-create track, unless someone else has already done so
1243 if (newSequence == oldSequence) {
1244 status = restoreTrack_l("obtainBuffer");
1245 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001246 buffer.mFrameCount = 0;
1247 buffer.mRaw = NULL;
1248 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001249 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001250 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001251 }
1252 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001253 oldSequence = newSequence;
1254
1255 // Keep the extra references
1256 proxy = mProxy;
1257 iMem = mCblkMemory;
1258
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001259 if (mState == STATE_STOPPING) {
1260 status = -EINTR;
1261 buffer.mFrameCount = 0;
1262 buffer.mRaw = NULL;
1263 buffer.mNonContig = 0;
1264 break;
1265 }
1266
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001267 // Non-blocking if track is stopped or paused
1268 if (mState != STATE_ACTIVE) {
1269 requested = &ClientProxy::kNonBlocking;
1270 }
1271
1272 } // end of lock scope
1273
1274 buffer.mFrameCount = audioBuffer->frameCount;
1275 // FIXME starts the requested timeout and elapsed over from scratch
1276 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1277
1278 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1279
1280 audioBuffer->frameCount = buffer.mFrameCount;
1281 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1282 audioBuffer->raw = buffer.mRaw;
1283 if (nonContig != NULL) {
1284 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001285 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001286 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001287}
1288
1289void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1290{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001291 if (mTransfer == TRANSFER_SHARED) {
1292 return;
1293 }
1294
1295 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1296 if (stepCount == 0) {
1297 return;
1298 }
1299
1300 Proxy::Buffer buffer;
1301 buffer.mFrameCount = stepCount;
1302 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001303
Eric Laurent1703cdf2011-03-07 14:52:59 -08001304 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001305 mInUnderrun = false;
1306 mProxy->releaseBuffer(&buffer);
1307
1308 // restart track if it was disabled by audioflinger due to previous underrun
1309 if (mState == STATE_ACTIVE) {
1310 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001311 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001312 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001313 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001314 mAudioTrack->start();
1315 }
1316 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001317}
1318
1319// -------------------------------------------------------------------------
1320
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001321ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001322{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001323 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001324 return INVALID_OPERATION;
1325 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001326
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001327 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001328 // Sanity-check: user is most-likely passing an error code, and it would
1329 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001330 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001331 return BAD_VALUE;
1332 }
1333
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001334 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001335 Buffer audioBuffer;
1336
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001337 while (userSize >= mFrameSize) {
1338 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001339
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001340 status_t err = obtainBuffer(&audioBuffer,
1341 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001342 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001343 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001344 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001345 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001346 return ssize_t(err);
1347 }
1348
1349 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001350 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001351 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001352 toWrite = audioBuffer.size >> 1;
1353 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001354 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001355 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001356 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001357 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001358 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001359 userSize -= toWrite;
1360 written += toWrite;
1361
1362 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001363 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001364
1365 return written;
1366}
1367
1368// -------------------------------------------------------------------------
1369
John Grossman4ff14ba2012-02-08 16:37:41 -08001370TimedAudioTrack::TimedAudioTrack() {
1371 mIsTimed = true;
1372}
1373
1374status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1375{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001376 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001377 status_t result = UNKNOWN_ERROR;
1378
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001379#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001380 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1381 // while we are accessing the cblk
1382 sp<IAudioTrack> audioTrack = mAudioTrack;
1383 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001384#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001385
John Grossman4ff14ba2012-02-08 16:37:41 -08001386 // If the track is not invalid already, try to allocate a buffer. alloc
1387 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001388 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001389 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001390 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001391 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1392 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001393 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001394 }
1395 }
1396
1397 // If the track is invalid at this point, attempt to restore it. and try the
1398 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001399 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001400 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001401
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001402 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001403 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001404 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001405 }
1406
1407 return result;
1408}
1409
1410status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1411 int64_t pts)
1412{
Eric Laurentdf839842012-05-31 14:27:14 -07001413 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1414 {
1415 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001416 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001417 // restart track if it was disabled by audioflinger due to previous underrun
1418 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001419 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1420 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001421 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001422 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001423 mAudioTrack->start();
1424 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001425 }
Eric Laurentdf839842012-05-31 14:27:14 -07001426 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001427}
1428
1429status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1430 TargetTimeline target)
1431{
1432 return mAudioTrack->setMediaTimeTransform(xform, target);
1433}
1434
1435// -------------------------------------------------------------------------
1436
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001437nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001438{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001439 // Currently the AudioTrack thread is not created if there are no callbacks.
1440 // Would it ever make sense to run the thread, even without callbacks?
1441 // If so, then replace this by checks at each use for mCbf != NULL.
1442 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1443
Eric Laurent1703cdf2011-03-07 14:52:59 -08001444 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001445 if (mAwaitBoost) {
1446 mAwaitBoost = false;
1447 mLock.unlock();
1448 static const int32_t kMaxTries = 5;
1449 int32_t tryCounter = kMaxTries;
1450 uint32_t pollUs = 10000;
1451 do {
1452 int policy = sched_getscheduler(0);
1453 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1454 break;
1455 }
1456 usleep(pollUs);
1457 pollUs <<= 1;
1458 } while (tryCounter-- > 0);
1459 if (tryCounter < 0) {
1460 ALOGE("did not receive expected priority boost on time");
1461 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001462 // Run again immediately
1463 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001464 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001465
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001466 // Can only reference mCblk while locked
1467 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001468 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001469
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001470 // Check for track invalidation
1471 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001472 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1473 // AudioSystem cache. We should not exit here but after calling the callback so
1474 // that the upper layers can recreate the track
Glenn Kasten23a75452014-01-13 10:37:17 -08001475 if (!isOffloaded_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001476 status_t status = restoreTrack_l("processAudioBuffer");
1477 mLock.unlock();
1478 // Run again immediately, but with a new IAudioTrack
1479 return 0;
1480 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001481 }
1482
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001483 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001484 bool active = mState == STATE_ACTIVE;
1485
1486 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1487 bool newUnderrun = false;
1488 if (flags & CBLK_UNDERRUN) {
1489#if 0
1490 // Currently in shared buffer mode, when the server reaches the end of buffer,
1491 // the track stays active in continuous underrun state. It's up to the application
1492 // to pause or stop the track, or set the position to a new offset within buffer.
1493 // This was some experimental code to auto-pause on underrun. Keeping it here
1494 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1495 if (mTransfer == TRANSFER_SHARED) {
1496 mState = STATE_PAUSED;
1497 active = false;
1498 }
1499#endif
1500 if (!mInUnderrun) {
1501 mInUnderrun = true;
1502 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001503 }
1504 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001505
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001506 // Get current position of server
1507 size_t position = mProxy->getPosition();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001508
1509 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001510 bool markerReached = false;
1511 size_t markerPosition = mMarkerPosition;
1512 // FIXME fails for wraparound, need 64 bits
1513 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1514 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001515 }
1516
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001517 // Determine number of new position callback(s) that will be needed, while locked
1518 size_t newPosCount = 0;
1519 size_t newPosition = mNewPosition;
1520 size_t updatePeriod = mUpdatePeriod;
1521 // FIXME fails for wraparound, need 64 bits
1522 if (updatePeriod > 0 && position >= newPosition) {
1523 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1524 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001525 }
1526
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001527 // Cache other fields that will be needed soon
1528 uint32_t loopPeriod = mLoopPeriod;
1529 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001530 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001531 if (mRefreshRemaining) {
1532 mRefreshRemaining = false;
1533 mRemainingFrames = notificationFrames;
1534 mRetryOnPartialBuffer = false;
1535 }
1536 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001537 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001538 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001539
1540 // These fields don't need to be cached, because they are assigned only by set():
1541 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1542 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1543
1544 mLock.unlock();
1545
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001546 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001547 struct timespec timeout;
1548 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1549 timeout.tv_nsec = 0;
1550
Glenn Kasten96f04882013-09-20 09:28:56 -07001551 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001552 switch (status) {
1553 case NO_ERROR:
1554 case DEAD_OBJECT:
1555 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001556 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001557 {
1558 AutoMutex lock(mLock);
1559 // The previously assigned value of waitStreamEnd is no longer valid,
1560 // since the mutex has been unlocked and either the callback handler
1561 // or another thread could have re-started the AudioTrack during that time.
1562 waitStreamEnd = mState == STATE_STOPPING;
1563 if (waitStreamEnd) {
1564 mState = STATE_STOPPED;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001565 }
1566 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001567 if (waitStreamEnd && status != DEAD_OBJECT) {
1568 return NS_INACTIVE;
1569 }
1570 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001571 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001572 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001573 }
1574
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001575 // perform callbacks while unlocked
1576 if (newUnderrun) {
1577 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1578 }
1579 // FIXME we will miss loops if loop cycle was signaled several times since last call
1580 // to processAudioBuffer()
1581 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1582 mCbf(EVENT_LOOP_END, mUserData, NULL);
1583 }
1584 if (flags & CBLK_BUFFER_END) {
1585 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1586 }
1587 if (markerReached) {
1588 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1589 }
1590 while (newPosCount > 0) {
1591 size_t temp = newPosition;
1592 mCbf(EVENT_NEW_POS, mUserData, &temp);
1593 newPosition += updatePeriod;
1594 newPosCount--;
1595 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001596
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001597 if (mObservedSequence != sequence) {
1598 mObservedSequence = sequence;
1599 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001600 // for offloaded tracks, just wait for the upper layers to recreate the track
1601 if (isOffloaded()) {
1602 return NS_INACTIVE;
1603 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001604 }
1605
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001606 // if inactive, then don't run me again until re-started
1607 if (!active) {
1608 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001609 }
1610
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001611 // Compute the estimated time until the next timed event (position, markers, loops)
1612 // FIXME only for non-compressed audio
1613 uint32_t minFrames = ~0;
1614 if (!markerReached && position < markerPosition) {
1615 minFrames = markerPosition - position;
1616 }
1617 if (loopPeriod > 0 && loopPeriod < minFrames) {
1618 minFrames = loopPeriod;
1619 }
1620 if (updatePeriod > 0 && updatePeriod < minFrames) {
1621 minFrames = updatePeriod;
1622 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001623
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001624 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1625 static const uint32_t kPoll = 0;
1626 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1627 minFrames = kPoll * notificationFrames;
1628 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001629
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001630 // Convert frame units to time units
1631 nsecs_t ns = NS_WHENEVER;
1632 if (minFrames != (uint32_t) ~0) {
1633 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1634 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1635 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1636 }
1637
1638 // If not supplying data by EVENT_MORE_DATA, then we're done
1639 if (mTransfer != TRANSFER_CALLBACK) {
1640 return ns;
1641 }
1642
1643 struct timespec timeout;
1644 const struct timespec *requested = &ClientProxy::kForever;
1645 if (ns != NS_WHENEVER) {
1646 timeout.tv_sec = ns / 1000000000LL;
1647 timeout.tv_nsec = ns % 1000000000LL;
1648 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1649 requested = &timeout;
1650 }
1651
1652 while (mRemainingFrames > 0) {
1653
1654 Buffer audioBuffer;
1655 audioBuffer.frameCount = mRemainingFrames;
1656 size_t nonContig;
1657 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1658 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1659 "obtainBuffer() err=%d frameCount=%u", err, audioBuffer.frameCount);
1660 requested = &ClientProxy::kNonBlocking;
1661 size_t avail = audioBuffer.frameCount + nonContig;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001662 ALOGV("obtainBuffer(%u) returned %u = %u + %u err %d",
1663 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001664 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001665 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1666 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001667 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001668 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001669 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1670 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001671 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001672
Eric Laurent42a6f422013-08-29 14:35:05 -07001673 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001674 mRetryOnPartialBuffer = false;
1675 if (avail < mRemainingFrames) {
1676 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1677 if (ns < 0 || myns < ns) {
1678 ns = myns;
1679 }
1680 return ns;
1681 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001682 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001683
1684 // Divide buffer size by 2 to take into account the expansion
1685 // due to 8 to 16 bit conversion: the callback must fill only half
1686 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001687 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001688 audioBuffer.size >>= 1;
1689 }
1690
1691 size_t reqSize = audioBuffer.size;
1692 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001693 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001694
1695 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001696 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
1697 ALOGE("EVENT_MORE_DATA requested %u bytes but callback returned %d bytes",
1698 reqSize, (int) writtenSize);
1699 return NS_NEVER;
1700 }
1701
1702 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001703 // The callback is done filling buffers
1704 // Keep this thread going to handle timed events and
1705 // still try to get more data in intervals of WAIT_PERIOD_MS
1706 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001707 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001708 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001709
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001710 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001711 // 8 to 16 bit conversion, note that source and destination are the same address
1712 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001713 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001714 }
1715
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001716 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1717 audioBuffer.frameCount = releasedFrames;
1718 mRemainingFrames -= releasedFrames;
1719 if (misalignment >= releasedFrames) {
1720 misalignment -= releasedFrames;
1721 } else {
1722 misalignment = 0;
1723 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001724
1725 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001726
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001727 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1728 // if callback doesn't like to accept the full chunk
1729 if (writtenSize < reqSize) {
1730 continue;
1731 }
1732
1733 // There could be enough non-contiguous frames available to satisfy the remaining request
1734 if (mRemainingFrames <= nonContig) {
1735 continue;
1736 }
1737
1738#if 0
1739 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1740 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1741 // that total to a sum == notificationFrames.
1742 if (0 < misalignment && misalignment <= mRemainingFrames) {
1743 mRemainingFrames = misalignment;
1744 return (mRemainingFrames * 1100000000LL) / sampleRate;
1745 }
1746#endif
1747
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001748 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001749 mRemainingFrames = notificationFrames;
1750 mRetryOnPartialBuffer = true;
1751
1752 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1753 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001754}
1755
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001756status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001757{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001758 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Glenn Kasten23a75452014-01-13 10:37:17 -08001759 isOffloaded_l() ? "Offloaded" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001760 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001761 status_t result;
1762
Glenn Kastena47f3162012-11-07 10:13:08 -08001763 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kasten38e905b2014-01-13 10:21:48 -08001764 // output parameters in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001765 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001766
Glenn Kasten23a75452014-01-13 10:37:17 -08001767 if (isOffloaded_l()) {
1768 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001769 return DEAD_OBJECT;
1770 }
1771
Glenn Kastena47f3162012-11-07 10:13:08 -08001772 // if the new IAudioTrack is created, createTrack_l() will modify the
1773 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1774 // It will also delete the strong references on previous IAudioTrack and IMemory
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001775
1776 // take the frames that will be lost by track recreation into account in saved position
1777 size_t position = mProxy->getPosition() + mProxy->getFramesFilled();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001778 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
Glenn Kasten363fb752014-01-15 12:27:31 -08001779 result = createTrack_l(position /*epoch*/);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001780
Glenn Kastena47f3162012-11-07 10:13:08 -08001781 if (result == NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001782 // continue playback from last known position, but
1783 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1784 if (mStaticProxy != NULL) {
1785 mLoopPeriod = 0;
1786 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1787 }
1788 // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1789 // track destruction have been played? This is critical for SoundPool implementation
1790 // This must be broken, and needs to be tested/debugged.
1791#if 0
Glenn Kastena47f3162012-11-07 10:13:08 -08001792 // restore write index and set other indexes to reflect empty buffer status
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001793 if (!strcmp(from, "start")) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001794 // Make sure that a client relying on callback events indicating underrun or
1795 // the actual amount of audio frames played (e.g SoundPool) receives them.
1796 if (mSharedBuffer == 0) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001797 // restart playback even if buffer is not completely filled.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001798 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001799 }
1800 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001801#endif
1802 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001803 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001804 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001805 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001806 if (result != NO_ERROR) {
1807 ALOGW("restoreTrack_l() failed status %d", result);
1808 mState = STATE_STOPPED;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001809 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001810
1811 return result;
1812}
1813
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001814status_t AudioTrack::setParameters(const String8& keyValuePairs)
1815{
1816 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001817 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001818}
1819
Glenn Kastence703742013-07-19 16:33:58 -07001820status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1821{
Glenn Kasten53cec222013-08-29 09:01:02 -07001822 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001823 // FIXME not implemented for fast tracks; should use proxy and SSQ
1824 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1825 return INVALID_OPERATION;
1826 }
1827 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
1828 return INVALID_OPERATION;
1829 }
1830 status_t status = mAudioTrack->getTimestamp(timestamp);
1831 if (status == NO_ERROR) {
1832 timestamp.mPosition += mProxy->getEpoch();
1833 }
1834 return status;
Glenn Kastence703742013-07-19 16:33:58 -07001835}
1836
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001837String8 AudioTrack::getParameters(const String8& keys)
1838{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08001839 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07001840 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08001841 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001842 } else {
1843 return String8::empty();
1844 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001845}
1846
Glenn Kasten23a75452014-01-13 10:37:17 -08001847bool AudioTrack::isOffloaded() const
1848{
1849 AutoMutex lock(mLock);
1850 return isOffloaded_l();
1851}
1852
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001853status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001854{
1855
1856 const size_t SIZE = 256;
1857 char buffer[SIZE];
1858 String8 result;
1859
1860 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001861 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07001862 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001863 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001864 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001865 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001866 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001867 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001868 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001869 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001870 result.append(buffer);
1871 ::write(fd, result.string(), result.size());
1872 return NO_ERROR;
1873}
1874
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001875uint32_t AudioTrack::getUnderrunFrames() const
1876{
1877 AutoMutex lock(mLock);
1878 return mProxy->getUnderrunFrames();
1879}
1880
Jean-Michel Trivifaabb512014-06-11 16:55:06 -07001881void AudioTrack::setAttributesFromStreamType(audio_stream_type_t streamType) {
1882 mAttributes.flags = 0x0;
1883
1884 switch(streamType) {
1885 case AUDIO_STREAM_DEFAULT:
1886 case AUDIO_STREAM_MUSIC:
1887 mAttributes.content_type = AUDIO_CONTENT_TYPE_MUSIC;
1888 mAttributes.usage = AUDIO_USAGE_MEDIA;
1889 break;
1890 case AUDIO_STREAM_VOICE_CALL:
1891 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1892 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION;
1893 break;
1894 case AUDIO_STREAM_ENFORCED_AUDIBLE:
1895 mAttributes.flags |= AUDIO_FLAG_AUDIBILITY_ENFORCED;
1896 // intended fall through, attributes in common with STREAM_SYSTEM
1897 case AUDIO_STREAM_SYSTEM:
1898 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1899 mAttributes.usage = AUDIO_USAGE_ASSISTANCE_SONIFICATION;
1900 break;
1901 case AUDIO_STREAM_RING:
1902 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1903 mAttributes.usage = AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE;
1904 break;
1905 case AUDIO_STREAM_ALARM:
1906 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1907 mAttributes.usage = AUDIO_USAGE_ALARM;
1908 break;
1909 case AUDIO_STREAM_NOTIFICATION:
1910 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1911 mAttributes.usage = AUDIO_USAGE_NOTIFICATION;
1912 break;
1913 case AUDIO_STREAM_BLUETOOTH_SCO:
1914 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1915 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION;
1916 mAttributes.flags |= AUDIO_FLAG_SCO;
1917 break;
1918 case AUDIO_STREAM_DTMF:
1919 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1920 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING;
1921 break;
1922 case AUDIO_STREAM_TTS:
1923 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1924 mAttributes.usage = AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY;
1925 break;
1926 default:
1927 ALOGE("invalid stream type %d when converting to attributes", streamType);
1928 }
1929}
1930
1931void AudioTrack::setStreamTypeFromAttributes(audio_attributes_t& aa) {
1932 // flags to stream type mapping
1933 if ((aa.flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
1934 mStreamType = AUDIO_STREAM_ENFORCED_AUDIBLE;
1935 return;
1936 }
1937 if ((aa.flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
1938 mStreamType = AUDIO_STREAM_BLUETOOTH_SCO;
1939 return;
1940 }
1941
1942 // usage to stream type mapping
1943 switch (aa.usage) {
1944 case AUDIO_USAGE_MEDIA:
1945 case AUDIO_USAGE_GAME:
1946 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
1947 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
1948 mStreamType = AUDIO_STREAM_MUSIC;
1949 return;
1950 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
1951 mStreamType = AUDIO_STREAM_SYSTEM;
1952 return;
1953 case AUDIO_USAGE_VOICE_COMMUNICATION:
1954 mStreamType = AUDIO_STREAM_VOICE_CALL;
1955 return;
1956
1957 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
1958 mStreamType = AUDIO_STREAM_DTMF;
1959 return;
1960
1961 case AUDIO_USAGE_ALARM:
1962 mStreamType = AUDIO_STREAM_ALARM;
1963 return;
1964 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
1965 mStreamType = AUDIO_STREAM_RING;
1966 return;
1967
1968 case AUDIO_USAGE_NOTIFICATION:
1969 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
1970 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
1971 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
1972 case AUDIO_USAGE_NOTIFICATION_EVENT:
1973 mStreamType = AUDIO_STREAM_NOTIFICATION;
1974 return;
1975
1976 case AUDIO_USAGE_UNKNOWN:
1977 default:
1978 mStreamType = AUDIO_STREAM_MUSIC;
1979 }
1980}
1981
1982bool AudioTrack::isValidAttributes(const audio_attributes_t *paa) {
1983 // has flags that map to a strategy?
1984 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO)) != 0) {
1985 return true;
1986 }
1987
1988 // has known usage?
1989 switch (paa->usage) {
1990 case AUDIO_USAGE_UNKNOWN:
1991 case AUDIO_USAGE_MEDIA:
1992 case AUDIO_USAGE_VOICE_COMMUNICATION:
1993 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
1994 case AUDIO_USAGE_ALARM:
1995 case AUDIO_USAGE_NOTIFICATION:
1996 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
1997 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
1998 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
1999 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
2000 case AUDIO_USAGE_NOTIFICATION_EVENT:
2001 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
2002 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
2003 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
2004 case AUDIO_USAGE_GAME:
2005 break;
2006 default:
2007 return false;
2008 }
2009 return true;
2010}
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002011// =========================================================================
2012
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002013void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002014{
2015 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2016 if (audioTrack != 0) {
2017 AutoMutex lock(audioTrack->mLock);
2018 audioTrack->mProxy->binderDied();
2019 }
2020}
2021
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002022// =========================================================================
2023
2024AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002025 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2026 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002027{
2028}
2029
2030AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002031{
2032}
2033
2034bool AudioTrack::AudioTrackThread::threadLoop()
2035{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002036 {
2037 AutoMutex _l(mMyLock);
2038 if (mPaused) {
2039 mMyCond.wait(mMyLock);
2040 // caller will check for exitPending()
2041 return true;
2042 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002043 if (mIgnoreNextPausedInt) {
2044 mIgnoreNextPausedInt = false;
2045 mPausedInt = false;
2046 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002047 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002048 if (mPausedNs > 0) {
2049 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2050 } else {
2051 mMyCond.wait(mMyLock);
2052 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002053 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002054 return true;
2055 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002056 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002057 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002058 switch (ns) {
2059 case 0:
2060 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002061 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002062 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002063 return true;
2064 case NS_NEVER:
2065 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002066 case NS_WHENEVER:
2067 // FIXME increase poll interval, or make event-driven
2068 ns = 1000000000LL;
2069 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002070 default:
2071 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002072 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002073 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002074 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002075}
2076
Glenn Kasten3acbd052012-02-28 10:39:56 -08002077void AudioTrack::AudioTrackThread::requestExit()
2078{
2079 // must be in this order to avoid a race condition
2080 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002081 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002082}
2083
2084void AudioTrack::AudioTrackThread::pause()
2085{
2086 AutoMutex _l(mMyLock);
2087 mPaused = true;
2088}
2089
2090void AudioTrack::AudioTrackThread::resume()
2091{
2092 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002093 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002094 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002095 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002096 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002097 mMyCond.signal();
2098 }
2099}
2100
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002101void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2102{
2103 AutoMutex _l(mMyLock);
2104 mPausedInt = true;
2105 mPausedNs = ns;
2106}
2107
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002108}; // namespace android