blob: 898d58ddaf2370700fa09363275f6f74f85a3fe1 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080018//#define LOG_NDEBUG 0
19#define LOG_TAG "AudioTrack"
20
Mark Salyzyn34fb2962014-06-18 16:30:56 -070021#include <inttypes.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070022#include <math.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080023#include <sys/resource.h>
Mark Salyzyn34fb2962014-06-18 16:30:56 -070024
Glenn Kasten9f80dd22012-12-18 15:57:32 -080025#include <audio_utils/primitives.h>
26#include <binder/IPCThreadState.h>
27#include <media/AudioTrack.h>
28#include <utils/Log.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080029#include <private/media/AudioTrackShared.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/IAudioFlinger.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080031
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010032#define WAIT_PERIOD_MS 10
33#define WAIT_STREAM_END_TIMEOUT_SEC 120
34
Glenn Kasten511754b2012-01-11 09:52:19 -080035
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080036namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080037// ---------------------------------------------------------------------------
38
39// static
40status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080041 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080042 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080043 uint32_t sampleRate)
44{
Glenn Kastend65d73c2012-06-22 17:21:07 -070045 if (frameCount == NULL) {
46 return BAD_VALUE;
47 }
Glenn Kasten04cd0182012-06-25 11:49:27 -070048
Glenn Kastene0fa4672012-04-24 14:35:14 -070049 // FIXME merge with similar code in createTrack_l(), except we're missing
50 // some information here that is available in createTrack_l():
51 // audio_io_handle_t output
52 // audio_format_t format
53 // audio_channel_mask_t channelMask
54 // audio_output_flags_t flags
Glenn Kasten3b16c762012-11-14 08:44:39 -080055 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080056 status_t status;
57 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
58 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080059 ALOGE("Unable to query output sample rate for stream type %d; status %d",
60 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080061 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080062 }
Glenn Kastene33054e2012-11-14 12:54:39 -080063 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -080064 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
65 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080066 ALOGE("Unable to query output frame count for stream type %d; status %d",
67 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080068 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080069 }
70 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -080071 status = AudioSystem::getOutputLatency(&afLatency, streamType);
72 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080073 ALOGE("Unable to query output latency for stream type %d; status %d",
74 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080075 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080076 }
77
78 // Ensure that buffer depth covers at least audio hardware latency
79 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080080 if (minBufCount < 2) {
81 minBufCount = 2;
82 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +080083
84 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
Glenn Kastene53b9ea2012-03-12 16:29:55 -070085 afFrameCount * minBufCount * sampleRate / afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080086 // The formula above should always produce a non-zero value, but return an error
87 // in the unlikely event that it does not, as that's part of the API contract.
88 if (*frameCount == 0) {
89 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %d",
90 streamType, sampleRate);
91 return BAD_VALUE;
92 }
Mark Salyzyn34fb2962014-06-18 16:30:56 -070093 ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, minBufCount=%d, afSampleRate=%d, afLatency=%d",
Glenn Kasten3acbd052012-02-28 10:39:56 -080094 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +080095 return NO_ERROR;
96}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080097
98// ---------------------------------------------------------------------------
99
100AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700101 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800102 mIsTimed(false),
103 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800104 mPreviousSchedulingGroup(SP_DEFAULT),
105 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800106{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700107 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
108 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
109 mAttributes.flags = 0x0;
110 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800111}
112
113AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800114 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800115 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800116 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700117 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800118 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700119 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800120 callback_t cbf,
121 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800122 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800123 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000124 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800125 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800126 int uid,
127 pid_t pid)
Glenn Kasten87913512011-06-22 16:15:25 -0700128 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800129 mIsTimed(false),
130 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800131 mPreviousSchedulingGroup(SP_DEFAULT),
132 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800133{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700134 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700135 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800136 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700137 offloadInfo, uid, pid, NULL /*no audio attributes*/);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800138}
139
Andreas Huberc8139852012-01-18 10:51:55 -0800140AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800141 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800142 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800143 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700144 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800145 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700146 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800147 callback_t cbf,
148 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800149 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800150 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000151 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800152 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800153 int uid,
154 pid_t pid)
Glenn Kasten87913512011-06-22 16:15:25 -0700155 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800156 mIsTimed(false),
157 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800158 mPreviousSchedulingGroup(SP_DEFAULT),
159 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800160{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700161 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800162 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800163 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700164 uid, pid, NULL /*no audio attributes*/);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800165}
166
167AudioTrack::~AudioTrack()
168{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800169 if (mStatus == NO_ERROR) {
170 // Make sure that callback function exits in the case where
171 // it is looping on buffer full condition in obtainBuffer().
172 // Otherwise the callback thread will never exit.
173 stop();
174 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100175 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800176 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800177 mAudioTrackThread->requestExitAndWait();
178 mAudioTrackThread.clear();
179 }
Glenn Kasten53cec222013-08-29 09:01:02 -0700180 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
181 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700182 mCblkMemory.clear();
183 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800184 IPCThreadState::self()->flushCommands();
Marco Nelissend457c972014-02-11 08:47:07 -0800185 ALOGV("~AudioTrack, releasing session id from %d on behalf of %d",
186 IPCThreadState::self()->getCallingPid(), mClientPid);
187 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800188 }
189}
190
191status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800192 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800193 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800194 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700195 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800196 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700197 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800198 callback_t cbf,
199 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800200 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800201 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700202 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800203 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000204 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800205 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800206 int uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700207 pid_t pid,
208 audio_attributes_t* pAttributes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800209{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800210 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten838b3d82014-02-27 15:30:41 -0800211 "flags #%x, notificationFrames %u, sessionId %d, transferType %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800212 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten86f04662014-02-24 15:13:05 -0800213 sessionId, transferType);
214
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800215 switch (transferType) {
216 case TRANSFER_DEFAULT:
217 if (sharedBuffer != 0) {
218 transferType = TRANSFER_SHARED;
219 } else if (cbf == NULL || threadCanCallJava) {
220 transferType = TRANSFER_SYNC;
221 } else {
222 transferType = TRANSFER_CALLBACK;
223 }
224 break;
225 case TRANSFER_CALLBACK:
226 if (cbf == NULL || sharedBuffer != 0) {
227 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
228 return BAD_VALUE;
229 }
230 break;
231 case TRANSFER_OBTAIN:
232 case TRANSFER_SYNC:
233 if (sharedBuffer != 0) {
234 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
235 return BAD_VALUE;
236 }
237 break;
238 case TRANSFER_SHARED:
239 if (sharedBuffer == 0) {
240 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
241 return BAD_VALUE;
242 }
243 break;
244 default:
245 ALOGE("Invalid transfer type %d", transferType);
246 return BAD_VALUE;
247 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800248 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800249 mTransfer = transferType;
250
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700251 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
252 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800253
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700254 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700255
Eric Laurent1703cdf2011-03-07 14:52:59 -0800256 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800257
Glenn Kasten53cec222013-08-29 09:01:02 -0700258 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700259 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000260 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800261 return INVALID_OPERATION;
262 }
263
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800264 // handle default values first.
Dima Zavinfce7a472011-04-19 22:30:36 -0700265 if (streamType == AUDIO_STREAM_DEFAULT) {
266 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800267 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700268
269 if (pAttributes == NULL) {
270 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
271 ALOGE("Invalid stream type %d", streamType);
272 return BAD_VALUE;
273 }
274 setAttributesFromStreamType(streamType);
275 mStreamType = streamType;
276 } else {
277 if (!isValidAttributes(pAttributes)) {
278 ALOGE("Invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
279 pAttributes->usage, pAttributes->content_type, pAttributes->flags,
280 pAttributes->tags);
281 }
282 // stream type shouldn't be looked at, this track has audio attributes
283 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
284 setStreamTypeFromAttributes(mAttributes);
285 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
286 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800287 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700288
Glenn Kastenb1bef512014-01-13 10:25:53 -0800289 status_t status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800290 if (sampleRate == 0) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700291 status = AudioSystem::getOutputSamplingRateForAttr(&sampleRate, &mAttributes);
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{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700639 if (mIsTimed || isOffloadedOrDirect()) {
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 Trivi5bd3f382014-06-13 16:06:54 -0700644 if (AudioSystem::getOutputSamplingRateForAttr(&afSamplingRate, &mAttributes) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700645 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800646 }
647 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Glenn Kastend65d73c2012-06-22 17:21:07 -0700648 if (rate == 0 || rate > afSamplingRate*2 ) {
649 return BAD_VALUE;
650 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800651
Eric Laurent1703cdf2011-03-07 14:52:59 -0800652 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800653 mSampleRate = rate;
654 mProxy->setSampleRate(rate);
655
Eric Laurent57326622009-07-07 07:10:45 -0700656 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800657}
658
Glenn Kastena5224f32012-01-04 12:41:44 -0800659uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800660{
John Grossman4ff14ba2012-02-08 16:37:41 -0800661 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800662 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800663 }
664
Eric Laurent1703cdf2011-03-07 14:52:59 -0800665 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700666
667 // sample rate can be updated during playback by the offloaded decoder so we need to
668 // query the HAL and update if needed.
669// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700670 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700671 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700672 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700673 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700674 if (status == NO_ERROR) {
675 mSampleRate = sampleRate;
676 }
677 }
678 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800679 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800680}
681
682status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
683{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700684 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800685 return INVALID_OPERATION;
686 }
687
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800688 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800689 ;
690 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
691 loopEnd - loopStart >= MIN_LOOP) {
692 ;
693 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800694 return BAD_VALUE;
695 }
696
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800697 AutoMutex lock(mLock);
698 // See setPosition() regarding setting parameters such as loop points or position while active
699 if (mState == STATE_ACTIVE) {
700 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700701 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800702 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800703 return NO_ERROR;
704}
705
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800706void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
707{
708 // FIXME If setting a loop also sets position to start of loop, then
709 // this is correct. Otherwise it should be removed.
710 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
711 mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0;
712 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
713}
714
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800715status_t AudioTrack::setMarkerPosition(uint32_t marker)
716{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700717 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700718 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700719 return INVALID_OPERATION;
720 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800721
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800722 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800723 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700724 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800725
726 return NO_ERROR;
727}
728
Glenn Kastena5224f32012-01-04 12:41:44 -0800729status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800730{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700731 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100732 return INVALID_OPERATION;
733 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700734 if (marker == NULL) {
735 return BAD_VALUE;
736 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800737
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800738 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800739 *marker = mMarkerPosition;
740
741 return NO_ERROR;
742}
743
744status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
745{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700746 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700747 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700748 return INVALID_OPERATION;
749 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800750
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800751 AutoMutex lock(mLock);
752 mNewPosition = mProxy->getPosition() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800753 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800754
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800755 return NO_ERROR;
756}
757
Glenn Kastena5224f32012-01-04 12:41:44 -0800758status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800759{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700760 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100761 return INVALID_OPERATION;
762 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700763 if (updatePeriod == NULL) {
764 return BAD_VALUE;
765 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800766
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800767 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800768 *updatePeriod = mUpdatePeriod;
769
770 return NO_ERROR;
771}
772
773status_t AudioTrack::setPosition(uint32_t position)
774{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700775 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700776 return INVALID_OPERATION;
777 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800778 if (position > mFrameCount) {
779 return BAD_VALUE;
780 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800781
Eric Laurent1703cdf2011-03-07 14:52:59 -0800782 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800783 // Currently we require that the player is inactive before setting parameters such as position
784 // or loop points. Otherwise, there could be a race condition: the application could read the
785 // current position, compute a new position or loop parameters, and then set that position or
786 // loop parameters but it would do the "wrong" thing since the position has continued to advance
787 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
788 // to specify how it wants to handle such scenarios.
789 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700790 return INVALID_OPERATION;
791 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800792 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
793 mLoopPeriod = 0;
794 // FIXME Check whether loops and setting position are incompatible in old code.
795 // If we use setLoop for both purposes we lose the capability to set the position while looping.
796 mStaticProxy->setLoop(position, mFrameCount, 0);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700797
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800798 return NO_ERROR;
799}
800
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800801status_t AudioTrack::getPosition(uint32_t *position) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800802{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700803 if (position == NULL) {
804 return BAD_VALUE;
805 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800806
Eric Laurent1703cdf2011-03-07 14:52:59 -0800807 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700808 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100809 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800810
Eric Laurentab5cdba2014-06-09 17:22:27 -0700811 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800812 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
813 *position = mPausedPosition;
814 return NO_ERROR;
815 }
816
Glenn Kasten142f5192014-03-25 17:44:59 -0700817 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100818 uint32_t halFrames;
819 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
820 }
821 *position = dspFrames;
822 } else {
823 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
824 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ? 0 :
825 mProxy->getPosition();
826 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800827 return NO_ERROR;
828}
829
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000830status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800831{
832 if (mSharedBuffer == 0 || mIsTimed) {
833 return INVALID_OPERATION;
834 }
835 if (position == NULL) {
836 return BAD_VALUE;
837 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800838
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800839 AutoMutex lock(mLock);
840 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800841 return NO_ERROR;
842}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800843
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800844status_t AudioTrack::reload()
845{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700846 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800847 return INVALID_OPERATION;
848 }
849
Eric Laurent1703cdf2011-03-07 14:52:59 -0800850 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800851 // See setPosition() regarding setting parameters such as loop points or position while active
852 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700853 return INVALID_OPERATION;
854 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800855 mNewPosition = mUpdatePeriod;
856 mLoopPeriod = 0;
857 // FIXME The new code cannot reload while keeping a loop specified.
858 // Need to check how the old code handled this, and whether it's a significant change.
859 mStaticProxy->setLoop(0, mFrameCount, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800860 return NO_ERROR;
861}
862
Glenn Kasten38e905b2014-01-13 10:21:48 -0800863audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700864{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800865 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100866 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800867}
868
Eric Laurentbe916aa2010-06-01 23:49:17 -0700869status_t AudioTrack::attachAuxEffect(int effectId)
870{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800871 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700872 status_t status = mAudioTrack->attachAuxEffect(effectId);
873 if (status == NO_ERROR) {
874 mAuxEffectId = effectId;
875 }
876 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700877}
878
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800879// -------------------------------------------------------------------------
880
Eric Laurent1703cdf2011-03-07 14:52:59 -0800881// must be called with mLock held
Glenn Kasten363fb752014-01-15 12:27:31 -0800882status_t AudioTrack::createTrack_l(size_t epoch)
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800883{
884 status_t status;
885 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
886 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700887 ALOGE("Could not get audioflinger");
888 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800889 }
890
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700891 audio_io_handle_t output = AudioSystem::getOutputForAttr(&mAttributes, mSampleRate, mFormat,
Glenn Kasten38e905b2014-01-13 10:21:48 -0800892 mChannelMask, mFlags, mOffloadInfo);
Glenn Kasten142f5192014-03-25 17:44:59 -0700893 if (output == AUDIO_IO_HANDLE_NONE) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700894 ALOGE("Could not get audio output for stream type %d, usage %d, sample rate %u, format %#x,"
895 " channel mask %#x, flags %#x",
896 mStreamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800897 return BAD_VALUE;
898 }
899 {
900 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
901 // we must release it ourselves if anything goes wrong.
902
Glenn Kastence8828a2013-09-16 18:07:38 -0700903 // Not all of these values are needed under all conditions, but it is easier to get them all
904
Eric Laurentd1b449a2010-05-14 03:26:45 -0700905 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -0700906 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700907 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800908 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800909 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700910 }
911
Glenn Kastence8828a2013-09-16 18:07:38 -0700912 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700913 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -0700914 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700915 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800916 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700917 }
918
919 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700920 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -0700921 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700922 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800923 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700924 }
925
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700926 // Client decides whether the track is TIMED (see below), but can only express a preference
927 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800928 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700929 // either of these use cases:
930 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -0800931 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -0800932 // use case 2: callback transfer mode
933 (mTransfer == TRANSFER_CALLBACK)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800934 // matching sample rate
935 (mSampleRate == afSampleRate))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800936 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -0700937 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -0800938 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700939 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700940 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700941
Glenn Kastence8828a2013-09-16 18:07:38 -0700942 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -0800943 // n = 1 fast track with single buffering; nBuffering is ignored
944 // n = 2 fast track with double buffering
Glenn Kastence8828a2013-09-16 18:07:38 -0700945 // n = 2 normal track, no sample rate conversion
946 // n = 3 normal track, with sample rate conversion
947 // (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering)
948 // n > 3 very high latency or very small notification interval; nBuffering is ignored
Glenn Kasten363fb752014-01-15 12:27:31 -0800949 const uint32_t nBuffering = (mSampleRate == afSampleRate) ? 2 : 3;
Glenn Kastence8828a2013-09-16 18:07:38 -0700950
Eric Laurentd1b449a2010-05-14 03:26:45 -0700951 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700952
Glenn Kasten363fb752014-01-15 12:27:31 -0800953 size_t frameCount = mReqFrameCount;
954 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700955
Glenn Kasten363fb752014-01-15 12:27:31 -0800956 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700957 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -0800958 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -0700959 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700960 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700961 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100962 if (mNotificationFramesAct != frameCount) {
963 mNotificationFramesAct = frameCount;
964 }
Glenn Kasten363fb752014-01-15 12:27:31 -0800965 } else if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700966
Glenn Kastena42ff002012-11-14 12:47:55 -0800967 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -0700968 // 8-bit data in shared memory is not currently supported by AudioFlinger
Glenn Kastenb7730382014-04-30 15:50:31 -0700969 size_t alignment = audio_bytes_per_sample(
970 mFormat == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : mFormat);
971 if (alignment & 1) {
972 alignment = 1;
973 }
Glenn Kastena42ff002012-11-14 12:47:55 -0800974 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700975 // More than 2 channels does not require stronger alignment than stereo
976 alignment <<= 1;
977 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000978 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -0800979 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -0800980 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800981 status = BAD_VALUE;
982 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700983 }
984
985 // When initializing a shared buffer AudioTrack via constructors,
986 // there's no frameCount parameter.
987 // But when initializing a shared buffer AudioTrack via set(),
988 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kastenb7730382014-04-30 15:50:31 -0700989 frameCount = mSharedBuffer->size() / mFrameSizeAF;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700990
Glenn Kasten363fb752014-01-15 12:27:31 -0800991 } else if (!(mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700992
993 // FIXME move these calculations and associated checks to server
Glenn Kastene0fa4672012-04-24 14:35:14 -0700994
Eric Laurentd1b449a2010-05-14 03:26:45 -0700995 // Ensure that buffer depth covers at least audio hardware latency
996 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700997 ALOGV("afFrameCount=%zu, minBufCount=%d, afSampleRate=%u, afLatency=%d",
Glenn Kastenbb6f0a02013-06-03 15:00:29 -0700998 afFrameCount, minBufCount, afSampleRate, afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700999 if (minBufCount <= nBuffering) {
1000 minBufCount = nBuffering;
Glenn Kasten7c027242012-12-26 14:43:16 -08001001 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001002
Glenn Kasten363fb752014-01-15 12:27:31 -08001003 size_t minFrameCount = (afFrameCount*mSampleRate*minBufCount)/afSampleRate;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001004 ALOGV("minFrameCount: %zu, afFrameCount=%zu, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -08001005 ", afLatency=%d",
Glenn Kasten363fb752014-01-15 12:27:31 -08001006 minFrameCount, afFrameCount, minBufCount, mSampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001007
1008 if (frameCount == 0) {
1009 frameCount = minFrameCount;
Glenn Kastence8828a2013-09-16 18:07:38 -07001010 } else if (frameCount < minFrameCount) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001011 // not ALOGW because it happens all the time when playing key clicks over A2DP
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001012 ALOGV("Minimum buffer size corrected from %zu to %zu",
Glenn Kastene0fa4672012-04-24 14:35:14 -07001013 frameCount, minFrameCount);
1014 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001015 }
Glenn Kastence8828a2013-09-16 18:07:38 -07001016 // Make sure that application is notified with sufficient margin before underrun
1017 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1018 mNotificationFramesAct = frameCount/nBuffering;
1019 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001020
Glenn Kastene0fa4672012-04-24 14:35:14 -07001021 } else {
1022 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -07001023 }
1024
Glenn Kastena075db42012-03-06 11:22:44 -08001025 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1026 if (mIsTimed) {
1027 trackFlags |= IAudioFlinger::TRACK_TIMED;
1028 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001029
1030 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001031 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001032 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001033 if (mAudioTrackThread != 0) {
1034 tid = mAudioTrackThread->getTid();
1035 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001036 }
1037
Glenn Kasten363fb752014-01-15 12:27:31 -08001038 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001039 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1040 }
1041
Eric Laurentab5cdba2014-06-09 17:22:27 -07001042 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1043 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1044 }
1045
Glenn Kasten74935e42013-12-19 08:56:45 -08001046 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1047 // but we will still need the original value also
Glenn Kasten363fb752014-01-15 12:27:31 -08001048 sp<IAudioTrack> track = audioFlinger->createTrack(mStreamType,
1049 mSampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -07001050 // AudioFlinger only sees 16-bit PCM
Glenn Kastenc4b88a82014-04-30 16:54:30 -07001051 mFormat == AUDIO_FORMAT_PCM_8_BIT &&
1052 !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ?
Glenn Kasten363fb752014-01-15 12:27:31 -08001053 AUDIO_FORMAT_PCM_16_BIT : mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001054 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001055 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001056 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001057 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001058 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001059 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001060 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001061 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001062 &status);
1063
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001064 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001065 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001066 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001067 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001068 ALOG_ASSERT(track != 0);
1069
Glenn Kasten38e905b2014-01-13 10:21:48 -08001070 // AudioFlinger now owns the reference to the I/O handle,
1071 // so we are no longer responsible for releasing it.
1072
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001073 sp<IMemory> iMem = track->getCblk();
1074 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001075 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001076 return NO_INIT;
1077 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001078 void *iMemPointer = iMem->pointer();
1079 if (iMemPointer == NULL) {
1080 ALOGE("Could not get control block pointer");
1081 return NO_INIT;
1082 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001083 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001084 if (mAudioTrack != 0) {
1085 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
1086 mDeathNotifier.clear();
1087 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001088 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001089 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001090 IPCThreadState::self()->flushCommands();
1091
Glenn Kasten0cde0762014-01-16 15:06:36 -08001092 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001093 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001094 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001095 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1096 // In current design, AudioTrack client checks and ensures frame count validity before
1097 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1098 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001099 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001100 }
1101 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001102
Glenn Kastena07f17c2013-04-23 12:39:37 -07001103 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001104 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001105 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001106 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001107 mAwaitBoost = true;
Glenn Kasten363fb752014-01-15 12:27:31 -08001108 if (mSharedBuffer == 0) {
Glenn Kastenb5fed682013-12-03 09:06:43 -08001109 // Theoretically double-buffering is not required for fast tracks,
1110 // due to tighter scheduling. But in practice, to accommodate kernels with
1111 // scheduling jitter, and apps with computation jitter, we use double-buffering.
1112 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1113 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001114 }
1115 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001116 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001117 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001118 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001119 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1120 if (mSharedBuffer == 0) {
Glenn Kastence8828a2013-09-16 18:07:38 -07001121 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1122 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001123 }
1124 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001125 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001126 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001127 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001128 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1129 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1130 } else {
1131 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001132 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001133 // FIXME This is a warning, not an error, so don't return error status
1134 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001135 }
1136 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001137 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1138 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1139 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1140 } else {
1141 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1142 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1143 // FIXME This is a warning, not an error, so don't return error status
1144 //return NO_INIT;
1145 }
1146 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001147
Glenn Kasten38e905b2014-01-13 10:21:48 -08001148 // We retain a copy of the I/O handle, but don't own the reference
1149 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001150 mRefreshRemaining = true;
1151
1152 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1153 // is the value of pointer() for the shared buffer, otherwise buffers points
1154 // immediately after the control block. This address is for the mapping within client
1155 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1156 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001157 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001158 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001159 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001160 buffers = mSharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001161 }
1162
Eric Laurent2beeb502010-07-16 07:43:46 -07001163 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001164 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001165 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001166
Glenn Kastenb6037442012-11-14 13:42:25 -08001167 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001168 // If IAudioTrack is re-created, don't let the requested frameCount
1169 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001170 if (frameCount > mReqFrameCount) {
1171 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001172 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001173
1174 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001175 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001176 mStaticProxy.clear();
1177 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1178 } else {
1179 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1180 mProxy = mStaticProxy;
1181 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001182 mProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001183 mProxy->setSendLevel(mSendLevel);
1184 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001185 mProxy->setEpoch(epoch);
1186 mProxy->setMinimum(mNotificationFramesAct);
1187
1188 mDeathNotifier = new DeathNotifier(this);
1189 mAudioTrack->asBinder()->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001190
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001191 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001192 }
1193
1194release:
1195 AudioSystem::releaseOutput(output);
1196 if (status == NO_ERROR) {
1197 status = NO_INIT;
1198 }
1199 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001200}
1201
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001202status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1203{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001204 if (audioBuffer == NULL) {
1205 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001206 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001207 if (mTransfer != TRANSFER_OBTAIN) {
1208 audioBuffer->frameCount = 0;
1209 audioBuffer->size = 0;
1210 audioBuffer->raw = NULL;
1211 return INVALID_OPERATION;
1212 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001213
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001214 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001215 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001216 if (waitCount == -1) {
1217 requested = &ClientProxy::kForever;
1218 } else if (waitCount == 0) {
1219 requested = &ClientProxy::kNonBlocking;
1220 } else if (waitCount > 0) {
1221 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001222 timeout.tv_sec = ms / 1000;
1223 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1224 requested = &timeout;
1225 } else {
1226 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1227 requested = NULL;
1228 }
1229 return obtainBuffer(audioBuffer, requested);
1230}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001231
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001232status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1233 struct timespec *elapsed, size_t *nonContig)
1234{
1235 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1236 uint32_t oldSequence = 0;
1237 uint32_t newSequence;
1238
1239 Proxy::Buffer buffer;
1240 status_t status = NO_ERROR;
1241
1242 static const int32_t kMaxTries = 5;
1243 int32_t tryCounter = kMaxTries;
1244
1245 do {
1246 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1247 // keep them from going away if another thread re-creates the track during obtainBuffer()
1248 sp<AudioTrackClientProxy> proxy;
1249 sp<IMemory> iMem;
1250
1251 { // start of lock scope
1252 AutoMutex lock(mLock);
1253
1254 newSequence = mSequence;
1255 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1256 if (status == DEAD_OBJECT) {
1257 // re-create track, unless someone else has already done so
1258 if (newSequence == oldSequence) {
1259 status = restoreTrack_l("obtainBuffer");
1260 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001261 buffer.mFrameCount = 0;
1262 buffer.mRaw = NULL;
1263 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001264 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001265 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001266 }
1267 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001268 oldSequence = newSequence;
1269
1270 // Keep the extra references
1271 proxy = mProxy;
1272 iMem = mCblkMemory;
1273
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001274 if (mState == STATE_STOPPING) {
1275 status = -EINTR;
1276 buffer.mFrameCount = 0;
1277 buffer.mRaw = NULL;
1278 buffer.mNonContig = 0;
1279 break;
1280 }
1281
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001282 // Non-blocking if track is stopped or paused
1283 if (mState != STATE_ACTIVE) {
1284 requested = &ClientProxy::kNonBlocking;
1285 }
1286
1287 } // end of lock scope
1288
1289 buffer.mFrameCount = audioBuffer->frameCount;
1290 // FIXME starts the requested timeout and elapsed over from scratch
1291 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1292
1293 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1294
1295 audioBuffer->frameCount = buffer.mFrameCount;
1296 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1297 audioBuffer->raw = buffer.mRaw;
1298 if (nonContig != NULL) {
1299 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001300 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001301 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001302}
1303
1304void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1305{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001306 if (mTransfer == TRANSFER_SHARED) {
1307 return;
1308 }
1309
1310 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1311 if (stepCount == 0) {
1312 return;
1313 }
1314
1315 Proxy::Buffer buffer;
1316 buffer.mFrameCount = stepCount;
1317 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001318
Eric Laurent1703cdf2011-03-07 14:52:59 -08001319 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001320 mInUnderrun = false;
1321 mProxy->releaseBuffer(&buffer);
1322
1323 // restart track if it was disabled by audioflinger due to previous underrun
1324 if (mState == STATE_ACTIVE) {
1325 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001326 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001327 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001328 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001329 mAudioTrack->start();
1330 }
1331 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001332}
1333
1334// -------------------------------------------------------------------------
1335
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001336ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001337{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001338 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001339 return INVALID_OPERATION;
1340 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001341
Eric Laurentab5cdba2014-06-09 17:22:27 -07001342 if (isDirect()) {
1343 AutoMutex lock(mLock);
1344 int32_t flags = android_atomic_and(
1345 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1346 &mCblk->mFlags);
1347 if (flags & CBLK_INVALID) {
1348 return DEAD_OBJECT;
1349 }
1350 }
1351
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001352 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001353 // Sanity-check: user is most-likely passing an error code, and it would
1354 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001355 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001356 return BAD_VALUE;
1357 }
1358
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001359 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001360 Buffer audioBuffer;
1361
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001362 while (userSize >= mFrameSize) {
1363 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001364
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001365 status_t err = obtainBuffer(&audioBuffer,
1366 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001367 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001368 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001369 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001370 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001371 return ssize_t(err);
1372 }
1373
1374 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001375 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001376 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001377 toWrite = audioBuffer.size >> 1;
1378 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001379 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001380 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001381 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001382 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001383 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001384 userSize -= toWrite;
1385 written += toWrite;
1386
1387 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001388 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001389
1390 return written;
1391}
1392
1393// -------------------------------------------------------------------------
1394
John Grossman4ff14ba2012-02-08 16:37:41 -08001395TimedAudioTrack::TimedAudioTrack() {
1396 mIsTimed = true;
1397}
1398
1399status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1400{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001401 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001402 status_t result = UNKNOWN_ERROR;
1403
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001404#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001405 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1406 // while we are accessing the cblk
1407 sp<IAudioTrack> audioTrack = mAudioTrack;
1408 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001409#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001410
John Grossman4ff14ba2012-02-08 16:37:41 -08001411 // If the track is not invalid already, try to allocate a buffer. alloc
1412 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001413 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001414 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001415 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001416 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1417 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001418 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001419 }
1420 }
1421
1422 // If the track is invalid at this point, attempt to restore it. and try the
1423 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001424 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001425 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001426
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001427 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001428 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001429 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001430 }
1431
1432 return result;
1433}
1434
1435status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1436 int64_t pts)
1437{
Eric Laurentdf839842012-05-31 14:27:14 -07001438 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1439 {
1440 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001441 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001442 // restart track if it was disabled by audioflinger due to previous underrun
1443 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001444 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1445 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001446 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001447 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001448 mAudioTrack->start();
1449 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001450 }
Eric Laurentdf839842012-05-31 14:27:14 -07001451 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001452}
1453
1454status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1455 TargetTimeline target)
1456{
1457 return mAudioTrack->setMediaTimeTransform(xform, target);
1458}
1459
1460// -------------------------------------------------------------------------
1461
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001462nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001463{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001464 // Currently the AudioTrack thread is not created if there are no callbacks.
1465 // Would it ever make sense to run the thread, even without callbacks?
1466 // If so, then replace this by checks at each use for mCbf != NULL.
1467 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1468
Eric Laurent1703cdf2011-03-07 14:52:59 -08001469 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001470 if (mAwaitBoost) {
1471 mAwaitBoost = false;
1472 mLock.unlock();
1473 static const int32_t kMaxTries = 5;
1474 int32_t tryCounter = kMaxTries;
1475 uint32_t pollUs = 10000;
1476 do {
1477 int policy = sched_getscheduler(0);
1478 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1479 break;
1480 }
1481 usleep(pollUs);
1482 pollUs <<= 1;
1483 } while (tryCounter-- > 0);
1484 if (tryCounter < 0) {
1485 ALOGE("did not receive expected priority boost on time");
1486 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001487 // Run again immediately
1488 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001489 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001490
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001491 // Can only reference mCblk while locked
1492 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001493 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001494
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001495 // Check for track invalidation
1496 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001497 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1498 // AudioSystem cache. We should not exit here but after calling the callback so
1499 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001500 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001501 status_t status = restoreTrack_l("processAudioBuffer");
1502 mLock.unlock();
1503 // Run again immediately, but with a new IAudioTrack
1504 return 0;
1505 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001506 }
1507
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001508 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001509 bool active = mState == STATE_ACTIVE;
1510
1511 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1512 bool newUnderrun = false;
1513 if (flags & CBLK_UNDERRUN) {
1514#if 0
1515 // Currently in shared buffer mode, when the server reaches the end of buffer,
1516 // the track stays active in continuous underrun state. It's up to the application
1517 // to pause or stop the track, or set the position to a new offset within buffer.
1518 // This was some experimental code to auto-pause on underrun. Keeping it here
1519 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1520 if (mTransfer == TRANSFER_SHARED) {
1521 mState = STATE_PAUSED;
1522 active = false;
1523 }
1524#endif
1525 if (!mInUnderrun) {
1526 mInUnderrun = true;
1527 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001528 }
1529 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001530
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001531 // Get current position of server
1532 size_t position = mProxy->getPosition();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001533
1534 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001535 bool markerReached = false;
1536 size_t markerPosition = mMarkerPosition;
1537 // FIXME fails for wraparound, need 64 bits
1538 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1539 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001540 }
1541
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001542 // Determine number of new position callback(s) that will be needed, while locked
1543 size_t newPosCount = 0;
1544 size_t newPosition = mNewPosition;
1545 size_t updatePeriod = mUpdatePeriod;
1546 // FIXME fails for wraparound, need 64 bits
1547 if (updatePeriod > 0 && position >= newPosition) {
1548 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1549 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001550 }
1551
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001552 // Cache other fields that will be needed soon
1553 uint32_t loopPeriod = mLoopPeriod;
1554 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001555 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001556 if (mRefreshRemaining) {
1557 mRefreshRemaining = false;
1558 mRemainingFrames = notificationFrames;
1559 mRetryOnPartialBuffer = false;
1560 }
1561 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001562 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001563 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001564
1565 // These fields don't need to be cached, because they are assigned only by set():
1566 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1567 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1568
1569 mLock.unlock();
1570
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001571 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001572 struct timespec timeout;
1573 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1574 timeout.tv_nsec = 0;
1575
Glenn Kasten96f04882013-09-20 09:28:56 -07001576 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001577 switch (status) {
1578 case NO_ERROR:
1579 case DEAD_OBJECT:
1580 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001581 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001582 {
1583 AutoMutex lock(mLock);
1584 // The previously assigned value of waitStreamEnd is no longer valid,
1585 // since the mutex has been unlocked and either the callback handler
1586 // or another thread could have re-started the AudioTrack during that time.
1587 waitStreamEnd = mState == STATE_STOPPING;
1588 if (waitStreamEnd) {
1589 mState = STATE_STOPPED;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001590 }
1591 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001592 if (waitStreamEnd && status != DEAD_OBJECT) {
1593 return NS_INACTIVE;
1594 }
1595 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001596 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001597 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001598 }
1599
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001600 // perform callbacks while unlocked
1601 if (newUnderrun) {
1602 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1603 }
1604 // FIXME we will miss loops if loop cycle was signaled several times since last call
1605 // to processAudioBuffer()
1606 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1607 mCbf(EVENT_LOOP_END, mUserData, NULL);
1608 }
1609 if (flags & CBLK_BUFFER_END) {
1610 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1611 }
1612 if (markerReached) {
1613 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1614 }
1615 while (newPosCount > 0) {
1616 size_t temp = newPosition;
1617 mCbf(EVENT_NEW_POS, mUserData, &temp);
1618 newPosition += updatePeriod;
1619 newPosCount--;
1620 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001621
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001622 if (mObservedSequence != sequence) {
1623 mObservedSequence = sequence;
1624 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001625 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001626 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001627 return NS_INACTIVE;
1628 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001629 }
1630
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001631 // if inactive, then don't run me again until re-started
1632 if (!active) {
1633 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001634 }
1635
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001636 // Compute the estimated time until the next timed event (position, markers, loops)
1637 // FIXME only for non-compressed audio
1638 uint32_t minFrames = ~0;
1639 if (!markerReached && position < markerPosition) {
1640 minFrames = markerPosition - position;
1641 }
1642 if (loopPeriod > 0 && loopPeriod < minFrames) {
1643 minFrames = loopPeriod;
1644 }
1645 if (updatePeriod > 0 && updatePeriod < minFrames) {
1646 minFrames = updatePeriod;
1647 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001648
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001649 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1650 static const uint32_t kPoll = 0;
1651 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1652 minFrames = kPoll * notificationFrames;
1653 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001654
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001655 // Convert frame units to time units
1656 nsecs_t ns = NS_WHENEVER;
1657 if (minFrames != (uint32_t) ~0) {
1658 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1659 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1660 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1661 }
1662
1663 // If not supplying data by EVENT_MORE_DATA, then we're done
1664 if (mTransfer != TRANSFER_CALLBACK) {
1665 return ns;
1666 }
1667
1668 struct timespec timeout;
1669 const struct timespec *requested = &ClientProxy::kForever;
1670 if (ns != NS_WHENEVER) {
1671 timeout.tv_sec = ns / 1000000000LL;
1672 timeout.tv_nsec = ns % 1000000000LL;
1673 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1674 requested = &timeout;
1675 }
1676
1677 while (mRemainingFrames > 0) {
1678
1679 Buffer audioBuffer;
1680 audioBuffer.frameCount = mRemainingFrames;
1681 size_t nonContig;
1682 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1683 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001684 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001685 requested = &ClientProxy::kNonBlocking;
1686 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001687 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001688 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001689 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001690 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1691 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001692 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001693 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001694 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1695 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001696 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001697
Eric Laurent42a6f422013-08-29 14:35:05 -07001698 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001699 mRetryOnPartialBuffer = false;
1700 if (avail < mRemainingFrames) {
1701 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1702 if (ns < 0 || myns < ns) {
1703 ns = myns;
1704 }
1705 return ns;
1706 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001707 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001708
1709 // Divide buffer size by 2 to take into account the expansion
1710 // due to 8 to 16 bit conversion: the callback must fill only half
1711 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001712 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001713 audioBuffer.size >>= 1;
1714 }
1715
1716 size_t reqSize = audioBuffer.size;
1717 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001718 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001719
1720 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001721 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001722 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1723 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001724 return NS_NEVER;
1725 }
1726
1727 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001728 // The callback is done filling buffers
1729 // Keep this thread going to handle timed events and
1730 // still try to get more data in intervals of WAIT_PERIOD_MS
1731 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001732 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001733 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001734
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001735 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001736 // 8 to 16 bit conversion, note that source and destination are the same address
1737 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001738 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001739 }
1740
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001741 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1742 audioBuffer.frameCount = releasedFrames;
1743 mRemainingFrames -= releasedFrames;
1744 if (misalignment >= releasedFrames) {
1745 misalignment -= releasedFrames;
1746 } else {
1747 misalignment = 0;
1748 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001749
1750 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001751
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001752 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1753 // if callback doesn't like to accept the full chunk
1754 if (writtenSize < reqSize) {
1755 continue;
1756 }
1757
1758 // There could be enough non-contiguous frames available to satisfy the remaining request
1759 if (mRemainingFrames <= nonContig) {
1760 continue;
1761 }
1762
1763#if 0
1764 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1765 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1766 // that total to a sum == notificationFrames.
1767 if (0 < misalignment && misalignment <= mRemainingFrames) {
1768 mRemainingFrames = misalignment;
1769 return (mRemainingFrames * 1100000000LL) / sampleRate;
1770 }
1771#endif
1772
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001773 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001774 mRemainingFrames = notificationFrames;
1775 mRetryOnPartialBuffer = true;
1776
1777 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1778 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001779}
1780
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001781status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001782{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001783 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001784 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001785 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001786 status_t result;
1787
Glenn Kastena47f3162012-11-07 10:13:08 -08001788 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kasten38e905b2014-01-13 10:21:48 -08001789 // output parameters in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001790 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001791
Eric Laurentab5cdba2014-06-09 17:22:27 -07001792 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001793 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001794 return DEAD_OBJECT;
1795 }
1796
Glenn Kastena47f3162012-11-07 10:13:08 -08001797 // if the new IAudioTrack is created, createTrack_l() will modify the
1798 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1799 // It will also delete the strong references on previous IAudioTrack and IMemory
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001800
1801 // take the frames that will be lost by track recreation into account in saved position
1802 size_t position = mProxy->getPosition() + mProxy->getFramesFilled();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001803 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
Glenn Kasten363fb752014-01-15 12:27:31 -08001804 result = createTrack_l(position /*epoch*/);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001805
Glenn Kastena47f3162012-11-07 10:13:08 -08001806 if (result == NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001807 // continue playback from last known position, but
1808 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1809 if (mStaticProxy != NULL) {
1810 mLoopPeriod = 0;
1811 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1812 }
1813 // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1814 // track destruction have been played? This is critical for SoundPool implementation
1815 // This must be broken, and needs to be tested/debugged.
1816#if 0
Glenn Kastena47f3162012-11-07 10:13:08 -08001817 // restore write index and set other indexes to reflect empty buffer status
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001818 if (!strcmp(from, "start")) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001819 // Make sure that a client relying on callback events indicating underrun or
1820 // the actual amount of audio frames played (e.g SoundPool) receives them.
1821 if (mSharedBuffer == 0) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001822 // restart playback even if buffer is not completely filled.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001823 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001824 }
1825 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001826#endif
1827 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001828 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001829 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001830 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001831 if (result != NO_ERROR) {
1832 ALOGW("restoreTrack_l() failed status %d", result);
1833 mState = STATE_STOPPED;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001834 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001835
1836 return result;
1837}
1838
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001839status_t AudioTrack::setParameters(const String8& keyValuePairs)
1840{
1841 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001842 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001843}
1844
Glenn Kastence703742013-07-19 16:33:58 -07001845status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1846{
Glenn Kasten53cec222013-08-29 09:01:02 -07001847 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001848 // FIXME not implemented for fast tracks; should use proxy and SSQ
1849 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1850 return INVALID_OPERATION;
1851 }
1852 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
1853 return INVALID_OPERATION;
1854 }
1855 status_t status = mAudioTrack->getTimestamp(timestamp);
1856 if (status == NO_ERROR) {
1857 timestamp.mPosition += mProxy->getEpoch();
1858 }
1859 return status;
Glenn Kastence703742013-07-19 16:33:58 -07001860}
1861
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001862String8 AudioTrack::getParameters(const String8& keys)
1863{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08001864 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07001865 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08001866 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001867 } else {
1868 return String8::empty();
1869 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001870}
1871
Glenn Kasten23a75452014-01-13 10:37:17 -08001872bool AudioTrack::isOffloaded() const
1873{
1874 AutoMutex lock(mLock);
1875 return isOffloaded_l();
1876}
1877
Eric Laurentab5cdba2014-06-09 17:22:27 -07001878bool AudioTrack::isDirect() const
1879{
1880 AutoMutex lock(mLock);
1881 return isDirect_l();
1882}
1883
1884bool AudioTrack::isOffloadedOrDirect() const
1885{
1886 AutoMutex lock(mLock);
1887 return isOffloadedOrDirect_l();
1888}
1889
1890
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001891status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001892{
1893
1894 const size_t SIZE = 256;
1895 char buffer[SIZE];
1896 String8 result;
1897
1898 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001899 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07001900 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001901 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001902 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001903 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001904 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001905 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001906 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001907 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001908 result.append(buffer);
1909 ::write(fd, result.string(), result.size());
1910 return NO_ERROR;
1911}
1912
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001913uint32_t AudioTrack::getUnderrunFrames() const
1914{
1915 AutoMutex lock(mLock);
1916 return mProxy->getUnderrunFrames();
1917}
1918
Jean-Michel Trivifaabb512014-06-11 16:55:06 -07001919void AudioTrack::setAttributesFromStreamType(audio_stream_type_t streamType) {
1920 mAttributes.flags = 0x0;
1921
1922 switch(streamType) {
1923 case AUDIO_STREAM_DEFAULT:
1924 case AUDIO_STREAM_MUSIC:
1925 mAttributes.content_type = AUDIO_CONTENT_TYPE_MUSIC;
1926 mAttributes.usage = AUDIO_USAGE_MEDIA;
1927 break;
1928 case AUDIO_STREAM_VOICE_CALL:
1929 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1930 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION;
1931 break;
1932 case AUDIO_STREAM_ENFORCED_AUDIBLE:
1933 mAttributes.flags |= AUDIO_FLAG_AUDIBILITY_ENFORCED;
1934 // intended fall through, attributes in common with STREAM_SYSTEM
1935 case AUDIO_STREAM_SYSTEM:
1936 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1937 mAttributes.usage = AUDIO_USAGE_ASSISTANCE_SONIFICATION;
1938 break;
1939 case AUDIO_STREAM_RING:
1940 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1941 mAttributes.usage = AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE;
1942 break;
1943 case AUDIO_STREAM_ALARM:
1944 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1945 mAttributes.usage = AUDIO_USAGE_ALARM;
1946 break;
1947 case AUDIO_STREAM_NOTIFICATION:
1948 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1949 mAttributes.usage = AUDIO_USAGE_NOTIFICATION;
1950 break;
1951 case AUDIO_STREAM_BLUETOOTH_SCO:
1952 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1953 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION;
1954 mAttributes.flags |= AUDIO_FLAG_SCO;
1955 break;
1956 case AUDIO_STREAM_DTMF:
1957 mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1958 mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING;
1959 break;
1960 case AUDIO_STREAM_TTS:
1961 mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1962 mAttributes.usage = AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY;
1963 break;
1964 default:
1965 ALOGE("invalid stream type %d when converting to attributes", streamType);
1966 }
1967}
1968
1969void AudioTrack::setStreamTypeFromAttributes(audio_attributes_t& aa) {
1970 // flags to stream type mapping
1971 if ((aa.flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
1972 mStreamType = AUDIO_STREAM_ENFORCED_AUDIBLE;
1973 return;
1974 }
1975 if ((aa.flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
1976 mStreamType = AUDIO_STREAM_BLUETOOTH_SCO;
1977 return;
1978 }
1979
1980 // usage to stream type mapping
1981 switch (aa.usage) {
1982 case AUDIO_USAGE_MEDIA:
1983 case AUDIO_USAGE_GAME:
1984 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
1985 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
1986 mStreamType = AUDIO_STREAM_MUSIC;
1987 return;
1988 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
1989 mStreamType = AUDIO_STREAM_SYSTEM;
1990 return;
1991 case AUDIO_USAGE_VOICE_COMMUNICATION:
1992 mStreamType = AUDIO_STREAM_VOICE_CALL;
1993 return;
1994
1995 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
1996 mStreamType = AUDIO_STREAM_DTMF;
1997 return;
1998
1999 case AUDIO_USAGE_ALARM:
2000 mStreamType = AUDIO_STREAM_ALARM;
2001 return;
2002 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
2003 mStreamType = AUDIO_STREAM_RING;
2004 return;
2005
2006 case AUDIO_USAGE_NOTIFICATION:
2007 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
2008 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
2009 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
2010 case AUDIO_USAGE_NOTIFICATION_EVENT:
2011 mStreamType = AUDIO_STREAM_NOTIFICATION;
2012 return;
2013
2014 case AUDIO_USAGE_UNKNOWN:
2015 default:
2016 mStreamType = AUDIO_STREAM_MUSIC;
2017 }
2018}
2019
2020bool AudioTrack::isValidAttributes(const audio_attributes_t *paa) {
2021 // has flags that map to a strategy?
2022 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO)) != 0) {
2023 return true;
2024 }
2025
2026 // has known usage?
2027 switch (paa->usage) {
2028 case AUDIO_USAGE_UNKNOWN:
2029 case AUDIO_USAGE_MEDIA:
2030 case AUDIO_USAGE_VOICE_COMMUNICATION:
2031 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
2032 case AUDIO_USAGE_ALARM:
2033 case AUDIO_USAGE_NOTIFICATION:
2034 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
2035 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
2036 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
2037 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
2038 case AUDIO_USAGE_NOTIFICATION_EVENT:
2039 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
2040 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
2041 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
2042 case AUDIO_USAGE_GAME:
2043 break;
2044 default:
2045 return false;
2046 }
2047 return true;
2048}
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002049// =========================================================================
2050
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002051void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002052{
2053 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2054 if (audioTrack != 0) {
2055 AutoMutex lock(audioTrack->mLock);
2056 audioTrack->mProxy->binderDied();
2057 }
2058}
2059
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002060// =========================================================================
2061
2062AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002063 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2064 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002065{
2066}
2067
2068AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002069{
2070}
2071
2072bool AudioTrack::AudioTrackThread::threadLoop()
2073{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002074 {
2075 AutoMutex _l(mMyLock);
2076 if (mPaused) {
2077 mMyCond.wait(mMyLock);
2078 // caller will check for exitPending()
2079 return true;
2080 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002081 if (mIgnoreNextPausedInt) {
2082 mIgnoreNextPausedInt = false;
2083 mPausedInt = false;
2084 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002085 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002086 if (mPausedNs > 0) {
2087 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2088 } else {
2089 mMyCond.wait(mMyLock);
2090 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002091 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002092 return true;
2093 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002094 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002095 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002096 switch (ns) {
2097 case 0:
2098 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002099 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002100 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002101 return true;
2102 case NS_NEVER:
2103 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002104 case NS_WHENEVER:
2105 // FIXME increase poll interval, or make event-driven
2106 ns = 1000000000LL;
2107 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002108 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002109 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002110 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002111 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002112 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002113}
2114
Glenn Kasten3acbd052012-02-28 10:39:56 -08002115void AudioTrack::AudioTrackThread::requestExit()
2116{
2117 // must be in this order to avoid a race condition
2118 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002119 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002120}
2121
2122void AudioTrack::AudioTrackThread::pause()
2123{
2124 AutoMutex _l(mMyLock);
2125 mPaused = true;
2126}
2127
2128void AudioTrack::AudioTrackThread::resume()
2129{
2130 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002131 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002132 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002133 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002134 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002135 mMyCond.signal();
2136 }
2137}
2138
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002139void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2140{
2141 AutoMutex _l(mMyLock);
2142 mPausedInt = true;
2143 mPausedNs = ns;
2144}
2145
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002146}; // namespace android