blob: 98f64fea9aa1345915eedfdb1f2c4aa47acf9f52 [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();
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700206 ALOGV("~AudioTrack, releasing session id %d from %d on behalf of %d",
207 mSessionId, IPCThreadState::self()->getCallingPid(), mClientPid);
Marco Nelissend457c972014-02-11 08:47:07 -0800208 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 Kasten4c36d6f2015-03-20 09:05:01 -0700232 "flags #%x, notificationFrames %u, sessionId %d, transferType %d, uid %d, pid %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800233 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700234 sessionId, transferType, uid, pid);
Glenn Kasten86f04662014-02-24 15:13:05 -0800235
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
Glenn Kasten53cec222013-08-29 09:01:02 -0700277 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700278 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000279 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800280 return INVALID_OPERATION;
281 }
282
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800283 // handle default values first.
Eric Laurente83b55d2014-11-14 10:06:21 -0800284 if (streamType == AUDIO_STREAM_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700285 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800286 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700287 if (pAttributes == NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800288 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700289 ALOGE("Invalid stream type %d", streamType);
290 return BAD_VALUE;
291 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700292 mStreamType = streamType;
Eric Laurente83b55d2014-11-14 10:06:21 -0800293
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700294 } else {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700295 // stream type shouldn't be looked at, this track has audio attributes
296 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700297 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
298 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800299 mStreamType = AUDIO_STREAM_DEFAULT;
Eric Laurentc6bd5db2015-03-09 16:29:33 -0700300 if ((mAttributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
301 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
302 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800303 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700304
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800305 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800306 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700307 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800308 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800309
310 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700311 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800312 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800313 return BAD_VALUE;
314 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800315 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700316
Glenn Kasten8ba90322013-10-30 11:29:27 -0700317 if (!audio_is_output_channel(channelMask)) {
318 ALOGE("Invalid channel mask %#x", channelMask);
319 return BAD_VALUE;
320 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800321 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700322 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800323 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700324
Eric Laurentc2f1f072009-07-17 12:17:14 -0700325 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100326 // or offload was requested
327 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
328 || !audio_is_linear_pcm(format)) {
329 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
330 ? "Offload request, forcing to Direct Output"
331 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700332 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800333 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700334 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700335 }
336
Eric Laurentd1f69b02014-12-15 14:33:13 -0800337 // force direct flag if HW A/V sync requested
338 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
339 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
340 }
341
Glenn Kastenb7730382014-04-30 15:50:31 -0700342 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
343 if (audio_is_linear_pcm(format)) {
344 mFrameSize = channelCount * audio_bytes_per_sample(format);
345 } else {
346 mFrameSize = sizeof(uint8_t);
347 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800348 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700349 ALOG_ASSERT(audio_is_linear_pcm(format));
350 mFrameSize = channelCount * audio_bytes_per_sample(format);
Glenn Kastenb7730382014-04-30 15:50:31 -0700351 // createTrack will return an error if PCM format is not supported by server,
352 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800353 }
354
Eric Laurent0d6db582014-11-12 18:39:44 -0800355 // sampling rate must be specified for direct outputs
356 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
357 return BAD_VALUE;
358 }
359 mSampleRate = sampleRate;
360
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800361 // Make copy of input parameter offloadInfo so that in the future:
362 // (a) createTrack_l doesn't need it as an input parameter
363 // (b) we can support re-creation of offloaded tracks
364 if (offloadInfo != NULL) {
365 mOffloadInfoCopy = *offloadInfo;
366 mOffloadInfo = &mOffloadInfoCopy;
367 } else {
368 mOffloadInfo = NULL;
369 }
370
Glenn Kasten66e46352014-01-16 17:44:23 -0800371 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
372 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800373 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800374 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800375 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700376 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800377 mNotificationFramesAct = 0;
Eric Laurentcaf7f482014-11-25 17:50:47 -0800378 if (sessionId == AUDIO_SESSION_ALLOCATE) {
379 mSessionId = AudioSystem::newAudioUniqueId();
380 } else {
381 mSessionId = sessionId;
382 }
Marco Nelissend457c972014-02-11 08:47:07 -0800383 int callingpid = IPCThreadState::self()->getCallingPid();
384 int mypid = getpid();
385 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800386 mClientUid = IPCThreadState::self()->getCallingUid();
387 } else {
388 mClientUid = uid;
389 }
Marco Nelissend457c972014-02-11 08:47:07 -0800390 if (pid == -1 || (callingpid != mypid)) {
391 mClientPid = callingpid;
392 } else {
393 mClientPid = pid;
394 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700395 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700396 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700397 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700398
Glenn Kastena997e7a2012-08-07 09:44:19 -0700399 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700400 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700401 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
Glenn Kastenbfd31842015-03-20 09:01:44 -0700402 // thread begins in paused state, and will not reference us until start()
Glenn Kastena997e7a2012-08-07 09:44:19 -0700403 }
404
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800405 // create the IAudioTrack
Eric Laurent0d6db582014-11-12 18:39:44 -0800406 status_t status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800407
Glenn Kastena997e7a2012-08-07 09:44:19 -0700408 if (status != NO_ERROR) {
409 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100410 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
411 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700412 mAudioTrackThread.clear();
413 }
414 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700415 }
416
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800417 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800418 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800419 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800420 mLoopCount = 0;
421 mLoopStart = 0;
422 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800423 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800424 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700425 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800426 mNewPosition = 0;
427 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700428 mServer = 0;
429 mPosition = 0;
430 mReleased = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700431 mStartUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800432 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800433 mSequence = 1;
434 mObservedSequence = mSequence;
435 mInUnderrun = false;
436
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800437 return NO_ERROR;
438}
439
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800440// -------------------------------------------------------------------------
441
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100442status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800443{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800444 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100445
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800446 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100447 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800448 }
449
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800450 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800451
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800452 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100453 if (previousState == STATE_PAUSED_STOPPING) {
454 mState = STATE_STOPPING;
455 } else {
456 mState = STATE_ACTIVE;
457 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700458 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800459 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
460 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700461 mPosition = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700462 // For offloaded tracks, we don't know if the hardware counters are really zero here,
463 // since the flush is asynchronous and stop may not fully drain.
464 // We save the time when the track is started to later verify whether
465 // the counters are realistic (i.e. start from zero after this time).
466 mStartUs = getNowUs();
467
Eric Laurentec9a0322013-08-28 10:23:01 -0700468 // force refresh of remaining frames by processAudioBuffer() as last
469 // write before stop could be partial.
470 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800471 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700472 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700473 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800474
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800475 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800476 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100477 if (previousState == STATE_STOPPING) {
478 mProxy->interrupt();
479 } else {
480 t->resume();
481 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800482 } else {
483 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
484 get_sched_policy(0, &mPreviousSchedulingGroup);
485 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
486 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800487
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800488 status_t status = NO_ERROR;
489 if (!(flags & CBLK_INVALID)) {
490 status = mAudioTrack->start();
491 if (status == DEAD_OBJECT) {
492 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800493 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800494 }
495 if (flags & CBLK_INVALID) {
496 status = restoreTrack_l("start");
497 }
498
499 if (status != NO_ERROR) {
500 ALOGE("start() status %d", status);
501 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800502 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100503 if (previousState != STATE_STOPPING) {
504 t->pause();
505 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800506 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700507 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700508 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800509 }
510 }
511
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100512 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800513}
514
515void AudioTrack::stop()
516{
517 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700518 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800519 return;
520 }
521
Glenn Kasten23a75452014-01-13 10:37:17 -0800522 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100523 mState = STATE_STOPPING;
524 } else {
525 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -0700526 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100527 }
528
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800529 mProxy->interrupt();
530 mAudioTrack->stop();
531 // the playback head position will reset to 0, so if a marker is set, we need
532 // to activate it again
533 mMarkerReached = false;
Andy Hung9b461582014-12-01 17:56:29 -0800534
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800535 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800536 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800537 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
538 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800539 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100540
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800541 sp<AudioTrackThread> t = mAudioTrackThread;
542 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800543 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100544 t->pause();
545 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800546 } else {
547 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
548 set_sched_policy(0, mPreviousSchedulingGroup);
549 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800550}
551
552bool AudioTrack::stopped() const
553{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800554 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800555 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800556}
557
558void AudioTrack::flush()
559{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800560 if (mSharedBuffer != 0) {
561 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800562 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800563 AutoMutex lock(mLock);
564 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
565 return;
566 }
567 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800568}
569
Eric Laurent1703cdf2011-03-07 14:52:59 -0800570void AudioTrack::flush_l()
571{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800572 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700573
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700574 // clear playback marker and periodic update counter
575 mMarkerPosition = 0;
576 mMarkerReached = false;
577 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100578 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700579
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800580 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700581 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800582 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100583 mProxy->interrupt();
584 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800585 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800586 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800587}
588
589void AudioTrack::pause()
590{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800591 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100592 if (mState == STATE_ACTIVE) {
593 mState = STATE_PAUSED;
594 } else if (mState == STATE_STOPPING) {
595 mState = STATE_PAUSED_STOPPING;
596 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800597 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800598 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800599 mProxy->interrupt();
600 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800601
Marco Nelissen3a90f282014-03-10 11:21:43 -0700602 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700603 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700604 // An offload output can be re-used between two audio tracks having
605 // the same configuration. A timestamp query for a paused track
606 // while the other is running would return an incorrect time.
607 // To fix this, cache the playback position on a pause() and return
608 // this time when requested until the track is resumed.
609
610 // OffloadThread sends HAL pause in its threadLoop. Time saved
611 // here can be slightly off.
612
613 // TODO: check return code for getRenderPosition.
614
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800615 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800616 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
617 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
618 }
619 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800620}
621
Eric Laurentbe916aa2010-06-01 23:49:17 -0700622status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800623{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700624 // This duplicates a test by AudioTrack JNI, but that is not the only caller
625 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
626 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700627 return BAD_VALUE;
628 }
629
Eric Laurent1703cdf2011-03-07 14:52:59 -0800630 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800631 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
632 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800633
Glenn Kastenc56f3422014-03-21 17:53:17 -0700634 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700635
Glenn Kasten23a75452014-01-13 10:37:17 -0800636 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700637 mAudioTrack->signal();
638 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700639 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800640}
641
Glenn Kastenb1c09932012-02-27 16:21:04 -0800642status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800643{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800644 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700645}
646
Eric Laurent2beeb502010-07-16 07:43:46 -0700647status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700648{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700649 // This duplicates a test by AudioTrack JNI, but that is not the only caller
650 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700651 return BAD_VALUE;
652 }
653
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800654 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700655 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800656 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700657
658 return NO_ERROR;
659}
660
Glenn Kastena5224f32012-01-04 12:41:44 -0800661void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700662{
663 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800664 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700665 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800666}
667
Glenn Kasten3b16c762012-11-14 08:44:39 -0800668status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800669{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700670 if (mIsTimed || isOffloadedOrDirect()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800671 return INVALID_OPERATION;
672 }
673
Eric Laurent0d6db582014-11-12 18:39:44 -0800674 AutoMutex lock(mLock);
675 if (mOutput == AUDIO_IO_HANDLE_NONE) {
676 return NO_INIT;
677 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800678 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800679 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700680 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800681 }
Andy Hungcd044842014-08-07 11:04:34 -0700682 if (rate == 0 || rate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700683 return BAD_VALUE;
684 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800685
Glenn Kastene3aa6592012-12-04 12:22:46 -0800686 mSampleRate = rate;
687 mProxy->setSampleRate(rate);
688
Eric Laurent57326622009-07-07 07:10:45 -0700689 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800690}
691
Glenn Kastena5224f32012-01-04 12:41:44 -0800692uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800693{
John Grossman4ff14ba2012-02-08 16:37:41 -0800694 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800695 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800696 }
697
Eric Laurent1703cdf2011-03-07 14:52:59 -0800698 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700699
700 // sample rate can be updated during playback by the offloaded decoder so we need to
701 // query the HAL and update if needed.
702// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700703 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700704 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700705 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700706 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700707 if (status == NO_ERROR) {
708 mSampleRate = sampleRate;
709 }
710 }
711 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800712 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800713}
714
715status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
716{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700717 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800718 return INVALID_OPERATION;
719 }
720
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800721 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800722 ;
723 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
724 loopEnd - loopStart >= MIN_LOOP) {
725 ;
726 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800727 return BAD_VALUE;
728 }
729
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800730 AutoMutex lock(mLock);
731 // See setPosition() regarding setting parameters such as loop points or position while active
732 if (mState == STATE_ACTIVE) {
733 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700734 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800735 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800736 return NO_ERROR;
737}
738
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800739void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
740{
Andy Hung4ede21d2014-12-12 15:37:34 -0800741 // We do not update the periodic notification point.
742 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
743 mLoopCount = loopCount;
744 mLoopEnd = loopEnd;
745 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800746 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800747 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -0800748
749 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800750}
751
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800752status_t AudioTrack::setMarkerPosition(uint32_t marker)
753{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700754 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700755 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700756 return INVALID_OPERATION;
757 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800758
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800759 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800760 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700761 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800762
Andy Hung3c09c782014-12-29 18:39:32 -0800763 sp<AudioTrackThread> t = mAudioTrackThread;
764 if (t != 0) {
765 t->wake();
766 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800767 return NO_ERROR;
768}
769
Glenn Kastena5224f32012-01-04 12:41:44 -0800770status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800771{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700772 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100773 return INVALID_OPERATION;
774 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700775 if (marker == NULL) {
776 return BAD_VALUE;
777 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800778
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800779 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800780 *marker = mMarkerPosition;
781
782 return NO_ERROR;
783}
784
785status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
786{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700787 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700788 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700789 return INVALID_OPERATION;
790 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800791
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800792 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700793 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800794 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800795
Andy Hung3c09c782014-12-29 18:39:32 -0800796 sp<AudioTrackThread> t = mAudioTrackThread;
797 if (t != 0) {
798 t->wake();
799 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800800 return NO_ERROR;
801}
802
Glenn Kastena5224f32012-01-04 12:41:44 -0800803status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800804{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700805 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100806 return INVALID_OPERATION;
807 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700808 if (updatePeriod == NULL) {
809 return BAD_VALUE;
810 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800811
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800812 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800813 *updatePeriod = mUpdatePeriod;
814
815 return NO_ERROR;
816}
817
818status_t AudioTrack::setPosition(uint32_t position)
819{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700820 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700821 return INVALID_OPERATION;
822 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800823 if (position > mFrameCount) {
824 return BAD_VALUE;
825 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800826
Eric Laurent1703cdf2011-03-07 14:52:59 -0800827 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800828 // Currently we require that the player is inactive before setting parameters such as position
829 // or loop points. Otherwise, there could be a race condition: the application could read the
830 // current position, compute a new position or loop parameters, and then set that position or
831 // loop parameters but it would do the "wrong" thing since the position has continued to advance
832 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
833 // to specify how it wants to handle such scenarios.
834 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700835 return INVALID_OPERATION;
836 }
Andy Hung9b461582014-12-01 17:56:29 -0800837 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -0700838 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800839 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -0800840
841 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800842 return NO_ERROR;
843}
844
Glenn Kasten200092b2014-08-15 15:13:30 -0700845status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800846{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700847 if (position == NULL) {
848 return BAD_VALUE;
849 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800850
Eric Laurent1703cdf2011-03-07 14:52:59 -0800851 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700852 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100853 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800854
Eric Laurentab5cdba2014-06-09 17:22:27 -0700855 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800856 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
857 *position = mPausedPosition;
858 return NO_ERROR;
859 }
860
Glenn Kasten142f5192014-03-25 17:44:59 -0700861 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100862 uint32_t halFrames;
863 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
864 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700865 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
866 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100867 *position = dspFrames;
868 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -0800869 if (mCblk->mFlags & CBLK_INVALID) {
870 restoreTrack_l("getPosition");
871 }
872
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100873 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700874 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
875 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100876 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800877 return NO_ERROR;
878}
879
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000880status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800881{
882 if (mSharedBuffer == 0 || mIsTimed) {
883 return INVALID_OPERATION;
884 }
885 if (position == NULL) {
886 return BAD_VALUE;
887 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800888
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800889 AutoMutex lock(mLock);
890 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800891 return NO_ERROR;
892}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800893
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800894status_t AudioTrack::reload()
895{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700896 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800897 return INVALID_OPERATION;
898 }
899
Eric Laurent1703cdf2011-03-07 14:52:59 -0800900 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800901 // See setPosition() regarding setting parameters such as loop points or position while active
902 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700903 return INVALID_OPERATION;
904 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800905 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800906 (void) updateAndGetPosition_l();
907 mPosition = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800908#if 0
Andy Hung9b461582014-12-01 17:56:29 -0800909 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -0800910 // of loop count. Historically we have not restored loop count, start, end,
911 // but it makes sense if one desires to repeat playing a particular sound.
912 if (mLoopCount != 0) {
913 mLoopCountNotified = mLoopCount;
914 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
915 }
916#endif
Andy Hung9b461582014-12-01 17:56:29 -0800917 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800918 return NO_ERROR;
919}
920
Glenn Kasten38e905b2014-01-13 10:21:48 -0800921audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700922{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800923 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100924 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800925}
926
Eric Laurentbe916aa2010-06-01 23:49:17 -0700927status_t AudioTrack::attachAuxEffect(int effectId)
928{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800929 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700930 status_t status = mAudioTrack->attachAuxEffect(effectId);
931 if (status == NO_ERROR) {
932 mAuxEffectId = effectId;
933 }
934 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700935}
936
Eric Laurente83b55d2014-11-14 10:06:21 -0800937audio_stream_type_t AudioTrack::streamType() const
938{
939 if (mStreamType == AUDIO_STREAM_DEFAULT) {
940 return audio_attributes_to_stream_type(&mAttributes);
941 }
942 return mStreamType;
943}
944
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800945// -------------------------------------------------------------------------
946
Eric Laurent1703cdf2011-03-07 14:52:59 -0800947// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -0700948status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800949{
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800950 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
951 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700952 ALOGE("Could not get audioflinger");
953 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800954 }
955
Eric Laurente83b55d2014-11-14 10:06:21 -0800956 audio_io_handle_t output;
957 audio_stream_type_t streamType = mStreamType;
958 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
959 status_t status = AudioSystem::getOutputForAttr(attr, &output,
960 (audio_session_t)mSessionId, &streamType,
961 mSampleRate, mFormat, mChannelMask,
962 mFlags, mOffloadInfo);
963
964
965 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700966 ALOGE("Could not get audio output for session %d, stream type %d, usage %d, sample rate %u, format %#x,"
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700967 " channel mask %#x, flags %#x",
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700968 mSessionId, streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800969 return BAD_VALUE;
970 }
971 {
972 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
973 // we must release it ourselves if anything goes wrong.
974
Glenn Kastence8828a2013-09-16 18:07:38 -0700975 // Not all of these values are needed under all conditions, but it is easier to get them all
976
Eric Laurentd1b449a2010-05-14 03:26:45 -0700977 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -0700978 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700979 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800980 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800981 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700982 }
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700983 ALOGV("createTrack_l() output %d afLatency %u", output, afLatency);
Eric Laurentd1b449a2010-05-14 03:26:45 -0700984
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 Kasten4c36d6f2015-03-20 09:05:01 -07001013 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client; transfer %d, track %u Hz, output %u Hz",
1014 mTransfer, mSampleRate, afSampleRate);
Glenn Kasten093000f2012-05-03 09:35:36 -07001015 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001016 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001017 }
1018
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
Glenn Kasten138d6f92015-03-20 10:54:51 -07001093 int originalSessionId = mSessionId;
Eric Laurente83b55d2014-11-14 10:06:21 -08001094 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001095 mSampleRate,
Andy Hungabdb9902015-01-12 15:08:22 -08001096 mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001097 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001098 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001099 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001100 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001101 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001102 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001103 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001104 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001105 &status);
Glenn Kasten138d6f92015-03-20 10:54:51 -07001106 ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
1107 "session ID changed from %d to %d", originalSessionId, mSessionId);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001108
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001109 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001110 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001111 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001112 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001113 ALOG_ASSERT(track != 0);
1114
Glenn Kasten38e905b2014-01-13 10:21:48 -08001115 // AudioFlinger now owns the reference to the I/O handle,
1116 // so we are no longer responsible for releasing it.
1117
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001118 sp<IMemory> iMem = track->getCblk();
1119 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001120 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001121 return NO_INIT;
1122 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001123 void *iMemPointer = iMem->pointer();
1124 if (iMemPointer == NULL) {
1125 ALOGE("Could not get control block pointer");
1126 return NO_INIT;
1127 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001128 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001129 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001130 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001131 mDeathNotifier.clear();
1132 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001133 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001134 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001135 IPCThreadState::self()->flushCommands();
1136
Glenn Kasten0cde0762014-01-16 15:06:36 -08001137 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001138 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001139 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001140 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1141 // In current design, AudioTrack client checks and ensures frame count validity before
1142 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1143 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001144 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001145 }
1146 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001147
Glenn Kastena07f17c2013-04-23 12:39:37 -07001148 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001149 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001150 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001151 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001152 mAwaitBoost = true;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001153 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001154 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001155 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001156 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001157 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001158 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001159 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001160 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1161 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1162 } else {
1163 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001164 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001165 // FIXME This is a warning, not an error, so don't return error status
1166 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001167 }
1168 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001169 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1170 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1171 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1172 } else {
1173 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1174 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1175 // FIXME This is a warning, not an error, so don't return error status
1176 //return NO_INIT;
1177 }
1178 }
Andy Hung0e48d252015-01-26 11:43:15 -08001179 // Make sure that application is notified with sufficient margin before underrun
1180 if (mSharedBuffer == 0 && audio_is_linear_pcm(mFormat)) {
1181 // Theoretically double-buffering is not required for fast tracks,
1182 // due to tighter scheduling. But in practice, to accommodate kernels with
1183 // scheduling jitter, and apps with computation jitter, we use double-buffering
1184 // for fast tracks just like normal streaming tracks.
1185 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount / nBuffering) {
1186 mNotificationFramesAct = frameCount / nBuffering;
1187 }
1188 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001189
Glenn Kasten38e905b2014-01-13 10:21:48 -08001190 // We retain a copy of the I/O handle, but don't own the reference
1191 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001192 mRefreshRemaining = true;
1193
1194 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1195 // is the value of pointer() for the shared buffer, otherwise buffers points
1196 // immediately after the control block. This address is for the mapping within client
1197 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1198 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001199 if (mSharedBuffer == 0) {
Glenn Kasten138d6f92015-03-20 10:54:51 -07001200 buffers = cblk + 1;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001201 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001202 buffers = mSharedBuffer->pointer();
Glenn Kasten138d6f92015-03-20 10:54:51 -07001203 if (buffers == NULL) {
1204 ALOGE("Could not get buffer pointer");
1205 return NO_INIT;
1206 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001207 }
1208
Eric Laurent2beeb502010-07-16 07:43:46 -07001209 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001210 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001211 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001212
Glenn Kastenb6037442012-11-14 13:42:25 -08001213 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001214 // If IAudioTrack is re-created, don't let the requested frameCount
1215 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001216 if (frameCount > mReqFrameCount) {
1217 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001218 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001219
1220 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001221 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001222 mStaticProxy.clear();
Andy Hungabdb9902015-01-12 15:08:22 -08001223 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001224 } else {
Andy Hungabdb9902015-01-12 15:08:22 -08001225 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001226 mProxy = mStaticProxy;
1227 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001228
1229 mProxy->setVolumeLR(gain_minifloat_pack(
1230 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1231 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1232
Glenn Kastene3aa6592012-12-04 12:22:46 -08001233 mProxy->setSendLevel(mSendLevel);
1234 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001235 mProxy->setMinimum(mNotificationFramesAct);
1236
1237 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001238 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001239
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001240 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001241 }
1242
1243release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001244 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001245 if (status == NO_ERROR) {
1246 status = NO_INIT;
1247 }
1248 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001249}
1250
Glenn Kastenb46f3942015-03-09 12:00:30 -07001251status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001252{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001253 if (audioBuffer == NULL) {
1254 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001255 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001256 if (mTransfer != TRANSFER_OBTAIN) {
1257 audioBuffer->frameCount = 0;
1258 audioBuffer->size = 0;
1259 audioBuffer->raw = NULL;
1260 return INVALID_OPERATION;
1261 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001262
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001263 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001264 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001265 if (waitCount == -1) {
1266 requested = &ClientProxy::kForever;
1267 } else if (waitCount == 0) {
1268 requested = &ClientProxy::kNonBlocking;
1269 } else if (waitCount > 0) {
1270 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001271 timeout.tv_sec = ms / 1000;
1272 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1273 requested = &timeout;
1274 } else {
1275 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1276 requested = NULL;
1277 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001278 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001279}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001280
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001281status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1282 struct timespec *elapsed, size_t *nonContig)
1283{
1284 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1285 uint32_t oldSequence = 0;
1286 uint32_t newSequence;
1287
1288 Proxy::Buffer buffer;
1289 status_t status = NO_ERROR;
1290
1291 static const int32_t kMaxTries = 5;
1292 int32_t tryCounter = kMaxTries;
1293
1294 do {
1295 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1296 // keep them from going away if another thread re-creates the track during obtainBuffer()
1297 sp<AudioTrackClientProxy> proxy;
1298 sp<IMemory> iMem;
1299
1300 { // start of lock scope
1301 AutoMutex lock(mLock);
1302
1303 newSequence = mSequence;
1304 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1305 if (status == DEAD_OBJECT) {
1306 // re-create track, unless someone else has already done so
1307 if (newSequence == oldSequence) {
1308 status = restoreTrack_l("obtainBuffer");
1309 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001310 buffer.mFrameCount = 0;
1311 buffer.mRaw = NULL;
1312 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001313 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001314 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001315 }
1316 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001317 oldSequence = newSequence;
1318
1319 // Keep the extra references
1320 proxy = mProxy;
1321 iMem = mCblkMemory;
1322
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001323 if (mState == STATE_STOPPING) {
1324 status = -EINTR;
1325 buffer.mFrameCount = 0;
1326 buffer.mRaw = NULL;
1327 buffer.mNonContig = 0;
1328 break;
1329 }
1330
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001331 // Non-blocking if track is stopped or paused
1332 if (mState != STATE_ACTIVE) {
1333 requested = &ClientProxy::kNonBlocking;
1334 }
1335
1336 } // end of lock scope
1337
1338 buffer.mFrameCount = audioBuffer->frameCount;
1339 // FIXME starts the requested timeout and elapsed over from scratch
1340 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1341
1342 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1343
1344 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001345 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001346 audioBuffer->raw = buffer.mRaw;
1347 if (nonContig != NULL) {
1348 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001349 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001350 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001351}
1352
Glenn Kasten54a8a452015-03-09 12:03:00 -07001353void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001354{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001355 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001356 if (mTransfer == TRANSFER_SHARED) {
1357 return;
1358 }
1359
Andy Hungabdb9902015-01-12 15:08:22 -08001360 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001361 if (stepCount == 0) {
1362 return;
1363 }
1364
1365 Proxy::Buffer buffer;
1366 buffer.mFrameCount = stepCount;
1367 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001368
Eric Laurent1703cdf2011-03-07 14:52:59 -08001369 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001370 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001371 mInUnderrun = false;
1372 mProxy->releaseBuffer(&buffer);
1373
1374 // restart track if it was disabled by audioflinger due to previous underrun
1375 if (mState == STATE_ACTIVE) {
1376 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001377 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001378 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001379 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001380 mAudioTrack->start();
1381 }
1382 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001383}
1384
1385// -------------------------------------------------------------------------
1386
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001387ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001388{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001389 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001390 return INVALID_OPERATION;
1391 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001392
Eric Laurentab5cdba2014-06-09 17:22:27 -07001393 if (isDirect()) {
1394 AutoMutex lock(mLock);
1395 int32_t flags = android_atomic_and(
1396 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1397 &mCblk->mFlags);
1398 if (flags & CBLK_INVALID) {
1399 return DEAD_OBJECT;
1400 }
1401 }
1402
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001403 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001404 // Sanity-check: user is most-likely passing an error code, and it would
1405 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001406 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001407 return BAD_VALUE;
1408 }
1409
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001410 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001411 Buffer audioBuffer;
1412
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001413 while (userSize >= mFrameSize) {
1414 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001415
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001416 status_t err = obtainBuffer(&audioBuffer,
1417 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001418 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001419 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001420 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001421 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001422 return ssize_t(err);
1423 }
1424
Glenn Kastenae4b8792015-03-20 09:04:21 -07001425 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08001426 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001427 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001428 userSize -= toWrite;
1429 written += toWrite;
1430
1431 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001432 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001433
1434 return written;
1435}
1436
1437// -------------------------------------------------------------------------
1438
John Grossman4ff14ba2012-02-08 16:37:41 -08001439TimedAudioTrack::TimedAudioTrack() {
1440 mIsTimed = true;
1441}
1442
1443status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1444{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001445 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001446 status_t result = UNKNOWN_ERROR;
1447
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001448#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001449 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1450 // while we are accessing the cblk
1451 sp<IAudioTrack> audioTrack = mAudioTrack;
1452 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001453#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001454
John Grossman4ff14ba2012-02-08 16:37:41 -08001455 // If the track is not invalid already, try to allocate a buffer. alloc
1456 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001457 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001458 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001459 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001460 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1461 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001462 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001463 }
1464 }
1465
1466 // If the track is invalid at this point, attempt to restore it. and try the
1467 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001468 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001469 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001470
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001471 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001472 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001473 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001474 }
1475
1476 return result;
1477}
1478
1479status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1480 int64_t pts)
1481{
Eric Laurentdf839842012-05-31 14:27:14 -07001482 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1483 {
1484 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001485 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001486 // restart track if it was disabled by audioflinger due to previous underrun
1487 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001488 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1489 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001490 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001491 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001492 mAudioTrack->start();
1493 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001494 }
Eric Laurentdf839842012-05-31 14:27:14 -07001495 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001496}
1497
1498status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1499 TargetTimeline target)
1500{
1501 return mAudioTrack->setMediaTimeTransform(xform, target);
1502}
1503
1504// -------------------------------------------------------------------------
1505
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001506nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001507{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001508 // Currently the AudioTrack thread is not created if there are no callbacks.
1509 // Would it ever make sense to run the thread, even without callbacks?
1510 // If so, then replace this by checks at each use for mCbf != NULL.
1511 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1512
Eric Laurent1703cdf2011-03-07 14:52:59 -08001513 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001514 if (mAwaitBoost) {
1515 mAwaitBoost = false;
1516 mLock.unlock();
1517 static const int32_t kMaxTries = 5;
1518 int32_t tryCounter = kMaxTries;
1519 uint32_t pollUs = 10000;
1520 do {
1521 int policy = sched_getscheduler(0);
1522 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1523 break;
1524 }
1525 usleep(pollUs);
1526 pollUs <<= 1;
1527 } while (tryCounter-- > 0);
1528 if (tryCounter < 0) {
1529 ALOGE("did not receive expected priority boost on time");
1530 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001531 // Run again immediately
1532 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001533 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001534
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001535 // Can only reference mCblk while locked
1536 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001537 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001538
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001539 // Check for track invalidation
1540 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001541 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1542 // AudioSystem cache. We should not exit here but after calling the callback so
1543 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001544 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001545 status_t status = restoreTrack_l("processAudioBuffer");
Andy Hung53c3b5f2014-12-15 16:42:05 -08001546 // after restoration, continue below to make sure that the loop and buffer events
1547 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001548 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001549 }
1550
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001551 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001552 bool active = mState == STATE_ACTIVE;
1553
1554 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1555 bool newUnderrun = false;
1556 if (flags & CBLK_UNDERRUN) {
1557#if 0
1558 // Currently in shared buffer mode, when the server reaches the end of buffer,
1559 // the track stays active in continuous underrun state. It's up to the application
1560 // to pause or stop the track, or set the position to a new offset within buffer.
1561 // This was some experimental code to auto-pause on underrun. Keeping it here
1562 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1563 if (mTransfer == TRANSFER_SHARED) {
1564 mState = STATE_PAUSED;
1565 active = false;
1566 }
1567#endif
1568 if (!mInUnderrun) {
1569 mInUnderrun = true;
1570 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001571 }
1572 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001573
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001574 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001575 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001576
1577 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001578 bool markerReached = false;
1579 size_t markerPosition = mMarkerPosition;
1580 // FIXME fails for wraparound, need 64 bits
1581 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1582 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001583 }
1584
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001585 // Determine number of new position callback(s) that will be needed, while locked
1586 size_t newPosCount = 0;
1587 size_t newPosition = mNewPosition;
1588 size_t updatePeriod = mUpdatePeriod;
1589 // FIXME fails for wraparound, need 64 bits
1590 if (updatePeriod > 0 && position >= newPosition) {
1591 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1592 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001593 }
1594
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001595 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001596 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001597 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001598 if (mRefreshRemaining) {
1599 mRefreshRemaining = false;
1600 mRemainingFrames = notificationFrames;
1601 mRetryOnPartialBuffer = false;
1602 }
1603 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001604 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001605 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001606
Andy Hung53c3b5f2014-12-15 16:42:05 -08001607 // Determine the number of new loop callback(s) that will be needed, while locked.
1608 int loopCountNotifications = 0;
1609 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1610
1611 if (mLoopCount > 0) {
1612 int loopCount;
1613 size_t bufferPosition;
1614 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1615 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1616 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1617 mLoopCountNotified = loopCount; // discard any excess notifications
1618 } else if (mLoopCount < 0) {
1619 // FIXME: We're not accurate with notification count and position with infinite looping
1620 // since loopCount from server side will always return -1 (we could decrement it).
1621 size_t bufferPosition = mStaticProxy->getBufferPosition();
1622 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1623 loopPeriod = mLoopEnd - bufferPosition;
1624 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1625 size_t bufferPosition = mStaticProxy->getBufferPosition();
1626 loopPeriod = mFrameCount - bufferPosition;
1627 }
1628
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001629 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08001630 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001631 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1632
1633 mLock.unlock();
1634
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001635 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001636 struct timespec timeout;
1637 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1638 timeout.tv_nsec = 0;
1639
Glenn Kasten96f04882013-09-20 09:28:56 -07001640 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001641 switch (status) {
1642 case NO_ERROR:
1643 case DEAD_OBJECT:
1644 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001645 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001646 {
1647 AutoMutex lock(mLock);
1648 // The previously assigned value of waitStreamEnd is no longer valid,
1649 // since the mutex has been unlocked and either the callback handler
1650 // or another thread could have re-started the AudioTrack during that time.
1651 waitStreamEnd = mState == STATE_STOPPING;
1652 if (waitStreamEnd) {
1653 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001654 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001655 }
1656 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001657 if (waitStreamEnd && status != DEAD_OBJECT) {
1658 return NS_INACTIVE;
1659 }
1660 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001661 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001662 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001663 }
1664
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001665 // perform callbacks while unlocked
1666 if (newUnderrun) {
1667 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1668 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001669 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001670 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001671 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001672 }
1673 if (flags & CBLK_BUFFER_END) {
1674 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1675 }
1676 if (markerReached) {
1677 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1678 }
1679 while (newPosCount > 0) {
1680 size_t temp = newPosition;
1681 mCbf(EVENT_NEW_POS, mUserData, &temp);
1682 newPosition += updatePeriod;
1683 newPosCount--;
1684 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001685
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001686 if (mObservedSequence != sequence) {
1687 mObservedSequence = sequence;
1688 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001689 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001690 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001691 return NS_INACTIVE;
1692 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001693 }
1694
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001695 // if inactive, then don't run me again until re-started
1696 if (!active) {
1697 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001698 }
1699
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001700 // Compute the estimated time until the next timed event (position, markers, loops)
1701 // FIXME only for non-compressed audio
1702 uint32_t minFrames = ~0;
1703 if (!markerReached && position < markerPosition) {
1704 minFrames = markerPosition - position;
1705 }
1706 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08001707 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001708 minFrames = loopPeriod;
1709 }
Andy Hung2d85f092015-01-07 12:45:13 -08001710 if (updatePeriod > 0) {
1711 minFrames = min(minFrames, uint32_t(newPosition - position));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001712 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001713
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001714 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1715 static const uint32_t kPoll = 0;
1716 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1717 minFrames = kPoll * notificationFrames;
1718 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001719
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001720 // Convert frame units to time units
1721 nsecs_t ns = NS_WHENEVER;
1722 if (minFrames != (uint32_t) ~0) {
1723 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1724 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1725 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1726 }
1727
1728 // If not supplying data by EVENT_MORE_DATA, then we're done
1729 if (mTransfer != TRANSFER_CALLBACK) {
1730 return ns;
1731 }
1732
1733 struct timespec timeout;
1734 const struct timespec *requested = &ClientProxy::kForever;
1735 if (ns != NS_WHENEVER) {
1736 timeout.tv_sec = ns / 1000000000LL;
1737 timeout.tv_nsec = ns % 1000000000LL;
1738 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1739 requested = &timeout;
1740 }
1741
1742 while (mRemainingFrames > 0) {
1743
1744 Buffer audioBuffer;
1745 audioBuffer.frameCount = mRemainingFrames;
1746 size_t nonContig;
1747 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1748 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001749 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001750 requested = &ClientProxy::kNonBlocking;
1751 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001752 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001753 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001754 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001755 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1756 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001757 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001758 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001759 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1760 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001761 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001762
Eric Laurent42a6f422013-08-29 14:35:05 -07001763 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001764 mRetryOnPartialBuffer = false;
1765 if (avail < mRemainingFrames) {
1766 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1767 if (ns < 0 || myns < ns) {
1768 ns = myns;
1769 }
1770 return ns;
1771 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001772 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001773
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001774 size_t reqSize = audioBuffer.size;
1775 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001776 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001777
1778 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001779 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001780 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1781 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001782 return NS_NEVER;
1783 }
1784
1785 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001786 // The callback is done filling buffers
1787 // Keep this thread going to handle timed events and
1788 // still try to get more data in intervals of WAIT_PERIOD_MS
1789 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001790 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001791 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001792
Glenn Kasten138d6f92015-03-20 10:54:51 -07001793 size_t releasedFrames = writtenSize / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001794 audioBuffer.frameCount = releasedFrames;
1795 mRemainingFrames -= releasedFrames;
1796 if (misalignment >= releasedFrames) {
1797 misalignment -= releasedFrames;
1798 } else {
1799 misalignment = 0;
1800 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001801
1802 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001803
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001804 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1805 // if callback doesn't like to accept the full chunk
1806 if (writtenSize < reqSize) {
1807 continue;
1808 }
1809
1810 // There could be enough non-contiguous frames available to satisfy the remaining request
1811 if (mRemainingFrames <= nonContig) {
1812 continue;
1813 }
1814
1815#if 0
1816 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1817 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1818 // that total to a sum == notificationFrames.
1819 if (0 < misalignment && misalignment <= mRemainingFrames) {
1820 mRemainingFrames = misalignment;
1821 return (mRemainingFrames * 1100000000LL) / sampleRate;
1822 }
1823#endif
1824
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001825 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001826 mRemainingFrames = notificationFrames;
1827 mRetryOnPartialBuffer = true;
1828
1829 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1830 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001831}
1832
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001833status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001834{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001835 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001836 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001837 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001838
Glenn Kastena47f3162012-11-07 10:13:08 -08001839 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08001840 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001841 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001842
Eric Laurentab5cdba2014-06-09 17:22:27 -07001843 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001844 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001845 return DEAD_OBJECT;
1846 }
1847
Glenn Kasten200092b2014-08-15 15:13:30 -07001848 // save the old static buffer position
Andy Hung4ede21d2014-12-12 15:37:34 -08001849 size_t bufferPosition = 0;
1850 int loopCount = 0;
1851 if (mStaticProxy != 0) {
1852 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1853 }
Glenn Kasten200092b2014-08-15 15:13:30 -07001854
1855 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001856 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001857 // It will also delete the strong references on previous IAudioTrack and IMemory.
1858 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Glenn Kastenae4b8792015-03-20 09:04:21 -07001859 status_t result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001860
1861 // take the frames that will be lost by track recreation into account in saved position
Andy Hung9b461582014-12-01 17:56:29 -08001862 // For streaming tracks, this is the amount we obtained from the user/client
1863 // (not the number actually consumed at the server - those are already lost).
Glenn Kasten200092b2014-08-15 15:13:30 -07001864 (void) updateAndGetPosition_l();
Andy Hung7ccdaad2015-03-20 00:38:32 -07001865 if (mStaticProxy == 0) {
Andy Hung9b461582014-12-01 17:56:29 -08001866 mPosition = mReleased;
1867 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001868
Glenn Kastena47f3162012-11-07 10:13:08 -08001869 if (result == NO_ERROR) {
Andy Hung4ede21d2014-12-12 15:37:34 -08001870 // Continue playback from last known position and restore loop.
1871 if (mStaticProxy != 0) {
1872 if (loopCount != 0) {
1873 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
1874 mLoopStart, mLoopEnd, loopCount);
1875 } else {
1876 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001877 if (bufferPosition == mFrameCount) {
1878 ALOGD("restoring track at end of static buffer");
1879 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001880 }
1881 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001882 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001883 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001884 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001885 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001886 if (result != NO_ERROR) {
1887 ALOGW("restoreTrack_l() failed status %d", result);
1888 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001889 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001890 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001891
1892 return result;
1893}
1894
Glenn Kasten200092b2014-08-15 15:13:30 -07001895uint32_t AudioTrack::updateAndGetPosition_l()
1896{
1897 // This is the sole place to read server consumed frames
1898 uint32_t newServer = mProxy->getPosition();
1899 int32_t delta = newServer - mServer;
1900 mServer = newServer;
1901 // TODO There is controversy about whether there can be "negative jitter" in server position.
1902 // This should be investigated further, and if possible, it should be addressed.
1903 // A more definite failure mode is infrequent polling by client.
1904 // One could call (void)getPosition_l() in releaseBuffer(),
1905 // so mReleased and mPosition are always lock-step as best possible.
1906 // That should ensure delta never goes negative for infrequent polling
1907 // unless the server has more than 2^31 frames in its buffer,
1908 // in which case the use of uint32_t for these counters has bigger issues.
1909 if (delta < 0) {
1910 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
1911 delta = 0;
1912 }
1913 return mPosition += (uint32_t) delta;
1914}
1915
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001916status_t AudioTrack::setParameters(const String8& keyValuePairs)
1917{
1918 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001919 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001920}
1921
Glenn Kastence703742013-07-19 16:33:58 -07001922status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1923{
Glenn Kasten53cec222013-08-29 09:01:02 -07001924 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001925 // FIXME not implemented for fast tracks; should use proxy and SSQ
1926 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1927 return INVALID_OPERATION;
1928 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001929
1930 switch (mState) {
1931 case STATE_ACTIVE:
1932 case STATE_PAUSED:
1933 break; // handle below
1934 case STATE_FLUSHED:
1935 case STATE_STOPPED:
1936 return WOULD_BLOCK;
1937 case STATE_STOPPING:
1938 case STATE_PAUSED_STOPPING:
1939 if (!isOffloaded_l()) {
1940 return INVALID_OPERATION;
1941 }
1942 break; // offloaded tracks handled below
1943 default:
1944 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
1945 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07001946 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001947
Eric Laurent275e8e92014-11-30 15:14:47 -08001948 if (mCblk->mFlags & CBLK_INVALID) {
1949 restoreTrack_l("getTimestamp");
1950 }
1951
Glenn Kasten200092b2014-08-15 15:13:30 -07001952 // The presented frame count must always lag behind the consumed frame count.
1953 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07001954 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001955 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07001956 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001957 return status;
1958 }
1959 if (isOffloadedOrDirect_l()) {
1960 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
1961 // use cached paused position in case another offloaded track is running.
1962 timestamp.mPosition = mPausedPosition;
1963 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
1964 return NO_ERROR;
1965 }
1966
1967 // Check whether a pending flush or stop has completed, as those commands may
1968 // be asynchronous or return near finish.
1969 if (mStartUs != 0 && mSampleRate != 0) {
1970 static const int kTimeJitterUs = 100000; // 100 ms
1971 static const int k1SecUs = 1000000;
1972
1973 const int64_t timeNow = getNowUs();
1974
1975 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
1976 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
1977 if (timestampTimeUs < mStartUs) {
1978 return WOULD_BLOCK; // stale timestamp time, occurs before start.
1979 }
1980 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
1981 const int64_t deltaPositionByUs = timestamp.mPosition * 1000000LL / mSampleRate;
1982
1983 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
1984 // Verify that the counter can't count faster than the sample rate
1985 // since the start time. If greater, then that means we have failed
1986 // to completely flush or stop the previous playing track.
1987 ALOGW("incomplete flush or stop:"
1988 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
1989 (long long)deltaTimeUs, (long long)deltaPositionByUs,
1990 timestamp.mPosition);
1991 return WOULD_BLOCK;
1992 }
1993 }
1994 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
1995 }
1996 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07001997 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
1998 (void) updateAndGetPosition_l();
1999 // Server consumed (mServer) and presented both use the same server time base,
2000 // and server consumed is always >= presented.
2001 // The delta between these represents the number of frames in the buffer pipeline.
2002 // If this delta between these is greater than the client position, it means that
2003 // actually presented is still stuck at the starting line (figuratively speaking),
2004 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
2005 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2006 return INVALID_OPERATION;
2007 }
2008 // Convert timestamp position from server time base to client time base.
2009 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2010 // But if we change it to 64-bit then this could fail.
2011 // If (mPosition - mServer) can be negative then should use:
2012 // (int32_t)(mPosition - mServer)
2013 timestamp.mPosition += mPosition - mServer;
2014 // Immediately after a call to getPosition_l(), mPosition and
2015 // mServer both represent the same frame position. mPosition is
2016 // in client's point of view, and mServer is in server's point of
2017 // view. So the difference between them is the "fudge factor"
2018 // between client and server views due to stop() and/or new
2019 // IAudioTrack. And timestamp.mPosition is initially in server's
2020 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002021 }
2022 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002023}
2024
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002025String8 AudioTrack::getParameters(const String8& keys)
2026{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002027 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002028 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002029 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002030 } else {
2031 return String8::empty();
2032 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002033}
2034
Glenn Kasten23a75452014-01-13 10:37:17 -08002035bool AudioTrack::isOffloaded() const
2036{
2037 AutoMutex lock(mLock);
2038 return isOffloaded_l();
2039}
2040
Eric Laurentab5cdba2014-06-09 17:22:27 -07002041bool AudioTrack::isDirect() const
2042{
2043 AutoMutex lock(mLock);
2044 return isDirect_l();
2045}
2046
2047bool AudioTrack::isOffloadedOrDirect() const
2048{
2049 AutoMutex lock(mLock);
2050 return isOffloadedOrDirect_l();
2051}
2052
2053
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002054status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002055{
2056
2057 const size_t SIZE = 256;
2058 char buffer[SIZE];
2059 String8 result;
2060
2061 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002062 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002063 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002064 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002065 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002066 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002067 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08002068 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002069 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002070 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002071 result.append(buffer);
2072 ::write(fd, result.string(), result.size());
2073 return NO_ERROR;
2074}
2075
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002076uint32_t AudioTrack::getUnderrunFrames() const
2077{
2078 AutoMutex lock(mLock);
2079 return mProxy->getUnderrunFrames();
2080}
2081
2082// =========================================================================
2083
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002084void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002085{
2086 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2087 if (audioTrack != 0) {
2088 AutoMutex lock(audioTrack->mLock);
2089 audioTrack->mProxy->binderDied();
2090 }
2091}
2092
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002093// =========================================================================
2094
2095AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002096 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2097 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002098{
2099}
2100
2101AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002102{
2103}
2104
2105bool AudioTrack::AudioTrackThread::threadLoop()
2106{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002107 {
2108 AutoMutex _l(mMyLock);
2109 if (mPaused) {
2110 mMyCond.wait(mMyLock);
2111 // caller will check for exitPending()
2112 return true;
2113 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002114 if (mIgnoreNextPausedInt) {
2115 mIgnoreNextPausedInt = false;
2116 mPausedInt = false;
2117 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002118 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002119 if (mPausedNs > 0) {
2120 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2121 } else {
2122 mMyCond.wait(mMyLock);
2123 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002124 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002125 return true;
2126 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002127 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002128 if (exitPending()) {
2129 return false;
2130 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002131 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002132 switch (ns) {
2133 case 0:
2134 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002135 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002136 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002137 return true;
2138 case NS_NEVER:
2139 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002140 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08002141 // Event driven: call wake() when callback notifications conditions change.
2142 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002143 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002144 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002145 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002146 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002147 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002148 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002149}
2150
Glenn Kasten3acbd052012-02-28 10:39:56 -08002151void AudioTrack::AudioTrackThread::requestExit()
2152{
2153 // must be in this order to avoid a race condition
2154 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002155 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002156}
2157
2158void AudioTrack::AudioTrackThread::pause()
2159{
2160 AutoMutex _l(mMyLock);
2161 mPaused = true;
2162}
2163
2164void AudioTrack::AudioTrackThread::resume()
2165{
2166 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002167 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002168 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002169 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002170 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002171 mMyCond.signal();
2172 }
2173}
2174
Andy Hung3c09c782014-12-29 18:39:32 -08002175void AudioTrack::AudioTrackThread::wake()
2176{
2177 AutoMutex _l(mMyLock);
2178 if (!mPaused && mPausedInt && mPausedNs > 0) {
2179 // audio track is active and internally paused with timeout.
2180 mIgnoreNextPausedInt = true;
2181 mPausedInt = false;
2182 mMyCond.signal();
2183 }
2184}
2185
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002186void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2187{
2188 AutoMutex _l(mMyLock);
2189 mPausedInt = true;
2190 mPausedNs = ns;
2191}
2192
Glenn Kasten40bc9062015-03-20 09:09:33 -07002193} // namespace android