blob: 5c82cfbb7dd37efaef72eae54a849a9a48ba9b32 [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{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700638 if (mIsTimed || isOffloadedOrDirect()) {
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
Eric Laurentab5cdba2014-06-09 17:22:27 -0700669 if (isOffloadedOrDirect_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{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700683 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
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
Eric Laurentab5cdba2014-06-09 17:22:27 -0700717 if (mCbf == NULL || isOffloadedOrDirect()) {
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{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700730 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100731 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
Eric Laurentab5cdba2014-06-09 17:22:27 -0700746 if (mCbf == NULL || isOffloadedOrDirect()) {
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{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700759 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100760 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{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700774 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
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);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700807 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100808 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800809
Eric Laurentab5cdba2014-06-09 17:22:27 -0700810 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800811 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{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700845 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
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
Eric Laurentab5cdba2014-06-09 17:22:27 -07001041 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1042 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1043 }
1044
Glenn Kasten74935e42013-12-19 08:56:45 -08001045 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1046 // but we will still need the original value also
Glenn Kasten363fb752014-01-15 12:27:31 -08001047 sp<IAudioTrack> track = audioFlinger->createTrack(mStreamType,
1048 mSampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -07001049 // AudioFlinger only sees 16-bit PCM
Glenn Kastenc4b88a82014-04-30 16:54:30 -07001050 mFormat == AUDIO_FORMAT_PCM_8_BIT &&
1051 !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ?
Glenn Kasten363fb752014-01-15 12:27:31 -08001052 AUDIO_FORMAT_PCM_16_BIT : mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001053 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001054 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001055 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001056 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001057 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001058 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001059 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001060 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001061 &status);
1062
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001063 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001064 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001065 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001066 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001067 ALOG_ASSERT(track != 0);
1068
Glenn Kasten38e905b2014-01-13 10:21:48 -08001069 // AudioFlinger now owns the reference to the I/O handle,
1070 // so we are no longer responsible for releasing it.
1071
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001072 sp<IMemory> iMem = track->getCblk();
1073 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001074 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001075 return NO_INIT;
1076 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001077 void *iMemPointer = iMem->pointer();
1078 if (iMemPointer == NULL) {
1079 ALOGE("Could not get control block pointer");
1080 return NO_INIT;
1081 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001082 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001083 if (mAudioTrack != 0) {
1084 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
1085 mDeathNotifier.clear();
1086 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001087 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001088 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001089 IPCThreadState::self()->flushCommands();
1090
Glenn Kasten0cde0762014-01-16 15:06:36 -08001091 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001092 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001093 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001094 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1095 // In current design, AudioTrack client checks and ensures frame count validity before
1096 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1097 // for fast track as it uses a special method of assigning frame count.
1098 ALOGW("Requested frameCount %u but received frameCount %u", frameCount, temp);
1099 }
1100 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001101
Glenn Kastena07f17c2013-04-23 12:39:37 -07001102 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001103 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001104 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Glenn Kastenb6037442012-11-14 13:42:25 -08001105 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %u", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001106 mAwaitBoost = true;
Glenn Kasten363fb752014-01-15 12:27:31 -08001107 if (mSharedBuffer == 0) {
Glenn Kastenb5fed682013-12-03 09:06:43 -08001108 // Theoretically double-buffering is not required for fast tracks,
1109 // due to tighter scheduling. But in practice, to accommodate kernels with
1110 // scheduling jitter, and apps with computation jitter, we use double-buffering.
1111 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1112 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001113 }
1114 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001115 } else {
Glenn Kastenb6037442012-11-14 13:42:25 -08001116 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %u", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001117 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001118 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1119 if (mSharedBuffer == 0) {
Glenn Kastence8828a2013-09-16 18:07:38 -07001120 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1121 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001122 }
1123 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001124 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001125 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001126 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001127 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1128 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1129 } else {
1130 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001131 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001132 // FIXME This is a warning, not an error, so don't return error status
1133 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001134 }
1135 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001136 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1137 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1138 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1139 } else {
1140 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1141 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1142 // FIXME This is a warning, not an error, so don't return error status
1143 //return NO_INIT;
1144 }
1145 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001146
Glenn Kasten38e905b2014-01-13 10:21:48 -08001147 // We retain a copy of the I/O handle, but don't own the reference
1148 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001149 mRefreshRemaining = true;
1150
1151 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1152 // is the value of pointer() for the shared buffer, otherwise buffers points
1153 // immediately after the control block. This address is for the mapping within client
1154 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1155 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001156 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001157 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001158 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001159 buffers = mSharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001160 }
1161
Eric Laurent2beeb502010-07-16 07:43:46 -07001162 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001163 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001164 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001165
Glenn Kastenb6037442012-11-14 13:42:25 -08001166 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001167 // If IAudioTrack is re-created, don't let the requested frameCount
1168 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001169 if (frameCount > mReqFrameCount) {
1170 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001171 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001172
1173 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001174 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001175 mStaticProxy.clear();
1176 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1177 } else {
1178 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1179 mProxy = mStaticProxy;
1180 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001181 mProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001182 mProxy->setSendLevel(mSendLevel);
1183 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001184 mProxy->setEpoch(epoch);
1185 mProxy->setMinimum(mNotificationFramesAct);
1186
1187 mDeathNotifier = new DeathNotifier(this);
1188 mAudioTrack->asBinder()->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001189
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001190 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001191 }
1192
1193release:
1194 AudioSystem::releaseOutput(output);
1195 if (status == NO_ERROR) {
1196 status = NO_INIT;
1197 }
1198 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001199}
1200
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001201status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1202{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001203 if (audioBuffer == NULL) {
1204 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001205 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001206 if (mTransfer != TRANSFER_OBTAIN) {
1207 audioBuffer->frameCount = 0;
1208 audioBuffer->size = 0;
1209 audioBuffer->raw = NULL;
1210 return INVALID_OPERATION;
1211 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001212
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001213 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001214 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001215 if (waitCount == -1) {
1216 requested = &ClientProxy::kForever;
1217 } else if (waitCount == 0) {
1218 requested = &ClientProxy::kNonBlocking;
1219 } else if (waitCount > 0) {
1220 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001221 timeout.tv_sec = ms / 1000;
1222 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1223 requested = &timeout;
1224 } else {
1225 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1226 requested = NULL;
1227 }
1228 return obtainBuffer(audioBuffer, requested);
1229}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001230
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001231status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1232 struct timespec *elapsed, size_t *nonContig)
1233{
1234 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1235 uint32_t oldSequence = 0;
1236 uint32_t newSequence;
1237
1238 Proxy::Buffer buffer;
1239 status_t status = NO_ERROR;
1240
1241 static const int32_t kMaxTries = 5;
1242 int32_t tryCounter = kMaxTries;
1243
1244 do {
1245 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1246 // keep them from going away if another thread re-creates the track during obtainBuffer()
1247 sp<AudioTrackClientProxy> proxy;
1248 sp<IMemory> iMem;
1249
1250 { // start of lock scope
1251 AutoMutex lock(mLock);
1252
1253 newSequence = mSequence;
1254 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1255 if (status == DEAD_OBJECT) {
1256 // re-create track, unless someone else has already done so
1257 if (newSequence == oldSequence) {
1258 status = restoreTrack_l("obtainBuffer");
1259 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001260 buffer.mFrameCount = 0;
1261 buffer.mRaw = NULL;
1262 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001263 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001264 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001265 }
1266 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001267 oldSequence = newSequence;
1268
1269 // Keep the extra references
1270 proxy = mProxy;
1271 iMem = mCblkMemory;
1272
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001273 if (mState == STATE_STOPPING) {
1274 status = -EINTR;
1275 buffer.mFrameCount = 0;
1276 buffer.mRaw = NULL;
1277 buffer.mNonContig = 0;
1278 break;
1279 }
1280
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001281 // Non-blocking if track is stopped or paused
1282 if (mState != STATE_ACTIVE) {
1283 requested = &ClientProxy::kNonBlocking;
1284 }
1285
1286 } // end of lock scope
1287
1288 buffer.mFrameCount = audioBuffer->frameCount;
1289 // FIXME starts the requested timeout and elapsed over from scratch
1290 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1291
1292 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1293
1294 audioBuffer->frameCount = buffer.mFrameCount;
1295 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1296 audioBuffer->raw = buffer.mRaw;
1297 if (nonContig != NULL) {
1298 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001299 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001300 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001301}
1302
1303void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1304{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001305 if (mTransfer == TRANSFER_SHARED) {
1306 return;
1307 }
1308
1309 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1310 if (stepCount == 0) {
1311 return;
1312 }
1313
1314 Proxy::Buffer buffer;
1315 buffer.mFrameCount = stepCount;
1316 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001317
Eric Laurent1703cdf2011-03-07 14:52:59 -08001318 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001319 mInUnderrun = false;
1320 mProxy->releaseBuffer(&buffer);
1321
1322 // restart track if it was disabled by audioflinger due to previous underrun
1323 if (mState == STATE_ACTIVE) {
1324 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001325 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001326 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001327 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001328 mAudioTrack->start();
1329 }
1330 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001331}
1332
1333// -------------------------------------------------------------------------
1334
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001335ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001336{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001337 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001338 return INVALID_OPERATION;
1339 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001340
Eric Laurentab5cdba2014-06-09 17:22:27 -07001341 if (isDirect()) {
1342 AutoMutex lock(mLock);
1343 int32_t flags = android_atomic_and(
1344 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1345 &mCblk->mFlags);
1346 if (flags & CBLK_INVALID) {
1347 return DEAD_OBJECT;
1348 }
1349 }
1350
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001351 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001352 // Sanity-check: user is most-likely passing an error code, and it would
1353 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001354 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001355 return BAD_VALUE;
1356 }
1357
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001358 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001359 Buffer audioBuffer;
1360
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001361 while (userSize >= mFrameSize) {
1362 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001363
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001364 status_t err = obtainBuffer(&audioBuffer,
1365 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001366 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001367 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001368 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001369 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001370 return ssize_t(err);
1371 }
1372
1373 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001374 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001375 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001376 toWrite = audioBuffer.size >> 1;
1377 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001378 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001379 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001380 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001381 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001382 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001383 userSize -= toWrite;
1384 written += toWrite;
1385
1386 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001387 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001388
1389 return written;
1390}
1391
1392// -------------------------------------------------------------------------
1393
John Grossman4ff14ba2012-02-08 16:37:41 -08001394TimedAudioTrack::TimedAudioTrack() {
1395 mIsTimed = true;
1396}
1397
1398status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1399{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001400 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001401 status_t result = UNKNOWN_ERROR;
1402
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001403#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001404 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1405 // while we are accessing the cblk
1406 sp<IAudioTrack> audioTrack = mAudioTrack;
1407 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001408#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001409
John Grossman4ff14ba2012-02-08 16:37:41 -08001410 // If the track is not invalid already, try to allocate a buffer. alloc
1411 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001412 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001413 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001414 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001415 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1416 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001417 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001418 }
1419 }
1420
1421 // If the track is invalid at this point, attempt to restore it. and try the
1422 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001423 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001424 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001425
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001426 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001427 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001428 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001429 }
1430
1431 return result;
1432}
1433
1434status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1435 int64_t pts)
1436{
Eric Laurentdf839842012-05-31 14:27:14 -07001437 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1438 {
1439 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001440 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001441 // restart track if it was disabled by audioflinger due to previous underrun
1442 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001443 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1444 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001445 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001446 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001447 mAudioTrack->start();
1448 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001449 }
Eric Laurentdf839842012-05-31 14:27:14 -07001450 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001451}
1452
1453status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1454 TargetTimeline target)
1455{
1456 return mAudioTrack->setMediaTimeTransform(xform, target);
1457}
1458
1459// -------------------------------------------------------------------------
1460
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001461nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001462{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001463 // Currently the AudioTrack thread is not created if there are no callbacks.
1464 // Would it ever make sense to run the thread, even without callbacks?
1465 // If so, then replace this by checks at each use for mCbf != NULL.
1466 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1467
Eric Laurent1703cdf2011-03-07 14:52:59 -08001468 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001469 if (mAwaitBoost) {
1470 mAwaitBoost = false;
1471 mLock.unlock();
1472 static const int32_t kMaxTries = 5;
1473 int32_t tryCounter = kMaxTries;
1474 uint32_t pollUs = 10000;
1475 do {
1476 int policy = sched_getscheduler(0);
1477 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1478 break;
1479 }
1480 usleep(pollUs);
1481 pollUs <<= 1;
1482 } while (tryCounter-- > 0);
1483 if (tryCounter < 0) {
1484 ALOGE("did not receive expected priority boost on time");
1485 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001486 // Run again immediately
1487 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001488 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001489
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001490 // Can only reference mCblk while locked
1491 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001492 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001493
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001494 // Check for track invalidation
1495 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001496 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1497 // AudioSystem cache. We should not exit here but after calling the callback so
1498 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001499 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001500 status_t status = restoreTrack_l("processAudioBuffer");
1501 mLock.unlock();
1502 // Run again immediately, but with a new IAudioTrack
1503 return 0;
1504 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001505 }
1506
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001507 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001508 bool active = mState == STATE_ACTIVE;
1509
1510 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1511 bool newUnderrun = false;
1512 if (flags & CBLK_UNDERRUN) {
1513#if 0
1514 // Currently in shared buffer mode, when the server reaches the end of buffer,
1515 // the track stays active in continuous underrun state. It's up to the application
1516 // to pause or stop the track, or set the position to a new offset within buffer.
1517 // This was some experimental code to auto-pause on underrun. Keeping it here
1518 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1519 if (mTransfer == TRANSFER_SHARED) {
1520 mState = STATE_PAUSED;
1521 active = false;
1522 }
1523#endif
1524 if (!mInUnderrun) {
1525 mInUnderrun = true;
1526 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001527 }
1528 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001529
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001530 // Get current position of server
1531 size_t position = mProxy->getPosition();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001532
1533 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001534 bool markerReached = false;
1535 size_t markerPosition = mMarkerPosition;
1536 // FIXME fails for wraparound, need 64 bits
1537 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1538 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001539 }
1540
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001541 // Determine number of new position callback(s) that will be needed, while locked
1542 size_t newPosCount = 0;
1543 size_t newPosition = mNewPosition;
1544 size_t updatePeriod = mUpdatePeriod;
1545 // FIXME fails for wraparound, need 64 bits
1546 if (updatePeriod > 0 && position >= newPosition) {
1547 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1548 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001549 }
1550
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001551 // Cache other fields that will be needed soon
1552 uint32_t loopPeriod = mLoopPeriod;
1553 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001554 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001555 if (mRefreshRemaining) {
1556 mRefreshRemaining = false;
1557 mRemainingFrames = notificationFrames;
1558 mRetryOnPartialBuffer = false;
1559 }
1560 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001561 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001562 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001563
1564 // These fields don't need to be cached, because they are assigned only by set():
1565 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1566 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1567
1568 mLock.unlock();
1569
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001570 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001571 struct timespec timeout;
1572 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1573 timeout.tv_nsec = 0;
1574
Glenn Kasten96f04882013-09-20 09:28:56 -07001575 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001576 switch (status) {
1577 case NO_ERROR:
1578 case DEAD_OBJECT:
1579 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001580 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001581 {
1582 AutoMutex lock(mLock);
1583 // The previously assigned value of waitStreamEnd is no longer valid,
1584 // since the mutex has been unlocked and either the callback handler
1585 // or another thread could have re-started the AudioTrack during that time.
1586 waitStreamEnd = mState == STATE_STOPPING;
1587 if (waitStreamEnd) {
1588 mState = STATE_STOPPED;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001589 }
1590 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001591 if (waitStreamEnd && status != DEAD_OBJECT) {
1592 return NS_INACTIVE;
1593 }
1594 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001595 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001596 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001597 }
1598
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001599 // perform callbacks while unlocked
1600 if (newUnderrun) {
1601 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1602 }
1603 // FIXME we will miss loops if loop cycle was signaled several times since last call
1604 // to processAudioBuffer()
1605 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1606 mCbf(EVENT_LOOP_END, mUserData, NULL);
1607 }
1608 if (flags & CBLK_BUFFER_END) {
1609 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1610 }
1611 if (markerReached) {
1612 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1613 }
1614 while (newPosCount > 0) {
1615 size_t temp = newPosition;
1616 mCbf(EVENT_NEW_POS, mUserData, &temp);
1617 newPosition += updatePeriod;
1618 newPosCount--;
1619 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001620
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001621 if (mObservedSequence != sequence) {
1622 mObservedSequence = sequence;
1623 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001624 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001625 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001626 return NS_INACTIVE;
1627 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001628 }
1629
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001630 // if inactive, then don't run me again until re-started
1631 if (!active) {
1632 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001633 }
1634
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001635 // Compute the estimated time until the next timed event (position, markers, loops)
1636 // FIXME only for non-compressed audio
1637 uint32_t minFrames = ~0;
1638 if (!markerReached && position < markerPosition) {
1639 minFrames = markerPosition - position;
1640 }
1641 if (loopPeriod > 0 && loopPeriod < minFrames) {
1642 minFrames = loopPeriod;
1643 }
1644 if (updatePeriod > 0 && updatePeriod < minFrames) {
1645 minFrames = updatePeriod;
1646 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001647
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001648 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1649 static const uint32_t kPoll = 0;
1650 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1651 minFrames = kPoll * notificationFrames;
1652 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001653
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001654 // Convert frame units to time units
1655 nsecs_t ns = NS_WHENEVER;
1656 if (minFrames != (uint32_t) ~0) {
1657 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1658 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1659 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1660 }
1661
1662 // If not supplying data by EVENT_MORE_DATA, then we're done
1663 if (mTransfer != TRANSFER_CALLBACK) {
1664 return ns;
1665 }
1666
1667 struct timespec timeout;
1668 const struct timespec *requested = &ClientProxy::kForever;
1669 if (ns != NS_WHENEVER) {
1670 timeout.tv_sec = ns / 1000000000LL;
1671 timeout.tv_nsec = ns % 1000000000LL;
1672 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1673 requested = &timeout;
1674 }
1675
1676 while (mRemainingFrames > 0) {
1677
1678 Buffer audioBuffer;
1679 audioBuffer.frameCount = mRemainingFrames;
1680 size_t nonContig;
1681 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1682 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1683 "obtainBuffer() err=%d frameCount=%u", err, audioBuffer.frameCount);
1684 requested = &ClientProxy::kNonBlocking;
1685 size_t avail = audioBuffer.frameCount + nonContig;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001686 ALOGV("obtainBuffer(%u) returned %u = %u + %u err %d",
1687 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001688 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001689 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1690 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001691 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001692 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001693 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1694 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001695 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001696
Eric Laurent42a6f422013-08-29 14:35:05 -07001697 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001698 mRetryOnPartialBuffer = false;
1699 if (avail < mRemainingFrames) {
1700 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1701 if (ns < 0 || myns < ns) {
1702 ns = myns;
1703 }
1704 return ns;
1705 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001706 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001707
1708 // Divide buffer size by 2 to take into account the expansion
1709 // due to 8 to 16 bit conversion: the callback must fill only half
1710 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001711 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001712 audioBuffer.size >>= 1;
1713 }
1714
1715 size_t reqSize = audioBuffer.size;
1716 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001717 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001718
1719 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001720 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
1721 ALOGE("EVENT_MORE_DATA requested %u bytes but callback returned %d bytes",
1722 reqSize, (int) writtenSize);
1723 return NS_NEVER;
1724 }
1725
1726 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001727 // The callback is done filling buffers
1728 // Keep this thread going to handle timed events and
1729 // still try to get more data in intervals of WAIT_PERIOD_MS
1730 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001731 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001732 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001733
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001734 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001735 // 8 to 16 bit conversion, note that source and destination are the same address
1736 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001737 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001738 }
1739
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001740 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1741 audioBuffer.frameCount = releasedFrames;
1742 mRemainingFrames -= releasedFrames;
1743 if (misalignment >= releasedFrames) {
1744 misalignment -= releasedFrames;
1745 } else {
1746 misalignment = 0;
1747 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001748
1749 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001750
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001751 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1752 // if callback doesn't like to accept the full chunk
1753 if (writtenSize < reqSize) {
1754 continue;
1755 }
1756
1757 // There could be enough non-contiguous frames available to satisfy the remaining request
1758 if (mRemainingFrames <= nonContig) {
1759 continue;
1760 }
1761
1762#if 0
1763 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1764 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1765 // that total to a sum == notificationFrames.
1766 if (0 < misalignment && misalignment <= mRemainingFrames) {
1767 mRemainingFrames = misalignment;
1768 return (mRemainingFrames * 1100000000LL) / sampleRate;
1769 }
1770#endif
1771
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001772 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001773 mRemainingFrames = notificationFrames;
1774 mRetryOnPartialBuffer = true;
1775
1776 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1777 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001778}
1779
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001780status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001781{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001782 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001783 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001784 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001785 status_t result;
1786
Glenn Kastena47f3162012-11-07 10:13:08 -08001787 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kasten38e905b2014-01-13 10:21:48 -08001788 // output parameters in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001789 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001790
Eric Laurentab5cdba2014-06-09 17:22:27 -07001791 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001792 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001793 return DEAD_OBJECT;
1794 }
1795
Glenn Kastena47f3162012-11-07 10:13:08 -08001796 // if the new IAudioTrack is created, createTrack_l() will modify the
1797 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1798 // It will also delete the strong references on previous IAudioTrack and IMemory
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001799
1800 // take the frames that will be lost by track recreation into account in saved position
1801 size_t position = mProxy->getPosition() + mProxy->getFramesFilled();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001802 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
Glenn Kasten363fb752014-01-15 12:27:31 -08001803 result = createTrack_l(position /*epoch*/);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001804
Glenn Kastena47f3162012-11-07 10:13:08 -08001805 if (result == NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001806 // continue playback from last known position, but
1807 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1808 if (mStaticProxy != NULL) {
1809 mLoopPeriod = 0;
1810 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1811 }
1812 // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1813 // track destruction have been played? This is critical for SoundPool implementation
1814 // This must be broken, and needs to be tested/debugged.
1815#if 0
Glenn Kastena47f3162012-11-07 10:13:08 -08001816 // restore write index and set other indexes to reflect empty buffer status
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001817 if (!strcmp(from, "start")) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001818 // Make sure that a client relying on callback events indicating underrun or
1819 // the actual amount of audio frames played (e.g SoundPool) receives them.
1820 if (mSharedBuffer == 0) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001821 // restart playback even if buffer is not completely filled.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001822 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001823 }
1824 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001825#endif
1826 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001827 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001828 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001829 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001830 if (result != NO_ERROR) {
1831 ALOGW("restoreTrack_l() failed status %d", result);
1832 mState = STATE_STOPPED;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001833 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001834
1835 return result;
1836}
1837
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001838status_t AudioTrack::setParameters(const String8& keyValuePairs)
1839{
1840 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001841 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001842}
1843
Glenn Kastence703742013-07-19 16:33:58 -07001844status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1845{
Glenn Kasten53cec222013-08-29 09:01:02 -07001846 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001847 // FIXME not implemented for fast tracks; should use proxy and SSQ
1848 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1849 return INVALID_OPERATION;
1850 }
1851 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
1852 return INVALID_OPERATION;
1853 }
1854 status_t status = mAudioTrack->getTimestamp(timestamp);
1855 if (status == NO_ERROR) {
1856 timestamp.mPosition += mProxy->getEpoch();
1857 }
1858 return status;
Glenn Kastence703742013-07-19 16:33:58 -07001859}
1860
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001861String8 AudioTrack::getParameters(const String8& keys)
1862{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08001863 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07001864 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08001865 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001866 } else {
1867 return String8::empty();
1868 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001869}
1870
Glenn Kasten23a75452014-01-13 10:37:17 -08001871bool AudioTrack::isOffloaded() const
1872{
1873 AutoMutex lock(mLock);
1874 return isOffloaded_l();
1875}
1876
Eric Laurentab5cdba2014-06-09 17:22:27 -07001877bool AudioTrack::isDirect() const
1878{
1879 AutoMutex lock(mLock);
1880 return isDirect_l();
1881}
1882
1883bool AudioTrack::isOffloadedOrDirect() const
1884{
1885 AutoMutex lock(mLock);
1886 return isOffloadedOrDirect_l();
1887}
1888
1889
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001890status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001891{
1892
1893 const size_t SIZE = 256;
1894 char buffer[SIZE];
1895 String8 result;
1896
1897 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001898 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07001899 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001900 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001901 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001902 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001903 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001904 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001905 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001906 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001907 result.append(buffer);
1908 ::write(fd, result.string(), result.size());
1909 return NO_ERROR;
1910}
1911
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001912uint32_t AudioTrack::getUnderrunFrames() const
1913{
1914 AutoMutex lock(mLock);
1915 return mProxy->getUnderrunFrames();
1916}
1917
Jean-Michel Trivifaabb512014-06-11 16:55:06 -07001918void AudioTrack::setAttributesFromStreamType(audio_stream_type_t streamType) {
1919 mAttributes.flags = 0x0;
1920
1921 switch(streamType) {
1922 case AUDIO_STREAM_DEFAULT:
1923 case AUDIO_STREAM_MUSIC:
1924 mAttributes.content_type = AUDIO_CONTENT_TYPE_MUSIC;
1925 mAttributes.usage = AUDIO_USAGE_MEDIA;
1926 break;
1927 case AUDIO_STREAM_VOICE_CALL:
1928 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1929 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION;
1930 break;
1931 case AUDIO_STREAM_ENFORCED_AUDIBLE:
1932 mAttributes.flags |= AUDIO_FLAG_AUDIBILITY_ENFORCED;
1933 // intended fall through, attributes in common with STREAM_SYSTEM
1934 case AUDIO_STREAM_SYSTEM:
1935 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1936 mAttributes.usage = AUDIO_USAGE_ASSISTANCE_SONIFICATION;
1937 break;
1938 case AUDIO_STREAM_RING:
1939 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1940 mAttributes.usage = AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE;
1941 break;
1942 case AUDIO_STREAM_ALARM:
1943 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1944 mAttributes.usage = AUDIO_USAGE_ALARM;
1945 break;
1946 case AUDIO_STREAM_NOTIFICATION:
1947 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1948 mAttributes.usage = AUDIO_USAGE_NOTIFICATION;
1949 break;
1950 case AUDIO_STREAM_BLUETOOTH_SCO:
1951 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1952 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION;
1953 mAttributes.flags |= AUDIO_FLAG_SCO;
1954 break;
1955 case AUDIO_STREAM_DTMF:
1956 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1957 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING;
1958 break;
1959 case AUDIO_STREAM_TTS:
1960 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1961 mAttributes.usage = AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY;
1962 break;
1963 default:
1964 ALOGE("invalid stream type %d when converting to attributes", streamType);
1965 }
1966}
1967
1968void AudioTrack::setStreamTypeFromAttributes(audio_attributes_t& aa) {
1969 // flags to stream type mapping
1970 if ((aa.flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
1971 mStreamType = AUDIO_STREAM_ENFORCED_AUDIBLE;
1972 return;
1973 }
1974 if ((aa.flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
1975 mStreamType = AUDIO_STREAM_BLUETOOTH_SCO;
1976 return;
1977 }
1978
1979 // usage to stream type mapping
1980 switch (aa.usage) {
1981 case AUDIO_USAGE_MEDIA:
1982 case AUDIO_USAGE_GAME:
1983 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
1984 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
1985 mStreamType = AUDIO_STREAM_MUSIC;
1986 return;
1987 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
1988 mStreamType = AUDIO_STREAM_SYSTEM;
1989 return;
1990 case AUDIO_USAGE_VOICE_COMMUNICATION:
1991 mStreamType = AUDIO_STREAM_VOICE_CALL;
1992 return;
1993
1994 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
1995 mStreamType = AUDIO_STREAM_DTMF;
1996 return;
1997
1998 case AUDIO_USAGE_ALARM:
1999 mStreamType = AUDIO_STREAM_ALARM;
2000 return;
2001 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
2002 mStreamType = AUDIO_STREAM_RING;
2003 return;
2004
2005 case AUDIO_USAGE_NOTIFICATION:
2006 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
2007 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
2008 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
2009 case AUDIO_USAGE_NOTIFICATION_EVENT:
2010 mStreamType = AUDIO_STREAM_NOTIFICATION;
2011 return;
2012
2013 case AUDIO_USAGE_UNKNOWN:
2014 default:
2015 mStreamType = AUDIO_STREAM_MUSIC;
2016 }
2017}
2018
2019bool AudioTrack::isValidAttributes(const audio_attributes_t *paa) {
2020 // has flags that map to a strategy?
2021 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO)) != 0) {
2022 return true;
2023 }
2024
2025 // has known usage?
2026 switch (paa->usage) {
2027 case AUDIO_USAGE_UNKNOWN:
2028 case AUDIO_USAGE_MEDIA:
2029 case AUDIO_USAGE_VOICE_COMMUNICATION:
2030 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
2031 case AUDIO_USAGE_ALARM:
2032 case AUDIO_USAGE_NOTIFICATION:
2033 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
2034 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
2035 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
2036 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
2037 case AUDIO_USAGE_NOTIFICATION_EVENT:
2038 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
2039 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
2040 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
2041 case AUDIO_USAGE_GAME:
2042 break;
2043 default:
2044 return false;
2045 }
2046 return true;
2047}
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002048// =========================================================================
2049
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002050void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002051{
2052 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2053 if (audioTrack != 0) {
2054 AutoMutex lock(audioTrack->mLock);
2055 audioTrack->mProxy->binderDied();
2056 }
2057}
2058
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002059// =========================================================================
2060
2061AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002062 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2063 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002064{
2065}
2066
2067AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002068{
2069}
2070
2071bool AudioTrack::AudioTrackThread::threadLoop()
2072{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002073 {
2074 AutoMutex _l(mMyLock);
2075 if (mPaused) {
2076 mMyCond.wait(mMyLock);
2077 // caller will check for exitPending()
2078 return true;
2079 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002080 if (mIgnoreNextPausedInt) {
2081 mIgnoreNextPausedInt = false;
2082 mPausedInt = false;
2083 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002084 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002085 if (mPausedNs > 0) {
2086 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2087 } else {
2088 mMyCond.wait(mMyLock);
2089 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002090 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002091 return true;
2092 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002093 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002094 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002095 switch (ns) {
2096 case 0:
2097 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002098 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002099 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002100 return true;
2101 case NS_NEVER:
2102 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002103 case NS_WHENEVER:
2104 // FIXME increase poll interval, or make event-driven
2105 ns = 1000000000LL;
2106 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002107 default:
2108 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002109 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002110 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002111 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002112}
2113
Glenn Kasten3acbd052012-02-28 10:39:56 -08002114void AudioTrack::AudioTrackThread::requestExit()
2115{
2116 // must be in this order to avoid a race condition
2117 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002118 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002119}
2120
2121void AudioTrack::AudioTrackThread::pause()
2122{
2123 AutoMutex _l(mMyLock);
2124 mPaused = true;
2125}
2126
2127void AudioTrack::AudioTrackThread::resume()
2128{
2129 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002130 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002131 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002132 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002133 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002134 mMyCond.signal();
2135 }
2136}
2137
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002138void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2139{
2140 AutoMutex _l(mMyLock);
2141 mPausedInt = true;
2142 mPausedNs = ns;
2143}
2144
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002145}; // namespace android