blob: b18a52843ff2c9ee7e9aac3cac45f9622deded48 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080018//#define LOG_NDEBUG 0
19#define LOG_TAG "AudioTrack"
20
Mark Salyzyn34fb2962014-06-18 16:30:56 -070021#include <inttypes.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070022#include <math.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080023#include <sys/resource.h>
Mark Salyzyn34fb2962014-06-18 16:30:56 -070024
Glenn Kasten9f80dd22012-12-18 15:57:32 -080025#include <audio_utils/primitives.h>
26#include <binder/IPCThreadState.h>
27#include <media/AudioTrack.h>
28#include <utils/Log.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080029#include <private/media/AudioTrackShared.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/IAudioFlinger.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080032
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010033#define WAIT_PERIOD_MS 10
34#define WAIT_STREAM_END_TIMEOUT_SEC 120
35
Glenn Kasten511754b2012-01-11 09:52:19 -080036
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080037namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080038// ---------------------------------------------------------------------------
39
Andy Hung7f1bc8a2014-09-12 14:43:11 -070040static int64_t convertTimespecToUs(const struct timespec &tv)
41{
42 return tv.tv_sec * 1000000ll + tv.tv_nsec / 1000;
43}
44
45// current monotonic time in microseconds.
46static int64_t getNowUs()
47{
48 struct timespec tv;
49 (void) clock_gettime(CLOCK_MONOTONIC, &tv);
50 return convertTimespecToUs(tv);
51}
52
Chia-chi Yeh33005a92010-06-16 06:33:13 +080053// static
54status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080055 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080056 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080057 uint32_t sampleRate)
58{
Glenn Kastend65d73c2012-06-22 17:21:07 -070059 if (frameCount == NULL) {
60 return BAD_VALUE;
61 }
Glenn Kasten04cd0182012-06-25 11:49:27 -070062
Glenn Kastene0fa4672012-04-24 14:35:14 -070063 // FIXME merge with similar code in createTrack_l(), except we're missing
64 // some information here that is available in createTrack_l():
65 // audio_io_handle_t output
66 // audio_format_t format
67 // audio_channel_mask_t channelMask
68 // audio_output_flags_t flags
Glenn Kasten3b16c762012-11-14 08:44:39 -080069 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080070 status_t status;
71 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
72 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080073 ALOGE("Unable to query output sample rate 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 }
Glenn Kastene33054e2012-11-14 12:54:39 -080077 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -080078 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
79 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080080 ALOGE("Unable to query output frame count for stream type %d; status %d",
81 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080082 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080083 }
84 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -080085 status = AudioSystem::getOutputLatency(&afLatency, streamType);
86 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080087 ALOGE("Unable to query output latency for stream type %d; status %d",
88 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080089 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080090 }
91
92 // Ensure that buffer depth covers at least audio hardware latency
93 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080094 if (minBufCount < 2) {
95 minBufCount = 2;
96 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +080097
98 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
Andy Hungcd044842014-08-07 11:04:34 -070099 afFrameCount * minBufCount * uint64_t(sampleRate) / afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -0800100 // The formula above should always produce a non-zero value, but return an error
101 // in the unlikely event that it does not, as that's part of the API contract.
102 if (*frameCount == 0) {
103 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %d",
104 streamType, sampleRate);
105 return BAD_VALUE;
106 }
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700107 ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, minBufCount=%d, afSampleRate=%d, afLatency=%d",
Glenn Kasten3acbd052012-02-28 10:39:56 -0800108 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800109 return NO_ERROR;
110}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800111
112// ---------------------------------------------------------------------------
113
114AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700115 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800116 mIsTimed(false),
117 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800118 mPreviousSchedulingGroup(SP_DEFAULT),
119 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800120{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700121 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
122 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
123 mAttributes.flags = 0x0;
124 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800125}
126
127AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800128 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800129 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800130 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700131 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800132 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700133 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800134 callback_t cbf,
135 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800136 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800137 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000138 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800139 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800140 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700141 pid_t pid,
142 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700143 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800144 mIsTimed(false),
145 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800146 mPreviousSchedulingGroup(SP_DEFAULT),
147 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800148{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700149 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700150 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800151 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700152 offloadInfo, uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800153}
154
Andreas Huberc8139852012-01-18 10:51:55 -0800155AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800156 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800157 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800158 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700159 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800160 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700161 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800162 callback_t cbf,
163 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800164 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800165 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000166 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800167 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800168 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700169 pid_t pid,
170 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700171 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800172 mIsTimed(false),
173 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800174 mPreviousSchedulingGroup(SP_DEFAULT),
175 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800176{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700177 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800178 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800179 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700180 uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800181}
182
183AudioTrack::~AudioTrack()
184{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800185 if (mStatus == NO_ERROR) {
186 // Make sure that callback function exits in the case where
187 // it is looping on buffer full condition in obtainBuffer().
188 // Otherwise the callback thread will never exit.
189 stop();
190 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100191 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800192 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800193 mAudioTrackThread->requestExitAndWait();
194 mAudioTrackThread.clear();
195 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800196 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700197 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700198 mCblkMemory.clear();
199 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800200 IPCThreadState::self()->flushCommands();
Marco Nelissend457c972014-02-11 08:47:07 -0800201 ALOGV("~AudioTrack, releasing session id from %d on behalf of %d",
202 IPCThreadState::self()->getCallingPid(), mClientPid);
203 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800204 }
205}
206
207status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800208 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800209 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800210 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700211 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800212 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700213 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800214 callback_t cbf,
215 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800216 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800217 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700218 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800219 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000220 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800221 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800222 int uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700223 pid_t pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700224 const audio_attributes_t* pAttributes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800225{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800226 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten838b3d82014-02-27 15:30:41 -0800227 "flags #%x, notificationFrames %u, sessionId %d, transferType %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800228 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten86f04662014-02-24 15:13:05 -0800229 sessionId, transferType);
230
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800231 switch (transferType) {
232 case TRANSFER_DEFAULT:
233 if (sharedBuffer != 0) {
234 transferType = TRANSFER_SHARED;
235 } else if (cbf == NULL || threadCanCallJava) {
236 transferType = TRANSFER_SYNC;
237 } else {
238 transferType = TRANSFER_CALLBACK;
239 }
240 break;
241 case TRANSFER_CALLBACK:
242 if (cbf == NULL || sharedBuffer != 0) {
243 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
244 return BAD_VALUE;
245 }
246 break;
247 case TRANSFER_OBTAIN:
248 case TRANSFER_SYNC:
249 if (sharedBuffer != 0) {
250 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
251 return BAD_VALUE;
252 }
253 break;
254 case TRANSFER_SHARED:
255 if (sharedBuffer == 0) {
256 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
257 return BAD_VALUE;
258 }
259 break;
260 default:
261 ALOGE("Invalid transfer type %d", transferType);
262 return BAD_VALUE;
263 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800264 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800265 mTransfer = transferType;
266
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700267 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
268 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800269
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700270 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700271
Eric Laurent1703cdf2011-03-07 14:52:59 -0800272 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800273
Glenn Kasten53cec222013-08-29 09:01:02 -0700274 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700275 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000276 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800277 return INVALID_OPERATION;
278 }
279
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800280 // handle default values first.
Dima Zavinfce7a472011-04-19 22:30:36 -0700281 if (streamType == AUDIO_STREAM_DEFAULT) {
282 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800283 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700284
285 if (pAttributes == NULL) {
286 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
287 ALOGE("Invalid stream type %d", streamType);
288 return BAD_VALUE;
289 }
290 setAttributesFromStreamType(streamType);
291 mStreamType = streamType;
292 } else {
293 if (!isValidAttributes(pAttributes)) {
294 ALOGE("Invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
295 pAttributes->usage, pAttributes->content_type, pAttributes->flags,
296 pAttributes->tags);
297 }
298 // stream type shouldn't be looked at, this track has audio attributes
299 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
300 setStreamTypeFromAttributes(mAttributes);
301 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
302 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800303 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700304
Glenn Kastenb1bef512014-01-13 10:25:53 -0800305 status_t status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800306 if (sampleRate == 0) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700307 status = AudioSystem::getOutputSamplingRateForAttr(&sampleRate, &mAttributes);
Glenn Kastenb1bef512014-01-13 10:25:53 -0800308 if (status != NO_ERROR) {
309 ALOGE("Could not get output sample rate for stream type %d; status %d",
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700310 mStreamType, status);
Glenn Kastenb1bef512014-01-13 10:25:53 -0800311 return status;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700312 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800313 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800314 mSampleRate = sampleRate;
Glenn Kastenea7939a2012-03-14 12:56:26 -0700315
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800316 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800317 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700318 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800319 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800320
321 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700322 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800323 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800324 return BAD_VALUE;
325 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800326 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700327
Glenn Kasten8ba90322013-10-30 11:29:27 -0700328 if (!audio_is_output_channel(channelMask)) {
329 ALOGE("Invalid channel mask %#x", channelMask);
330 return BAD_VALUE;
331 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800332 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700333 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800334 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700335
Glenn Kastene0fa4672012-04-24 14:35:14 -0700336 // AudioFlinger does not currently support 8-bit data in shared memory
337 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
338 ALOGE("8-bit data in shared memory is not supported");
339 return BAD_VALUE;
340 }
341
Eric Laurentc2f1f072009-07-17 12:17:14 -0700342 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100343 // or offload was requested
344 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
345 || !audio_is_linear_pcm(format)) {
346 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
347 ? "Offload request, forcing to Direct Output"
348 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700349 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800350 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700351 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700352 }
Eric Laurent1948eb32012-04-13 16:50:19 -0700353 // only allow deep buffering for music stream type
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700354 if (mStreamType != AUDIO_STREAM_MUSIC) {
Eric Laurent1948eb32012-04-13 16:50:19 -0700355 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
356 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700357
Glenn Kastenb7730382014-04-30 15:50:31 -0700358 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
359 if (audio_is_linear_pcm(format)) {
360 mFrameSize = channelCount * audio_bytes_per_sample(format);
361 } else {
362 mFrameSize = sizeof(uint8_t);
363 }
364 mFrameSizeAF = mFrameSize;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800365 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700366 ALOG_ASSERT(audio_is_linear_pcm(format));
367 mFrameSize = channelCount * audio_bytes_per_sample(format);
368 mFrameSizeAF = channelCount * audio_bytes_per_sample(
369 format == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : format);
370 // createTrack will return an error if PCM format is not supported by server,
371 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800372 }
373
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800374 // Make copy of input parameter offloadInfo so that in the future:
375 // (a) createTrack_l doesn't need it as an input parameter
376 // (b) we can support re-creation of offloaded tracks
377 if (offloadInfo != NULL) {
378 mOffloadInfoCopy = *offloadInfo;
379 mOffloadInfo = &mOffloadInfoCopy;
380 } else {
381 mOffloadInfo = NULL;
382 }
383
Glenn Kasten66e46352014-01-16 17:44:23 -0800384 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
385 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800386 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800387 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800388 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700389 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800390 mNotificationFramesAct = 0;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700391 mSessionId = sessionId;
Marco Nelissend457c972014-02-11 08:47:07 -0800392 int callingpid = IPCThreadState::self()->getCallingPid();
393 int mypid = getpid();
394 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800395 mClientUid = IPCThreadState::self()->getCallingUid();
396 } else {
397 mClientUid = uid;
398 }
Marco Nelissend457c972014-02-11 08:47:07 -0800399 if (pid == -1 || (callingpid != mypid)) {
400 mClientPid = callingpid;
401 } else {
402 mClientPid = pid;
403 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700404 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700405 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700406 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700407
Glenn Kastena997e7a2012-08-07 09:44:19 -0700408 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700409 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700410 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
411 }
412
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800413 // create the IAudioTrack
Glenn Kasten200092b2014-08-15 15:13:30 -0700414 status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800415
Glenn Kastena997e7a2012-08-07 09:44:19 -0700416 if (status != NO_ERROR) {
417 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100418 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
419 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700420 mAudioTrackThread.clear();
421 }
422 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700423 }
424
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800425 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800426 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800427 mUserData = user;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800428 mLoopPeriod = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800429 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700430 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800431 mNewPosition = 0;
432 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700433 mServer = 0;
434 mPosition = 0;
435 mReleased = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700436 mStartUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800437 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800438 mSequence = 1;
439 mObservedSequence = mSequence;
440 mInUnderrun = false;
441
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800442 return NO_ERROR;
443}
444
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800445// -------------------------------------------------------------------------
446
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100447status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800448{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800449 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100450
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800451 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100452 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800453 }
454
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800455 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800456
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800457 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100458 if (previousState == STATE_PAUSED_STOPPING) {
459 mState = STATE_STOPPING;
460 } else {
461 mState = STATE_ACTIVE;
462 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700463 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800464 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
465 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700466 mPosition = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700467 // For offloaded tracks, we don't know if the hardware counters are really zero here,
468 // since the flush is asynchronous and stop may not fully drain.
469 // We save the time when the track is started to later verify whether
470 // the counters are realistic (i.e. start from zero after this time).
471 mStartUs = getNowUs();
472
Eric Laurentec9a0322013-08-28 10:23:01 -0700473 // force refresh of remaining frames by processAudioBuffer() as last
474 // write before stop could be partial.
475 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800476 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700477 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700478 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800479
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800480 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800481 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100482 if (previousState == STATE_STOPPING) {
483 mProxy->interrupt();
484 } else {
485 t->resume();
486 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800487 } else {
488 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
489 get_sched_policy(0, &mPreviousSchedulingGroup);
490 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
491 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800492
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800493 status_t status = NO_ERROR;
494 if (!(flags & CBLK_INVALID)) {
495 status = mAudioTrack->start();
496 if (status == DEAD_OBJECT) {
497 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800498 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800499 }
500 if (flags & CBLK_INVALID) {
501 status = restoreTrack_l("start");
502 }
503
504 if (status != NO_ERROR) {
505 ALOGE("start() status %d", status);
506 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800507 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100508 if (previousState != STATE_STOPPING) {
509 t->pause();
510 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800511 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700512 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700513 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800514 }
515 }
516
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100517 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800518}
519
520void AudioTrack::stop()
521{
522 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700523 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800524 return;
525 }
526
Glenn Kasten23a75452014-01-13 10:37:17 -0800527 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100528 mState = STATE_STOPPING;
529 } else {
530 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -0700531 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100532 }
533
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800534 mProxy->interrupt();
535 mAudioTrack->stop();
536 // the playback head position will reset to 0, so if a marker is set, we need
537 // to activate it again
538 mMarkerReached = false;
539#if 0
540 // Force flush if a shared buffer is used otherwise audioflinger
541 // will not stop before end of buffer is reached.
542 // It may be needed to make sure that we stop playback, likely in case looping is on.
543 if (mSharedBuffer != 0) {
544 flush_l();
545 }
546#endif
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100547
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800548 sp<AudioTrackThread> t = mAudioTrackThread;
549 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800550 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100551 t->pause();
552 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800553 } else {
554 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
555 set_sched_policy(0, mPreviousSchedulingGroup);
556 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800557}
558
559bool AudioTrack::stopped() const
560{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800561 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800562 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800563}
564
565void AudioTrack::flush()
566{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800567 if (mSharedBuffer != 0) {
568 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800569 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800570 AutoMutex lock(mLock);
571 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
572 return;
573 }
574 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800575}
576
Eric Laurent1703cdf2011-03-07 14:52:59 -0800577void AudioTrack::flush_l()
578{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800579 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700580
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700581 // clear playback marker and periodic update counter
582 mMarkerPosition = 0;
583 mMarkerReached = false;
584 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100585 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700586
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800587 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700588 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800589 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100590 mProxy->interrupt();
591 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800592 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800593 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800594}
595
596void AudioTrack::pause()
597{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800598 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100599 if (mState == STATE_ACTIVE) {
600 mState = STATE_PAUSED;
601 } else if (mState == STATE_STOPPING) {
602 mState = STATE_PAUSED_STOPPING;
603 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800604 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800605 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800606 mProxy->interrupt();
607 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800608
Marco Nelissen3a90f282014-03-10 11:21:43 -0700609 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700610 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700611 // An offload output can be re-used between two audio tracks having
612 // the same configuration. A timestamp query for a paused track
613 // while the other is running would return an incorrect time.
614 // To fix this, cache the playback position on a pause() and return
615 // this time when requested until the track is resumed.
616
617 // OffloadThread sends HAL pause in its threadLoop. Time saved
618 // here can be slightly off.
619
620 // TODO: check return code for getRenderPosition.
621
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800622 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800623 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
624 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
625 }
626 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800627}
628
Eric Laurentbe916aa2010-06-01 23:49:17 -0700629status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800630{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700631 // This duplicates a test by AudioTrack JNI, but that is not the only caller
632 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
633 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700634 return BAD_VALUE;
635 }
636
Eric Laurent1703cdf2011-03-07 14:52:59 -0800637 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800638 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
639 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800640
Glenn Kastenc56f3422014-03-21 17:53:17 -0700641 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700642
Glenn Kasten23a75452014-01-13 10:37:17 -0800643 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700644 mAudioTrack->signal();
645 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700646 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800647}
648
Glenn Kastenb1c09932012-02-27 16:21:04 -0800649status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800650{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800651 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700652}
653
Eric Laurent2beeb502010-07-16 07:43:46 -0700654status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700655{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700656 // This duplicates a test by AudioTrack JNI, but that is not the only caller
657 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700658 return BAD_VALUE;
659 }
660
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800661 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700662 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800663 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700664
665 return NO_ERROR;
666}
667
Glenn Kastena5224f32012-01-04 12:41:44 -0800668void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700669{
670 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800671 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700672 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800673}
674
Glenn Kasten3b16c762012-11-14 08:44:39 -0800675status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800676{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700677 if (mIsTimed || isOffloadedOrDirect()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800678 return INVALID_OPERATION;
679 }
680
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800681 uint32_t afSamplingRate;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700682 if (AudioSystem::getOutputSamplingRateForAttr(&afSamplingRate, &mAttributes) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700683 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800684 }
Andy Hungcd044842014-08-07 11:04:34 -0700685 if (rate == 0 || rate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700686 return BAD_VALUE;
687 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800688
Eric Laurent1703cdf2011-03-07 14:52:59 -0800689 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800690 mSampleRate = rate;
691 mProxy->setSampleRate(rate);
692
Eric Laurent57326622009-07-07 07:10:45 -0700693 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800694}
695
Glenn Kastena5224f32012-01-04 12:41:44 -0800696uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800697{
John Grossman4ff14ba2012-02-08 16:37:41 -0800698 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800699 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800700 }
701
Eric Laurent1703cdf2011-03-07 14:52:59 -0800702 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700703
704 // sample rate can be updated during playback by the offloaded decoder so we need to
705 // query the HAL and update if needed.
706// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700707 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700708 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700709 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700710 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700711 if (status == NO_ERROR) {
712 mSampleRate = sampleRate;
713 }
714 }
715 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800716 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800717}
718
719status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
720{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700721 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800722 return INVALID_OPERATION;
723 }
724
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800725 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800726 ;
727 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
728 loopEnd - loopStart >= MIN_LOOP) {
729 ;
730 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800731 return BAD_VALUE;
732 }
733
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800734 AutoMutex lock(mLock);
735 // See setPosition() regarding setting parameters such as loop points or position while active
736 if (mState == STATE_ACTIVE) {
737 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700738 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800739 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800740 return NO_ERROR;
741}
742
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800743void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
744{
745 // FIXME If setting a loop also sets position to start of loop, then
746 // this is correct. Otherwise it should be removed.
Glenn Kasten200092b2014-08-15 15:13:30 -0700747 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800748 mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0;
749 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
750}
751
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800752status_t AudioTrack::setMarkerPosition(uint32_t marker)
753{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700754 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700755 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700756 return INVALID_OPERATION;
757 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800758
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800759 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800760 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700761 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800762
763 return NO_ERROR;
764}
765
Glenn Kastena5224f32012-01-04 12:41:44 -0800766status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800767{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700768 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100769 return INVALID_OPERATION;
770 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700771 if (marker == NULL) {
772 return BAD_VALUE;
773 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800774
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800775 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800776 *marker = mMarkerPosition;
777
778 return NO_ERROR;
779}
780
781status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
782{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700783 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700784 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700785 return INVALID_OPERATION;
786 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800787
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800788 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700789 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800790 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800791
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800792 return NO_ERROR;
793}
794
Glenn Kastena5224f32012-01-04 12:41:44 -0800795status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800796{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700797 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100798 return INVALID_OPERATION;
799 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700800 if (updatePeriod == NULL) {
801 return BAD_VALUE;
802 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800803
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800804 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800805 *updatePeriod = mUpdatePeriod;
806
807 return NO_ERROR;
808}
809
810status_t AudioTrack::setPosition(uint32_t position)
811{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700812 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700813 return INVALID_OPERATION;
814 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800815 if (position > mFrameCount) {
816 return BAD_VALUE;
817 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800818
Eric Laurent1703cdf2011-03-07 14:52:59 -0800819 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800820 // Currently we require that the player is inactive before setting parameters such as position
821 // or loop points. Otherwise, there could be a race condition: the application could read the
822 // current position, compute a new position or loop parameters, and then set that position or
823 // loop parameters but it would do the "wrong" thing since the position has continued to advance
824 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
825 // to specify how it wants to handle such scenarios.
826 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700827 return INVALID_OPERATION;
828 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700829 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800830 mLoopPeriod = 0;
831 // FIXME Check whether loops and setting position are incompatible in old code.
832 // If we use setLoop for both purposes we lose the capability to set the position while looping.
833 mStaticProxy->setLoop(position, mFrameCount, 0);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700834
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800835 return NO_ERROR;
836}
837
Glenn Kasten200092b2014-08-15 15:13:30 -0700838status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800839{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700840 if (position == NULL) {
841 return BAD_VALUE;
842 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800843
Eric Laurent1703cdf2011-03-07 14:52:59 -0800844 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700845 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100846 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800847
Eric Laurentab5cdba2014-06-09 17:22:27 -0700848 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800849 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
850 *position = mPausedPosition;
851 return NO_ERROR;
852 }
853
Glenn Kasten142f5192014-03-25 17:44:59 -0700854 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100855 uint32_t halFrames;
856 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
857 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700858 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
859 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100860 *position = dspFrames;
861 } else {
862 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700863 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
864 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100865 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800866 return NO_ERROR;
867}
868
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000869status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800870{
871 if (mSharedBuffer == 0 || mIsTimed) {
872 return INVALID_OPERATION;
873 }
874 if (position == NULL) {
875 return BAD_VALUE;
876 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800877
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800878 AutoMutex lock(mLock);
879 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800880 return NO_ERROR;
881}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800882
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800883status_t AudioTrack::reload()
884{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700885 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800886 return INVALID_OPERATION;
887 }
888
Eric Laurent1703cdf2011-03-07 14:52:59 -0800889 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800890 // See setPosition() regarding setting parameters such as loop points or position while active
891 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700892 return INVALID_OPERATION;
893 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800894 mNewPosition = mUpdatePeriod;
895 mLoopPeriod = 0;
896 // FIXME The new code cannot reload while keeping a loop specified.
897 // Need to check how the old code handled this, and whether it's a significant change.
898 mStaticProxy->setLoop(0, mFrameCount, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800899 return NO_ERROR;
900}
901
Glenn Kasten38e905b2014-01-13 10:21:48 -0800902audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700903{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800904 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100905 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800906}
907
Eric Laurentbe916aa2010-06-01 23:49:17 -0700908status_t AudioTrack::attachAuxEffect(int effectId)
909{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800910 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700911 status_t status = mAudioTrack->attachAuxEffect(effectId);
912 if (status == NO_ERROR) {
913 mAuxEffectId = effectId;
914 }
915 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700916}
917
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800918// -------------------------------------------------------------------------
919
Eric Laurent1703cdf2011-03-07 14:52:59 -0800920// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -0700921status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800922{
923 status_t status;
924 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
925 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700926 ALOGE("Could not get audioflinger");
927 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800928 }
929
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700930 audio_io_handle_t output = AudioSystem::getOutputForAttr(&mAttributes, mSampleRate, mFormat,
Glenn Kasten38e905b2014-01-13 10:21:48 -0800931 mChannelMask, mFlags, mOffloadInfo);
Glenn Kasten142f5192014-03-25 17:44:59 -0700932 if (output == AUDIO_IO_HANDLE_NONE) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700933 ALOGE("Could not get audio output for stream type %d, usage %d, sample rate %u, format %#x,"
934 " channel mask %#x, flags %#x",
935 mStreamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800936 return BAD_VALUE;
937 }
938 {
939 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
940 // we must release it ourselves if anything goes wrong.
941
Glenn Kastence8828a2013-09-16 18:07:38 -0700942 // Not all of these values are needed under all conditions, but it is easier to get them all
943
Eric Laurentd1b449a2010-05-14 03:26:45 -0700944 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -0700945 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700946 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800947 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800948 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700949 }
950
Glenn Kastence8828a2013-09-16 18:07:38 -0700951 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700952 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -0700953 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700954 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800955 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700956 }
957
958 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700959 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -0700960 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700961 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800962 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700963 }
964
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700965 // Client decides whether the track is TIMED (see below), but can only express a preference
966 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800967 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700968 // either of these use cases:
969 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -0800970 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -0800971 // use case 2: callback transfer mode
972 (mTransfer == TRANSFER_CALLBACK)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800973 // matching sample rate
974 (mSampleRate == afSampleRate))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800975 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -0700976 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -0800977 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700978 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700979 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700980
Glenn Kastence8828a2013-09-16 18:07:38 -0700981 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -0800982 // n = 1 fast track with single buffering; nBuffering is ignored
983 // n = 2 fast track with double buffering
Glenn Kastence8828a2013-09-16 18:07:38 -0700984 // n = 2 normal track, no sample rate conversion
985 // n = 3 normal track, with sample rate conversion
986 // (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering)
987 // n > 3 very high latency or very small notification interval; nBuffering is ignored
Glenn Kasten363fb752014-01-15 12:27:31 -0800988 const uint32_t nBuffering = (mSampleRate == afSampleRate) ? 2 : 3;
Glenn Kastence8828a2013-09-16 18:07:38 -0700989
Eric Laurentd1b449a2010-05-14 03:26:45 -0700990 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700991
Glenn Kasten363fb752014-01-15 12:27:31 -0800992 size_t frameCount = mReqFrameCount;
993 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700994
Glenn Kasten363fb752014-01-15 12:27:31 -0800995 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700996 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -0800997 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -0700998 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700999 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001000 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001001 if (mNotificationFramesAct != frameCount) {
1002 mNotificationFramesAct = frameCount;
1003 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001004 } else if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001005
Glenn Kastena42ff002012-11-14 12:47:55 -08001006 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -07001007 // 8-bit data in shared memory is not currently supported by AudioFlinger
Glenn Kastenb7730382014-04-30 15:50:31 -07001008 size_t alignment = audio_bytes_per_sample(
1009 mFormat == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : mFormat);
1010 if (alignment & 1) {
1011 alignment = 1;
1012 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001013 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001014 // More than 2 channels does not require stronger alignment than stereo
1015 alignment <<= 1;
1016 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001017 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001018 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001019 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001020 status = BAD_VALUE;
1021 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001022 }
1023
1024 // When initializing a shared buffer AudioTrack via constructors,
1025 // there's no frameCount parameter.
1026 // But when initializing a shared buffer AudioTrack via set(),
1027 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kastenb7730382014-04-30 15:50:31 -07001028 frameCount = mSharedBuffer->size() / mFrameSizeAF;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001029
Glenn Kasten363fb752014-01-15 12:27:31 -08001030 } else if (!(mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001031
1032 // FIXME move these calculations and associated checks to server
Glenn Kastene0fa4672012-04-24 14:35:14 -07001033
Eric Laurentd1b449a2010-05-14 03:26:45 -07001034 // Ensure that buffer depth covers at least audio hardware latency
1035 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001036 ALOGV("afFrameCount=%zu, minBufCount=%d, afSampleRate=%u, afLatency=%d",
Glenn Kastenbb6f0a02013-06-03 15:00:29 -07001037 afFrameCount, minBufCount, afSampleRate, afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001038 if (minBufCount <= nBuffering) {
1039 minBufCount = nBuffering;
Glenn Kasten7c027242012-12-26 14:43:16 -08001040 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001041
Andy Hungcd044842014-08-07 11:04:34 -07001042 size_t minFrameCount = afFrameCount * minBufCount * uint64_t(mSampleRate) / afSampleRate;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001043 ALOGV("minFrameCount: %zu, afFrameCount=%zu, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -08001044 ", afLatency=%d",
Glenn Kasten363fb752014-01-15 12:27:31 -08001045 minFrameCount, afFrameCount, minBufCount, mSampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001046
1047 if (frameCount == 0) {
1048 frameCount = minFrameCount;
Glenn Kastence8828a2013-09-16 18:07:38 -07001049 } else if (frameCount < minFrameCount) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001050 // not ALOGW because it happens all the time when playing key clicks over A2DP
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001051 ALOGV("Minimum buffer size corrected from %zu to %zu",
Glenn Kastene0fa4672012-04-24 14:35:14 -07001052 frameCount, minFrameCount);
1053 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001054 }
Glenn Kastence8828a2013-09-16 18:07:38 -07001055 // Make sure that application is notified with sufficient margin before underrun
1056 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1057 mNotificationFramesAct = frameCount/nBuffering;
1058 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001059
Glenn Kastene0fa4672012-04-24 14:35:14 -07001060 } else {
1061 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -07001062 }
1063
Glenn Kastena075db42012-03-06 11:22:44 -08001064 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1065 if (mIsTimed) {
1066 trackFlags |= IAudioFlinger::TRACK_TIMED;
1067 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001068
1069 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001070 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001071 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001072 if (mAudioTrackThread != 0) {
1073 tid = mAudioTrackThread->getTid();
1074 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001075 }
1076
Glenn Kasten363fb752014-01-15 12:27:31 -08001077 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001078 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1079 }
1080
Eric Laurentab5cdba2014-06-09 17:22:27 -07001081 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1082 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1083 }
1084
Glenn Kasten74935e42013-12-19 08:56:45 -08001085 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1086 // but we will still need the original value also
Glenn Kasten363fb752014-01-15 12:27:31 -08001087 sp<IAudioTrack> track = audioFlinger->createTrack(mStreamType,
1088 mSampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -07001089 // AudioFlinger only sees 16-bit PCM
Glenn Kastenc4b88a82014-04-30 16:54:30 -07001090 mFormat == AUDIO_FORMAT_PCM_8_BIT &&
1091 !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ?
Glenn Kasten363fb752014-01-15 12:27:31 -08001092 AUDIO_FORMAT_PCM_16_BIT : mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001093 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001094 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001095 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001096 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001097 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001098 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001099 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001100 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001101 &status);
1102
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001103 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001104 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001105 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001106 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001107 ALOG_ASSERT(track != 0);
1108
Glenn Kasten38e905b2014-01-13 10:21:48 -08001109 // AudioFlinger now owns the reference to the I/O handle,
1110 // so we are no longer responsible for releasing it.
1111
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001112 sp<IMemory> iMem = track->getCblk();
1113 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001114 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001115 return NO_INIT;
1116 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001117 void *iMemPointer = iMem->pointer();
1118 if (iMemPointer == NULL) {
1119 ALOGE("Could not get control block pointer");
1120 return NO_INIT;
1121 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001122 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001123 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001124 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001125 mDeathNotifier.clear();
1126 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001127 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001128 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001129 IPCThreadState::self()->flushCommands();
1130
Glenn Kasten0cde0762014-01-16 15:06:36 -08001131 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001132 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001133 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001134 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1135 // In current design, AudioTrack client checks and ensures frame count validity before
1136 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1137 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001138 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001139 }
1140 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001141
Glenn Kastena07f17c2013-04-23 12:39:37 -07001142 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001143 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001144 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001145 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001146 mAwaitBoost = true;
Glenn Kasten363fb752014-01-15 12:27:31 -08001147 if (mSharedBuffer == 0) {
Glenn Kastenb5fed682013-12-03 09:06:43 -08001148 // Theoretically double-buffering is not required for fast tracks,
1149 // due to tighter scheduling. But in practice, to accommodate kernels with
1150 // scheduling jitter, and apps with computation jitter, we use double-buffering.
1151 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1152 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001153 }
1154 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001155 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001156 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001157 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001158 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1159 if (mSharedBuffer == 0) {
Glenn Kastence8828a2013-09-16 18:07:38 -07001160 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1161 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001162 }
1163 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001164 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001165 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001166 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001167 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1168 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1169 } else {
1170 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001171 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001172 // FIXME This is a warning, not an error, so don't return error status
1173 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001174 }
1175 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001176 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1177 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1178 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1179 } else {
1180 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1181 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1182 // FIXME This is a warning, not an error, so don't return error status
1183 //return NO_INIT;
1184 }
1185 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001186
Glenn Kasten38e905b2014-01-13 10:21:48 -08001187 // We retain a copy of the I/O handle, but don't own the reference
1188 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001189 mRefreshRemaining = true;
1190
1191 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1192 // is the value of pointer() for the shared buffer, otherwise buffers points
1193 // immediately after the control block. This address is for the mapping within client
1194 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1195 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001196 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001197 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001198 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001199 buffers = mSharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001200 }
1201
Eric Laurent2beeb502010-07-16 07:43:46 -07001202 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001203 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001204 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001205
Glenn Kastenb6037442012-11-14 13:42:25 -08001206 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001207 // If IAudioTrack is re-created, don't let the requested frameCount
1208 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001209 if (frameCount > mReqFrameCount) {
1210 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001211 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001212
1213 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001214 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001215 mStaticProxy.clear();
1216 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1217 } else {
1218 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1219 mProxy = mStaticProxy;
1220 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001221
1222 mProxy->setVolumeLR(gain_minifloat_pack(
1223 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1224 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1225
Glenn Kastene3aa6592012-12-04 12:22:46 -08001226 mProxy->setSendLevel(mSendLevel);
1227 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001228 mProxy->setMinimum(mNotificationFramesAct);
1229
1230 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001231 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001232
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001233 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001234 }
1235
1236release:
1237 AudioSystem::releaseOutput(output);
1238 if (status == NO_ERROR) {
1239 status = NO_INIT;
1240 }
1241 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001242}
1243
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001244status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1245{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001246 if (audioBuffer == NULL) {
1247 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001248 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001249 if (mTransfer != TRANSFER_OBTAIN) {
1250 audioBuffer->frameCount = 0;
1251 audioBuffer->size = 0;
1252 audioBuffer->raw = NULL;
1253 return INVALID_OPERATION;
1254 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001255
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001256 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001257 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001258 if (waitCount == -1) {
1259 requested = &ClientProxy::kForever;
1260 } else if (waitCount == 0) {
1261 requested = &ClientProxy::kNonBlocking;
1262 } else if (waitCount > 0) {
1263 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001264 timeout.tv_sec = ms / 1000;
1265 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1266 requested = &timeout;
1267 } else {
1268 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1269 requested = NULL;
1270 }
1271 return obtainBuffer(audioBuffer, requested);
1272}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001273
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001274status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1275 struct timespec *elapsed, size_t *nonContig)
1276{
1277 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1278 uint32_t oldSequence = 0;
1279 uint32_t newSequence;
1280
1281 Proxy::Buffer buffer;
1282 status_t status = NO_ERROR;
1283
1284 static const int32_t kMaxTries = 5;
1285 int32_t tryCounter = kMaxTries;
1286
1287 do {
1288 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1289 // keep them from going away if another thread re-creates the track during obtainBuffer()
1290 sp<AudioTrackClientProxy> proxy;
1291 sp<IMemory> iMem;
1292
1293 { // start of lock scope
1294 AutoMutex lock(mLock);
1295
1296 newSequence = mSequence;
1297 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1298 if (status == DEAD_OBJECT) {
1299 // re-create track, unless someone else has already done so
1300 if (newSequence == oldSequence) {
1301 status = restoreTrack_l("obtainBuffer");
1302 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001303 buffer.mFrameCount = 0;
1304 buffer.mRaw = NULL;
1305 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001306 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001307 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001308 }
1309 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001310 oldSequence = newSequence;
1311
1312 // Keep the extra references
1313 proxy = mProxy;
1314 iMem = mCblkMemory;
1315
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001316 if (mState == STATE_STOPPING) {
1317 status = -EINTR;
1318 buffer.mFrameCount = 0;
1319 buffer.mRaw = NULL;
1320 buffer.mNonContig = 0;
1321 break;
1322 }
1323
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001324 // Non-blocking if track is stopped or paused
1325 if (mState != STATE_ACTIVE) {
1326 requested = &ClientProxy::kNonBlocking;
1327 }
1328
1329 } // end of lock scope
1330
1331 buffer.mFrameCount = audioBuffer->frameCount;
1332 // FIXME starts the requested timeout and elapsed over from scratch
1333 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1334
1335 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1336
1337 audioBuffer->frameCount = buffer.mFrameCount;
1338 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1339 audioBuffer->raw = buffer.mRaw;
1340 if (nonContig != NULL) {
1341 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001342 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001343 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001344}
1345
1346void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1347{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001348 if (mTransfer == TRANSFER_SHARED) {
1349 return;
1350 }
1351
1352 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1353 if (stepCount == 0) {
1354 return;
1355 }
1356
1357 Proxy::Buffer buffer;
1358 buffer.mFrameCount = stepCount;
1359 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001360
Eric Laurent1703cdf2011-03-07 14:52:59 -08001361 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001362 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001363 mInUnderrun = false;
1364 mProxy->releaseBuffer(&buffer);
1365
1366 // restart track if it was disabled by audioflinger due to previous underrun
1367 if (mState == STATE_ACTIVE) {
1368 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001369 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001370 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001371 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001372 mAudioTrack->start();
1373 }
1374 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001375}
1376
1377// -------------------------------------------------------------------------
1378
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001379ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001380{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001381 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001382 return INVALID_OPERATION;
1383 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001384
Eric Laurentab5cdba2014-06-09 17:22:27 -07001385 if (isDirect()) {
1386 AutoMutex lock(mLock);
1387 int32_t flags = android_atomic_and(
1388 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1389 &mCblk->mFlags);
1390 if (flags & CBLK_INVALID) {
1391 return DEAD_OBJECT;
1392 }
1393 }
1394
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001395 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001396 // Sanity-check: user is most-likely passing an error code, and it would
1397 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001398 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001399 return BAD_VALUE;
1400 }
1401
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001402 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001403 Buffer audioBuffer;
1404
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001405 while (userSize >= mFrameSize) {
1406 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001407
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001408 status_t err = obtainBuffer(&audioBuffer,
1409 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001410 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001411 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001412 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001413 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001414 return ssize_t(err);
1415 }
1416
1417 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001418 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001419 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001420 toWrite = audioBuffer.size >> 1;
1421 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001422 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001423 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001424 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001425 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001426 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001427 userSize -= toWrite;
1428 written += toWrite;
1429
1430 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001431 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001432
1433 return written;
1434}
1435
1436// -------------------------------------------------------------------------
1437
John Grossman4ff14ba2012-02-08 16:37:41 -08001438TimedAudioTrack::TimedAudioTrack() {
1439 mIsTimed = true;
1440}
1441
1442status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1443{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001444 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001445 status_t result = UNKNOWN_ERROR;
1446
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001447#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001448 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1449 // while we are accessing the cblk
1450 sp<IAudioTrack> audioTrack = mAudioTrack;
1451 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001452#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001453
John Grossman4ff14ba2012-02-08 16:37:41 -08001454 // If the track is not invalid already, try to allocate a buffer. alloc
1455 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001456 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001457 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001458 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001459 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1460 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001461 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001462 }
1463 }
1464
1465 // If the track is invalid at this point, attempt to restore it. and try the
1466 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001467 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001468 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001469
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001470 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001471 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001472 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001473 }
1474
1475 return result;
1476}
1477
1478status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1479 int64_t pts)
1480{
Eric Laurentdf839842012-05-31 14:27:14 -07001481 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1482 {
1483 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001484 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001485 // restart track if it was disabled by audioflinger due to previous underrun
1486 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001487 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1488 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001489 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001490 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001491 mAudioTrack->start();
1492 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001493 }
Eric Laurentdf839842012-05-31 14:27:14 -07001494 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001495}
1496
1497status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1498 TargetTimeline target)
1499{
1500 return mAudioTrack->setMediaTimeTransform(xform, target);
1501}
1502
1503// -------------------------------------------------------------------------
1504
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001505nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001506{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001507 // Currently the AudioTrack thread is not created if there are no callbacks.
1508 // Would it ever make sense to run the thread, even without callbacks?
1509 // If so, then replace this by checks at each use for mCbf != NULL.
1510 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1511
Eric Laurent1703cdf2011-03-07 14:52:59 -08001512 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001513 if (mAwaitBoost) {
1514 mAwaitBoost = false;
1515 mLock.unlock();
1516 static const int32_t kMaxTries = 5;
1517 int32_t tryCounter = kMaxTries;
1518 uint32_t pollUs = 10000;
1519 do {
1520 int policy = sched_getscheduler(0);
1521 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1522 break;
1523 }
1524 usleep(pollUs);
1525 pollUs <<= 1;
1526 } while (tryCounter-- > 0);
1527 if (tryCounter < 0) {
1528 ALOGE("did not receive expected priority boost on time");
1529 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001530 // Run again immediately
1531 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001532 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001533
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001534 // Can only reference mCblk while locked
1535 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001536 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001537
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001538 // Check for track invalidation
1539 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001540 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1541 // AudioSystem cache. We should not exit here but after calling the callback so
1542 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001543 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001544 status_t status = restoreTrack_l("processAudioBuffer");
1545 mLock.unlock();
1546 // Run again immediately, but with a new IAudioTrack
1547 return 0;
1548 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001549 }
1550
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001551 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001552 bool active = mState == STATE_ACTIVE;
1553
1554 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1555 bool newUnderrun = false;
1556 if (flags & CBLK_UNDERRUN) {
1557#if 0
1558 // Currently in shared buffer mode, when the server reaches the end of buffer,
1559 // the track stays active in continuous underrun state. It's up to the application
1560 // to pause or stop the track, or set the position to a new offset within buffer.
1561 // This was some experimental code to auto-pause on underrun. Keeping it here
1562 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1563 if (mTransfer == TRANSFER_SHARED) {
1564 mState = STATE_PAUSED;
1565 active = false;
1566 }
1567#endif
1568 if (!mInUnderrun) {
1569 mInUnderrun = true;
1570 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001571 }
1572 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001573
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001574 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001575 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001576
1577 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001578 bool markerReached = false;
1579 size_t markerPosition = mMarkerPosition;
1580 // FIXME fails for wraparound, need 64 bits
1581 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1582 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001583 }
1584
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001585 // Determine number of new position callback(s) that will be needed, while locked
1586 size_t newPosCount = 0;
1587 size_t newPosition = mNewPosition;
1588 size_t updatePeriod = mUpdatePeriod;
1589 // FIXME fails for wraparound, need 64 bits
1590 if (updatePeriod > 0 && position >= newPosition) {
1591 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1592 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001593 }
1594
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001595 // Cache other fields that will be needed soon
1596 uint32_t loopPeriod = mLoopPeriod;
1597 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001598 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001599 if (mRefreshRemaining) {
1600 mRefreshRemaining = false;
1601 mRemainingFrames = notificationFrames;
1602 mRetryOnPartialBuffer = false;
1603 }
1604 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001605 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001606 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001607
1608 // These fields don't need to be cached, because they are assigned only by set():
1609 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1610 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1611
1612 mLock.unlock();
1613
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001614 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001615 struct timespec timeout;
1616 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1617 timeout.tv_nsec = 0;
1618
Glenn Kasten96f04882013-09-20 09:28:56 -07001619 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001620 switch (status) {
1621 case NO_ERROR:
1622 case DEAD_OBJECT:
1623 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001624 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001625 {
1626 AutoMutex lock(mLock);
1627 // The previously assigned value of waitStreamEnd is no longer valid,
1628 // since the mutex has been unlocked and either the callback handler
1629 // or another thread could have re-started the AudioTrack during that time.
1630 waitStreamEnd = mState == STATE_STOPPING;
1631 if (waitStreamEnd) {
1632 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001633 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001634 }
1635 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001636 if (waitStreamEnd && status != DEAD_OBJECT) {
1637 return NS_INACTIVE;
1638 }
1639 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001640 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001641 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001642 }
1643
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001644 // perform callbacks while unlocked
1645 if (newUnderrun) {
1646 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1647 }
1648 // FIXME we will miss loops if loop cycle was signaled several times since last call
1649 // to processAudioBuffer()
1650 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1651 mCbf(EVENT_LOOP_END, mUserData, NULL);
1652 }
1653 if (flags & CBLK_BUFFER_END) {
1654 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1655 }
1656 if (markerReached) {
1657 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1658 }
1659 while (newPosCount > 0) {
1660 size_t temp = newPosition;
1661 mCbf(EVENT_NEW_POS, mUserData, &temp);
1662 newPosition += updatePeriod;
1663 newPosCount--;
1664 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001665
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001666 if (mObservedSequence != sequence) {
1667 mObservedSequence = sequence;
1668 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001669 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001670 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001671 return NS_INACTIVE;
1672 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001673 }
1674
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001675 // if inactive, then don't run me again until re-started
1676 if (!active) {
1677 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001678 }
1679
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001680 // Compute the estimated time until the next timed event (position, markers, loops)
1681 // FIXME only for non-compressed audio
1682 uint32_t minFrames = ~0;
1683 if (!markerReached && position < markerPosition) {
1684 minFrames = markerPosition - position;
1685 }
1686 if (loopPeriod > 0 && loopPeriod < minFrames) {
1687 minFrames = loopPeriod;
1688 }
1689 if (updatePeriod > 0 && updatePeriod < minFrames) {
1690 minFrames = updatePeriod;
1691 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001692
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001693 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1694 static const uint32_t kPoll = 0;
1695 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1696 minFrames = kPoll * notificationFrames;
1697 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001698
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001699 // Convert frame units to time units
1700 nsecs_t ns = NS_WHENEVER;
1701 if (minFrames != (uint32_t) ~0) {
1702 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1703 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1704 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1705 }
1706
1707 // If not supplying data by EVENT_MORE_DATA, then we're done
1708 if (mTransfer != TRANSFER_CALLBACK) {
1709 return ns;
1710 }
1711
1712 struct timespec timeout;
1713 const struct timespec *requested = &ClientProxy::kForever;
1714 if (ns != NS_WHENEVER) {
1715 timeout.tv_sec = ns / 1000000000LL;
1716 timeout.tv_nsec = ns % 1000000000LL;
1717 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1718 requested = &timeout;
1719 }
1720
1721 while (mRemainingFrames > 0) {
1722
1723 Buffer audioBuffer;
1724 audioBuffer.frameCount = mRemainingFrames;
1725 size_t nonContig;
1726 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1727 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001728 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001729 requested = &ClientProxy::kNonBlocking;
1730 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001731 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001732 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001733 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001734 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1735 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001736 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001737 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001738 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1739 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001740 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001741
Eric Laurent42a6f422013-08-29 14:35:05 -07001742 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001743 mRetryOnPartialBuffer = false;
1744 if (avail < mRemainingFrames) {
1745 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1746 if (ns < 0 || myns < ns) {
1747 ns = myns;
1748 }
1749 return ns;
1750 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001751 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001752
1753 // Divide buffer size by 2 to take into account the expansion
1754 // due to 8 to 16 bit conversion: the callback must fill only half
1755 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001756 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001757 audioBuffer.size >>= 1;
1758 }
1759
1760 size_t reqSize = audioBuffer.size;
1761 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001762 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001763
1764 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001765 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001766 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1767 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001768 return NS_NEVER;
1769 }
1770
1771 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001772 // The callback is done filling buffers
1773 // Keep this thread going to handle timed events and
1774 // still try to get more data in intervals of WAIT_PERIOD_MS
1775 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001776 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001777 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001778
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001779 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001780 // 8 to 16 bit conversion, note that source and destination are the same address
1781 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001782 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001783 }
1784
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001785 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1786 audioBuffer.frameCount = releasedFrames;
1787 mRemainingFrames -= releasedFrames;
1788 if (misalignment >= releasedFrames) {
1789 misalignment -= releasedFrames;
1790 } else {
1791 misalignment = 0;
1792 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001793
1794 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001795
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001796 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1797 // if callback doesn't like to accept the full chunk
1798 if (writtenSize < reqSize) {
1799 continue;
1800 }
1801
1802 // There could be enough non-contiguous frames available to satisfy the remaining request
1803 if (mRemainingFrames <= nonContig) {
1804 continue;
1805 }
1806
1807#if 0
1808 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1809 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1810 // that total to a sum == notificationFrames.
1811 if (0 < misalignment && misalignment <= mRemainingFrames) {
1812 mRemainingFrames = misalignment;
1813 return (mRemainingFrames * 1100000000LL) / sampleRate;
1814 }
1815#endif
1816
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001817 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001818 mRemainingFrames = notificationFrames;
1819 mRetryOnPartialBuffer = true;
1820
1821 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1822 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001823}
1824
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001825status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001826{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001827 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001828 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001829 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001830 status_t result;
1831
Glenn Kastena47f3162012-11-07 10:13:08 -08001832 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kasten38e905b2014-01-13 10:21:48 -08001833 // output parameters in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001834 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001835
Eric Laurentab5cdba2014-06-09 17:22:27 -07001836 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001837 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001838 return DEAD_OBJECT;
1839 }
1840
Glenn Kasten200092b2014-08-15 15:13:30 -07001841 // save the old static buffer position
1842 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
1843
1844 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001845 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001846 // It will also delete the strong references on previous IAudioTrack and IMemory.
1847 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
1848 result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001849
1850 // take the frames that will be lost by track recreation into account in saved position
Glenn Kasten200092b2014-08-15 15:13:30 -07001851 (void) updateAndGetPosition_l();
1852 mPosition = mReleased;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001853
Glenn Kastena47f3162012-11-07 10:13:08 -08001854 if (result == NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001855 // continue playback from last known position, but
1856 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1857 if (mStaticProxy != NULL) {
1858 mLoopPeriod = 0;
1859 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1860 }
1861 // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1862 // track destruction have been played? This is critical for SoundPool implementation
1863 // This must be broken, and needs to be tested/debugged.
1864#if 0
Glenn Kastena47f3162012-11-07 10:13:08 -08001865 // restore write index and set other indexes to reflect empty buffer status
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001866 if (!strcmp(from, "start")) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001867 // Make sure that a client relying on callback events indicating underrun or
1868 // the actual amount of audio frames played (e.g SoundPool) receives them.
1869 if (mSharedBuffer == 0) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001870 // restart playback even if buffer is not completely filled.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001871 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001872 }
1873 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001874#endif
1875 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001876 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001877 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001878 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001879 if (result != NO_ERROR) {
1880 ALOGW("restoreTrack_l() failed status %d", result);
1881 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001882 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001883 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001884
1885 return result;
1886}
1887
Glenn Kasten200092b2014-08-15 15:13:30 -07001888uint32_t AudioTrack::updateAndGetPosition_l()
1889{
1890 // This is the sole place to read server consumed frames
1891 uint32_t newServer = mProxy->getPosition();
1892 int32_t delta = newServer - mServer;
1893 mServer = newServer;
1894 // TODO There is controversy about whether there can be "negative jitter" in server position.
1895 // This should be investigated further, and if possible, it should be addressed.
1896 // A more definite failure mode is infrequent polling by client.
1897 // One could call (void)getPosition_l() in releaseBuffer(),
1898 // so mReleased and mPosition are always lock-step as best possible.
1899 // That should ensure delta never goes negative for infrequent polling
1900 // unless the server has more than 2^31 frames in its buffer,
1901 // in which case the use of uint32_t for these counters has bigger issues.
1902 if (delta < 0) {
1903 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
1904 delta = 0;
1905 }
1906 return mPosition += (uint32_t) delta;
1907}
1908
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001909status_t AudioTrack::setParameters(const String8& keyValuePairs)
1910{
1911 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001912 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001913}
1914
Glenn Kastence703742013-07-19 16:33:58 -07001915status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1916{
Glenn Kasten53cec222013-08-29 09:01:02 -07001917 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001918 // FIXME not implemented for fast tracks; should use proxy and SSQ
1919 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1920 return INVALID_OPERATION;
1921 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001922
1923 switch (mState) {
1924 case STATE_ACTIVE:
1925 case STATE_PAUSED:
1926 break; // handle below
1927 case STATE_FLUSHED:
1928 case STATE_STOPPED:
1929 return WOULD_BLOCK;
1930 case STATE_STOPPING:
1931 case STATE_PAUSED_STOPPING:
1932 if (!isOffloaded_l()) {
1933 return INVALID_OPERATION;
1934 }
1935 break; // offloaded tracks handled below
1936 default:
1937 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
1938 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07001939 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001940
Glenn Kasten200092b2014-08-15 15:13:30 -07001941 // The presented frame count must always lag behind the consumed frame count.
1942 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07001943 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001944 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07001945 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001946 return status;
1947 }
1948 if (isOffloadedOrDirect_l()) {
1949 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
1950 // use cached paused position in case another offloaded track is running.
1951 timestamp.mPosition = mPausedPosition;
1952 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
1953 return NO_ERROR;
1954 }
1955
1956 // Check whether a pending flush or stop has completed, as those commands may
1957 // be asynchronous or return near finish.
1958 if (mStartUs != 0 && mSampleRate != 0) {
1959 static const int kTimeJitterUs = 100000; // 100 ms
1960 static const int k1SecUs = 1000000;
1961
1962 const int64_t timeNow = getNowUs();
1963
1964 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
1965 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
1966 if (timestampTimeUs < mStartUs) {
1967 return WOULD_BLOCK; // stale timestamp time, occurs before start.
1968 }
1969 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
1970 const int64_t deltaPositionByUs = timestamp.mPosition * 1000000LL / mSampleRate;
1971
1972 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
1973 // Verify that the counter can't count faster than the sample rate
1974 // since the start time. If greater, then that means we have failed
1975 // to completely flush or stop the previous playing track.
1976 ALOGW("incomplete flush or stop:"
1977 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
1978 (long long)deltaTimeUs, (long long)deltaPositionByUs,
1979 timestamp.mPosition);
1980 return WOULD_BLOCK;
1981 }
1982 }
1983 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
1984 }
1985 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07001986 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
1987 (void) updateAndGetPosition_l();
1988 // Server consumed (mServer) and presented both use the same server time base,
1989 // and server consumed is always >= presented.
1990 // The delta between these represents the number of frames in the buffer pipeline.
1991 // If this delta between these is greater than the client position, it means that
1992 // actually presented is still stuck at the starting line (figuratively speaking),
1993 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
1994 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
1995 return INVALID_OPERATION;
1996 }
1997 // Convert timestamp position from server time base to client time base.
1998 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
1999 // But if we change it to 64-bit then this could fail.
2000 // If (mPosition - mServer) can be negative then should use:
2001 // (int32_t)(mPosition - mServer)
2002 timestamp.mPosition += mPosition - mServer;
2003 // Immediately after a call to getPosition_l(), mPosition and
2004 // mServer both represent the same frame position. mPosition is
2005 // in client's point of view, and mServer is in server's point of
2006 // view. So the difference between them is the "fudge factor"
2007 // between client and server views due to stop() and/or new
2008 // IAudioTrack. And timestamp.mPosition is initially in server's
2009 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002010 }
2011 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002012}
2013
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002014String8 AudioTrack::getParameters(const String8& keys)
2015{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002016 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002017 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002018 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002019 } else {
2020 return String8::empty();
2021 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002022}
2023
Glenn Kasten23a75452014-01-13 10:37:17 -08002024bool AudioTrack::isOffloaded() const
2025{
2026 AutoMutex lock(mLock);
2027 return isOffloaded_l();
2028}
2029
Eric Laurentab5cdba2014-06-09 17:22:27 -07002030bool AudioTrack::isDirect() const
2031{
2032 AutoMutex lock(mLock);
2033 return isDirect_l();
2034}
2035
2036bool AudioTrack::isOffloadedOrDirect() const
2037{
2038 AutoMutex lock(mLock);
2039 return isOffloadedOrDirect_l();
2040}
2041
2042
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002043status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002044{
2045
2046 const size_t SIZE = 256;
2047 char buffer[SIZE];
2048 String8 result;
2049
2050 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002051 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002052 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002053 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002054 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002055 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002056 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08002057 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002058 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002059 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002060 result.append(buffer);
2061 ::write(fd, result.string(), result.size());
2062 return NO_ERROR;
2063}
2064
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002065uint32_t AudioTrack::getUnderrunFrames() const
2066{
2067 AutoMutex lock(mLock);
2068 return mProxy->getUnderrunFrames();
2069}
2070
Jean-Michel Trivifaabb512014-06-11 16:55:06 -07002071void AudioTrack::setAttributesFromStreamType(audio_stream_type_t streamType) {
2072 mAttributes.flags = 0x0;
2073
2074 switch(streamType) {
2075 case AUDIO_STREAM_DEFAULT:
2076 case AUDIO_STREAM_MUSIC:
2077 mAttributes.content_type = AUDIO_CONTENT_TYPE_MUSIC;
2078 mAttributes.usage = AUDIO_USAGE_MEDIA;
2079 break;
2080 case AUDIO_STREAM_VOICE_CALL:
2081 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
2082 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION;
2083 break;
2084 case AUDIO_STREAM_ENFORCED_AUDIBLE:
2085 mAttributes.flags |= AUDIO_FLAG_AUDIBILITY_ENFORCED;
2086 // intended fall through, attributes in common with STREAM_SYSTEM
2087 case AUDIO_STREAM_SYSTEM:
2088 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
2089 mAttributes.usage = AUDIO_USAGE_ASSISTANCE_SONIFICATION;
2090 break;
2091 case AUDIO_STREAM_RING:
2092 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
2093 mAttributes.usage = AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE;
2094 break;
2095 case AUDIO_STREAM_ALARM:
2096 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
2097 mAttributes.usage = AUDIO_USAGE_ALARM;
2098 break;
2099 case AUDIO_STREAM_NOTIFICATION:
2100 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
2101 mAttributes.usage = AUDIO_USAGE_NOTIFICATION;
2102 break;
2103 case AUDIO_STREAM_BLUETOOTH_SCO:
2104 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
2105 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION;
2106 mAttributes.flags |= AUDIO_FLAG_SCO;
2107 break;
2108 case AUDIO_STREAM_DTMF:
2109 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
2110 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING;
2111 break;
2112 case AUDIO_STREAM_TTS:
2113 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
2114 mAttributes.usage = AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY;
2115 break;
2116 default:
2117 ALOGE("invalid stream type %d when converting to attributes", streamType);
2118 }
2119}
2120
2121void AudioTrack::setStreamTypeFromAttributes(audio_attributes_t& aa) {
2122 // flags to stream type mapping
2123 if ((aa.flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
2124 mStreamType = AUDIO_STREAM_ENFORCED_AUDIBLE;
2125 return;
2126 }
2127 if ((aa.flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
2128 mStreamType = AUDIO_STREAM_BLUETOOTH_SCO;
2129 return;
2130 }
2131
2132 // usage to stream type mapping
2133 switch (aa.usage) {
Eric Laurentbb6c9a02014-09-25 14:11:47 -07002134 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
2135 // TODO once AudioPolicyManager fully supports audio_attributes_t,
2136 // remove stream change based on phone state
2137 if (AudioSystem::getPhoneState() == AUDIO_MODE_RINGTONE) {
2138 mStreamType = AUDIO_STREAM_RING;
2139 break;
2140 }
2141 /// FALL THROUGH
Jean-Michel Trivifaabb512014-06-11 16:55:06 -07002142 case AUDIO_USAGE_MEDIA:
2143 case AUDIO_USAGE_GAME:
Jean-Michel Trivifaabb512014-06-11 16:55:06 -07002144 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
2145 mStreamType = AUDIO_STREAM_MUSIC;
2146 return;
2147 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
2148 mStreamType = AUDIO_STREAM_SYSTEM;
2149 return;
2150 case AUDIO_USAGE_VOICE_COMMUNICATION:
2151 mStreamType = AUDIO_STREAM_VOICE_CALL;
2152 return;
2153
2154 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
2155 mStreamType = AUDIO_STREAM_DTMF;
2156 return;
2157
2158 case AUDIO_USAGE_ALARM:
2159 mStreamType = AUDIO_STREAM_ALARM;
2160 return;
2161 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
2162 mStreamType = AUDIO_STREAM_RING;
2163 return;
2164
2165 case AUDIO_USAGE_NOTIFICATION:
2166 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
2167 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
2168 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
2169 case AUDIO_USAGE_NOTIFICATION_EVENT:
2170 mStreamType = AUDIO_STREAM_NOTIFICATION;
2171 return;
2172
2173 case AUDIO_USAGE_UNKNOWN:
2174 default:
2175 mStreamType = AUDIO_STREAM_MUSIC;
2176 }
2177}
2178
2179bool AudioTrack::isValidAttributes(const audio_attributes_t *paa) {
2180 // has flags that map to a strategy?
2181 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO)) != 0) {
2182 return true;
2183 }
2184
2185 // has known usage?
2186 switch (paa->usage) {
2187 case AUDIO_USAGE_UNKNOWN:
2188 case AUDIO_USAGE_MEDIA:
2189 case AUDIO_USAGE_VOICE_COMMUNICATION:
2190 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
2191 case AUDIO_USAGE_ALARM:
2192 case AUDIO_USAGE_NOTIFICATION:
2193 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
2194 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
2195 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
2196 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
2197 case AUDIO_USAGE_NOTIFICATION_EVENT:
2198 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
2199 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
2200 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
2201 case AUDIO_USAGE_GAME:
2202 break;
2203 default:
2204 return false;
2205 }
2206 return true;
2207}
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002208// =========================================================================
2209
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002210void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002211{
2212 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2213 if (audioTrack != 0) {
2214 AutoMutex lock(audioTrack->mLock);
2215 audioTrack->mProxy->binderDied();
2216 }
2217}
2218
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002219// =========================================================================
2220
2221AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002222 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2223 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002224{
2225}
2226
2227AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002228{
2229}
2230
2231bool AudioTrack::AudioTrackThread::threadLoop()
2232{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002233 {
2234 AutoMutex _l(mMyLock);
2235 if (mPaused) {
2236 mMyCond.wait(mMyLock);
2237 // caller will check for exitPending()
2238 return true;
2239 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002240 if (mIgnoreNextPausedInt) {
2241 mIgnoreNextPausedInt = false;
2242 mPausedInt = false;
2243 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002244 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002245 if (mPausedNs > 0) {
2246 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2247 } else {
2248 mMyCond.wait(mMyLock);
2249 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002250 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002251 return true;
2252 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002253 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002254 if (exitPending()) {
2255 return false;
2256 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002257 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002258 switch (ns) {
2259 case 0:
2260 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002261 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002262 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002263 return true;
2264 case NS_NEVER:
2265 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002266 case NS_WHENEVER:
2267 // FIXME increase poll interval, or make event-driven
2268 ns = 1000000000LL;
2269 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002270 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002271 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002272 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002273 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002274 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002275}
2276
Glenn Kasten3acbd052012-02-28 10:39:56 -08002277void AudioTrack::AudioTrackThread::requestExit()
2278{
2279 // must be in this order to avoid a race condition
2280 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002281 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002282}
2283
2284void AudioTrack::AudioTrackThread::pause()
2285{
2286 AutoMutex _l(mMyLock);
2287 mPaused = true;
2288}
2289
2290void AudioTrack::AudioTrackThread::resume()
2291{
2292 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002293 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002294 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002295 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002296 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002297 mMyCond.signal();
2298 }
2299}
2300
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002301void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2302{
2303 AutoMutex _l(mMyLock);
2304 mPausedInt = true;
2305 mPausedNs = ns;
2306}
2307
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002308}; // namespace android