blob: 8d345876c34959b90077380775464326341ba20e [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>
Eric Laurente83b55d2014-11-14 10:06:21 -080031#include <media/AudioPolicyHelper.h>
Andy Hungcd044842014-08-07 11:04:34 -070032#include <media/AudioResamplerPublic.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080033
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010034#define WAIT_PERIOD_MS 10
35#define WAIT_STREAM_END_TIMEOUT_SEC 120
Andy Hung53c3b5f2014-12-15 16:42:05 -080036static const int kMaxLoopCountNotifications = 32;
Glenn Kasten511754b2012-01-11 09:52:19 -080037
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080038namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080039// ---------------------------------------------------------------------------
40
Andy Hung4ede21d2014-12-12 15:37:34 -080041template <typename T>
42const T &min(const T &x, const T &y) {
43 return x < y ? x : y;
44}
45
Andy Hung7f1bc8a2014-09-12 14:43:11 -070046static int64_t convertTimespecToUs(const struct timespec &tv)
47{
48 return tv.tv_sec * 1000000ll + tv.tv_nsec / 1000;
49}
50
51// current monotonic time in microseconds.
52static int64_t getNowUs()
53{
54 struct timespec tv;
55 (void) clock_gettime(CLOCK_MONOTONIC, &tv);
56 return convertTimespecToUs(tv);
57}
58
Chia-chi Yeh33005a92010-06-16 06:33:13 +080059// static
60status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080061 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080062 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080063 uint32_t sampleRate)
64{
Glenn Kastend65d73c2012-06-22 17:21:07 -070065 if (frameCount == NULL) {
66 return BAD_VALUE;
67 }
Glenn Kasten04cd0182012-06-25 11:49:27 -070068
Andy Hung0e48d252015-01-26 11:43:15 -080069 // FIXME handle in server, like createTrack_l(), possible missing info:
Glenn Kastene0fa4672012-04-24 14:35:14 -070070 // audio_io_handle_t output
71 // audio_format_t format
72 // audio_channel_mask_t channelMask
Andy Hung0e48d252015-01-26 11:43:15 -080073 // audio_output_flags_t flags (FAST)
Glenn Kasten3b16c762012-11-14 08:44:39 -080074 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080075 status_t status;
76 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
77 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080078 ALOGE("Unable to query output sample rate for stream type %d; status %d",
79 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080080 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080081 }
Glenn Kastene33054e2012-11-14 12:54:39 -080082 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -080083 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
84 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080085 ALOGE("Unable to query output frame count for stream type %d; status %d",
86 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080087 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080088 }
89 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -080090 status = AudioSystem::getOutputLatency(&afLatency, streamType);
91 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080092 ALOGE("Unable to query output latency for stream type %d; status %d",
93 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080094 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080095 }
96
97 // Ensure that buffer depth covers at least audio hardware latency
98 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080099 if (minBufCount < 2) {
100 minBufCount = 2;
101 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800102
Andy Hung0e48d252015-01-26 11:43:15 -0800103 *frameCount = minBufCount * sourceFramesNeeded(sampleRate, afFrameCount, afSampleRate);
104 // The formula above should always produce a non-zero value under normal circumstances:
105 // AudioTrack.SAMPLE_RATE_HZ_MIN <= sampleRate <= AudioTrack.SAMPLE_RATE_HZ_MAX.
106 // Return error in the unlikely event that it does not, as that's part of the API contract.
Glenn Kasten66a04672014-01-08 08:53:44 -0800107 if (*frameCount == 0) {
Andy Hung0e48d252015-01-26 11:43:15 -0800108 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %u",
Glenn Kasten66a04672014-01-08 08:53:44 -0800109 streamType, sampleRate);
110 return BAD_VALUE;
111 }
Andy Hung0e48d252015-01-26 11:43:15 -0800112 ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, minBufCount=%u, afSampleRate=%u, afLatency=%u",
Glenn Kasten3acbd052012-02-28 10:39:56 -0800113 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800114 return NO_ERROR;
115}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800116
117// ---------------------------------------------------------------------------
118
119AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700120 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800121 mIsTimed(false),
122 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800123 mPreviousSchedulingGroup(SP_DEFAULT),
124 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800125{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700126 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
127 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
128 mAttributes.flags = 0x0;
129 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800130}
131
132AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800133 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800134 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800135 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700136 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800137 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700138 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800139 callback_t cbf,
140 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800141 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800142 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000143 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800144 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800145 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700146 pid_t pid,
147 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700148 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800149 mIsTimed(false),
150 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800151 mPreviousSchedulingGroup(SP_DEFAULT),
152 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800153{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700154 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700155 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800156 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700157 offloadInfo, uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800158}
159
Andreas Huberc8139852012-01-18 10:51:55 -0800160AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800161 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800162 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800163 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700164 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800165 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700166 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800167 callback_t cbf,
168 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800169 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800170 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000171 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800172 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800173 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700174 pid_t pid,
175 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700176 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800177 mIsTimed(false),
178 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800179 mPreviousSchedulingGroup(SP_DEFAULT),
180 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800181{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700182 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800183 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800184 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700185 uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800186}
187
188AudioTrack::~AudioTrack()
189{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800190 if (mStatus == NO_ERROR) {
191 // Make sure that callback function exits in the case where
192 // it is looping on buffer full condition in obtainBuffer().
193 // Otherwise the callback thread will never exit.
194 stop();
195 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100196 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800197 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800198 mAudioTrackThread->requestExitAndWait();
199 mAudioTrackThread.clear();
200 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800201 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700202 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700203 mCblkMemory.clear();
204 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800205 IPCThreadState::self()->flushCommands();
Marco Nelissend457c972014-02-11 08:47:07 -0800206 ALOGV("~AudioTrack, releasing session id from %d on behalf of %d",
207 IPCThreadState::self()->getCallingPid(), mClientPid);
208 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800209 }
210}
211
212status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800213 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800214 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800215 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700216 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800217 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700218 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800219 callback_t cbf,
220 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800221 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800222 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700223 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800224 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000225 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800226 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800227 int uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700228 pid_t pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700229 const audio_attributes_t* pAttributes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800230{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800231 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten838b3d82014-02-27 15:30:41 -0800232 "flags #%x, notificationFrames %u, sessionId %d, transferType %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800233 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten86f04662014-02-24 15:13:05 -0800234 sessionId, transferType);
235
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800236 switch (transferType) {
237 case TRANSFER_DEFAULT:
238 if (sharedBuffer != 0) {
239 transferType = TRANSFER_SHARED;
240 } else if (cbf == NULL || threadCanCallJava) {
241 transferType = TRANSFER_SYNC;
242 } else {
243 transferType = TRANSFER_CALLBACK;
244 }
245 break;
246 case TRANSFER_CALLBACK:
247 if (cbf == NULL || sharedBuffer != 0) {
248 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
249 return BAD_VALUE;
250 }
251 break;
252 case TRANSFER_OBTAIN:
253 case TRANSFER_SYNC:
254 if (sharedBuffer != 0) {
255 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
256 return BAD_VALUE;
257 }
258 break;
259 case TRANSFER_SHARED:
260 if (sharedBuffer == 0) {
261 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
262 return BAD_VALUE;
263 }
264 break;
265 default:
266 ALOGE("Invalid transfer type %d", transferType);
267 return BAD_VALUE;
268 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800269 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800270 mTransfer = transferType;
271
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700272 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
273 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800274
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700275 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700276
Eric Laurent1703cdf2011-03-07 14:52:59 -0800277 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800278
Glenn Kasten53cec222013-08-29 09:01:02 -0700279 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700280 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000281 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800282 return INVALID_OPERATION;
283 }
284
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800285 // handle default values first.
Eric Laurente83b55d2014-11-14 10:06:21 -0800286 if (streamType == AUDIO_STREAM_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700287 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800288 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700289 if (pAttributes == NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800290 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700291 ALOGE("Invalid stream type %d", streamType);
292 return BAD_VALUE;
293 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700294 mStreamType = streamType;
Eric Laurente83b55d2014-11-14 10:06:21 -0800295
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700296 } else {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700297 // stream type shouldn't be looked at, this track has audio attributes
298 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700299 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
300 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800301 mStreamType = AUDIO_STREAM_DEFAULT;
Eric Laurentc6bd5db2015-03-09 16:29:33 -0700302 if ((mAttributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
303 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
304 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800305 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700306
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800307 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800308 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700309 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800310 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800311
312 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700313 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800314 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800315 return BAD_VALUE;
316 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800317 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700318
Glenn Kasten8ba90322013-10-30 11:29:27 -0700319 if (!audio_is_output_channel(channelMask)) {
320 ALOGE("Invalid channel mask %#x", channelMask);
321 return BAD_VALUE;
322 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800323 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700324 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800325 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700326
Eric Laurentc2f1f072009-07-17 12:17:14 -0700327 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100328 // or offload was requested
329 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
330 || !audio_is_linear_pcm(format)) {
331 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
332 ? "Offload request, forcing to Direct Output"
333 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700334 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800335 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700336 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700337 }
338
Eric Laurentd1f69b02014-12-15 14:33:13 -0800339 // force direct flag if HW A/V sync requested
340 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
341 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
342 }
343
Glenn Kastenb7730382014-04-30 15:50:31 -0700344 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
345 if (audio_is_linear_pcm(format)) {
346 mFrameSize = channelCount * audio_bytes_per_sample(format);
347 } else {
348 mFrameSize = sizeof(uint8_t);
349 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800350 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700351 ALOG_ASSERT(audio_is_linear_pcm(format));
352 mFrameSize = channelCount * audio_bytes_per_sample(format);
Glenn Kastenb7730382014-04-30 15:50:31 -0700353 // createTrack will return an error if PCM format is not supported by server,
354 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800355 }
356
Eric Laurent0d6db582014-11-12 18:39:44 -0800357 // sampling rate must be specified for direct outputs
358 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
359 return BAD_VALUE;
360 }
361 mSampleRate = sampleRate;
362
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800363 // Make copy of input parameter offloadInfo so that in the future:
364 // (a) createTrack_l doesn't need it as an input parameter
365 // (b) we can support re-creation of offloaded tracks
366 if (offloadInfo != NULL) {
367 mOffloadInfoCopy = *offloadInfo;
368 mOffloadInfo = &mOffloadInfoCopy;
369 } else {
370 mOffloadInfo = NULL;
371 }
372
Glenn Kasten66e46352014-01-16 17:44:23 -0800373 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
374 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800375 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800376 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800377 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700378 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800379 mNotificationFramesAct = 0;
Eric Laurentcaf7f482014-11-25 17:50:47 -0800380 if (sessionId == AUDIO_SESSION_ALLOCATE) {
381 mSessionId = AudioSystem::newAudioUniqueId();
382 } else {
383 mSessionId = sessionId;
384 }
Marco Nelissend457c972014-02-11 08:47:07 -0800385 int callingpid = IPCThreadState::self()->getCallingPid();
386 int mypid = getpid();
387 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800388 mClientUid = IPCThreadState::self()->getCallingUid();
389 } else {
390 mClientUid = uid;
391 }
Marco Nelissend457c972014-02-11 08:47:07 -0800392 if (pid == -1 || (callingpid != mypid)) {
393 mClientPid = callingpid;
394 } else {
395 mClientPid = pid;
396 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700397 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700398 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700399 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700400
Glenn Kastena997e7a2012-08-07 09:44:19 -0700401 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700402 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700403 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
404 }
405
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800406 // create the IAudioTrack
Eric Laurent0d6db582014-11-12 18:39:44 -0800407 status_t status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800408
Glenn Kastena997e7a2012-08-07 09:44:19 -0700409 if (status != NO_ERROR) {
410 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100411 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
412 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700413 mAudioTrackThread.clear();
414 }
415 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700416 }
417
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800418 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800419 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800420 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800421 mLoopCount = 0;
422 mLoopStart = 0;
423 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800424 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800425 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700426 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800427 mNewPosition = 0;
428 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700429 mServer = 0;
430 mPosition = 0;
431 mReleased = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700432 mStartUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800433 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800434 mSequence = 1;
435 mObservedSequence = mSequence;
436 mInUnderrun = false;
437
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800438 return NO_ERROR;
439}
440
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800441// -------------------------------------------------------------------------
442
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100443status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800444{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800445 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100446
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800447 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100448 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800449 }
450
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800451 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800452
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800453 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100454 if (previousState == STATE_PAUSED_STOPPING) {
455 mState = STATE_STOPPING;
456 } else {
457 mState = STATE_ACTIVE;
458 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700459 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800460 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
461 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700462 mPosition = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700463 // For offloaded tracks, we don't know if the hardware counters are really zero here,
464 // since the flush is asynchronous and stop may not fully drain.
465 // We save the time when the track is started to later verify whether
466 // the counters are realistic (i.e. start from zero after this time).
467 mStartUs = getNowUs();
468
Eric Laurentec9a0322013-08-28 10:23:01 -0700469 // force refresh of remaining frames by processAudioBuffer() as last
470 // write before stop could be partial.
471 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800472 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700473 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700474 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800475
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800476 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800477 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100478 if (previousState == STATE_STOPPING) {
479 mProxy->interrupt();
480 } else {
481 t->resume();
482 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800483 } else {
484 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
485 get_sched_policy(0, &mPreviousSchedulingGroup);
486 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
487 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800488
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800489 status_t status = NO_ERROR;
490 if (!(flags & CBLK_INVALID)) {
491 status = mAudioTrack->start();
492 if (status == DEAD_OBJECT) {
493 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800494 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800495 }
496 if (flags & CBLK_INVALID) {
497 status = restoreTrack_l("start");
498 }
499
500 if (status != NO_ERROR) {
501 ALOGE("start() status %d", status);
502 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800503 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100504 if (previousState != STATE_STOPPING) {
505 t->pause();
506 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800507 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700508 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700509 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800510 }
511 }
512
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100513 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800514}
515
516void AudioTrack::stop()
517{
518 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700519 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800520 return;
521 }
522
Glenn Kasten23a75452014-01-13 10:37:17 -0800523 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100524 mState = STATE_STOPPING;
525 } else {
526 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -0700527 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100528 }
529
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800530 mProxy->interrupt();
531 mAudioTrack->stop();
532 // the playback head position will reset to 0, so if a marker is set, we need
533 // to activate it again
534 mMarkerReached = false;
Andy Hung9b461582014-12-01 17:56:29 -0800535
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800536 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800537 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800538 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
539 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800540 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100541
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800542 sp<AudioTrackThread> t = mAudioTrackThread;
543 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800544 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100545 t->pause();
546 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800547 } else {
548 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
549 set_sched_policy(0, mPreviousSchedulingGroup);
550 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800551}
552
553bool AudioTrack::stopped() const
554{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800555 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800556 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800557}
558
559void AudioTrack::flush()
560{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800561 if (mSharedBuffer != 0) {
562 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800563 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800564 AutoMutex lock(mLock);
565 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
566 return;
567 }
568 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800569}
570
Eric Laurent1703cdf2011-03-07 14:52:59 -0800571void AudioTrack::flush_l()
572{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800573 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700574
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700575 // clear playback marker and periodic update counter
576 mMarkerPosition = 0;
577 mMarkerReached = false;
578 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100579 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700580
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800581 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700582 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800583 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100584 mProxy->interrupt();
585 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800586 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800587 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800588}
589
590void AudioTrack::pause()
591{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800592 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100593 if (mState == STATE_ACTIVE) {
594 mState = STATE_PAUSED;
595 } else if (mState == STATE_STOPPING) {
596 mState = STATE_PAUSED_STOPPING;
597 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800598 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800599 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800600 mProxy->interrupt();
601 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800602
Marco Nelissen3a90f282014-03-10 11:21:43 -0700603 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700604 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700605 // An offload output can be re-used between two audio tracks having
606 // the same configuration. A timestamp query for a paused track
607 // while the other is running would return an incorrect time.
608 // To fix this, cache the playback position on a pause() and return
609 // this time when requested until the track is resumed.
610
611 // OffloadThread sends HAL pause in its threadLoop. Time saved
612 // here can be slightly off.
613
614 // TODO: check return code for getRenderPosition.
615
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800616 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800617 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
618 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
619 }
620 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800621}
622
Eric Laurentbe916aa2010-06-01 23:49:17 -0700623status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800624{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700625 // This duplicates a test by AudioTrack JNI, but that is not the only caller
626 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
627 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700628 return BAD_VALUE;
629 }
630
Eric Laurent1703cdf2011-03-07 14:52:59 -0800631 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800632 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
633 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800634
Glenn Kastenc56f3422014-03-21 17:53:17 -0700635 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700636
Glenn Kasten23a75452014-01-13 10:37:17 -0800637 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700638 mAudioTrack->signal();
639 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700640 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800641}
642
Glenn Kastenb1c09932012-02-27 16:21:04 -0800643status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800644{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800645 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700646}
647
Eric Laurent2beeb502010-07-16 07:43:46 -0700648status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700649{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700650 // This duplicates a test by AudioTrack JNI, but that is not the only caller
651 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700652 return BAD_VALUE;
653 }
654
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800655 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700656 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800657 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700658
659 return NO_ERROR;
660}
661
Glenn Kastena5224f32012-01-04 12:41:44 -0800662void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700663{
664 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800665 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700666 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800667}
668
Glenn Kasten3b16c762012-11-14 08:44:39 -0800669status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800670{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700671 if (mIsTimed || isOffloadedOrDirect()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800672 return INVALID_OPERATION;
673 }
674
Eric Laurent0d6db582014-11-12 18:39:44 -0800675 AutoMutex lock(mLock);
676 if (mOutput == AUDIO_IO_HANDLE_NONE) {
677 return NO_INIT;
678 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800679 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800680 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700681 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800682 }
Andy Hungcd044842014-08-07 11:04:34 -0700683 if (rate == 0 || rate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700684 return BAD_VALUE;
685 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800686
Glenn Kastene3aa6592012-12-04 12:22:46 -0800687 mSampleRate = rate;
688 mProxy->setSampleRate(rate);
689
Eric Laurent57326622009-07-07 07:10:45 -0700690 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800691}
692
Glenn Kastena5224f32012-01-04 12:41:44 -0800693uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800694{
John Grossman4ff14ba2012-02-08 16:37:41 -0800695 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800696 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800697 }
698
Eric Laurent1703cdf2011-03-07 14:52:59 -0800699 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700700
701 // sample rate can be updated during playback by the offloaded decoder so we need to
702 // query the HAL and update if needed.
703// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700704 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700705 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700706 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700707 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700708 if (status == NO_ERROR) {
709 mSampleRate = sampleRate;
710 }
711 }
712 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800713 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800714}
715
716status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
717{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700718 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800719 return INVALID_OPERATION;
720 }
721
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800722 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800723 ;
724 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
725 loopEnd - loopStart >= MIN_LOOP) {
726 ;
727 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800728 return BAD_VALUE;
729 }
730
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800731 AutoMutex lock(mLock);
732 // See setPosition() regarding setting parameters such as loop points or position while active
733 if (mState == STATE_ACTIVE) {
734 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700735 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800736 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800737 return NO_ERROR;
738}
739
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800740void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
741{
Andy Hung4ede21d2014-12-12 15:37:34 -0800742 // We do not update the periodic notification point.
743 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
744 mLoopCount = loopCount;
745 mLoopEnd = loopEnd;
746 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800747 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800748 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -0800749
750 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800751}
752
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800753status_t AudioTrack::setMarkerPosition(uint32_t marker)
754{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700755 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700756 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700757 return INVALID_OPERATION;
758 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800759
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800760 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800761 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700762 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800763
Andy Hung3c09c782014-12-29 18:39:32 -0800764 sp<AudioTrackThread> t = mAudioTrackThread;
765 if (t != 0) {
766 t->wake();
767 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800768 return NO_ERROR;
769}
770
Glenn Kastena5224f32012-01-04 12:41:44 -0800771status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800772{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700773 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100774 return INVALID_OPERATION;
775 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700776 if (marker == NULL) {
777 return BAD_VALUE;
778 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800779
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800780 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800781 *marker = mMarkerPosition;
782
783 return NO_ERROR;
784}
785
786status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
787{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700788 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700789 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700790 return INVALID_OPERATION;
791 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800792
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800793 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700794 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800795 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800796
Andy Hung3c09c782014-12-29 18:39:32 -0800797 sp<AudioTrackThread> t = mAudioTrackThread;
798 if (t != 0) {
799 t->wake();
800 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800801 return NO_ERROR;
802}
803
Glenn Kastena5224f32012-01-04 12:41:44 -0800804status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800805{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700806 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100807 return INVALID_OPERATION;
808 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700809 if (updatePeriod == NULL) {
810 return BAD_VALUE;
811 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800812
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800813 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800814 *updatePeriod = mUpdatePeriod;
815
816 return NO_ERROR;
817}
818
819status_t AudioTrack::setPosition(uint32_t position)
820{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700821 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700822 return INVALID_OPERATION;
823 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800824 if (position > mFrameCount) {
825 return BAD_VALUE;
826 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800827
Eric Laurent1703cdf2011-03-07 14:52:59 -0800828 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800829 // Currently we require that the player is inactive before setting parameters such as position
830 // or loop points. Otherwise, there could be a race condition: the application could read the
831 // current position, compute a new position or loop parameters, and then set that position or
832 // loop parameters but it would do the "wrong" thing since the position has continued to advance
833 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
834 // to specify how it wants to handle such scenarios.
835 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700836 return INVALID_OPERATION;
837 }
Andy Hung9b461582014-12-01 17:56:29 -0800838 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -0700839 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800840 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -0800841
842 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800843 return NO_ERROR;
844}
845
Glenn Kasten200092b2014-08-15 15:13:30 -0700846status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800847{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700848 if (position == NULL) {
849 return BAD_VALUE;
850 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800851
Eric Laurent1703cdf2011-03-07 14:52:59 -0800852 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700853 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100854 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800855
Eric Laurentab5cdba2014-06-09 17:22:27 -0700856 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800857 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
858 *position = mPausedPosition;
859 return NO_ERROR;
860 }
861
Glenn Kasten142f5192014-03-25 17:44:59 -0700862 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100863 uint32_t halFrames;
864 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
865 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700866 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
867 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100868 *position = dspFrames;
869 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -0800870 if (mCblk->mFlags & CBLK_INVALID) {
871 restoreTrack_l("getPosition");
872 }
873
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100874 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700875 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
876 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100877 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800878 return NO_ERROR;
879}
880
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000881status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800882{
883 if (mSharedBuffer == 0 || mIsTimed) {
884 return INVALID_OPERATION;
885 }
886 if (position == NULL) {
887 return BAD_VALUE;
888 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800889
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800890 AutoMutex lock(mLock);
891 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800892 return NO_ERROR;
893}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800894
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800895status_t AudioTrack::reload()
896{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700897 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800898 return INVALID_OPERATION;
899 }
900
Eric Laurent1703cdf2011-03-07 14:52:59 -0800901 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800902 // See setPosition() regarding setting parameters such as loop points or position while active
903 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700904 return INVALID_OPERATION;
905 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800906 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800907 (void) updateAndGetPosition_l();
908 mPosition = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800909#if 0
Andy Hung9b461582014-12-01 17:56:29 -0800910 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -0800911 // of loop count. Historically we have not restored loop count, start, end,
912 // but it makes sense if one desires to repeat playing a particular sound.
913 if (mLoopCount != 0) {
914 mLoopCountNotified = mLoopCount;
915 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
916 }
917#endif
Andy Hung9b461582014-12-01 17:56:29 -0800918 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800919 return NO_ERROR;
920}
921
Glenn Kasten38e905b2014-01-13 10:21:48 -0800922audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700923{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800924 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100925 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800926}
927
Eric Laurentbe916aa2010-06-01 23:49:17 -0700928status_t AudioTrack::attachAuxEffect(int effectId)
929{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800930 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700931 status_t status = mAudioTrack->attachAuxEffect(effectId);
932 if (status == NO_ERROR) {
933 mAuxEffectId = effectId;
934 }
935 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700936}
937
Eric Laurente83b55d2014-11-14 10:06:21 -0800938audio_stream_type_t AudioTrack::streamType() const
939{
940 if (mStreamType == AUDIO_STREAM_DEFAULT) {
941 return audio_attributes_to_stream_type(&mAttributes);
942 }
943 return mStreamType;
944}
945
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800946// -------------------------------------------------------------------------
947
Eric Laurent1703cdf2011-03-07 14:52:59 -0800948// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -0700949status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800950{
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800951 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
952 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700953 ALOGE("Could not get audioflinger");
954 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800955 }
956
Eric Laurente83b55d2014-11-14 10:06:21 -0800957 audio_io_handle_t output;
958 audio_stream_type_t streamType = mStreamType;
959 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
960 status_t status = AudioSystem::getOutputForAttr(attr, &output,
961 (audio_session_t)mSessionId, &streamType,
962 mSampleRate, mFormat, mChannelMask,
963 mFlags, mOffloadInfo);
964
965
966 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700967 ALOGE("Could not get audio output for stream type %d, usage %d, sample rate %u, format %#x,"
968 " channel mask %#x, flags %#x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800969 streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800970 return BAD_VALUE;
971 }
972 {
973 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
974 // we must release it ourselves if anything goes wrong.
975
Glenn Kastence8828a2013-09-16 18:07:38 -0700976 // Not all of these values are needed under all conditions, but it is easier to get them all
977
Eric Laurentd1b449a2010-05-14 03:26:45 -0700978 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -0700979 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700980 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800981 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800982 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700983 }
984
Glenn Kastence8828a2013-09-16 18:07:38 -0700985 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700986 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -0700987 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700988 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800989 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700990 }
991
992 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700993 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -0700994 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700995 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800996 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700997 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800998 if (mSampleRate == 0) {
999 mSampleRate = afSampleRate;
1000 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001001 // Client decides whether the track is TIMED (see below), but can only express a preference
1002 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001003 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001004 // either of these use cases:
1005 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -08001006 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001007 // use case 2: callback transfer mode
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001008 (mTransfer == TRANSFER_CALLBACK) ||
1009 // use case 3: obtain/release mode
1010 (mTransfer == TRANSFER_OBTAIN)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001011 // matching sample rate
1012 (mSampleRate == afSampleRate))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08001013 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -07001014 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001015 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001016 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001017 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001018
Glenn Kastence8828a2013-09-16 18:07:38 -07001019 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -08001020 // n = 1 fast track with single buffering; nBuffering is ignored
1021 // n = 2 fast track with double buffering
Andy Hung0e48d252015-01-26 11:43:15 -08001022 // n = 2 normal track, (including those with sample rate conversion)
1023 // n >= 3 very high latency or very small notification interval (unused).
1024 const uint32_t nBuffering = 2;
Glenn Kastence8828a2013-09-16 18:07:38 -07001025
Eric Laurentd1b449a2010-05-14 03:26:45 -07001026 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001027
Glenn Kasten363fb752014-01-15 12:27:31 -08001028 size_t frameCount = mReqFrameCount;
1029 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001030
Glenn Kasten363fb752014-01-15 12:27:31 -08001031 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001032 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001033 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001034 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001035 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001036 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001037 if (mNotificationFramesAct != frameCount) {
1038 mNotificationFramesAct = frameCount;
1039 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001040 } else if (mSharedBuffer != 0) {
Andy Hungabdb9902015-01-12 15:08:22 -08001041 // FIXME: Ensure client side memory buffers need
1042 // not have additional alignment beyond sample
1043 // (e.g. 16 bit stereo accessed as 32 bit frame).
1044 size_t alignment = audio_bytes_per_sample(mFormat);
Glenn Kastenb7730382014-04-30 15:50:31 -07001045 if (alignment & 1) {
Andy Hungabdb9902015-01-12 15:08:22 -08001046 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
Glenn Kastenb7730382014-04-30 15:50:31 -07001047 alignment = 1;
1048 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001049 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001050 // More than 2 channels does not require stronger alignment than stereo
1051 alignment <<= 1;
1052 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001053 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001054 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001055 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001056 status = BAD_VALUE;
1057 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001058 }
1059
1060 // When initializing a shared buffer AudioTrack via constructors,
1061 // there's no frameCount parameter.
1062 // But when initializing a shared buffer AudioTrack via set(),
1063 // there _is_ a frameCount parameter. We silently ignore it.
Andy Hungabdb9902015-01-12 15:08:22 -08001064 frameCount = mSharedBuffer->size() / mFrameSize;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001065 } else {
Andy Hung0e48d252015-01-26 11:43:15 -08001066 // For fast and normal streaming tracks,
1067 // the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -07001068 }
1069
Glenn Kastena075db42012-03-06 11:22:44 -08001070 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1071 if (mIsTimed) {
1072 trackFlags |= IAudioFlinger::TRACK_TIMED;
1073 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001074
1075 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001076 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001077 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001078 if (mAudioTrackThread != 0) {
1079 tid = mAudioTrackThread->getTid();
1080 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001081 }
1082
Glenn Kasten363fb752014-01-15 12:27:31 -08001083 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001084 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1085 }
1086
Eric Laurentab5cdba2014-06-09 17:22:27 -07001087 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1088 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1089 }
1090
Glenn Kasten74935e42013-12-19 08:56:45 -08001091 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1092 // but we will still need the original value also
Eric Laurente83b55d2014-11-14 10:06:21 -08001093 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001094 mSampleRate,
Andy Hungabdb9902015-01-12 15:08:22 -08001095 mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001096 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001097 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001098 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001099 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001100 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001101 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001102 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001103 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001104 &status);
1105
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001106 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001107 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001108 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001109 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001110 ALOG_ASSERT(track != 0);
1111
Glenn Kasten38e905b2014-01-13 10:21:48 -08001112 // AudioFlinger now owns the reference to the I/O handle,
1113 // so we are no longer responsible for releasing it.
1114
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001115 sp<IMemory> iMem = track->getCblk();
1116 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001117 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001118 return NO_INIT;
1119 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001120 void *iMemPointer = iMem->pointer();
1121 if (iMemPointer == NULL) {
1122 ALOGE("Could not get control block pointer");
1123 return NO_INIT;
1124 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001125 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001126 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001127 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001128 mDeathNotifier.clear();
1129 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001130 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001131 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001132 IPCThreadState::self()->flushCommands();
1133
Glenn Kasten0cde0762014-01-16 15:06:36 -08001134 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001135 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001136 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001137 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1138 // In current design, AudioTrack client checks and ensures frame count validity before
1139 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1140 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001141 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001142 }
1143 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001144
Glenn Kastena07f17c2013-04-23 12:39:37 -07001145 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001146 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001147 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001148 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001149 mAwaitBoost = true;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001150 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001151 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001152 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001153 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001154 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001155 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001156 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001157 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1158 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1159 } else {
1160 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001161 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001162 // FIXME This is a warning, not an error, so don't return error status
1163 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001164 }
1165 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001166 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1167 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1168 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1169 } else {
1170 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1171 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1172 // FIXME This is a warning, not an error, so don't return error status
1173 //return NO_INIT;
1174 }
1175 }
Andy Hung0e48d252015-01-26 11:43:15 -08001176 // Make sure that application is notified with sufficient margin before underrun
1177 if (mSharedBuffer == 0 && audio_is_linear_pcm(mFormat)) {
1178 // Theoretically double-buffering is not required for fast tracks,
1179 // due to tighter scheduling. But in practice, to accommodate kernels with
1180 // scheduling jitter, and apps with computation jitter, we use double-buffering
1181 // for fast tracks just like normal streaming tracks.
1182 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount / nBuffering) {
1183 mNotificationFramesAct = frameCount / nBuffering;
1184 }
1185 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001186
Glenn Kasten38e905b2014-01-13 10:21:48 -08001187 // We retain a copy of the I/O handle, but don't own the reference
1188 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001189 mRefreshRemaining = true;
1190
1191 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1192 // is the value of pointer() for the shared buffer, otherwise buffers points
1193 // immediately after the control block. This address is for the mapping within client
1194 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1195 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001196 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001197 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001198 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001199 buffers = mSharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001200 }
1201
Eric Laurent2beeb502010-07-16 07:43:46 -07001202 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001203 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001204 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001205
Glenn Kastenb6037442012-11-14 13:42:25 -08001206 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001207 // If IAudioTrack is re-created, don't let the requested frameCount
1208 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001209 if (frameCount > mReqFrameCount) {
1210 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001211 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001212
1213 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001214 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001215 mStaticProxy.clear();
Andy Hungabdb9902015-01-12 15:08:22 -08001216 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001217 } else {
Andy Hungabdb9902015-01-12 15:08:22 -08001218 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001219 mProxy = mStaticProxy;
1220 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001221
1222 mProxy->setVolumeLR(gain_minifloat_pack(
1223 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1224 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1225
Glenn Kastene3aa6592012-12-04 12:22:46 -08001226 mProxy->setSendLevel(mSendLevel);
1227 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001228 mProxy->setMinimum(mNotificationFramesAct);
1229
1230 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001231 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001232
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001233 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001234 }
1235
1236release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001237 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001238 if (status == NO_ERROR) {
1239 status = NO_INIT;
1240 }
1241 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001242}
1243
Glenn Kastenb46f3942015-03-09 12:00:30 -07001244status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001245{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001246 if (audioBuffer == NULL) {
1247 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001248 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001249 if (mTransfer != TRANSFER_OBTAIN) {
1250 audioBuffer->frameCount = 0;
1251 audioBuffer->size = 0;
1252 audioBuffer->raw = NULL;
1253 return INVALID_OPERATION;
1254 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001255
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001256 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001257 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001258 if (waitCount == -1) {
1259 requested = &ClientProxy::kForever;
1260 } else if (waitCount == 0) {
1261 requested = &ClientProxy::kNonBlocking;
1262 } else if (waitCount > 0) {
1263 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001264 timeout.tv_sec = ms / 1000;
1265 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1266 requested = &timeout;
1267 } else {
1268 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1269 requested = NULL;
1270 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001271 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001272}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001273
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001274status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1275 struct timespec *elapsed, size_t *nonContig)
1276{
1277 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1278 uint32_t oldSequence = 0;
1279 uint32_t newSequence;
1280
1281 Proxy::Buffer buffer;
1282 status_t status = NO_ERROR;
1283
1284 static const int32_t kMaxTries = 5;
1285 int32_t tryCounter = kMaxTries;
1286
1287 do {
1288 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1289 // keep them from going away if another thread re-creates the track during obtainBuffer()
1290 sp<AudioTrackClientProxy> proxy;
1291 sp<IMemory> iMem;
1292
1293 { // start of lock scope
1294 AutoMutex lock(mLock);
1295
1296 newSequence = mSequence;
1297 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1298 if (status == DEAD_OBJECT) {
1299 // re-create track, unless someone else has already done so
1300 if (newSequence == oldSequence) {
1301 status = restoreTrack_l("obtainBuffer");
1302 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001303 buffer.mFrameCount = 0;
1304 buffer.mRaw = NULL;
1305 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001306 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001307 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001308 }
1309 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001310 oldSequence = newSequence;
1311
1312 // Keep the extra references
1313 proxy = mProxy;
1314 iMem = mCblkMemory;
1315
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001316 if (mState == STATE_STOPPING) {
1317 status = -EINTR;
1318 buffer.mFrameCount = 0;
1319 buffer.mRaw = NULL;
1320 buffer.mNonContig = 0;
1321 break;
1322 }
1323
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001324 // Non-blocking if track is stopped or paused
1325 if (mState != STATE_ACTIVE) {
1326 requested = &ClientProxy::kNonBlocking;
1327 }
1328
1329 } // end of lock scope
1330
1331 buffer.mFrameCount = audioBuffer->frameCount;
1332 // FIXME starts the requested timeout and elapsed over from scratch
1333 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1334
1335 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1336
1337 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001338 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001339 audioBuffer->raw = buffer.mRaw;
1340 if (nonContig != NULL) {
1341 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001342 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001343 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001344}
1345
Glenn Kasten54a8a452015-03-09 12:03:00 -07001346void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001347{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001348 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001349 if (mTransfer == TRANSFER_SHARED) {
1350 return;
1351 }
1352
Andy Hungabdb9902015-01-12 15:08:22 -08001353 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001354 if (stepCount == 0) {
1355 return;
1356 }
1357
1358 Proxy::Buffer buffer;
1359 buffer.mFrameCount = stepCount;
1360 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001361
Eric Laurent1703cdf2011-03-07 14:52:59 -08001362 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001363 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001364 mInUnderrun = false;
1365 mProxy->releaseBuffer(&buffer);
1366
1367 // restart track if it was disabled by audioflinger due to previous underrun
1368 if (mState == STATE_ACTIVE) {
1369 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001370 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001371 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001372 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001373 mAudioTrack->start();
1374 }
1375 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001376}
1377
1378// -------------------------------------------------------------------------
1379
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001380ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001381{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001382 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001383 return INVALID_OPERATION;
1384 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001385
Eric Laurentab5cdba2014-06-09 17:22:27 -07001386 if (isDirect()) {
1387 AutoMutex lock(mLock);
1388 int32_t flags = android_atomic_and(
1389 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1390 &mCblk->mFlags);
1391 if (flags & CBLK_INVALID) {
1392 return DEAD_OBJECT;
1393 }
1394 }
1395
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001396 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001397 // Sanity-check: user is most-likely passing an error code, and it would
1398 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001399 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001400 return BAD_VALUE;
1401 }
1402
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001403 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001404 Buffer audioBuffer;
1405
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001406 while (userSize >= mFrameSize) {
1407 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001408
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001409 status_t err = obtainBuffer(&audioBuffer,
1410 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001411 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001412 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001413 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001414 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001415 return ssize_t(err);
1416 }
1417
Glenn Kastenae4b8792015-03-20 09:04:21 -07001418 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08001419 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001420 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001421 userSize -= toWrite;
1422 written += toWrite;
1423
1424 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001425 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001426
1427 return written;
1428}
1429
1430// -------------------------------------------------------------------------
1431
John Grossman4ff14ba2012-02-08 16:37:41 -08001432TimedAudioTrack::TimedAudioTrack() {
1433 mIsTimed = true;
1434}
1435
1436status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1437{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001438 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001439 status_t result = UNKNOWN_ERROR;
1440
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001441#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001442 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1443 // while we are accessing the cblk
1444 sp<IAudioTrack> audioTrack = mAudioTrack;
1445 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001446#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001447
John Grossman4ff14ba2012-02-08 16:37:41 -08001448 // If the track is not invalid already, try to allocate a buffer. alloc
1449 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001450 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001451 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001452 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001453 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1454 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001455 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001456 }
1457 }
1458
1459 // If the track is invalid at this point, attempt to restore it. and try the
1460 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001461 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001462 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001463
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001464 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001465 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001466 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001467 }
1468
1469 return result;
1470}
1471
1472status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1473 int64_t pts)
1474{
Eric Laurentdf839842012-05-31 14:27:14 -07001475 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1476 {
1477 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001478 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001479 // restart track if it was disabled by audioflinger due to previous underrun
1480 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001481 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1482 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001483 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001484 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001485 mAudioTrack->start();
1486 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001487 }
Eric Laurentdf839842012-05-31 14:27:14 -07001488 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001489}
1490
1491status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1492 TargetTimeline target)
1493{
1494 return mAudioTrack->setMediaTimeTransform(xform, target);
1495}
1496
1497// -------------------------------------------------------------------------
1498
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001499nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001500{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001501 // Currently the AudioTrack thread is not created if there are no callbacks.
1502 // Would it ever make sense to run the thread, even without callbacks?
1503 // If so, then replace this by checks at each use for mCbf != NULL.
1504 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1505
Eric Laurent1703cdf2011-03-07 14:52:59 -08001506 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001507 if (mAwaitBoost) {
1508 mAwaitBoost = false;
1509 mLock.unlock();
1510 static const int32_t kMaxTries = 5;
1511 int32_t tryCounter = kMaxTries;
1512 uint32_t pollUs = 10000;
1513 do {
1514 int policy = sched_getscheduler(0);
1515 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1516 break;
1517 }
1518 usleep(pollUs);
1519 pollUs <<= 1;
1520 } while (tryCounter-- > 0);
1521 if (tryCounter < 0) {
1522 ALOGE("did not receive expected priority boost on time");
1523 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001524 // Run again immediately
1525 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001526 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001527
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001528 // Can only reference mCblk while locked
1529 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001530 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001531
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001532 // Check for track invalidation
1533 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001534 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1535 // AudioSystem cache. We should not exit here but after calling the callback so
1536 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001537 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001538 status_t status = restoreTrack_l("processAudioBuffer");
Andy Hung53c3b5f2014-12-15 16:42:05 -08001539 // after restoration, continue below to make sure that the loop and buffer events
1540 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001541 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001542 }
1543
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001544 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001545 bool active = mState == STATE_ACTIVE;
1546
1547 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1548 bool newUnderrun = false;
1549 if (flags & CBLK_UNDERRUN) {
1550#if 0
1551 // Currently in shared buffer mode, when the server reaches the end of buffer,
1552 // the track stays active in continuous underrun state. It's up to the application
1553 // to pause or stop the track, or set the position to a new offset within buffer.
1554 // This was some experimental code to auto-pause on underrun. Keeping it here
1555 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1556 if (mTransfer == TRANSFER_SHARED) {
1557 mState = STATE_PAUSED;
1558 active = false;
1559 }
1560#endif
1561 if (!mInUnderrun) {
1562 mInUnderrun = true;
1563 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001564 }
1565 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001566
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001567 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001568 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001569
1570 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001571 bool markerReached = false;
1572 size_t markerPosition = mMarkerPosition;
1573 // FIXME fails for wraparound, need 64 bits
1574 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1575 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001576 }
1577
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001578 // Determine number of new position callback(s) that will be needed, while locked
1579 size_t newPosCount = 0;
1580 size_t newPosition = mNewPosition;
1581 size_t updatePeriod = mUpdatePeriod;
1582 // FIXME fails for wraparound, need 64 bits
1583 if (updatePeriod > 0 && position >= newPosition) {
1584 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1585 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001586 }
1587
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001588 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001589 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001590 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001591 if (mRefreshRemaining) {
1592 mRefreshRemaining = false;
1593 mRemainingFrames = notificationFrames;
1594 mRetryOnPartialBuffer = false;
1595 }
1596 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001597 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001598 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001599
Andy Hung53c3b5f2014-12-15 16:42:05 -08001600 // Determine the number of new loop callback(s) that will be needed, while locked.
1601 int loopCountNotifications = 0;
1602 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1603
1604 if (mLoopCount > 0) {
1605 int loopCount;
1606 size_t bufferPosition;
1607 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1608 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1609 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1610 mLoopCountNotified = loopCount; // discard any excess notifications
1611 } else if (mLoopCount < 0) {
1612 // FIXME: We're not accurate with notification count and position with infinite looping
1613 // since loopCount from server side will always return -1 (we could decrement it).
1614 size_t bufferPosition = mStaticProxy->getBufferPosition();
1615 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1616 loopPeriod = mLoopEnd - bufferPosition;
1617 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1618 size_t bufferPosition = mStaticProxy->getBufferPosition();
1619 loopPeriod = mFrameCount - bufferPosition;
1620 }
1621
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001622 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08001623 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001624 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1625
1626 mLock.unlock();
1627
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001628 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001629 struct timespec timeout;
1630 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1631 timeout.tv_nsec = 0;
1632
Glenn Kasten96f04882013-09-20 09:28:56 -07001633 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001634 switch (status) {
1635 case NO_ERROR:
1636 case DEAD_OBJECT:
1637 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001638 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001639 {
1640 AutoMutex lock(mLock);
1641 // The previously assigned value of waitStreamEnd is no longer valid,
1642 // since the mutex has been unlocked and either the callback handler
1643 // or another thread could have re-started the AudioTrack during that time.
1644 waitStreamEnd = mState == STATE_STOPPING;
1645 if (waitStreamEnd) {
1646 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001647 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001648 }
1649 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001650 if (waitStreamEnd && status != DEAD_OBJECT) {
1651 return NS_INACTIVE;
1652 }
1653 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001654 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001655 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001656 }
1657
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001658 // perform callbacks while unlocked
1659 if (newUnderrun) {
1660 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1661 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001662 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001663 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001664 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001665 }
1666 if (flags & CBLK_BUFFER_END) {
1667 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1668 }
1669 if (markerReached) {
1670 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1671 }
1672 while (newPosCount > 0) {
1673 size_t temp = newPosition;
1674 mCbf(EVENT_NEW_POS, mUserData, &temp);
1675 newPosition += updatePeriod;
1676 newPosCount--;
1677 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001678
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001679 if (mObservedSequence != sequence) {
1680 mObservedSequence = sequence;
1681 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001682 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001683 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001684 return NS_INACTIVE;
1685 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001686 }
1687
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001688 // if inactive, then don't run me again until re-started
1689 if (!active) {
1690 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001691 }
1692
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001693 // Compute the estimated time until the next timed event (position, markers, loops)
1694 // FIXME only for non-compressed audio
1695 uint32_t minFrames = ~0;
1696 if (!markerReached && position < markerPosition) {
1697 minFrames = markerPosition - position;
1698 }
1699 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08001700 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001701 minFrames = loopPeriod;
1702 }
Andy Hung2d85f092015-01-07 12:45:13 -08001703 if (updatePeriod > 0) {
1704 minFrames = min(minFrames, uint32_t(newPosition - position));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001705 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001706
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001707 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1708 static const uint32_t kPoll = 0;
1709 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1710 minFrames = kPoll * notificationFrames;
1711 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001712
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001713 // Convert frame units to time units
1714 nsecs_t ns = NS_WHENEVER;
1715 if (minFrames != (uint32_t) ~0) {
1716 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1717 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1718 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1719 }
1720
1721 // If not supplying data by EVENT_MORE_DATA, then we're done
1722 if (mTransfer != TRANSFER_CALLBACK) {
1723 return ns;
1724 }
1725
1726 struct timespec timeout;
1727 const struct timespec *requested = &ClientProxy::kForever;
1728 if (ns != NS_WHENEVER) {
1729 timeout.tv_sec = ns / 1000000000LL;
1730 timeout.tv_nsec = ns % 1000000000LL;
1731 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1732 requested = &timeout;
1733 }
1734
1735 while (mRemainingFrames > 0) {
1736
1737 Buffer audioBuffer;
1738 audioBuffer.frameCount = mRemainingFrames;
1739 size_t nonContig;
1740 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1741 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001742 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001743 requested = &ClientProxy::kNonBlocking;
1744 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001745 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001746 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001747 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001748 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1749 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001750 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001751 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001752 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1753 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001754 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001755
Eric Laurent42a6f422013-08-29 14:35:05 -07001756 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001757 mRetryOnPartialBuffer = false;
1758 if (avail < mRemainingFrames) {
1759 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1760 if (ns < 0 || myns < ns) {
1761 ns = myns;
1762 }
1763 return ns;
1764 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001765 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001766
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001767 size_t reqSize = audioBuffer.size;
1768 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001769 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001770
1771 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001772 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001773 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1774 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001775 return NS_NEVER;
1776 }
1777
1778 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001779 // The callback is done filling buffers
1780 // Keep this thread going to handle timed events and
1781 // still try to get more data in intervals of WAIT_PERIOD_MS
1782 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001783 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001784 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001785
Andy Hungabdb9902015-01-12 15:08:22 -08001786 size_t releasedFrames = audioBuffer.size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001787 audioBuffer.frameCount = releasedFrames;
1788 mRemainingFrames -= releasedFrames;
1789 if (misalignment >= releasedFrames) {
1790 misalignment -= releasedFrames;
1791 } else {
1792 misalignment = 0;
1793 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001794
1795 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001796
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001797 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1798 // if callback doesn't like to accept the full chunk
1799 if (writtenSize < reqSize) {
1800 continue;
1801 }
1802
1803 // There could be enough non-contiguous frames available to satisfy the remaining request
1804 if (mRemainingFrames <= nonContig) {
1805 continue;
1806 }
1807
1808#if 0
1809 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1810 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1811 // that total to a sum == notificationFrames.
1812 if (0 < misalignment && misalignment <= mRemainingFrames) {
1813 mRemainingFrames = misalignment;
1814 return (mRemainingFrames * 1100000000LL) / sampleRate;
1815 }
1816#endif
1817
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001818 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001819 mRemainingFrames = notificationFrames;
1820 mRetryOnPartialBuffer = true;
1821
1822 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1823 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001824}
1825
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001826status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001827{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001828 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001829 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001830 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001831
Glenn Kastena47f3162012-11-07 10:13:08 -08001832 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08001833 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001834 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001835
Eric Laurentab5cdba2014-06-09 17:22:27 -07001836 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001837 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001838 return DEAD_OBJECT;
1839 }
1840
Glenn Kasten200092b2014-08-15 15:13:30 -07001841 // save the old static buffer position
Andy Hung4ede21d2014-12-12 15:37:34 -08001842 size_t bufferPosition = 0;
1843 int loopCount = 0;
1844 if (mStaticProxy != 0) {
1845 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1846 }
Glenn Kasten200092b2014-08-15 15:13:30 -07001847
1848 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001849 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001850 // It will also delete the strong references on previous IAudioTrack and IMemory.
1851 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Glenn Kastenae4b8792015-03-20 09:04:21 -07001852 status_t result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001853
1854 // take the frames that will be lost by track recreation into account in saved position
Andy Hung9b461582014-12-01 17:56:29 -08001855 // For streaming tracks, this is the amount we obtained from the user/client
1856 // (not the number actually consumed at the server - those are already lost).
Glenn Kasten200092b2014-08-15 15:13:30 -07001857 (void) updateAndGetPosition_l();
Andy Hung9b461582014-12-01 17:56:29 -08001858 if (mStaticProxy != 0) {
1859 mPosition = mReleased;
1860 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001861
Glenn Kastena47f3162012-11-07 10:13:08 -08001862 if (result == NO_ERROR) {
Andy Hung4ede21d2014-12-12 15:37:34 -08001863 // Continue playback from last known position and restore loop.
1864 if (mStaticProxy != 0) {
1865 if (loopCount != 0) {
1866 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
1867 mLoopStart, mLoopEnd, loopCount);
1868 } else {
1869 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001870 if (bufferPosition == mFrameCount) {
1871 ALOGD("restoring track at end of static buffer");
1872 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001873 }
1874 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001875 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001876 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001877 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001878 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001879 if (result != NO_ERROR) {
1880 ALOGW("restoreTrack_l() failed status %d", result);
1881 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001882 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001883 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001884
1885 return result;
1886}
1887
Glenn Kasten200092b2014-08-15 15:13:30 -07001888uint32_t AudioTrack::updateAndGetPosition_l()
1889{
1890 // This is the sole place to read server consumed frames
1891 uint32_t newServer = mProxy->getPosition();
1892 int32_t delta = newServer - mServer;
1893 mServer = newServer;
1894 // TODO There is controversy about whether there can be "negative jitter" in server position.
1895 // This should be investigated further, and if possible, it should be addressed.
1896 // A more definite failure mode is infrequent polling by client.
1897 // One could call (void)getPosition_l() in releaseBuffer(),
1898 // so mReleased and mPosition are always lock-step as best possible.
1899 // That should ensure delta never goes negative for infrequent polling
1900 // unless the server has more than 2^31 frames in its buffer,
1901 // in which case the use of uint32_t for these counters has bigger issues.
1902 if (delta < 0) {
1903 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
1904 delta = 0;
1905 }
1906 return mPosition += (uint32_t) delta;
1907}
1908
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001909status_t AudioTrack::setParameters(const String8& keyValuePairs)
1910{
1911 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001912 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001913}
1914
Glenn Kastence703742013-07-19 16:33:58 -07001915status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1916{
Glenn Kasten53cec222013-08-29 09:01:02 -07001917 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001918 // FIXME not implemented for fast tracks; should use proxy and SSQ
1919 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1920 return INVALID_OPERATION;
1921 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001922
1923 switch (mState) {
1924 case STATE_ACTIVE:
1925 case STATE_PAUSED:
1926 break; // handle below
1927 case STATE_FLUSHED:
1928 case STATE_STOPPED:
1929 return WOULD_BLOCK;
1930 case STATE_STOPPING:
1931 case STATE_PAUSED_STOPPING:
1932 if (!isOffloaded_l()) {
1933 return INVALID_OPERATION;
1934 }
1935 break; // offloaded tracks handled below
1936 default:
1937 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
1938 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07001939 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001940
Eric Laurent275e8e92014-11-30 15:14:47 -08001941 if (mCblk->mFlags & CBLK_INVALID) {
1942 restoreTrack_l("getTimestamp");
1943 }
1944
Glenn Kasten200092b2014-08-15 15:13:30 -07001945 // The presented frame count must always lag behind the consumed frame count.
1946 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07001947 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001948 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07001949 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001950 return status;
1951 }
1952 if (isOffloadedOrDirect_l()) {
1953 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
1954 // use cached paused position in case another offloaded track is running.
1955 timestamp.mPosition = mPausedPosition;
1956 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
1957 return NO_ERROR;
1958 }
1959
1960 // Check whether a pending flush or stop has completed, as those commands may
1961 // be asynchronous or return near finish.
1962 if (mStartUs != 0 && mSampleRate != 0) {
1963 static const int kTimeJitterUs = 100000; // 100 ms
1964 static const int k1SecUs = 1000000;
1965
1966 const int64_t timeNow = getNowUs();
1967
1968 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
1969 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
1970 if (timestampTimeUs < mStartUs) {
1971 return WOULD_BLOCK; // stale timestamp time, occurs before start.
1972 }
1973 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
1974 const int64_t deltaPositionByUs = timestamp.mPosition * 1000000LL / mSampleRate;
1975
1976 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
1977 // Verify that the counter can't count faster than the sample rate
1978 // since the start time. If greater, then that means we have failed
1979 // to completely flush or stop the previous playing track.
1980 ALOGW("incomplete flush or stop:"
1981 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
1982 (long long)deltaTimeUs, (long long)deltaPositionByUs,
1983 timestamp.mPosition);
1984 return WOULD_BLOCK;
1985 }
1986 }
1987 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
1988 }
1989 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07001990 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
1991 (void) updateAndGetPosition_l();
1992 // Server consumed (mServer) and presented both use the same server time base,
1993 // and server consumed is always >= presented.
1994 // The delta between these represents the number of frames in the buffer pipeline.
1995 // If this delta between these is greater than the client position, it means that
1996 // actually presented is still stuck at the starting line (figuratively speaking),
1997 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
1998 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
1999 return INVALID_OPERATION;
2000 }
2001 // Convert timestamp position from server time base to client time base.
2002 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2003 // But if we change it to 64-bit then this could fail.
2004 // If (mPosition - mServer) can be negative then should use:
2005 // (int32_t)(mPosition - mServer)
2006 timestamp.mPosition += mPosition - mServer;
2007 // Immediately after a call to getPosition_l(), mPosition and
2008 // mServer both represent the same frame position. mPosition is
2009 // in client's point of view, and mServer is in server's point of
2010 // view. So the difference between them is the "fudge factor"
2011 // between client and server views due to stop() and/or new
2012 // IAudioTrack. And timestamp.mPosition is initially in server's
2013 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002014 }
2015 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002016}
2017
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002018String8 AudioTrack::getParameters(const String8& keys)
2019{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002020 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002021 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002022 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002023 } else {
2024 return String8::empty();
2025 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002026}
2027
Glenn Kasten23a75452014-01-13 10:37:17 -08002028bool AudioTrack::isOffloaded() const
2029{
2030 AutoMutex lock(mLock);
2031 return isOffloaded_l();
2032}
2033
Eric Laurentab5cdba2014-06-09 17:22:27 -07002034bool AudioTrack::isDirect() const
2035{
2036 AutoMutex lock(mLock);
2037 return isDirect_l();
2038}
2039
2040bool AudioTrack::isOffloadedOrDirect() const
2041{
2042 AutoMutex lock(mLock);
2043 return isOffloadedOrDirect_l();
2044}
2045
2046
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002047status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002048{
2049
2050 const size_t SIZE = 256;
2051 char buffer[SIZE];
2052 String8 result;
2053
2054 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002055 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002056 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002057 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002058 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002059 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002060 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08002061 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002062 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002063 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002064 result.append(buffer);
2065 ::write(fd, result.string(), result.size());
2066 return NO_ERROR;
2067}
2068
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002069uint32_t AudioTrack::getUnderrunFrames() const
2070{
2071 AutoMutex lock(mLock);
2072 return mProxy->getUnderrunFrames();
2073}
2074
2075// =========================================================================
2076
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002077void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002078{
2079 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2080 if (audioTrack != 0) {
2081 AutoMutex lock(audioTrack->mLock);
2082 audioTrack->mProxy->binderDied();
2083 }
2084}
2085
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002086// =========================================================================
2087
2088AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002089 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2090 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002091{
2092}
2093
2094AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002095{
2096}
2097
2098bool AudioTrack::AudioTrackThread::threadLoop()
2099{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002100 {
2101 AutoMutex _l(mMyLock);
2102 if (mPaused) {
2103 mMyCond.wait(mMyLock);
2104 // caller will check for exitPending()
2105 return true;
2106 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002107 if (mIgnoreNextPausedInt) {
2108 mIgnoreNextPausedInt = false;
2109 mPausedInt = false;
2110 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002111 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002112 if (mPausedNs > 0) {
2113 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2114 } else {
2115 mMyCond.wait(mMyLock);
2116 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002117 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002118 return true;
2119 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002120 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002121 if (exitPending()) {
2122 return false;
2123 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002124 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002125 switch (ns) {
2126 case 0:
2127 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002128 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002129 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002130 return true;
2131 case NS_NEVER:
2132 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002133 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08002134 // Event driven: call wake() when callback notifications conditions change.
2135 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002136 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002137 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002138 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002139 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002140 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002141 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002142}
2143
Glenn Kasten3acbd052012-02-28 10:39:56 -08002144void AudioTrack::AudioTrackThread::requestExit()
2145{
2146 // must be in this order to avoid a race condition
2147 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002148 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002149}
2150
2151void AudioTrack::AudioTrackThread::pause()
2152{
2153 AutoMutex _l(mMyLock);
2154 mPaused = true;
2155}
2156
2157void AudioTrack::AudioTrackThread::resume()
2158{
2159 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002160 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002161 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002162 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002163 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002164 mMyCond.signal();
2165 }
2166}
2167
Andy Hung3c09c782014-12-29 18:39:32 -08002168void AudioTrack::AudioTrackThread::wake()
2169{
2170 AutoMutex _l(mMyLock);
2171 if (!mPaused && mPausedInt && mPausedNs > 0) {
2172 // audio track is active and internally paused with timeout.
2173 mIgnoreNextPausedInt = true;
2174 mPausedInt = false;
2175 mMyCond.signal();
2176 }
2177}
2178
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002179void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2180{
2181 AutoMutex _l(mMyLock);
2182 mPausedInt = true;
2183 mPausedNs = ns;
2184}
2185
Glenn Kasten40bc9062015-03-20 09:09:33 -07002186} // namespace android