blob: 000185bde071ec6c215694688aacd9917fa43b07 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19//#define LOG_NDEBUG 0
20#define LOG_TAG "AudioTrack"
21
Glenn Kastenc56f3422014-03-21 17:53:17 -070022#include <math.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080023#include <sys/resource.h>
Glenn Kasten9f80dd22012-12-18 15:57:32 -080024#include <audio_utils/primitives.h>
25#include <binder/IPCThreadState.h>
26#include <media/AudioTrack.h>
27#include <utils/Log.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080028#include <private/media/AudioTrackShared.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070029#include <media/IAudioFlinger.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080030
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010031#define WAIT_PERIOD_MS 10
32#define WAIT_STREAM_END_TIMEOUT_SEC 120
33
Glenn Kasten511754b2012-01-11 09:52:19 -080034
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080035namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080036// ---------------------------------------------------------------------------
37
38// static
39status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080040 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080041 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080042 uint32_t sampleRate)
43{
Glenn Kastend65d73c2012-06-22 17:21:07 -070044 if (frameCount == NULL) {
45 return BAD_VALUE;
46 }
Glenn Kasten04cd0182012-06-25 11:49:27 -070047
Glenn Kastene0fa4672012-04-24 14:35:14 -070048 // FIXME merge with similar code in createTrack_l(), except we're missing
49 // some information here that is available in createTrack_l():
50 // audio_io_handle_t output
51 // audio_format_t format
52 // audio_channel_mask_t channelMask
53 // audio_output_flags_t flags
Glenn Kasten3b16c762012-11-14 08:44:39 -080054 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080055 status_t status;
56 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
57 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080058 ALOGE("Unable to query output sample rate for stream type %d; status %d",
59 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080060 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080061 }
Glenn Kastene33054e2012-11-14 12:54:39 -080062 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -080063 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
64 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080065 ALOGE("Unable to query output frame count for stream type %d; status %d",
66 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080067 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080068 }
69 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -080070 status = AudioSystem::getOutputLatency(&afLatency, streamType);
71 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080072 ALOGE("Unable to query output latency for stream type %d; status %d",
73 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080074 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080075 }
76
77 // Ensure that buffer depth covers at least audio hardware latency
78 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080079 if (minBufCount < 2) {
80 minBufCount = 2;
81 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +080082
83 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
Glenn Kastene53b9ea2012-03-12 16:29:55 -070084 afFrameCount * minBufCount * sampleRate / afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080085 // The formula above should always produce a non-zero value, but return an error
86 // in the unlikely event that it does not, as that's part of the API contract.
87 if (*frameCount == 0) {
88 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %d",
89 streamType, sampleRate);
90 return BAD_VALUE;
91 }
Glenn Kasten3acbd052012-02-28 10:39:56 -080092 ALOGV("getMinFrameCount=%d: afFrameCount=%d, minBufCount=%d, afSampleRate=%d, afLatency=%d",
93 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +080094 return NO_ERROR;
95}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080096
97// ---------------------------------------------------------------------------
98
99AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700100 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800101 mIsTimed(false),
102 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800103 mPreviousSchedulingGroup(SP_DEFAULT),
104 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800105{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700106 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
107 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
108 mAttributes.flags = 0x0;
109 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800110}
111
112AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800113 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800114 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800115 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700116 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800117 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700118 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800119 callback_t cbf,
120 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800121 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800122 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000123 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800124 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800125 int uid,
126 pid_t pid)
Glenn Kasten87913512011-06-22 16:15:25 -0700127 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800128 mIsTimed(false),
129 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800130 mPreviousSchedulingGroup(SP_DEFAULT),
131 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800132{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700133 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700134 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800135 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700136 offloadInfo, uid, pid, NULL /*no audio attributes*/);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800137}
138
Andreas Huberc8139852012-01-18 10:51:55 -0800139AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800140 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800141 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800142 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700143 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800144 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700145 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800146 callback_t cbf,
147 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800148 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800149 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000150 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800151 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800152 int uid,
153 pid_t pid)
Glenn Kasten87913512011-06-22 16:15:25 -0700154 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800155 mIsTimed(false),
156 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800157 mPreviousSchedulingGroup(SP_DEFAULT),
158 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800159{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700160 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800161 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800162 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700163 uid, pid, NULL /*no audio attributes*/);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800164}
165
166AudioTrack::~AudioTrack()
167{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800168 if (mStatus == NO_ERROR) {
169 // Make sure that callback function exits in the case where
170 // it is looping on buffer full condition in obtainBuffer().
171 // Otherwise the callback thread will never exit.
172 stop();
173 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100174 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800175 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800176 mAudioTrackThread->requestExitAndWait();
177 mAudioTrackThread.clear();
178 }
Glenn Kasten53cec222013-08-29 09:01:02 -0700179 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
180 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700181 mCblkMemory.clear();
182 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800183 IPCThreadState::self()->flushCommands();
Marco Nelissend457c972014-02-11 08:47:07 -0800184 ALOGV("~AudioTrack, releasing session id from %d on behalf of %d",
185 IPCThreadState::self()->getCallingPid(), mClientPid);
186 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800187 }
188}
189
190status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800191 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800192 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800193 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700194 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800195 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700196 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800197 callback_t cbf,
198 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800199 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800200 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700201 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800202 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000203 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800204 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800205 int uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700206 pid_t pid,
207 audio_attributes_t* pAttributes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800208{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800209 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten838b3d82014-02-27 15:30:41 -0800210 "flags #%x, notificationFrames %u, sessionId %d, transferType %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800211 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten86f04662014-02-24 15:13:05 -0800212 sessionId, transferType);
213
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800214 switch (transferType) {
215 case TRANSFER_DEFAULT:
216 if (sharedBuffer != 0) {
217 transferType = TRANSFER_SHARED;
218 } else if (cbf == NULL || threadCanCallJava) {
219 transferType = TRANSFER_SYNC;
220 } else {
221 transferType = TRANSFER_CALLBACK;
222 }
223 break;
224 case TRANSFER_CALLBACK:
225 if (cbf == NULL || sharedBuffer != 0) {
226 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
227 return BAD_VALUE;
228 }
229 break;
230 case TRANSFER_OBTAIN:
231 case TRANSFER_SYNC:
232 if (sharedBuffer != 0) {
233 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
234 return BAD_VALUE;
235 }
236 break;
237 case TRANSFER_SHARED:
238 if (sharedBuffer == 0) {
239 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
240 return BAD_VALUE;
241 }
242 break;
243 default:
244 ALOGE("Invalid transfer type %d", transferType);
245 return BAD_VALUE;
246 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800247 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800248 mTransfer = transferType;
249
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700250 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
251 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800252
Glenn Kastene33054e2012-11-14 12:54:39 -0800253 ALOGV("set() streamType %d frameCount %u flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700254
Eric Laurent1703cdf2011-03-07 14:52:59 -0800255 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800256
Glenn Kasten53cec222013-08-29 09:01:02 -0700257 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700258 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000259 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800260 return INVALID_OPERATION;
261 }
262
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800263 // handle default values first.
Dima Zavinfce7a472011-04-19 22:30:36 -0700264 if (streamType == AUDIO_STREAM_DEFAULT) {
265 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800266 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700267
268 if (pAttributes == NULL) {
269 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
270 ALOGE("Invalid stream type %d", streamType);
271 return BAD_VALUE;
272 }
273 setAttributesFromStreamType(streamType);
274 mStreamType = streamType;
275 } else {
276 if (!isValidAttributes(pAttributes)) {
277 ALOGE("Invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
278 pAttributes->usage, pAttributes->content_type, pAttributes->flags,
279 pAttributes->tags);
280 }
281 // stream type shouldn't be looked at, this track has audio attributes
282 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
283 setStreamTypeFromAttributes(mAttributes);
284 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
285 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800286 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700287
Glenn Kastenb1bef512014-01-13 10:25:53 -0800288 status_t status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800289 if (sampleRate == 0) {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700290 // TODO replace with new APM method with support for audio_attributes_t
291 status = AudioSystem::getOutputSamplingRate(&sampleRate, mStreamType);
Glenn Kastenb1bef512014-01-13 10:25:53 -0800292 if (status != NO_ERROR) {
293 ALOGE("Could not get output sample rate for stream type %d; status %d",
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700294 mStreamType, status);
Glenn Kastenb1bef512014-01-13 10:25:53 -0800295 return status;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700296 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800297 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800298 mSampleRate = sampleRate;
Glenn Kastenea7939a2012-03-14 12:56:26 -0700299
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800300 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800301 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700302 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800303 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800304
305 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700306 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800307 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800308 return BAD_VALUE;
309 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800310 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700311
Glenn Kasten8ba90322013-10-30 11:29:27 -0700312 if (!audio_is_output_channel(channelMask)) {
313 ALOGE("Invalid channel mask %#x", channelMask);
314 return BAD_VALUE;
315 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800316 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700317 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800318 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700319
Glenn Kastene0fa4672012-04-24 14:35:14 -0700320 // AudioFlinger does not currently support 8-bit data in shared memory
321 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
322 ALOGE("8-bit data in shared memory is not supported");
323 return BAD_VALUE;
324 }
325
Eric Laurentc2f1f072009-07-17 12:17:14 -0700326 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100327 // or offload was requested
328 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
329 || !audio_is_linear_pcm(format)) {
330 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
331 ? "Offload request, forcing to Direct Output"
332 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700333 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800334 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700335 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700336 }
Eric Laurent1948eb32012-04-13 16:50:19 -0700337 // only allow deep buffering for music stream type
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700338 if (mStreamType != AUDIO_STREAM_MUSIC) {
Eric Laurent1948eb32012-04-13 16:50:19 -0700339 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
340 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700341
Glenn Kastenb7730382014-04-30 15:50:31 -0700342 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
343 if (audio_is_linear_pcm(format)) {
344 mFrameSize = channelCount * audio_bytes_per_sample(format);
345 } else {
346 mFrameSize = sizeof(uint8_t);
347 }
348 mFrameSizeAF = mFrameSize;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800349 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700350 ALOG_ASSERT(audio_is_linear_pcm(format));
351 mFrameSize = channelCount * audio_bytes_per_sample(format);
352 mFrameSizeAF = channelCount * audio_bytes_per_sample(
353 format == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : format);
354 // createTrack will return an error if PCM format is not supported by server,
355 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800356 }
357
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800358 // Make copy of input parameter offloadInfo so that in the future:
359 // (a) createTrack_l doesn't need it as an input parameter
360 // (b) we can support re-creation of offloaded tracks
361 if (offloadInfo != NULL) {
362 mOffloadInfoCopy = *offloadInfo;
363 mOffloadInfo = &mOffloadInfoCopy;
364 } else {
365 mOffloadInfo = NULL;
366 }
367
Glenn Kasten66e46352014-01-16 17:44:23 -0800368 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
369 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800370 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800371 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800372 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700373 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800374 mNotificationFramesAct = 0;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700375 mSessionId = sessionId;
Marco Nelissend457c972014-02-11 08:47:07 -0800376 int callingpid = IPCThreadState::self()->getCallingPid();
377 int mypid = getpid();
378 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800379 mClientUid = IPCThreadState::self()->getCallingUid();
380 } else {
381 mClientUid = uid;
382 }
Marco Nelissend457c972014-02-11 08:47:07 -0800383 if (pid == -1 || (callingpid != mypid)) {
384 mClientPid = callingpid;
385 } else {
386 mClientPid = pid;
387 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700388 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700389 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700390 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700391
Glenn Kastena997e7a2012-08-07 09:44:19 -0700392 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700393 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700394 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
395 }
396
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800397 // create the IAudioTrack
Glenn Kasten363fb752014-01-15 12:27:31 -0800398 status = createTrack_l(0 /*epoch*/);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800399
Glenn Kastena997e7a2012-08-07 09:44:19 -0700400 if (status != NO_ERROR) {
401 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100402 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
403 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700404 mAudioTrackThread.clear();
405 }
406 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700407 }
408
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800409 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800410 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800411 mUserData = user;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800412 mLoopPeriod = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800413 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700414 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800415 mNewPosition = 0;
416 mUpdatePeriod = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800417 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800418 mSequence = 1;
419 mObservedSequence = mSequence;
420 mInUnderrun = false;
421
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800422 return NO_ERROR;
423}
424
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800425// -------------------------------------------------------------------------
426
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100427status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800428{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800429 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100430
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800431 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100432 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800433 }
434
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800435 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800436
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800437 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100438 if (previousState == STATE_PAUSED_STOPPING) {
439 mState = STATE_STOPPING;
440 } else {
441 mState = STATE_ACTIVE;
442 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800443 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
444 // reset current position as seen by client to 0
445 mProxy->setEpoch(mProxy->getEpoch() - mProxy->getPosition());
Eric Laurentec9a0322013-08-28 10:23:01 -0700446 // force refresh of remaining frames by processAudioBuffer() as last
447 // write before stop could be partial.
448 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800449 }
450 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700451 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800452
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800453 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800454 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100455 if (previousState == STATE_STOPPING) {
456 mProxy->interrupt();
457 } else {
458 t->resume();
459 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800460 } else {
461 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
462 get_sched_policy(0, &mPreviousSchedulingGroup);
463 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
464 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800465
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800466 status_t status = NO_ERROR;
467 if (!(flags & CBLK_INVALID)) {
468 status = mAudioTrack->start();
469 if (status == DEAD_OBJECT) {
470 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800471 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800472 }
473 if (flags & CBLK_INVALID) {
474 status = restoreTrack_l("start");
475 }
476
477 if (status != NO_ERROR) {
478 ALOGE("start() status %d", status);
479 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800480 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100481 if (previousState != STATE_STOPPING) {
482 t->pause();
483 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800484 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700485 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700486 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800487 }
488 }
489
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100490 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800491}
492
493void AudioTrack::stop()
494{
495 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700496 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800497 return;
498 }
499
Glenn Kasten23a75452014-01-13 10:37:17 -0800500 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100501 mState = STATE_STOPPING;
502 } else {
503 mState = STATE_STOPPED;
504 }
505
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800506 mProxy->interrupt();
507 mAudioTrack->stop();
508 // the playback head position will reset to 0, so if a marker is set, we need
509 // to activate it again
510 mMarkerReached = false;
511#if 0
512 // Force flush if a shared buffer is used otherwise audioflinger
513 // will not stop before end of buffer is reached.
514 // It may be needed to make sure that we stop playback, likely in case looping is on.
515 if (mSharedBuffer != 0) {
516 flush_l();
517 }
518#endif
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100519
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800520 sp<AudioTrackThread> t = mAudioTrackThread;
521 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800522 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100523 t->pause();
524 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800525 } else {
526 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
527 set_sched_policy(0, mPreviousSchedulingGroup);
528 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800529}
530
531bool AudioTrack::stopped() const
532{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800533 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800534 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800535}
536
537void AudioTrack::flush()
538{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800539 if (mSharedBuffer != 0) {
540 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800541 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800542 AutoMutex lock(mLock);
543 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
544 return;
545 }
546 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800547}
548
Eric Laurent1703cdf2011-03-07 14:52:59 -0800549void AudioTrack::flush_l()
550{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800551 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700552
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700553 // clear playback marker and periodic update counter
554 mMarkerPosition = 0;
555 mMarkerReached = false;
556 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100557 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700558
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800559 mState = STATE_FLUSHED;
Glenn Kasten23a75452014-01-13 10:37:17 -0800560 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100561 mProxy->interrupt();
562 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800563 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800564 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800565}
566
567void AudioTrack::pause()
568{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800569 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100570 if (mState == STATE_ACTIVE) {
571 mState = STATE_PAUSED;
572 } else if (mState == STATE_STOPPING) {
573 mState = STATE_PAUSED_STOPPING;
574 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800575 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800576 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800577 mProxy->interrupt();
578 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800579
Marco Nelissen3a90f282014-03-10 11:21:43 -0700580 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700581 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800582 uint32_t halFrames;
583 // OffloadThread sends HAL pause in its threadLoop.. time saved
584 // here can be slightly off
585 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
586 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
587 }
588 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800589}
590
Eric Laurentbe916aa2010-06-01 23:49:17 -0700591status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800592{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700593 // This duplicates a test by AudioTrack JNI, but that is not the only caller
594 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
595 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700596 return BAD_VALUE;
597 }
598
Eric Laurent1703cdf2011-03-07 14:52:59 -0800599 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800600 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
601 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800602
Glenn Kastenc56f3422014-03-21 17:53:17 -0700603 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700604
Glenn Kasten23a75452014-01-13 10:37:17 -0800605 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700606 mAudioTrack->signal();
607 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700608 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800609}
610
Glenn Kastenb1c09932012-02-27 16:21:04 -0800611status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800612{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800613 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700614}
615
Eric Laurent2beeb502010-07-16 07:43:46 -0700616status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700617{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700618 // This duplicates a test by AudioTrack JNI, but that is not the only caller
619 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700620 return BAD_VALUE;
621 }
622
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800623 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700624 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800625 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700626
627 return NO_ERROR;
628}
629
Glenn Kastena5224f32012-01-04 12:41:44 -0800630void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700631{
632 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800633 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700634 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800635}
636
Glenn Kasten3b16c762012-11-14 08:44:39 -0800637status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800638{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100639 if (mIsTimed || isOffloaded()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800640 return INVALID_OPERATION;
641 }
642
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800643 uint32_t afSamplingRate;
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700644 // TODO replace with new APM method with support for audio_attributes_t
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800645 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700646 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800647 }
648 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Glenn Kastend65d73c2012-06-22 17:21:07 -0700649 if (rate == 0 || rate > afSamplingRate*2 ) {
650 return BAD_VALUE;
651 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800652
Eric Laurent1703cdf2011-03-07 14:52:59 -0800653 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800654 mSampleRate = rate;
655 mProxy->setSampleRate(rate);
656
Eric Laurent57326622009-07-07 07:10:45 -0700657 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800658}
659
Glenn Kastena5224f32012-01-04 12:41:44 -0800660uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800661{
John Grossman4ff14ba2012-02-08 16:37:41 -0800662 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800663 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800664 }
665
Eric Laurent1703cdf2011-03-07 14:52:59 -0800666 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700667
668 // sample rate can be updated during playback by the offloaded decoder so we need to
669 // query the HAL and update if needed.
670// FIXME use Proxy return channel to update the rate from server and avoid polling here
Glenn Kasten23a75452014-01-13 10:37:17 -0800671 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700672 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700673 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700674 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700675 if (status == NO_ERROR) {
676 mSampleRate = sampleRate;
677 }
678 }
679 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800680 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800681}
682
683status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
684{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100685 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800686 return INVALID_OPERATION;
687 }
688
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800689 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800690 ;
691 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
692 loopEnd - loopStart >= MIN_LOOP) {
693 ;
694 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800695 return BAD_VALUE;
696 }
697
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800698 AutoMutex lock(mLock);
699 // See setPosition() regarding setting parameters such as loop points or position while active
700 if (mState == STATE_ACTIVE) {
701 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700702 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800703 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800704 return NO_ERROR;
705}
706
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800707void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
708{
709 // FIXME If setting a loop also sets position to start of loop, then
710 // this is correct. Otherwise it should be removed.
711 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
712 mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0;
713 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
714}
715
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800716status_t AudioTrack::setMarkerPosition(uint32_t marker)
717{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700718 // The only purpose of setting marker position is to get a callback
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100719 if (mCbf == NULL || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700720 return INVALID_OPERATION;
721 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800722
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800723 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800724 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700725 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800726
727 return NO_ERROR;
728}
729
Glenn Kastena5224f32012-01-04 12:41:44 -0800730status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800731{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100732 if (isOffloaded()) {
733 return INVALID_OPERATION;
734 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700735 if (marker == NULL) {
736 return BAD_VALUE;
737 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800738
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800739 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800740 *marker = mMarkerPosition;
741
742 return NO_ERROR;
743}
744
745status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
746{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700747 // The only purpose of setting position update period is to get a callback
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100748 if (mCbf == NULL || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700749 return INVALID_OPERATION;
750 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800751
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800752 AutoMutex lock(mLock);
753 mNewPosition = mProxy->getPosition() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800754 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800755
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800756 return NO_ERROR;
757}
758
Glenn Kastena5224f32012-01-04 12:41:44 -0800759status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800760{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100761 if (isOffloaded()) {
762 return INVALID_OPERATION;
763 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700764 if (updatePeriod == NULL) {
765 return BAD_VALUE;
766 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800767
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800768 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800769 *updatePeriod = mUpdatePeriod;
770
771 return NO_ERROR;
772}
773
774status_t AudioTrack::setPosition(uint32_t position)
775{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100776 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700777 return INVALID_OPERATION;
778 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800779 if (position > mFrameCount) {
780 return BAD_VALUE;
781 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800782
Eric Laurent1703cdf2011-03-07 14:52:59 -0800783 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800784 // Currently we require that the player is inactive before setting parameters such as position
785 // or loop points. Otherwise, there could be a race condition: the application could read the
786 // current position, compute a new position or loop parameters, and then set that position or
787 // loop parameters but it would do the "wrong" thing since the position has continued to advance
788 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
789 // to specify how it wants to handle such scenarios.
790 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700791 return INVALID_OPERATION;
792 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800793 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
794 mLoopPeriod = 0;
795 // FIXME Check whether loops and setting position are incompatible in old code.
796 // If we use setLoop for both purposes we lose the capability to set the position while looping.
797 mStaticProxy->setLoop(position, mFrameCount, 0);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700798
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800799 return NO_ERROR;
800}
801
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800802status_t AudioTrack::getPosition(uint32_t *position) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800803{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700804 if (position == NULL) {
805 return BAD_VALUE;
806 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800807
Eric Laurent1703cdf2011-03-07 14:52:59 -0800808 AutoMutex lock(mLock);
Glenn Kasten23a75452014-01-13 10:37:17 -0800809 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100810 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800811
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800812 if ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING)) {
813 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
814 *position = mPausedPosition;
815 return NO_ERROR;
816 }
817
Glenn Kasten142f5192014-03-25 17:44:59 -0700818 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100819 uint32_t halFrames;
820 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
821 }
822 *position = dspFrames;
823 } else {
824 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
825 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ? 0 :
826 mProxy->getPosition();
827 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800828 return NO_ERROR;
829}
830
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000831status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800832{
833 if (mSharedBuffer == 0 || mIsTimed) {
834 return INVALID_OPERATION;
835 }
836 if (position == NULL) {
837 return BAD_VALUE;
838 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800839
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800840 AutoMutex lock(mLock);
841 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800842 return NO_ERROR;
843}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800844
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800845status_t AudioTrack::reload()
846{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100847 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800848 return INVALID_OPERATION;
849 }
850
Eric Laurent1703cdf2011-03-07 14:52:59 -0800851 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800852 // See setPosition() regarding setting parameters such as loop points or position while active
853 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700854 return INVALID_OPERATION;
855 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800856 mNewPosition = mUpdatePeriod;
857 mLoopPeriod = 0;
858 // FIXME The new code cannot reload while keeping a loop specified.
859 // Need to check how the old code handled this, and whether it's a significant change.
860 mStaticProxy->setLoop(0, mFrameCount, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800861 return NO_ERROR;
862}
863
Glenn Kasten38e905b2014-01-13 10:21:48 -0800864audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700865{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800866 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100867 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800868}
869
Eric Laurentbe916aa2010-06-01 23:49:17 -0700870status_t AudioTrack::attachAuxEffect(int effectId)
871{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800872 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700873 status_t status = mAudioTrack->attachAuxEffect(effectId);
874 if (status == NO_ERROR) {
875 mAuxEffectId = effectId;
876 }
877 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700878}
879
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800880// -------------------------------------------------------------------------
881
Eric Laurent1703cdf2011-03-07 14:52:59 -0800882// must be called with mLock held
Glenn Kasten363fb752014-01-15 12:27:31 -0800883status_t AudioTrack::createTrack_l(size_t epoch)
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800884{
885 status_t status;
886 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
887 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700888 ALOGE("Could not get audioflinger");
889 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800890 }
891
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700892 // TODO replace with new APM method with support for audio_attributes_t
Glenn Kasten38e905b2014-01-13 10:21:48 -0800893 audio_io_handle_t output = AudioSystem::getOutput(mStreamType, mSampleRate, mFormat,
894 mChannelMask, mFlags, mOffloadInfo);
Glenn Kasten142f5192014-03-25 17:44:59 -0700895 if (output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasten38e905b2014-01-13 10:21:48 -0800896 ALOGE("Could not get audio output for stream type %d, sample rate %u, format %#x, "
897 "channel mask %#x, flags %#x",
898 mStreamType, mSampleRate, mFormat, mChannelMask, mFlags);
899 return BAD_VALUE;
900 }
901 {
902 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
903 // we must release it ourselves if anything goes wrong.
904
Glenn Kastence8828a2013-09-16 18:07:38 -0700905 // Not all of these values are needed under all conditions, but it is easier to get them all
906
Eric Laurentd1b449a2010-05-14 03:26:45 -0700907 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -0700908 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700909 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800910 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800911 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700912 }
913
Glenn Kastence8828a2013-09-16 18:07:38 -0700914 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700915 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -0700916 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700917 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800918 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700919 }
920
921 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700922 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -0700923 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700924 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800925 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700926 }
927
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700928 // Client decides whether the track is TIMED (see below), but can only express a preference
929 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800930 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700931 // either of these use cases:
932 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -0800933 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -0800934 // use case 2: callback transfer mode
935 (mTransfer == TRANSFER_CALLBACK)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800936 // matching sample rate
937 (mSampleRate == afSampleRate))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800938 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -0700939 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -0800940 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700941 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700942 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700943
Glenn Kastence8828a2013-09-16 18:07:38 -0700944 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -0800945 // n = 1 fast track with single buffering; nBuffering is ignored
946 // n = 2 fast track with double buffering
Glenn Kastence8828a2013-09-16 18:07:38 -0700947 // n = 2 normal track, no sample rate conversion
948 // n = 3 normal track, with sample rate conversion
949 // (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering)
950 // n > 3 very high latency or very small notification interval; nBuffering is ignored
Glenn Kasten363fb752014-01-15 12:27:31 -0800951 const uint32_t nBuffering = (mSampleRate == afSampleRate) ? 2 : 3;
Glenn Kastence8828a2013-09-16 18:07:38 -0700952
Eric Laurentd1b449a2010-05-14 03:26:45 -0700953 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700954
Glenn Kasten363fb752014-01-15 12:27:31 -0800955 size_t frameCount = mReqFrameCount;
956 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700957
Glenn Kasten363fb752014-01-15 12:27:31 -0800958 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700959 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -0800960 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -0700961 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700962 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700963 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100964 if (mNotificationFramesAct != frameCount) {
965 mNotificationFramesAct = frameCount;
966 }
Glenn Kasten363fb752014-01-15 12:27:31 -0800967 } else if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700968
Glenn Kastena42ff002012-11-14 12:47:55 -0800969 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -0700970 // 8-bit data in shared memory is not currently supported by AudioFlinger
Glenn Kastenb7730382014-04-30 15:50:31 -0700971 size_t alignment = audio_bytes_per_sample(
972 mFormat == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : mFormat);
973 if (alignment & 1) {
974 alignment = 1;
975 }
Glenn Kastena42ff002012-11-14 12:47:55 -0800976 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700977 // More than 2 channels does not require stronger alignment than stereo
978 alignment <<= 1;
979 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000980 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -0800981 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -0800982 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800983 status = BAD_VALUE;
984 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700985 }
986
987 // When initializing a shared buffer AudioTrack via constructors,
988 // there's no frameCount parameter.
989 // But when initializing a shared buffer AudioTrack via set(),
990 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kastenb7730382014-04-30 15:50:31 -0700991 frameCount = mSharedBuffer->size() / mFrameSizeAF;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700992
Glenn Kasten363fb752014-01-15 12:27:31 -0800993 } else if (!(mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700994
995 // FIXME move these calculations and associated checks to server
Glenn Kastene0fa4672012-04-24 14:35:14 -0700996
Eric Laurentd1b449a2010-05-14 03:26:45 -0700997 // Ensure that buffer depth covers at least audio hardware latency
998 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Glenn Kastenbb6f0a02013-06-03 15:00:29 -0700999 ALOGV("afFrameCount=%d, minBufCount=%d, afSampleRate=%u, afLatency=%d",
1000 afFrameCount, minBufCount, afSampleRate, afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001001 if (minBufCount <= nBuffering) {
1002 minBufCount = nBuffering;
Glenn Kasten7c027242012-12-26 14:43:16 -08001003 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001004
Glenn Kasten363fb752014-01-15 12:27:31 -08001005 size_t minFrameCount = (afFrameCount*mSampleRate*minBufCount)/afSampleRate;
Glenn Kastene33054e2012-11-14 12:54:39 -08001006 ALOGV("minFrameCount: %u, afFrameCount=%d, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -08001007 ", afLatency=%d",
Glenn Kasten363fb752014-01-15 12:27:31 -08001008 minFrameCount, afFrameCount, minBufCount, mSampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001009
1010 if (frameCount == 0) {
1011 frameCount = minFrameCount;
Glenn Kastence8828a2013-09-16 18:07:38 -07001012 } else if (frameCount < minFrameCount) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001013 // not ALOGW because it happens all the time when playing key clicks over A2DP
1014 ALOGV("Minimum buffer size corrected from %d to %d",
1015 frameCount, minFrameCount);
1016 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001017 }
Glenn Kastence8828a2013-09-16 18:07:38 -07001018 // Make sure that application is notified with sufficient margin before underrun
1019 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1020 mNotificationFramesAct = frameCount/nBuffering;
1021 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001022
Glenn Kastene0fa4672012-04-24 14:35:14 -07001023 } else {
1024 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -07001025 }
1026
Glenn Kastena075db42012-03-06 11:22:44 -08001027 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1028 if (mIsTimed) {
1029 trackFlags |= IAudioFlinger::TRACK_TIMED;
1030 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001031
1032 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001033 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001034 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001035 if (mAudioTrackThread != 0) {
1036 tid = mAudioTrackThread->getTid();
1037 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001038 }
1039
Glenn Kasten363fb752014-01-15 12:27:31 -08001040 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001041 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1042 }
1043
Glenn Kasten74935e42013-12-19 08:56:45 -08001044 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1045 // but we will still need the original value also
Glenn Kasten363fb752014-01-15 12:27:31 -08001046 sp<IAudioTrack> track = audioFlinger->createTrack(mStreamType,
1047 mSampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -07001048 // AudioFlinger only sees 16-bit PCM
Glenn Kastenc4b88a82014-04-30 16:54:30 -07001049 mFormat == AUDIO_FORMAT_PCM_8_BIT &&
1050 !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ?
Glenn Kasten363fb752014-01-15 12:27:31 -08001051 AUDIO_FORMAT_PCM_16_BIT : mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001052 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001053 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001054 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001055 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001056 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001057 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001058 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001059 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001060 &status);
1061
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001062 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001063 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001064 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001065 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001066 ALOG_ASSERT(track != 0);
1067
Glenn Kasten38e905b2014-01-13 10:21:48 -08001068 // AudioFlinger now owns the reference to the I/O handle,
1069 // so we are no longer responsible for releasing it.
1070
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001071 sp<IMemory> iMem = track->getCblk();
1072 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001073 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001074 return NO_INIT;
1075 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001076 void *iMemPointer = iMem->pointer();
1077 if (iMemPointer == NULL) {
1078 ALOGE("Could not get control block pointer");
1079 return NO_INIT;
1080 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001081 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001082 if (mAudioTrack != 0) {
1083 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
1084 mDeathNotifier.clear();
1085 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001086 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001087 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001088 IPCThreadState::self()->flushCommands();
1089
Glenn Kasten0cde0762014-01-16 15:06:36 -08001090 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001091 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001092 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001093 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1094 // In current design, AudioTrack client checks and ensures frame count validity before
1095 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1096 // for fast track as it uses a special method of assigning frame count.
1097 ALOGW("Requested frameCount %u but received frameCount %u", frameCount, temp);
1098 }
1099 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001100
Glenn Kastena07f17c2013-04-23 12:39:37 -07001101 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001102 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001103 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Glenn Kastenb6037442012-11-14 13:42:25 -08001104 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %u", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001105 mAwaitBoost = true;
Glenn Kasten363fb752014-01-15 12:27:31 -08001106 if (mSharedBuffer == 0) {
Glenn Kastenb5fed682013-12-03 09:06:43 -08001107 // Theoretically double-buffering is not required for fast tracks,
1108 // due to tighter scheduling. But in practice, to accommodate kernels with
1109 // scheduling jitter, and apps with computation jitter, we use double-buffering.
1110 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1111 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001112 }
1113 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001114 } else {
Glenn Kastenb6037442012-11-14 13:42:25 -08001115 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %u", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001116 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001117 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1118 if (mSharedBuffer == 0) {
Glenn Kastence8828a2013-09-16 18:07:38 -07001119 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1120 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001121 }
1122 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001123 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001124 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001125 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001126 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1127 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1128 } else {
1129 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001130 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001131 // FIXME This is a warning, not an error, so don't return error status
1132 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001133 }
1134 }
1135
Glenn Kasten38e905b2014-01-13 10:21:48 -08001136 // We retain a copy of the I/O handle, but don't own the reference
1137 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001138 mRefreshRemaining = true;
1139
1140 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1141 // is the value of pointer() for the shared buffer, otherwise buffers points
1142 // immediately after the control block. This address is for the mapping within client
1143 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1144 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001145 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001146 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001147 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001148 buffers = mSharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001149 }
1150
Eric Laurent2beeb502010-07-16 07:43:46 -07001151 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001152 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001153 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001154
Glenn Kastenb6037442012-11-14 13:42:25 -08001155 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001156 // If IAudioTrack is re-created, don't let the requested frameCount
1157 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001158 if (frameCount > mReqFrameCount) {
1159 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001160 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001161
1162 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001163 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001164 mStaticProxy.clear();
1165 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1166 } else {
1167 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1168 mProxy = mStaticProxy;
1169 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001170 mProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001171 mProxy->setSendLevel(mSendLevel);
1172 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001173 mProxy->setEpoch(epoch);
1174 mProxy->setMinimum(mNotificationFramesAct);
1175
1176 mDeathNotifier = new DeathNotifier(this);
1177 mAudioTrack->asBinder()->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001178
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001179 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001180 }
1181
1182release:
1183 AudioSystem::releaseOutput(output);
1184 if (status == NO_ERROR) {
1185 status = NO_INIT;
1186 }
1187 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001188}
1189
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001190status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1191{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001192 if (audioBuffer == NULL) {
1193 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001194 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001195 if (mTransfer != TRANSFER_OBTAIN) {
1196 audioBuffer->frameCount = 0;
1197 audioBuffer->size = 0;
1198 audioBuffer->raw = NULL;
1199 return INVALID_OPERATION;
1200 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001201
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001202 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001203 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001204 if (waitCount == -1) {
1205 requested = &ClientProxy::kForever;
1206 } else if (waitCount == 0) {
1207 requested = &ClientProxy::kNonBlocking;
1208 } else if (waitCount > 0) {
1209 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001210 timeout.tv_sec = ms / 1000;
1211 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1212 requested = &timeout;
1213 } else {
1214 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1215 requested = NULL;
1216 }
1217 return obtainBuffer(audioBuffer, requested);
1218}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001219
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001220status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1221 struct timespec *elapsed, size_t *nonContig)
1222{
1223 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1224 uint32_t oldSequence = 0;
1225 uint32_t newSequence;
1226
1227 Proxy::Buffer buffer;
1228 status_t status = NO_ERROR;
1229
1230 static const int32_t kMaxTries = 5;
1231 int32_t tryCounter = kMaxTries;
1232
1233 do {
1234 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1235 // keep them from going away if another thread re-creates the track during obtainBuffer()
1236 sp<AudioTrackClientProxy> proxy;
1237 sp<IMemory> iMem;
1238
1239 { // start of lock scope
1240 AutoMutex lock(mLock);
1241
1242 newSequence = mSequence;
1243 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1244 if (status == DEAD_OBJECT) {
1245 // re-create track, unless someone else has already done so
1246 if (newSequence == oldSequence) {
1247 status = restoreTrack_l("obtainBuffer");
1248 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001249 buffer.mFrameCount = 0;
1250 buffer.mRaw = NULL;
1251 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001252 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001253 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001254 }
1255 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001256 oldSequence = newSequence;
1257
1258 // Keep the extra references
1259 proxy = mProxy;
1260 iMem = mCblkMemory;
1261
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001262 if (mState == STATE_STOPPING) {
1263 status = -EINTR;
1264 buffer.mFrameCount = 0;
1265 buffer.mRaw = NULL;
1266 buffer.mNonContig = 0;
1267 break;
1268 }
1269
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001270 // Non-blocking if track is stopped or paused
1271 if (mState != STATE_ACTIVE) {
1272 requested = &ClientProxy::kNonBlocking;
1273 }
1274
1275 } // end of lock scope
1276
1277 buffer.mFrameCount = audioBuffer->frameCount;
1278 // FIXME starts the requested timeout and elapsed over from scratch
1279 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1280
1281 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1282
1283 audioBuffer->frameCount = buffer.mFrameCount;
1284 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1285 audioBuffer->raw = buffer.mRaw;
1286 if (nonContig != NULL) {
1287 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001288 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001289 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001290}
1291
1292void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1293{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001294 if (mTransfer == TRANSFER_SHARED) {
1295 return;
1296 }
1297
1298 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1299 if (stepCount == 0) {
1300 return;
1301 }
1302
1303 Proxy::Buffer buffer;
1304 buffer.mFrameCount = stepCount;
1305 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001306
Eric Laurent1703cdf2011-03-07 14:52:59 -08001307 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001308 mInUnderrun = false;
1309 mProxy->releaseBuffer(&buffer);
1310
1311 // restart track if it was disabled by audioflinger due to previous underrun
1312 if (mState == STATE_ACTIVE) {
1313 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001314 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001315 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001316 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001317 mAudioTrack->start();
1318 }
1319 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001320}
1321
1322// -------------------------------------------------------------------------
1323
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001324ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001325{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001326 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001327 return INVALID_OPERATION;
1328 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001329
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001330 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001331 // Sanity-check: user is most-likely passing an error code, and it would
1332 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001333 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001334 return BAD_VALUE;
1335 }
1336
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001337 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001338 Buffer audioBuffer;
1339
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001340 while (userSize >= mFrameSize) {
1341 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001342
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001343 status_t err = obtainBuffer(&audioBuffer,
1344 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001345 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001346 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001347 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001348 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001349 return ssize_t(err);
1350 }
1351
1352 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001353 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001354 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001355 toWrite = audioBuffer.size >> 1;
1356 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001357 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001358 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001359 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001360 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001361 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001362 userSize -= toWrite;
1363 written += toWrite;
1364
1365 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001366 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001367
1368 return written;
1369}
1370
1371// -------------------------------------------------------------------------
1372
John Grossman4ff14ba2012-02-08 16:37:41 -08001373TimedAudioTrack::TimedAudioTrack() {
1374 mIsTimed = true;
1375}
1376
1377status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1378{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001379 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001380 status_t result = UNKNOWN_ERROR;
1381
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001382#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001383 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1384 // while we are accessing the cblk
1385 sp<IAudioTrack> audioTrack = mAudioTrack;
1386 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001387#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001388
John Grossman4ff14ba2012-02-08 16:37:41 -08001389 // If the track is not invalid already, try to allocate a buffer. alloc
1390 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001391 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001392 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001393 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001394 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1395 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001396 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001397 }
1398 }
1399
1400 // If the track is invalid at this point, attempt to restore it. and try the
1401 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001402 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001403 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001404
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001405 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001406 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001407 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001408 }
1409
1410 return result;
1411}
1412
1413status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1414 int64_t pts)
1415{
Eric Laurentdf839842012-05-31 14:27:14 -07001416 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1417 {
1418 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001419 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001420 // restart track if it was disabled by audioflinger due to previous underrun
1421 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001422 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1423 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001424 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001425 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001426 mAudioTrack->start();
1427 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001428 }
Eric Laurentdf839842012-05-31 14:27:14 -07001429 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001430}
1431
1432status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1433 TargetTimeline target)
1434{
1435 return mAudioTrack->setMediaTimeTransform(xform, target);
1436}
1437
1438// -------------------------------------------------------------------------
1439
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001440nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001441{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001442 // Currently the AudioTrack thread is not created if there are no callbacks.
1443 // Would it ever make sense to run the thread, even without callbacks?
1444 // If so, then replace this by checks at each use for mCbf != NULL.
1445 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1446
Eric Laurent1703cdf2011-03-07 14:52:59 -08001447 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001448 if (mAwaitBoost) {
1449 mAwaitBoost = false;
1450 mLock.unlock();
1451 static const int32_t kMaxTries = 5;
1452 int32_t tryCounter = kMaxTries;
1453 uint32_t pollUs = 10000;
1454 do {
1455 int policy = sched_getscheduler(0);
1456 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1457 break;
1458 }
1459 usleep(pollUs);
1460 pollUs <<= 1;
1461 } while (tryCounter-- > 0);
1462 if (tryCounter < 0) {
1463 ALOGE("did not receive expected priority boost on time");
1464 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001465 // Run again immediately
1466 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001467 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001468
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001469 // Can only reference mCblk while locked
1470 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001471 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001472
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001473 // Check for track invalidation
1474 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001475 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1476 // AudioSystem cache. We should not exit here but after calling the callback so
1477 // that the upper layers can recreate the track
Glenn Kasten23a75452014-01-13 10:37:17 -08001478 if (!isOffloaded_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001479 status_t status = restoreTrack_l("processAudioBuffer");
1480 mLock.unlock();
1481 // Run again immediately, but with a new IAudioTrack
1482 return 0;
1483 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001484 }
1485
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001486 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001487 bool active = mState == STATE_ACTIVE;
1488
1489 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1490 bool newUnderrun = false;
1491 if (flags & CBLK_UNDERRUN) {
1492#if 0
1493 // Currently in shared buffer mode, when the server reaches the end of buffer,
1494 // the track stays active in continuous underrun state. It's up to the application
1495 // to pause or stop the track, or set the position to a new offset within buffer.
1496 // This was some experimental code to auto-pause on underrun. Keeping it here
1497 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1498 if (mTransfer == TRANSFER_SHARED) {
1499 mState = STATE_PAUSED;
1500 active = false;
1501 }
1502#endif
1503 if (!mInUnderrun) {
1504 mInUnderrun = true;
1505 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001506 }
1507 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001508
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001509 // Get current position of server
1510 size_t position = mProxy->getPosition();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001511
1512 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001513 bool markerReached = false;
1514 size_t markerPosition = mMarkerPosition;
1515 // FIXME fails for wraparound, need 64 bits
1516 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1517 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001518 }
1519
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001520 // Determine number of new position callback(s) that will be needed, while locked
1521 size_t newPosCount = 0;
1522 size_t newPosition = mNewPosition;
1523 size_t updatePeriod = mUpdatePeriod;
1524 // FIXME fails for wraparound, need 64 bits
1525 if (updatePeriod > 0 && position >= newPosition) {
1526 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1527 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001528 }
1529
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001530 // Cache other fields that will be needed soon
1531 uint32_t loopPeriod = mLoopPeriod;
1532 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001533 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001534 if (mRefreshRemaining) {
1535 mRefreshRemaining = false;
1536 mRemainingFrames = notificationFrames;
1537 mRetryOnPartialBuffer = false;
1538 }
1539 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001540 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001541 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001542
1543 // These fields don't need to be cached, because they are assigned only by set():
1544 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1545 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1546
1547 mLock.unlock();
1548
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001549 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001550 struct timespec timeout;
1551 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1552 timeout.tv_nsec = 0;
1553
Glenn Kasten96f04882013-09-20 09:28:56 -07001554 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001555 switch (status) {
1556 case NO_ERROR:
1557 case DEAD_OBJECT:
1558 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001559 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001560 {
1561 AutoMutex lock(mLock);
1562 // The previously assigned value of waitStreamEnd is no longer valid,
1563 // since the mutex has been unlocked and either the callback handler
1564 // or another thread could have re-started the AudioTrack during that time.
1565 waitStreamEnd = mState == STATE_STOPPING;
1566 if (waitStreamEnd) {
1567 mState = STATE_STOPPED;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001568 }
1569 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001570 if (waitStreamEnd && status != DEAD_OBJECT) {
1571 return NS_INACTIVE;
1572 }
1573 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001574 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001575 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001576 }
1577
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001578 // perform callbacks while unlocked
1579 if (newUnderrun) {
1580 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1581 }
1582 // FIXME we will miss loops if loop cycle was signaled several times since last call
1583 // to processAudioBuffer()
1584 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1585 mCbf(EVENT_LOOP_END, mUserData, NULL);
1586 }
1587 if (flags & CBLK_BUFFER_END) {
1588 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1589 }
1590 if (markerReached) {
1591 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1592 }
1593 while (newPosCount > 0) {
1594 size_t temp = newPosition;
1595 mCbf(EVENT_NEW_POS, mUserData, &temp);
1596 newPosition += updatePeriod;
1597 newPosCount--;
1598 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001599
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001600 if (mObservedSequence != sequence) {
1601 mObservedSequence = sequence;
1602 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001603 // for offloaded tracks, just wait for the upper layers to recreate the track
1604 if (isOffloaded()) {
1605 return NS_INACTIVE;
1606 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001607 }
1608
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001609 // if inactive, then don't run me again until re-started
1610 if (!active) {
1611 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001612 }
1613
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001614 // Compute the estimated time until the next timed event (position, markers, loops)
1615 // FIXME only for non-compressed audio
1616 uint32_t minFrames = ~0;
1617 if (!markerReached && position < markerPosition) {
1618 minFrames = markerPosition - position;
1619 }
1620 if (loopPeriod > 0 && loopPeriod < minFrames) {
1621 minFrames = loopPeriod;
1622 }
1623 if (updatePeriod > 0 && updatePeriod < minFrames) {
1624 minFrames = updatePeriod;
1625 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001626
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001627 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1628 static const uint32_t kPoll = 0;
1629 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1630 minFrames = kPoll * notificationFrames;
1631 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001632
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001633 // Convert frame units to time units
1634 nsecs_t ns = NS_WHENEVER;
1635 if (minFrames != (uint32_t) ~0) {
1636 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1637 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1638 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1639 }
1640
1641 // If not supplying data by EVENT_MORE_DATA, then we're done
1642 if (mTransfer != TRANSFER_CALLBACK) {
1643 return ns;
1644 }
1645
1646 struct timespec timeout;
1647 const struct timespec *requested = &ClientProxy::kForever;
1648 if (ns != NS_WHENEVER) {
1649 timeout.tv_sec = ns / 1000000000LL;
1650 timeout.tv_nsec = ns % 1000000000LL;
1651 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1652 requested = &timeout;
1653 }
1654
1655 while (mRemainingFrames > 0) {
1656
1657 Buffer audioBuffer;
1658 audioBuffer.frameCount = mRemainingFrames;
1659 size_t nonContig;
1660 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1661 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1662 "obtainBuffer() err=%d frameCount=%u", err, audioBuffer.frameCount);
1663 requested = &ClientProxy::kNonBlocking;
1664 size_t avail = audioBuffer.frameCount + nonContig;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001665 ALOGV("obtainBuffer(%u) returned %u = %u + %u err %d",
1666 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001667 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001668 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1669 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001670 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001671 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001672 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1673 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001674 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001675
Eric Laurent42a6f422013-08-29 14:35:05 -07001676 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001677 mRetryOnPartialBuffer = false;
1678 if (avail < mRemainingFrames) {
1679 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1680 if (ns < 0 || myns < ns) {
1681 ns = myns;
1682 }
1683 return ns;
1684 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001685 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001686
1687 // Divide buffer size by 2 to take into account the expansion
1688 // due to 8 to 16 bit conversion: the callback must fill only half
1689 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001690 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001691 audioBuffer.size >>= 1;
1692 }
1693
1694 size_t reqSize = audioBuffer.size;
1695 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001696 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001697
1698 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001699 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
1700 ALOGE("EVENT_MORE_DATA requested %u bytes but callback returned %d bytes",
1701 reqSize, (int) writtenSize);
1702 return NS_NEVER;
1703 }
1704
1705 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001706 // The callback is done filling buffers
1707 // Keep this thread going to handle timed events and
1708 // still try to get more data in intervals of WAIT_PERIOD_MS
1709 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001710 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001711 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001712
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001713 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001714 // 8 to 16 bit conversion, note that source and destination are the same address
1715 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001716 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001717 }
1718
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001719 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1720 audioBuffer.frameCount = releasedFrames;
1721 mRemainingFrames -= releasedFrames;
1722 if (misalignment >= releasedFrames) {
1723 misalignment -= releasedFrames;
1724 } else {
1725 misalignment = 0;
1726 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001727
1728 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001729
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001730 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1731 // if callback doesn't like to accept the full chunk
1732 if (writtenSize < reqSize) {
1733 continue;
1734 }
1735
1736 // There could be enough non-contiguous frames available to satisfy the remaining request
1737 if (mRemainingFrames <= nonContig) {
1738 continue;
1739 }
1740
1741#if 0
1742 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1743 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1744 // that total to a sum == notificationFrames.
1745 if (0 < misalignment && misalignment <= mRemainingFrames) {
1746 mRemainingFrames = misalignment;
1747 return (mRemainingFrames * 1100000000LL) / sampleRate;
1748 }
1749#endif
1750
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001751 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001752 mRemainingFrames = notificationFrames;
1753 mRetryOnPartialBuffer = true;
1754
1755 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1756 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001757}
1758
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001759status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001760{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001761 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Glenn Kasten23a75452014-01-13 10:37:17 -08001762 isOffloaded_l() ? "Offloaded" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001763 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001764 status_t result;
1765
Glenn Kastena47f3162012-11-07 10:13:08 -08001766 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kasten38e905b2014-01-13 10:21:48 -08001767 // output parameters in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001768 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001769
Glenn Kasten23a75452014-01-13 10:37:17 -08001770 if (isOffloaded_l()) {
1771 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001772 return DEAD_OBJECT;
1773 }
1774
Glenn Kastena47f3162012-11-07 10:13:08 -08001775 // if the new IAudioTrack is created, createTrack_l() will modify the
1776 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1777 // It will also delete the strong references on previous IAudioTrack and IMemory
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001778
1779 // take the frames that will be lost by track recreation into account in saved position
1780 size_t position = mProxy->getPosition() + mProxy->getFramesFilled();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001781 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
Glenn Kasten363fb752014-01-15 12:27:31 -08001782 result = createTrack_l(position /*epoch*/);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001783
Glenn Kastena47f3162012-11-07 10:13:08 -08001784 if (result == NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001785 // continue playback from last known position, but
1786 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1787 if (mStaticProxy != NULL) {
1788 mLoopPeriod = 0;
1789 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1790 }
1791 // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1792 // track destruction have been played? This is critical for SoundPool implementation
1793 // This must be broken, and needs to be tested/debugged.
1794#if 0
Glenn Kastena47f3162012-11-07 10:13:08 -08001795 // restore write index and set other indexes to reflect empty buffer status
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001796 if (!strcmp(from, "start")) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001797 // Make sure that a client relying on callback events indicating underrun or
1798 // the actual amount of audio frames played (e.g SoundPool) receives them.
1799 if (mSharedBuffer == 0) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001800 // restart playback even if buffer is not completely filled.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001801 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001802 }
1803 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001804#endif
1805 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001806 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001807 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001808 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001809 if (result != NO_ERROR) {
1810 ALOGW("restoreTrack_l() failed status %d", result);
1811 mState = STATE_STOPPED;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001812 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001813
1814 return result;
1815}
1816
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001817status_t AudioTrack::setParameters(const String8& keyValuePairs)
1818{
1819 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001820 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001821}
1822
Glenn Kastence703742013-07-19 16:33:58 -07001823status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1824{
Glenn Kasten53cec222013-08-29 09:01:02 -07001825 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001826 // FIXME not implemented for fast tracks; should use proxy and SSQ
1827 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1828 return INVALID_OPERATION;
1829 }
1830 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
1831 return INVALID_OPERATION;
1832 }
1833 status_t status = mAudioTrack->getTimestamp(timestamp);
1834 if (status == NO_ERROR) {
1835 timestamp.mPosition += mProxy->getEpoch();
1836 }
1837 return status;
Glenn Kastence703742013-07-19 16:33:58 -07001838}
1839
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001840String8 AudioTrack::getParameters(const String8& keys)
1841{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08001842 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07001843 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08001844 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001845 } else {
1846 return String8::empty();
1847 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001848}
1849
Glenn Kasten23a75452014-01-13 10:37:17 -08001850bool AudioTrack::isOffloaded() const
1851{
1852 AutoMutex lock(mLock);
1853 return isOffloaded_l();
1854}
1855
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001856status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001857{
1858
1859 const size_t SIZE = 256;
1860 char buffer[SIZE];
1861 String8 result;
1862
1863 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001864 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07001865 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001866 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001867 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001868 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001869 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001870 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001871 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001872 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001873 result.append(buffer);
1874 ::write(fd, result.string(), result.size());
1875 return NO_ERROR;
1876}
1877
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001878uint32_t AudioTrack::getUnderrunFrames() const
1879{
1880 AutoMutex lock(mLock);
1881 return mProxy->getUnderrunFrames();
1882}
1883
Jean-Michel Trivifaabb512014-06-11 16:55:06 -07001884void AudioTrack::setAttributesFromStreamType(audio_stream_type_t streamType) {
1885 mAttributes.flags = 0x0;
1886
1887 switch(streamType) {
1888 case AUDIO_STREAM_DEFAULT:
1889 case AUDIO_STREAM_MUSIC:
1890 mAttributes.content_type = AUDIO_CONTENT_TYPE_MUSIC;
1891 mAttributes.usage = AUDIO_USAGE_MEDIA;
1892 break;
1893 case AUDIO_STREAM_VOICE_CALL:
1894 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1895 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION;
1896 break;
1897 case AUDIO_STREAM_ENFORCED_AUDIBLE:
1898 mAttributes.flags |= AUDIO_FLAG_AUDIBILITY_ENFORCED;
1899 // intended fall through, attributes in common with STREAM_SYSTEM
1900 case AUDIO_STREAM_SYSTEM:
1901 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1902 mAttributes.usage = AUDIO_USAGE_ASSISTANCE_SONIFICATION;
1903 break;
1904 case AUDIO_STREAM_RING:
1905 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1906 mAttributes.usage = AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE;
1907 break;
1908 case AUDIO_STREAM_ALARM:
1909 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1910 mAttributes.usage = AUDIO_USAGE_ALARM;
1911 break;
1912 case AUDIO_STREAM_NOTIFICATION:
1913 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1914 mAttributes.usage = AUDIO_USAGE_NOTIFICATION;
1915 break;
1916 case AUDIO_STREAM_BLUETOOTH_SCO:
1917 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1918 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION;
1919 mAttributes.flags |= AUDIO_FLAG_SCO;
1920 break;
1921 case AUDIO_STREAM_DTMF:
1922 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1923 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING;
1924 break;
1925 case AUDIO_STREAM_TTS:
1926 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1927 mAttributes.usage = AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY;
1928 break;
1929 default:
1930 ALOGE("invalid stream type %d when converting to attributes", streamType);
1931 }
1932}
1933
1934void AudioTrack::setStreamTypeFromAttributes(audio_attributes_t& aa) {
1935 // flags to stream type mapping
1936 if ((aa.flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
1937 mStreamType = AUDIO_STREAM_ENFORCED_AUDIBLE;
1938 return;
1939 }
1940 if ((aa.flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
1941 mStreamType = AUDIO_STREAM_BLUETOOTH_SCO;
1942 return;
1943 }
1944
1945 // usage to stream type mapping
1946 switch (aa.usage) {
1947 case AUDIO_USAGE_MEDIA:
1948 case AUDIO_USAGE_GAME:
1949 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
1950 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
1951 mStreamType = AUDIO_STREAM_MUSIC;
1952 return;
1953 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
1954 mStreamType = AUDIO_STREAM_SYSTEM;
1955 return;
1956 case AUDIO_USAGE_VOICE_COMMUNICATION:
1957 mStreamType = AUDIO_STREAM_VOICE_CALL;
1958 return;
1959
1960 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
1961 mStreamType = AUDIO_STREAM_DTMF;
1962 return;
1963
1964 case AUDIO_USAGE_ALARM:
1965 mStreamType = AUDIO_STREAM_ALARM;
1966 return;
1967 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
1968 mStreamType = AUDIO_STREAM_RING;
1969 return;
1970
1971 case AUDIO_USAGE_NOTIFICATION:
1972 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
1973 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
1974 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
1975 case AUDIO_USAGE_NOTIFICATION_EVENT:
1976 mStreamType = AUDIO_STREAM_NOTIFICATION;
1977 return;
1978
1979 case AUDIO_USAGE_UNKNOWN:
1980 default:
1981 mStreamType = AUDIO_STREAM_MUSIC;
1982 }
1983}
1984
1985bool AudioTrack::isValidAttributes(const audio_attributes_t *paa) {
1986 // has flags that map to a strategy?
1987 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO)) != 0) {
1988 return true;
1989 }
1990
1991 // has known usage?
1992 switch (paa->usage) {
1993 case AUDIO_USAGE_UNKNOWN:
1994 case AUDIO_USAGE_MEDIA:
1995 case AUDIO_USAGE_VOICE_COMMUNICATION:
1996 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
1997 case AUDIO_USAGE_ALARM:
1998 case AUDIO_USAGE_NOTIFICATION:
1999 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
2000 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
2001 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
2002 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
2003 case AUDIO_USAGE_NOTIFICATION_EVENT:
2004 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
2005 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
2006 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
2007 case AUDIO_USAGE_GAME:
2008 break;
2009 default:
2010 return false;
2011 }
2012 return true;
2013}
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002014// =========================================================================
2015
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002016void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002017{
2018 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2019 if (audioTrack != 0) {
2020 AutoMutex lock(audioTrack->mLock);
2021 audioTrack->mProxy->binderDied();
2022 }
2023}
2024
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002025// =========================================================================
2026
2027AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002028 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2029 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002030{
2031}
2032
2033AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002034{
2035}
2036
2037bool AudioTrack::AudioTrackThread::threadLoop()
2038{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002039 {
2040 AutoMutex _l(mMyLock);
2041 if (mPaused) {
2042 mMyCond.wait(mMyLock);
2043 // caller will check for exitPending()
2044 return true;
2045 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002046 if (mIgnoreNextPausedInt) {
2047 mIgnoreNextPausedInt = false;
2048 mPausedInt = false;
2049 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002050 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002051 if (mPausedNs > 0) {
2052 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2053 } else {
2054 mMyCond.wait(mMyLock);
2055 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002056 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002057 return true;
2058 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002059 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002060 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002061 switch (ns) {
2062 case 0:
2063 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002064 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002065 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002066 return true;
2067 case NS_NEVER:
2068 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002069 case NS_WHENEVER:
2070 // FIXME increase poll interval, or make event-driven
2071 ns = 1000000000LL;
2072 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002073 default:
2074 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002075 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002076 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002077 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002078}
2079
Glenn Kasten3acbd052012-02-28 10:39:56 -08002080void AudioTrack::AudioTrackThread::requestExit()
2081{
2082 // must be in this order to avoid a race condition
2083 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002084 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002085}
2086
2087void AudioTrack::AudioTrackThread::pause()
2088{
2089 AutoMutex _l(mMyLock);
2090 mPaused = true;
2091}
2092
2093void AudioTrack::AudioTrackThread::resume()
2094{
2095 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002096 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002097 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002098 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002099 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002100 mMyCond.signal();
2101 }
2102}
2103
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002104void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2105{
2106 AutoMutex _l(mMyLock);
2107 mPausedInt = true;
2108 mPausedNs = ns;
2109}
2110
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002111}; // namespace android