blob: b5c91252dfb44822439468cddf6cbfbe8ddba6de [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080018//#define LOG_NDEBUG 0
19#define LOG_TAG "AudioTrack"
20
Mark Salyzyn34fb2962014-06-18 16:30:56 -070021#include <inttypes.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070022#include <math.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080023#include <sys/resource.h>
Mark Salyzyn34fb2962014-06-18 16:30:56 -070024
Glenn Kasten9f80dd22012-12-18 15:57:32 -080025#include <audio_utils/primitives.h>
26#include <binder/IPCThreadState.h>
27#include <media/AudioTrack.h>
28#include <utils/Log.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080029#include <private/media/AudioTrackShared.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/IAudioFlinger.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080031
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010032#define WAIT_PERIOD_MS 10
33#define WAIT_STREAM_END_TIMEOUT_SEC 120
34
Glenn Kasten511754b2012-01-11 09:52:19 -080035
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080036namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080037// ---------------------------------------------------------------------------
38
39// static
40status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080041 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080042 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080043 uint32_t sampleRate)
44{
Glenn Kastend65d73c2012-06-22 17:21:07 -070045 if (frameCount == NULL) {
46 return BAD_VALUE;
47 }
Glenn Kasten04cd0182012-06-25 11:49:27 -070048
Glenn Kastene0fa4672012-04-24 14:35:14 -070049 // FIXME merge with similar code in createTrack_l(), except we're missing
50 // some information here that is available in createTrack_l():
51 // audio_io_handle_t output
52 // audio_format_t format
53 // audio_channel_mask_t channelMask
54 // audio_output_flags_t flags
Glenn Kasten3b16c762012-11-14 08:44:39 -080055 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080056 status_t status;
57 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
58 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080059 ALOGE("Unable to query output sample rate for stream type %d; status %d",
60 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080061 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080062 }
Glenn Kastene33054e2012-11-14 12:54:39 -080063 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -080064 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
65 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080066 ALOGE("Unable to query output frame count for stream type %d; status %d",
67 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080068 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080069 }
70 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -080071 status = AudioSystem::getOutputLatency(&afLatency, streamType);
72 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080073 ALOGE("Unable to query output latency for stream type %d; status %d",
74 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080075 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080076 }
77
78 // Ensure that buffer depth covers at least audio hardware latency
79 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080080 if (minBufCount < 2) {
81 minBufCount = 2;
82 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +080083
84 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
Glenn Kastene53b9ea2012-03-12 16:29:55 -070085 afFrameCount * minBufCount * sampleRate / afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080086 // The formula above should always produce a non-zero value, but return an error
87 // in the unlikely event that it does not, as that's part of the API contract.
88 if (*frameCount == 0) {
89 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %d",
90 streamType, sampleRate);
91 return BAD_VALUE;
92 }
Mark Salyzyn34fb2962014-06-18 16:30:56 -070093 ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, minBufCount=%d, afSampleRate=%d, afLatency=%d",
Glenn Kasten3acbd052012-02-28 10:39:56 -080094 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +080095 return NO_ERROR;
96}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080097
98// ---------------------------------------------------------------------------
99
100AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700101 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800102 mIsTimed(false),
103 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800104 mPreviousSchedulingGroup(SP_DEFAULT),
105 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800106{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700107 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
108 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
109 mAttributes.flags = 0x0;
110 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800111}
112
113AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800114 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800115 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800116 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700117 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800118 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700119 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800120 callback_t cbf,
121 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800122 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800123 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000124 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800125 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800126 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700127 pid_t pid,
128 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700129 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800130 mIsTimed(false),
131 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800132 mPreviousSchedulingGroup(SP_DEFAULT),
133 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800134{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700135 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700136 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800137 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700138 offloadInfo, uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800139}
140
Andreas Huberc8139852012-01-18 10:51:55 -0800141AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800142 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800143 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800144 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700145 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800146 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700147 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800148 callback_t cbf,
149 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800150 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800151 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000152 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800153 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800154 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700155 pid_t pid,
156 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700157 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800158 mIsTimed(false),
159 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800160 mPreviousSchedulingGroup(SP_DEFAULT),
161 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800162{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700163 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800164 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800165 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700166 uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800167}
168
169AudioTrack::~AudioTrack()
170{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800171 if (mStatus == NO_ERROR) {
172 // Make sure that callback function exits in the case where
173 // it is looping on buffer full condition in obtainBuffer().
174 // Otherwise the callback thread will never exit.
175 stop();
176 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100177 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800178 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800179 mAudioTrackThread->requestExitAndWait();
180 mAudioTrackThread.clear();
181 }
Glenn Kasten53cec222013-08-29 09:01:02 -0700182 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
183 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700184 mCblkMemory.clear();
185 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800186 IPCThreadState::self()->flushCommands();
Marco Nelissend457c972014-02-11 08:47:07 -0800187 ALOGV("~AudioTrack, releasing session id from %d on behalf of %d",
188 IPCThreadState::self()->getCallingPid(), mClientPid);
189 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800190 }
191}
192
193status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800194 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800195 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800196 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700197 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800198 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700199 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800200 callback_t cbf,
201 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800202 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800203 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700204 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800205 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000206 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800207 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800208 int uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700209 pid_t pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700210 const audio_attributes_t* pAttributes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800211{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800212 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten838b3d82014-02-27 15:30:41 -0800213 "flags #%x, notificationFrames %u, sessionId %d, transferType %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800214 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten86f04662014-02-24 15:13:05 -0800215 sessionId, transferType);
216
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800217 switch (transferType) {
218 case TRANSFER_DEFAULT:
219 if (sharedBuffer != 0) {
220 transferType = TRANSFER_SHARED;
221 } else if (cbf == NULL || threadCanCallJava) {
222 transferType = TRANSFER_SYNC;
223 } else {
224 transferType = TRANSFER_CALLBACK;
225 }
226 break;
227 case TRANSFER_CALLBACK:
228 if (cbf == NULL || sharedBuffer != 0) {
229 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
230 return BAD_VALUE;
231 }
232 break;
233 case TRANSFER_OBTAIN:
234 case TRANSFER_SYNC:
235 if (sharedBuffer != 0) {
236 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
237 return BAD_VALUE;
238 }
239 break;
240 case TRANSFER_SHARED:
241 if (sharedBuffer == 0) {
242 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
243 return BAD_VALUE;
244 }
245 break;
246 default:
247 ALOGE("Invalid transfer type %d", transferType);
248 return BAD_VALUE;
249 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800250 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800251 mTransfer = transferType;
252
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700253 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
254 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800255
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700256 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700257
Eric Laurent1703cdf2011-03-07 14:52:59 -0800258 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800259
Glenn Kasten53cec222013-08-29 09:01:02 -0700260 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700261 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000262 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800263 return INVALID_OPERATION;
264 }
265
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800266 // handle default values first.
Dima Zavinfce7a472011-04-19 22:30:36 -0700267 if (streamType == AUDIO_STREAM_DEFAULT) {
268 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800269 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700270
271 if (pAttributes == NULL) {
272 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
273 ALOGE("Invalid stream type %d", streamType);
274 return BAD_VALUE;
275 }
276 setAttributesFromStreamType(streamType);
277 mStreamType = streamType;
278 } else {
279 if (!isValidAttributes(pAttributes)) {
280 ALOGE("Invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
281 pAttributes->usage, pAttributes->content_type, pAttributes->flags,
282 pAttributes->tags);
283 }
284 // stream type shouldn't be looked at, this track has audio attributes
285 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
286 setStreamTypeFromAttributes(mAttributes);
287 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
288 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800289 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700290
Glenn Kastenb1bef512014-01-13 10:25:53 -0800291 status_t status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800292 if (sampleRate == 0) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700293 status = AudioSystem::getOutputSamplingRateForAttr(&sampleRate, &mAttributes);
Glenn Kastenb1bef512014-01-13 10:25:53 -0800294 if (status != NO_ERROR) {
295 ALOGE("Could not get output sample rate for stream type %d; status %d",
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700296 mStreamType, status);
Glenn Kastenb1bef512014-01-13 10:25:53 -0800297 return status;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700298 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800299 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800300 mSampleRate = sampleRate;
Glenn Kastenea7939a2012-03-14 12:56:26 -0700301
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800302 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800303 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700304 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800305 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800306
307 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700308 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800309 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800310 return BAD_VALUE;
311 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800312 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700313
Glenn Kasten8ba90322013-10-30 11:29:27 -0700314 if (!audio_is_output_channel(channelMask)) {
315 ALOGE("Invalid channel mask %#x", channelMask);
316 return BAD_VALUE;
317 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800318 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700319 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800320 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700321
Glenn Kastene0fa4672012-04-24 14:35:14 -0700322 // AudioFlinger does not currently support 8-bit data in shared memory
323 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
324 ALOGE("8-bit data in shared memory is not supported");
325 return BAD_VALUE;
326 }
327
Eric Laurentc2f1f072009-07-17 12:17:14 -0700328 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100329 // or offload was requested
330 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
331 || !audio_is_linear_pcm(format)) {
332 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
333 ? "Offload request, forcing to Direct Output"
334 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700335 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800336 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700337 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700338 }
Eric Laurent1948eb32012-04-13 16:50:19 -0700339 // only allow deep buffering for music stream type
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700340 if (mStreamType != AUDIO_STREAM_MUSIC) {
Eric Laurent1948eb32012-04-13 16:50:19 -0700341 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
342 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700343
Glenn Kastenb7730382014-04-30 15:50:31 -0700344 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
345 if (audio_is_linear_pcm(format)) {
346 mFrameSize = channelCount * audio_bytes_per_sample(format);
347 } else {
348 mFrameSize = sizeof(uint8_t);
349 }
350 mFrameSizeAF = mFrameSize;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800351 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700352 ALOG_ASSERT(audio_is_linear_pcm(format));
353 mFrameSize = channelCount * audio_bytes_per_sample(format);
354 mFrameSizeAF = channelCount * audio_bytes_per_sample(
355 format == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : format);
356 // createTrack will return an error if PCM format is not supported by server,
357 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800358 }
359
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800360 // Make copy of input parameter offloadInfo so that in the future:
361 // (a) createTrack_l doesn't need it as an input parameter
362 // (b) we can support re-creation of offloaded tracks
363 if (offloadInfo != NULL) {
364 mOffloadInfoCopy = *offloadInfo;
365 mOffloadInfo = &mOffloadInfoCopy;
366 } else {
367 mOffloadInfo = NULL;
368 }
369
Glenn Kasten66e46352014-01-16 17:44:23 -0800370 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
371 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800372 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800373 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800374 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700375 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800376 mNotificationFramesAct = 0;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700377 mSessionId = sessionId;
Marco Nelissend457c972014-02-11 08:47:07 -0800378 int callingpid = IPCThreadState::self()->getCallingPid();
379 int mypid = getpid();
380 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800381 mClientUid = IPCThreadState::self()->getCallingUid();
382 } else {
383 mClientUid = uid;
384 }
Marco Nelissend457c972014-02-11 08:47:07 -0800385 if (pid == -1 || (callingpid != mypid)) {
386 mClientPid = callingpid;
387 } else {
388 mClientPid = pid;
389 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700390 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700391 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700392 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700393
Glenn Kastena997e7a2012-08-07 09:44:19 -0700394 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700395 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700396 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
397 }
398
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800399 // create the IAudioTrack
Glenn Kasten363fb752014-01-15 12:27:31 -0800400 status = createTrack_l(0 /*epoch*/);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800401
Glenn Kastena997e7a2012-08-07 09:44:19 -0700402 if (status != NO_ERROR) {
403 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100404 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
405 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700406 mAudioTrackThread.clear();
407 }
408 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700409 }
410
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800411 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800412 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800413 mUserData = user;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800414 mLoopPeriod = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800415 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700416 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800417 mNewPosition = 0;
418 mUpdatePeriod = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800419 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800420 mSequence = 1;
421 mObservedSequence = mSequence;
422 mInUnderrun = false;
423
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800424 return NO_ERROR;
425}
426
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800427// -------------------------------------------------------------------------
428
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100429status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800430{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800431 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100432
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800433 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100434 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800435 }
436
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800437 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800438
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800439 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100440 if (previousState == STATE_PAUSED_STOPPING) {
441 mState = STATE_STOPPING;
442 } else {
443 mState = STATE_ACTIVE;
444 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800445 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
446 // reset current position as seen by client to 0
447 mProxy->setEpoch(mProxy->getEpoch() - mProxy->getPosition());
Eric Laurentec9a0322013-08-28 10:23:01 -0700448 // force refresh of remaining frames by processAudioBuffer() as last
449 // write before stop could be partial.
450 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800451 }
452 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700453 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800454
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800455 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800456 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100457 if (previousState == STATE_STOPPING) {
458 mProxy->interrupt();
459 } else {
460 t->resume();
461 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800462 } else {
463 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
464 get_sched_policy(0, &mPreviousSchedulingGroup);
465 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
466 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800467
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800468 status_t status = NO_ERROR;
469 if (!(flags & CBLK_INVALID)) {
470 status = mAudioTrack->start();
471 if (status == DEAD_OBJECT) {
472 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800473 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800474 }
475 if (flags & CBLK_INVALID) {
476 status = restoreTrack_l("start");
477 }
478
479 if (status != NO_ERROR) {
480 ALOGE("start() status %d", status);
481 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800482 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100483 if (previousState != STATE_STOPPING) {
484 t->pause();
485 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800486 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700487 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700488 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800489 }
490 }
491
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100492 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800493}
494
495void AudioTrack::stop()
496{
497 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700498 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800499 return;
500 }
501
Glenn Kasten23a75452014-01-13 10:37:17 -0800502 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100503 mState = STATE_STOPPING;
504 } else {
505 mState = STATE_STOPPED;
506 }
507
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800508 mProxy->interrupt();
509 mAudioTrack->stop();
510 // the playback head position will reset to 0, so if a marker is set, we need
511 // to activate it again
512 mMarkerReached = false;
513#if 0
514 // Force flush if a shared buffer is used otherwise audioflinger
515 // will not stop before end of buffer is reached.
516 // It may be needed to make sure that we stop playback, likely in case looping is on.
517 if (mSharedBuffer != 0) {
518 flush_l();
519 }
520#endif
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100521
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800522 sp<AudioTrackThread> t = mAudioTrackThread;
523 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800524 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100525 t->pause();
526 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800527 } else {
528 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
529 set_sched_policy(0, mPreviousSchedulingGroup);
530 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800531}
532
533bool AudioTrack::stopped() const
534{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800535 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800536 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800537}
538
539void AudioTrack::flush()
540{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800541 if (mSharedBuffer != 0) {
542 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800543 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800544 AutoMutex lock(mLock);
545 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
546 return;
547 }
548 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800549}
550
Eric Laurent1703cdf2011-03-07 14:52:59 -0800551void AudioTrack::flush_l()
552{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800553 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700554
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700555 // clear playback marker and periodic update counter
556 mMarkerPosition = 0;
557 mMarkerReached = false;
558 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100559 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700560
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800561 mState = STATE_FLUSHED;
Glenn Kasten23a75452014-01-13 10:37:17 -0800562 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100563 mProxy->interrupt();
564 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800565 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800566 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800567}
568
569void AudioTrack::pause()
570{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800571 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100572 if (mState == STATE_ACTIVE) {
573 mState = STATE_PAUSED;
574 } else if (mState == STATE_STOPPING) {
575 mState = STATE_PAUSED_STOPPING;
576 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800577 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800578 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800579 mProxy->interrupt();
580 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800581
Marco Nelissen3a90f282014-03-10 11:21:43 -0700582 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700583 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800584 uint32_t halFrames;
585 // OffloadThread sends HAL pause in its threadLoop.. time saved
586 // here can be slightly off
587 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
588 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
589 }
590 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800591}
592
Eric Laurentbe916aa2010-06-01 23:49:17 -0700593status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800594{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700595 // This duplicates a test by AudioTrack JNI, but that is not the only caller
596 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
597 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700598 return BAD_VALUE;
599 }
600
Eric Laurent1703cdf2011-03-07 14:52:59 -0800601 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800602 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
603 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800604
Glenn Kastenc56f3422014-03-21 17:53:17 -0700605 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700606
Glenn Kasten23a75452014-01-13 10:37:17 -0800607 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700608 mAudioTrack->signal();
609 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700610 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800611}
612
Glenn Kastenb1c09932012-02-27 16:21:04 -0800613status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800614{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800615 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700616}
617
Eric Laurent2beeb502010-07-16 07:43:46 -0700618status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700619{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700620 // This duplicates a test by AudioTrack JNI, but that is not the only caller
621 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700622 return BAD_VALUE;
623 }
624
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800625 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700626 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800627 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700628
629 return NO_ERROR;
630}
631
Glenn Kastena5224f32012-01-04 12:41:44 -0800632void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700633{
634 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800635 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700636 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800637}
638
Glenn Kasten3b16c762012-11-14 08:44:39 -0800639status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800640{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700641 if (mIsTimed || isOffloadedOrDirect()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800642 return INVALID_OPERATION;
643 }
644
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800645 uint32_t afSamplingRate;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700646 if (AudioSystem::getOutputSamplingRateForAttr(&afSamplingRate, &mAttributes) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700647 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800648 }
649 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Glenn Kastend65d73c2012-06-22 17:21:07 -0700650 if (rate == 0 || rate > afSamplingRate*2 ) {
651 return BAD_VALUE;
652 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800653
Eric Laurent1703cdf2011-03-07 14:52:59 -0800654 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800655 mSampleRate = rate;
656 mProxy->setSampleRate(rate);
657
Eric Laurent57326622009-07-07 07:10:45 -0700658 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800659}
660
Glenn Kastena5224f32012-01-04 12:41:44 -0800661uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800662{
John Grossman4ff14ba2012-02-08 16:37:41 -0800663 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800664 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800665 }
666
Eric Laurent1703cdf2011-03-07 14:52:59 -0800667 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700668
669 // sample rate can be updated during playback by the offloaded decoder so we need to
670 // query the HAL and update if needed.
671// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700672 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700673 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700674 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700675 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700676 if (status == NO_ERROR) {
677 mSampleRate = sampleRate;
678 }
679 }
680 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800681 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800682}
683
684status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
685{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700686 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800687 return INVALID_OPERATION;
688 }
689
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800690 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800691 ;
692 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
693 loopEnd - loopStart >= MIN_LOOP) {
694 ;
695 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800696 return BAD_VALUE;
697 }
698
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800699 AutoMutex lock(mLock);
700 // See setPosition() regarding setting parameters such as loop points or position while active
701 if (mState == STATE_ACTIVE) {
702 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700703 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800704 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800705 return NO_ERROR;
706}
707
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800708void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
709{
710 // FIXME If setting a loop also sets position to start of loop, then
711 // this is correct. Otherwise it should be removed.
712 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
713 mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0;
714 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
715}
716
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800717status_t AudioTrack::setMarkerPosition(uint32_t marker)
718{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700719 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700720 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700721 return INVALID_OPERATION;
722 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800723
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800724 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800725 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700726 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800727
728 return NO_ERROR;
729}
730
Glenn Kastena5224f32012-01-04 12:41:44 -0800731status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800732{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700733 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100734 return INVALID_OPERATION;
735 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700736 if (marker == NULL) {
737 return BAD_VALUE;
738 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800739
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800740 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800741 *marker = mMarkerPosition;
742
743 return NO_ERROR;
744}
745
746status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
747{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700748 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700749 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700750 return INVALID_OPERATION;
751 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800752
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800753 AutoMutex lock(mLock);
754 mNewPosition = mProxy->getPosition() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800755 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800756
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800757 return NO_ERROR;
758}
759
Glenn Kastena5224f32012-01-04 12:41:44 -0800760status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800761{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700762 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100763 return INVALID_OPERATION;
764 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700765 if (updatePeriod == NULL) {
766 return BAD_VALUE;
767 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800768
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800769 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800770 *updatePeriod = mUpdatePeriod;
771
772 return NO_ERROR;
773}
774
775status_t AudioTrack::setPosition(uint32_t position)
776{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700777 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700778 return INVALID_OPERATION;
779 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800780 if (position > mFrameCount) {
781 return BAD_VALUE;
782 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800783
Eric Laurent1703cdf2011-03-07 14:52:59 -0800784 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800785 // Currently we require that the player is inactive before setting parameters such as position
786 // or loop points. Otherwise, there could be a race condition: the application could read the
787 // current position, compute a new position or loop parameters, and then set that position or
788 // loop parameters but it would do the "wrong" thing since the position has continued to advance
789 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
790 // to specify how it wants to handle such scenarios.
791 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700792 return INVALID_OPERATION;
793 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800794 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
795 mLoopPeriod = 0;
796 // FIXME Check whether loops and setting position are incompatible in old code.
797 // If we use setLoop for both purposes we lose the capability to set the position while looping.
798 mStaticProxy->setLoop(position, mFrameCount, 0);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700799
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800800 return NO_ERROR;
801}
802
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800803status_t AudioTrack::getPosition(uint32_t *position) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800804{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700805 if (position == NULL) {
806 return BAD_VALUE;
807 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800808
Eric Laurent1703cdf2011-03-07 14:52:59 -0800809 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700810 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100811 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800812
Eric Laurentab5cdba2014-06-09 17:22:27 -0700813 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800814 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
815 *position = mPausedPosition;
816 return NO_ERROR;
817 }
818
Glenn Kasten142f5192014-03-25 17:44:59 -0700819 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100820 uint32_t halFrames;
821 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
822 }
823 *position = dspFrames;
824 } else {
825 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
826 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ? 0 :
827 mProxy->getPosition();
828 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800829 return NO_ERROR;
830}
831
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000832status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800833{
834 if (mSharedBuffer == 0 || mIsTimed) {
835 return INVALID_OPERATION;
836 }
837 if (position == NULL) {
838 return BAD_VALUE;
839 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800840
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800841 AutoMutex lock(mLock);
842 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800843 return NO_ERROR;
844}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800845
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800846status_t AudioTrack::reload()
847{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700848 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800849 return INVALID_OPERATION;
850 }
851
Eric Laurent1703cdf2011-03-07 14:52:59 -0800852 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800853 // See setPosition() regarding setting parameters such as loop points or position while active
854 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700855 return INVALID_OPERATION;
856 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800857 mNewPosition = mUpdatePeriod;
858 mLoopPeriod = 0;
859 // FIXME The new code cannot reload while keeping a loop specified.
860 // Need to check how the old code handled this, and whether it's a significant change.
861 mStaticProxy->setLoop(0, mFrameCount, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800862 return NO_ERROR;
863}
864
Glenn Kasten38e905b2014-01-13 10:21:48 -0800865audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700866{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800867 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100868 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800869}
870
Eric Laurentbe916aa2010-06-01 23:49:17 -0700871status_t AudioTrack::attachAuxEffect(int effectId)
872{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800873 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700874 status_t status = mAudioTrack->attachAuxEffect(effectId);
875 if (status == NO_ERROR) {
876 mAuxEffectId = effectId;
877 }
878 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700879}
880
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800881// -------------------------------------------------------------------------
882
Eric Laurent1703cdf2011-03-07 14:52:59 -0800883// must be called with mLock held
Glenn Kasten363fb752014-01-15 12:27:31 -0800884status_t AudioTrack::createTrack_l(size_t epoch)
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800885{
886 status_t status;
887 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
888 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700889 ALOGE("Could not get audioflinger");
890 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800891 }
892
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700893 audio_io_handle_t output = AudioSystem::getOutputForAttr(&mAttributes, mSampleRate, mFormat,
Glenn Kasten38e905b2014-01-13 10:21:48 -0800894 mChannelMask, mFlags, mOffloadInfo);
Glenn Kasten142f5192014-03-25 17:44:59 -0700895 if (output == AUDIO_IO_HANDLE_NONE) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700896 ALOGE("Could not get audio output for stream type %d, usage %d, sample rate %u, format %#x,"
897 " channel mask %#x, flags %#x",
898 mStreamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800899 return BAD_VALUE;
900 }
901 {
902 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
903 // we must release it ourselves if anything goes wrong.
904
Glenn Kastence8828a2013-09-16 18:07:38 -0700905 // Not all of these values are needed under all conditions, but it is easier to get them all
906
Eric Laurentd1b449a2010-05-14 03:26:45 -0700907 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -0700908 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700909 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800910 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800911 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700912 }
913
Glenn Kastence8828a2013-09-16 18:07:38 -0700914 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700915 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -0700916 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700917 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800918 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700919 }
920
921 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700922 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -0700923 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700924 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800925 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700926 }
927
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700928 // Client decides whether the track is TIMED (see below), but can only express a preference
929 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800930 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700931 // either of these use cases:
932 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -0800933 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -0800934 // use case 2: callback transfer mode
935 (mTransfer == TRANSFER_CALLBACK)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800936 // matching sample rate
937 (mSampleRate == afSampleRate))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800938 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -0700939 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -0800940 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700941 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700942 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700943
Glenn Kastence8828a2013-09-16 18:07:38 -0700944 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -0800945 // n = 1 fast track with single buffering; nBuffering is ignored
946 // n = 2 fast track with double buffering
Glenn Kastence8828a2013-09-16 18:07:38 -0700947 // n = 2 normal track, no sample rate conversion
948 // n = 3 normal track, with sample rate conversion
949 // (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering)
950 // n > 3 very high latency or very small notification interval; nBuffering is ignored
Glenn Kasten363fb752014-01-15 12:27:31 -0800951 const uint32_t nBuffering = (mSampleRate == afSampleRate) ? 2 : 3;
Glenn Kastence8828a2013-09-16 18:07:38 -0700952
Eric Laurentd1b449a2010-05-14 03:26:45 -0700953 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700954
Glenn Kasten363fb752014-01-15 12:27:31 -0800955 size_t frameCount = mReqFrameCount;
956 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700957
Glenn Kasten363fb752014-01-15 12:27:31 -0800958 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700959 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -0800960 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -0700961 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700962 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700963 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100964 if (mNotificationFramesAct != frameCount) {
965 mNotificationFramesAct = frameCount;
966 }
Glenn Kasten363fb752014-01-15 12:27:31 -0800967 } else if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700968
Glenn Kastena42ff002012-11-14 12:47:55 -0800969 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -0700970 // 8-bit data in shared memory is not currently supported by AudioFlinger
Glenn Kastenb7730382014-04-30 15:50:31 -0700971 size_t alignment = audio_bytes_per_sample(
972 mFormat == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : mFormat);
973 if (alignment & 1) {
974 alignment = 1;
975 }
Glenn Kastena42ff002012-11-14 12:47:55 -0800976 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700977 // More than 2 channels does not require stronger alignment than stereo
978 alignment <<= 1;
979 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000980 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -0800981 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -0800982 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800983 status = BAD_VALUE;
984 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700985 }
986
987 // When initializing a shared buffer AudioTrack via constructors,
988 // there's no frameCount parameter.
989 // But when initializing a shared buffer AudioTrack via set(),
990 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kastenb7730382014-04-30 15:50:31 -0700991 frameCount = mSharedBuffer->size() / mFrameSizeAF;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700992
Glenn Kasten363fb752014-01-15 12:27:31 -0800993 } else if (!(mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700994
995 // FIXME move these calculations and associated checks to server
Glenn Kastene0fa4672012-04-24 14:35:14 -0700996
Eric Laurentd1b449a2010-05-14 03:26:45 -0700997 // Ensure that buffer depth covers at least audio hardware latency
998 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700999 ALOGV("afFrameCount=%zu, minBufCount=%d, afSampleRate=%u, afLatency=%d",
Glenn Kastenbb6f0a02013-06-03 15:00:29 -07001000 afFrameCount, minBufCount, afSampleRate, afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001001 if (minBufCount <= nBuffering) {
1002 minBufCount = nBuffering;
Glenn Kasten7c027242012-12-26 14:43:16 -08001003 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001004
Glenn Kasten363fb752014-01-15 12:27:31 -08001005 size_t minFrameCount = (afFrameCount*mSampleRate*minBufCount)/afSampleRate;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001006 ALOGV("minFrameCount: %zu, afFrameCount=%zu, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -08001007 ", afLatency=%d",
Glenn Kasten363fb752014-01-15 12:27:31 -08001008 minFrameCount, afFrameCount, minBufCount, mSampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001009
1010 if (frameCount == 0) {
1011 frameCount = minFrameCount;
Glenn Kastence8828a2013-09-16 18:07:38 -07001012 } else if (frameCount < minFrameCount) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001013 // not ALOGW because it happens all the time when playing key clicks over A2DP
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001014 ALOGV("Minimum buffer size corrected from %zu to %zu",
Glenn Kastene0fa4672012-04-24 14:35:14 -07001015 frameCount, minFrameCount);
1016 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001017 }
Glenn Kastence8828a2013-09-16 18:07:38 -07001018 // Make sure that application is notified with sufficient margin before underrun
1019 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1020 mNotificationFramesAct = frameCount/nBuffering;
1021 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001022
Glenn Kastene0fa4672012-04-24 14:35:14 -07001023 } else {
1024 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -07001025 }
1026
Glenn Kastena075db42012-03-06 11:22:44 -08001027 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1028 if (mIsTimed) {
1029 trackFlags |= IAudioFlinger::TRACK_TIMED;
1030 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001031
1032 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001033 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001034 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001035 if (mAudioTrackThread != 0) {
1036 tid = mAudioTrackThread->getTid();
1037 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001038 }
1039
Glenn Kasten363fb752014-01-15 12:27:31 -08001040 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001041 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1042 }
1043
Eric Laurentab5cdba2014-06-09 17:22:27 -07001044 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1045 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1046 }
1047
Glenn Kasten74935e42013-12-19 08:56:45 -08001048 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1049 // but we will still need the original value also
Glenn Kasten363fb752014-01-15 12:27:31 -08001050 sp<IAudioTrack> track = audioFlinger->createTrack(mStreamType,
1051 mSampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -07001052 // AudioFlinger only sees 16-bit PCM
Glenn Kastenc4b88a82014-04-30 16:54:30 -07001053 mFormat == AUDIO_FORMAT_PCM_8_BIT &&
1054 !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ?
Glenn Kasten363fb752014-01-15 12:27:31 -08001055 AUDIO_FORMAT_PCM_16_BIT : mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001056 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001057 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001058 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001059 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001060 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001061 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001062 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001063 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001064 &status);
1065
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001066 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001067 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001068 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001069 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001070 ALOG_ASSERT(track != 0);
1071
Glenn Kasten38e905b2014-01-13 10:21:48 -08001072 // AudioFlinger now owns the reference to the I/O handle,
1073 // so we are no longer responsible for releasing it.
1074
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001075 sp<IMemory> iMem = track->getCblk();
1076 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001077 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001078 return NO_INIT;
1079 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001080 void *iMemPointer = iMem->pointer();
1081 if (iMemPointer == NULL) {
1082 ALOGE("Could not get control block pointer");
1083 return NO_INIT;
1084 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001085 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001086 if (mAudioTrack != 0) {
1087 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
1088 mDeathNotifier.clear();
1089 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001090 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001091 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001092 IPCThreadState::self()->flushCommands();
1093
Glenn Kasten0cde0762014-01-16 15:06:36 -08001094 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001095 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001096 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001097 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1098 // In current design, AudioTrack client checks and ensures frame count validity before
1099 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1100 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001101 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001102 }
1103 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001104
Glenn Kastena07f17c2013-04-23 12:39:37 -07001105 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001106 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001107 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001108 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001109 mAwaitBoost = true;
Glenn Kasten363fb752014-01-15 12:27:31 -08001110 if (mSharedBuffer == 0) {
Glenn Kastenb5fed682013-12-03 09:06:43 -08001111 // Theoretically double-buffering is not required for fast tracks,
1112 // due to tighter scheduling. But in practice, to accommodate kernels with
1113 // scheduling jitter, and apps with computation jitter, we use double-buffering.
1114 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1115 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001116 }
1117 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001118 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001119 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001120 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001121 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1122 if (mSharedBuffer == 0) {
Glenn Kastence8828a2013-09-16 18:07:38 -07001123 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1124 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001125 }
1126 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001127 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001128 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001129 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001130 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1131 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1132 } else {
1133 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001134 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001135 // FIXME This is a warning, not an error, so don't return error status
1136 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001137 }
1138 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001139 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1140 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1141 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1142 } else {
1143 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1144 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1145 // FIXME This is a warning, not an error, so don't return error status
1146 //return NO_INIT;
1147 }
1148 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001149
Glenn Kasten38e905b2014-01-13 10:21:48 -08001150 // We retain a copy of the I/O handle, but don't own the reference
1151 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001152 mRefreshRemaining = true;
1153
1154 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1155 // is the value of pointer() for the shared buffer, otherwise buffers points
1156 // immediately after the control block. This address is for the mapping within client
1157 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1158 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001159 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001160 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001161 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001162 buffers = mSharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001163 }
1164
Eric Laurent2beeb502010-07-16 07:43:46 -07001165 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001166 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001167 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001168
Glenn Kastenb6037442012-11-14 13:42:25 -08001169 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001170 // If IAudioTrack is re-created, don't let the requested frameCount
1171 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001172 if (frameCount > mReqFrameCount) {
1173 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001174 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001175
1176 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001177 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001178 mStaticProxy.clear();
1179 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1180 } else {
1181 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1182 mProxy = mStaticProxy;
1183 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001184 mProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001185 mProxy->setSendLevel(mSendLevel);
1186 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001187 mProxy->setEpoch(epoch);
1188 mProxy->setMinimum(mNotificationFramesAct);
1189
1190 mDeathNotifier = new DeathNotifier(this);
1191 mAudioTrack->asBinder()->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001192
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001193 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001194 }
1195
1196release:
1197 AudioSystem::releaseOutput(output);
1198 if (status == NO_ERROR) {
1199 status = NO_INIT;
1200 }
1201 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001202}
1203
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001204status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1205{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001206 if (audioBuffer == NULL) {
1207 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001208 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001209 if (mTransfer != TRANSFER_OBTAIN) {
1210 audioBuffer->frameCount = 0;
1211 audioBuffer->size = 0;
1212 audioBuffer->raw = NULL;
1213 return INVALID_OPERATION;
1214 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001215
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001216 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001217 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001218 if (waitCount == -1) {
1219 requested = &ClientProxy::kForever;
1220 } else if (waitCount == 0) {
1221 requested = &ClientProxy::kNonBlocking;
1222 } else if (waitCount > 0) {
1223 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001224 timeout.tv_sec = ms / 1000;
1225 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1226 requested = &timeout;
1227 } else {
1228 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1229 requested = NULL;
1230 }
1231 return obtainBuffer(audioBuffer, requested);
1232}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001233
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001234status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1235 struct timespec *elapsed, size_t *nonContig)
1236{
1237 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1238 uint32_t oldSequence = 0;
1239 uint32_t newSequence;
1240
1241 Proxy::Buffer buffer;
1242 status_t status = NO_ERROR;
1243
1244 static const int32_t kMaxTries = 5;
1245 int32_t tryCounter = kMaxTries;
1246
1247 do {
1248 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1249 // keep them from going away if another thread re-creates the track during obtainBuffer()
1250 sp<AudioTrackClientProxy> proxy;
1251 sp<IMemory> iMem;
1252
1253 { // start of lock scope
1254 AutoMutex lock(mLock);
1255
1256 newSequence = mSequence;
1257 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1258 if (status == DEAD_OBJECT) {
1259 // re-create track, unless someone else has already done so
1260 if (newSequence == oldSequence) {
1261 status = restoreTrack_l("obtainBuffer");
1262 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001263 buffer.mFrameCount = 0;
1264 buffer.mRaw = NULL;
1265 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001266 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001267 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001268 }
1269 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001270 oldSequence = newSequence;
1271
1272 // Keep the extra references
1273 proxy = mProxy;
1274 iMem = mCblkMemory;
1275
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001276 if (mState == STATE_STOPPING) {
1277 status = -EINTR;
1278 buffer.mFrameCount = 0;
1279 buffer.mRaw = NULL;
1280 buffer.mNonContig = 0;
1281 break;
1282 }
1283
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001284 // Non-blocking if track is stopped or paused
1285 if (mState != STATE_ACTIVE) {
1286 requested = &ClientProxy::kNonBlocking;
1287 }
1288
1289 } // end of lock scope
1290
1291 buffer.mFrameCount = audioBuffer->frameCount;
1292 // FIXME starts the requested timeout and elapsed over from scratch
1293 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1294
1295 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1296
1297 audioBuffer->frameCount = buffer.mFrameCount;
1298 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1299 audioBuffer->raw = buffer.mRaw;
1300 if (nonContig != NULL) {
1301 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001302 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001303 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001304}
1305
1306void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1307{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001308 if (mTransfer == TRANSFER_SHARED) {
1309 return;
1310 }
1311
1312 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1313 if (stepCount == 0) {
1314 return;
1315 }
1316
1317 Proxy::Buffer buffer;
1318 buffer.mFrameCount = stepCount;
1319 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001320
Eric Laurent1703cdf2011-03-07 14:52:59 -08001321 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001322 mInUnderrun = false;
1323 mProxy->releaseBuffer(&buffer);
1324
1325 // restart track if it was disabled by audioflinger due to previous underrun
1326 if (mState == STATE_ACTIVE) {
1327 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001328 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001329 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001330 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001331 mAudioTrack->start();
1332 }
1333 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001334}
1335
1336// -------------------------------------------------------------------------
1337
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001338ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001339{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001340 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001341 return INVALID_OPERATION;
1342 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001343
Eric Laurentab5cdba2014-06-09 17:22:27 -07001344 if (isDirect()) {
1345 AutoMutex lock(mLock);
1346 int32_t flags = android_atomic_and(
1347 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1348 &mCblk->mFlags);
1349 if (flags & CBLK_INVALID) {
1350 return DEAD_OBJECT;
1351 }
1352 }
1353
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001354 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001355 // Sanity-check: user is most-likely passing an error code, and it would
1356 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001357 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001358 return BAD_VALUE;
1359 }
1360
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001361 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001362 Buffer audioBuffer;
1363
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001364 while (userSize >= mFrameSize) {
1365 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001366
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001367 status_t err = obtainBuffer(&audioBuffer,
1368 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001369 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001370 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001371 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001372 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001373 return ssize_t(err);
1374 }
1375
1376 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001377 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001378 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001379 toWrite = audioBuffer.size >> 1;
1380 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001381 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001382 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001383 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001384 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001385 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001386 userSize -= toWrite;
1387 written += toWrite;
1388
1389 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001390 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001391
1392 return written;
1393}
1394
1395// -------------------------------------------------------------------------
1396
John Grossman4ff14ba2012-02-08 16:37:41 -08001397TimedAudioTrack::TimedAudioTrack() {
1398 mIsTimed = true;
1399}
1400
1401status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1402{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001403 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001404 status_t result = UNKNOWN_ERROR;
1405
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001406#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001407 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1408 // while we are accessing the cblk
1409 sp<IAudioTrack> audioTrack = mAudioTrack;
1410 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001411#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001412
John Grossman4ff14ba2012-02-08 16:37:41 -08001413 // If the track is not invalid already, try to allocate a buffer. alloc
1414 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001415 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001416 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001417 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001418 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1419 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001420 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001421 }
1422 }
1423
1424 // If the track is invalid at this point, attempt to restore it. and try the
1425 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001426 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001427 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001428
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001429 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001430 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001431 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001432 }
1433
1434 return result;
1435}
1436
1437status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1438 int64_t pts)
1439{
Eric Laurentdf839842012-05-31 14:27:14 -07001440 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1441 {
1442 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001443 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001444 // restart track if it was disabled by audioflinger due to previous underrun
1445 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001446 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1447 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001448 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001449 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001450 mAudioTrack->start();
1451 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001452 }
Eric Laurentdf839842012-05-31 14:27:14 -07001453 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001454}
1455
1456status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1457 TargetTimeline target)
1458{
1459 return mAudioTrack->setMediaTimeTransform(xform, target);
1460}
1461
1462// -------------------------------------------------------------------------
1463
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001464nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001465{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001466 // Currently the AudioTrack thread is not created if there are no callbacks.
1467 // Would it ever make sense to run the thread, even without callbacks?
1468 // If so, then replace this by checks at each use for mCbf != NULL.
1469 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1470
Eric Laurent1703cdf2011-03-07 14:52:59 -08001471 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001472 if (mAwaitBoost) {
1473 mAwaitBoost = false;
1474 mLock.unlock();
1475 static const int32_t kMaxTries = 5;
1476 int32_t tryCounter = kMaxTries;
1477 uint32_t pollUs = 10000;
1478 do {
1479 int policy = sched_getscheduler(0);
1480 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1481 break;
1482 }
1483 usleep(pollUs);
1484 pollUs <<= 1;
1485 } while (tryCounter-- > 0);
1486 if (tryCounter < 0) {
1487 ALOGE("did not receive expected priority boost on time");
1488 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001489 // Run again immediately
1490 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001491 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001492
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001493 // Can only reference mCblk while locked
1494 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001495 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001496
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001497 // Check for track invalidation
1498 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001499 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1500 // AudioSystem cache. We should not exit here but after calling the callback so
1501 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001502 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001503 status_t status = restoreTrack_l("processAudioBuffer");
1504 mLock.unlock();
1505 // Run again immediately, but with a new IAudioTrack
1506 return 0;
1507 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001508 }
1509
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001510 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001511 bool active = mState == STATE_ACTIVE;
1512
1513 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1514 bool newUnderrun = false;
1515 if (flags & CBLK_UNDERRUN) {
1516#if 0
1517 // Currently in shared buffer mode, when the server reaches the end of buffer,
1518 // the track stays active in continuous underrun state. It's up to the application
1519 // to pause or stop the track, or set the position to a new offset within buffer.
1520 // This was some experimental code to auto-pause on underrun. Keeping it here
1521 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1522 if (mTransfer == TRANSFER_SHARED) {
1523 mState = STATE_PAUSED;
1524 active = false;
1525 }
1526#endif
1527 if (!mInUnderrun) {
1528 mInUnderrun = true;
1529 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001530 }
1531 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001532
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001533 // Get current position of server
1534 size_t position = mProxy->getPosition();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001535
1536 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001537 bool markerReached = false;
1538 size_t markerPosition = mMarkerPosition;
1539 // FIXME fails for wraparound, need 64 bits
1540 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1541 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001542 }
1543
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001544 // Determine number of new position callback(s) that will be needed, while locked
1545 size_t newPosCount = 0;
1546 size_t newPosition = mNewPosition;
1547 size_t updatePeriod = mUpdatePeriod;
1548 // FIXME fails for wraparound, need 64 bits
1549 if (updatePeriod > 0 && position >= newPosition) {
1550 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1551 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001552 }
1553
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001554 // Cache other fields that will be needed soon
1555 uint32_t loopPeriod = mLoopPeriod;
1556 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001557 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001558 if (mRefreshRemaining) {
1559 mRefreshRemaining = false;
1560 mRemainingFrames = notificationFrames;
1561 mRetryOnPartialBuffer = false;
1562 }
1563 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001564 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001565 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001566
1567 // These fields don't need to be cached, because they are assigned only by set():
1568 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1569 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1570
1571 mLock.unlock();
1572
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001573 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001574 struct timespec timeout;
1575 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1576 timeout.tv_nsec = 0;
1577
Glenn Kasten96f04882013-09-20 09:28:56 -07001578 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001579 switch (status) {
1580 case NO_ERROR:
1581 case DEAD_OBJECT:
1582 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001583 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001584 {
1585 AutoMutex lock(mLock);
1586 // The previously assigned value of waitStreamEnd is no longer valid,
1587 // since the mutex has been unlocked and either the callback handler
1588 // or another thread could have re-started the AudioTrack during that time.
1589 waitStreamEnd = mState == STATE_STOPPING;
1590 if (waitStreamEnd) {
1591 mState = STATE_STOPPED;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001592 }
1593 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001594 if (waitStreamEnd && status != DEAD_OBJECT) {
1595 return NS_INACTIVE;
1596 }
1597 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001598 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001599 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001600 }
1601
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001602 // perform callbacks while unlocked
1603 if (newUnderrun) {
1604 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1605 }
1606 // FIXME we will miss loops if loop cycle was signaled several times since last call
1607 // to processAudioBuffer()
1608 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1609 mCbf(EVENT_LOOP_END, mUserData, NULL);
1610 }
1611 if (flags & CBLK_BUFFER_END) {
1612 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1613 }
1614 if (markerReached) {
1615 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1616 }
1617 while (newPosCount > 0) {
1618 size_t temp = newPosition;
1619 mCbf(EVENT_NEW_POS, mUserData, &temp);
1620 newPosition += updatePeriod;
1621 newPosCount--;
1622 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001623
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001624 if (mObservedSequence != sequence) {
1625 mObservedSequence = sequence;
1626 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001627 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001628 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001629 return NS_INACTIVE;
1630 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001631 }
1632
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001633 // if inactive, then don't run me again until re-started
1634 if (!active) {
1635 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001636 }
1637
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001638 // Compute the estimated time until the next timed event (position, markers, loops)
1639 // FIXME only for non-compressed audio
1640 uint32_t minFrames = ~0;
1641 if (!markerReached && position < markerPosition) {
1642 minFrames = markerPosition - position;
1643 }
1644 if (loopPeriod > 0 && loopPeriod < minFrames) {
1645 minFrames = loopPeriod;
1646 }
1647 if (updatePeriod > 0 && updatePeriod < minFrames) {
1648 minFrames = updatePeriod;
1649 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001650
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001651 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1652 static const uint32_t kPoll = 0;
1653 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1654 minFrames = kPoll * notificationFrames;
1655 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001656
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001657 // Convert frame units to time units
1658 nsecs_t ns = NS_WHENEVER;
1659 if (minFrames != (uint32_t) ~0) {
1660 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1661 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1662 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1663 }
1664
1665 // If not supplying data by EVENT_MORE_DATA, then we're done
1666 if (mTransfer != TRANSFER_CALLBACK) {
1667 return ns;
1668 }
1669
1670 struct timespec timeout;
1671 const struct timespec *requested = &ClientProxy::kForever;
1672 if (ns != NS_WHENEVER) {
1673 timeout.tv_sec = ns / 1000000000LL;
1674 timeout.tv_nsec = ns % 1000000000LL;
1675 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1676 requested = &timeout;
1677 }
1678
1679 while (mRemainingFrames > 0) {
1680
1681 Buffer audioBuffer;
1682 audioBuffer.frameCount = mRemainingFrames;
1683 size_t nonContig;
1684 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1685 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001686 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001687 requested = &ClientProxy::kNonBlocking;
1688 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001689 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001690 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001691 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001692 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1693 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001694 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001695 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001696 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1697 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001698 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001699
Eric Laurent42a6f422013-08-29 14:35:05 -07001700 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001701 mRetryOnPartialBuffer = false;
1702 if (avail < mRemainingFrames) {
1703 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1704 if (ns < 0 || myns < ns) {
1705 ns = myns;
1706 }
1707 return ns;
1708 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001709 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001710
1711 // Divide buffer size by 2 to take into account the expansion
1712 // due to 8 to 16 bit conversion: the callback must fill only half
1713 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001714 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001715 audioBuffer.size >>= 1;
1716 }
1717
1718 size_t reqSize = audioBuffer.size;
1719 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001720 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001721
1722 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001723 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001724 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1725 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001726 return NS_NEVER;
1727 }
1728
1729 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001730 // The callback is done filling buffers
1731 // Keep this thread going to handle timed events and
1732 // still try to get more data in intervals of WAIT_PERIOD_MS
1733 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001734 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001735 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001736
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001737 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001738 // 8 to 16 bit conversion, note that source and destination are the same address
1739 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001740 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001741 }
1742
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001743 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1744 audioBuffer.frameCount = releasedFrames;
1745 mRemainingFrames -= releasedFrames;
1746 if (misalignment >= releasedFrames) {
1747 misalignment -= releasedFrames;
1748 } else {
1749 misalignment = 0;
1750 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001751
1752 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001753
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001754 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1755 // if callback doesn't like to accept the full chunk
1756 if (writtenSize < reqSize) {
1757 continue;
1758 }
1759
1760 // There could be enough non-contiguous frames available to satisfy the remaining request
1761 if (mRemainingFrames <= nonContig) {
1762 continue;
1763 }
1764
1765#if 0
1766 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1767 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1768 // that total to a sum == notificationFrames.
1769 if (0 < misalignment && misalignment <= mRemainingFrames) {
1770 mRemainingFrames = misalignment;
1771 return (mRemainingFrames * 1100000000LL) / sampleRate;
1772 }
1773#endif
1774
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001775 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001776 mRemainingFrames = notificationFrames;
1777 mRetryOnPartialBuffer = true;
1778
1779 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1780 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001781}
1782
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001783status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001784{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001785 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001786 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001787 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001788 status_t result;
1789
Glenn Kastena47f3162012-11-07 10:13:08 -08001790 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kasten38e905b2014-01-13 10:21:48 -08001791 // output parameters in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001792 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001793
Eric Laurentab5cdba2014-06-09 17:22:27 -07001794 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001795 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001796 return DEAD_OBJECT;
1797 }
1798
Glenn Kastena47f3162012-11-07 10:13:08 -08001799 // if the new IAudioTrack is created, createTrack_l() will modify the
1800 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1801 // It will also delete the strong references on previous IAudioTrack and IMemory
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001802
1803 // take the frames that will be lost by track recreation into account in saved position
1804 size_t position = mProxy->getPosition() + mProxy->getFramesFilled();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001805 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
Glenn Kasten363fb752014-01-15 12:27:31 -08001806 result = createTrack_l(position /*epoch*/);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001807
Glenn Kastena47f3162012-11-07 10:13:08 -08001808 if (result == NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001809 // continue playback from last known position, but
1810 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1811 if (mStaticProxy != NULL) {
1812 mLoopPeriod = 0;
1813 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1814 }
1815 // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1816 // track destruction have been played? This is critical for SoundPool implementation
1817 // This must be broken, and needs to be tested/debugged.
1818#if 0
Glenn Kastena47f3162012-11-07 10:13:08 -08001819 // restore write index and set other indexes to reflect empty buffer status
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001820 if (!strcmp(from, "start")) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001821 // Make sure that a client relying on callback events indicating underrun or
1822 // the actual amount of audio frames played (e.g SoundPool) receives them.
1823 if (mSharedBuffer == 0) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001824 // restart playback even if buffer is not completely filled.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001825 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001826 }
1827 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001828#endif
1829 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001830 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001831 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001832 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001833 if (result != NO_ERROR) {
1834 ALOGW("restoreTrack_l() failed status %d", result);
1835 mState = STATE_STOPPED;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001836 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001837
1838 return result;
1839}
1840
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001841status_t AudioTrack::setParameters(const String8& keyValuePairs)
1842{
1843 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001844 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001845}
1846
Glenn Kastence703742013-07-19 16:33:58 -07001847status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1848{
Glenn Kasten53cec222013-08-29 09:01:02 -07001849 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001850 // FIXME not implemented for fast tracks; should use proxy and SSQ
1851 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1852 return INVALID_OPERATION;
1853 }
1854 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
1855 return INVALID_OPERATION;
1856 }
1857 status_t status = mAudioTrack->getTimestamp(timestamp);
1858 if (status == NO_ERROR) {
1859 timestamp.mPosition += mProxy->getEpoch();
1860 }
1861 return status;
Glenn Kastence703742013-07-19 16:33:58 -07001862}
1863
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001864String8 AudioTrack::getParameters(const String8& keys)
1865{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08001866 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07001867 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08001868 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001869 } else {
1870 return String8::empty();
1871 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001872}
1873
Glenn Kasten23a75452014-01-13 10:37:17 -08001874bool AudioTrack::isOffloaded() const
1875{
1876 AutoMutex lock(mLock);
1877 return isOffloaded_l();
1878}
1879
Eric Laurentab5cdba2014-06-09 17:22:27 -07001880bool AudioTrack::isDirect() const
1881{
1882 AutoMutex lock(mLock);
1883 return isDirect_l();
1884}
1885
1886bool AudioTrack::isOffloadedOrDirect() const
1887{
1888 AutoMutex lock(mLock);
1889 return isOffloadedOrDirect_l();
1890}
1891
1892
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001893status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001894{
1895
1896 const size_t SIZE = 256;
1897 char buffer[SIZE];
1898 String8 result;
1899
1900 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001901 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07001902 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001903 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001904 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001905 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001906 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001907 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001908 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001909 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001910 result.append(buffer);
1911 ::write(fd, result.string(), result.size());
1912 return NO_ERROR;
1913}
1914
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001915uint32_t AudioTrack::getUnderrunFrames() const
1916{
1917 AutoMutex lock(mLock);
1918 return mProxy->getUnderrunFrames();
1919}
1920
Jean-Michel Trivifaabb512014-06-11 16:55:06 -07001921void AudioTrack::setAttributesFromStreamType(audio_stream_type_t streamType) {
1922 mAttributes.flags = 0x0;
1923
1924 switch(streamType) {
1925 case AUDIO_STREAM_DEFAULT:
1926 case AUDIO_STREAM_MUSIC:
1927 mAttributes.content_type = AUDIO_CONTENT_TYPE_MUSIC;
1928 mAttributes.usage = AUDIO_USAGE_MEDIA;
1929 break;
1930 case AUDIO_STREAM_VOICE_CALL:
1931 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1932 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION;
1933 break;
1934 case AUDIO_STREAM_ENFORCED_AUDIBLE:
1935 mAttributes.flags |= AUDIO_FLAG_AUDIBILITY_ENFORCED;
1936 // intended fall through, attributes in common with STREAM_SYSTEM
1937 case AUDIO_STREAM_SYSTEM:
1938 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1939 mAttributes.usage = AUDIO_USAGE_ASSISTANCE_SONIFICATION;
1940 break;
1941 case AUDIO_STREAM_RING:
1942 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1943 mAttributes.usage = AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE;
1944 break;
1945 case AUDIO_STREAM_ALARM:
1946 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1947 mAttributes.usage = AUDIO_USAGE_ALARM;
1948 break;
1949 case AUDIO_STREAM_NOTIFICATION:
1950 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1951 mAttributes.usage = AUDIO_USAGE_NOTIFICATION;
1952 break;
1953 case AUDIO_STREAM_BLUETOOTH_SCO:
1954 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1955 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION;
1956 mAttributes.flags |= AUDIO_FLAG_SCO;
1957 break;
1958 case AUDIO_STREAM_DTMF:
1959 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1960 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING;
1961 break;
1962 case AUDIO_STREAM_TTS:
1963 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1964 mAttributes.usage = AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY;
1965 break;
1966 default:
1967 ALOGE("invalid stream type %d when converting to attributes", streamType);
1968 }
1969}
1970
1971void AudioTrack::setStreamTypeFromAttributes(audio_attributes_t& aa) {
1972 // flags to stream type mapping
1973 if ((aa.flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
1974 mStreamType = AUDIO_STREAM_ENFORCED_AUDIBLE;
1975 return;
1976 }
1977 if ((aa.flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
1978 mStreamType = AUDIO_STREAM_BLUETOOTH_SCO;
1979 return;
1980 }
1981
1982 // usage to stream type mapping
1983 switch (aa.usage) {
1984 case AUDIO_USAGE_MEDIA:
1985 case AUDIO_USAGE_GAME:
1986 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
1987 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
1988 mStreamType = AUDIO_STREAM_MUSIC;
1989 return;
1990 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
1991 mStreamType = AUDIO_STREAM_SYSTEM;
1992 return;
1993 case AUDIO_USAGE_VOICE_COMMUNICATION:
1994 mStreamType = AUDIO_STREAM_VOICE_CALL;
1995 return;
1996
1997 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
1998 mStreamType = AUDIO_STREAM_DTMF;
1999 return;
2000
2001 case AUDIO_USAGE_ALARM:
2002 mStreamType = AUDIO_STREAM_ALARM;
2003 return;
2004 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
2005 mStreamType = AUDIO_STREAM_RING;
2006 return;
2007
2008 case AUDIO_USAGE_NOTIFICATION:
2009 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
2010 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
2011 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
2012 case AUDIO_USAGE_NOTIFICATION_EVENT:
2013 mStreamType = AUDIO_STREAM_NOTIFICATION;
2014 return;
2015
2016 case AUDIO_USAGE_UNKNOWN:
2017 default:
2018 mStreamType = AUDIO_STREAM_MUSIC;
2019 }
2020}
2021
2022bool AudioTrack::isValidAttributes(const audio_attributes_t *paa) {
2023 // has flags that map to a strategy?
2024 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO)) != 0) {
2025 return true;
2026 }
2027
2028 // has known usage?
2029 switch (paa->usage) {
2030 case AUDIO_USAGE_UNKNOWN:
2031 case AUDIO_USAGE_MEDIA:
2032 case AUDIO_USAGE_VOICE_COMMUNICATION:
2033 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
2034 case AUDIO_USAGE_ALARM:
2035 case AUDIO_USAGE_NOTIFICATION:
2036 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
2037 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
2038 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
2039 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
2040 case AUDIO_USAGE_NOTIFICATION_EVENT:
2041 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
2042 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
2043 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
2044 case AUDIO_USAGE_GAME:
2045 break;
2046 default:
2047 return false;
2048 }
2049 return true;
2050}
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002051// =========================================================================
2052
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002053void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002054{
2055 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2056 if (audioTrack != 0) {
2057 AutoMutex lock(audioTrack->mLock);
2058 audioTrack->mProxy->binderDied();
2059 }
2060}
2061
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002062// =========================================================================
2063
2064AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002065 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2066 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002067{
2068}
2069
2070AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002071{
2072}
2073
2074bool AudioTrack::AudioTrackThread::threadLoop()
2075{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002076 {
2077 AutoMutex _l(mMyLock);
2078 if (mPaused) {
2079 mMyCond.wait(mMyLock);
2080 // caller will check for exitPending()
2081 return true;
2082 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002083 if (mIgnoreNextPausedInt) {
2084 mIgnoreNextPausedInt = false;
2085 mPausedInt = false;
2086 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002087 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002088 if (mPausedNs > 0) {
2089 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2090 } else {
2091 mMyCond.wait(mMyLock);
2092 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002093 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002094 return true;
2095 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002096 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002097 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002098 switch (ns) {
2099 case 0:
2100 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002101 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002102 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002103 return true;
2104 case NS_NEVER:
2105 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002106 case NS_WHENEVER:
2107 // FIXME increase poll interval, or make event-driven
2108 ns = 1000000000LL;
2109 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002110 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002111 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002112 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002113 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002114 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002115}
2116
Glenn Kasten3acbd052012-02-28 10:39:56 -08002117void AudioTrack::AudioTrackThread::requestExit()
2118{
2119 // must be in this order to avoid a race condition
2120 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002121 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002122}
2123
2124void AudioTrack::AudioTrackThread::pause()
2125{
2126 AutoMutex _l(mMyLock);
2127 mPaused = true;
2128}
2129
2130void AudioTrack::AudioTrackThread::resume()
2131{
2132 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002133 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002134 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002135 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002136 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002137 mMyCond.signal();
2138 }
2139}
2140
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002141void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2142{
2143 AutoMutex _l(mMyLock);
2144 mPausedInt = true;
2145 mPausedNs = ns;
2146}
2147
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002148}; // namespace android