blob: cfdb19ce77a2c57dba0f6adf764f515a5c6ef59a [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{
Andy Hung5cbb5782015-03-27 18:39:59 -0700670 AutoMutex lock(mLock);
671 if (rate == mSampleRate) {
672 return NO_ERROR;
673 }
674 if (mIsTimed || isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800675 return INVALID_OPERATION;
676 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800677 if (mOutput == AUDIO_IO_HANDLE_NONE) {
678 return NO_INIT;
679 }
Andy Hung5cbb5782015-03-27 18:39:59 -0700680 // NOTE: it is theoretically possible, but highly unlikely, that a device change
681 // could mean a previously allowed sampling rate is no longer allowed.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800682 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800683 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700684 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800685 }
Andy Hungcd044842014-08-07 11:04:34 -0700686 if (rate == 0 || rate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700687 return BAD_VALUE;
688 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800689
Glenn Kastene3aa6592012-12-04 12:22:46 -0800690 mSampleRate = rate;
691 mProxy->setSampleRate(rate);
692
Eric Laurent57326622009-07-07 07:10:45 -0700693 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800694}
695
Glenn Kastena5224f32012-01-04 12:41:44 -0800696uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800697{
John Grossman4ff14ba2012-02-08 16:37:41 -0800698 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800699 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800700 }
701
Eric Laurent1703cdf2011-03-07 14:52:59 -0800702 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700703
704 // sample rate can be updated during playback by the offloaded decoder so we need to
705 // query the HAL and update if needed.
706// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700707 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700708 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700709 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700710 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700711 if (status == NO_ERROR) {
712 mSampleRate = sampleRate;
713 }
714 }
715 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800716 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800717}
718
719status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
720{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700721 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800722 return INVALID_OPERATION;
723 }
724
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800725 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800726 ;
727 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
728 loopEnd - loopStart >= MIN_LOOP) {
729 ;
730 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800731 return BAD_VALUE;
732 }
733
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800734 AutoMutex lock(mLock);
735 // See setPosition() regarding setting parameters such as loop points or position while active
736 if (mState == STATE_ACTIVE) {
737 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700738 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800739 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800740 return NO_ERROR;
741}
742
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800743void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
744{
Andy Hung4ede21d2014-12-12 15:37:34 -0800745 // We do not update the periodic notification point.
746 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
747 mLoopCount = loopCount;
748 mLoopEnd = loopEnd;
749 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800750 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800751 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -0800752
753 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800754}
755
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800756status_t AudioTrack::setMarkerPosition(uint32_t marker)
757{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700758 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700759 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700760 return INVALID_OPERATION;
761 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800762
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800763 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800764 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700765 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800766
Andy Hung3c09c782014-12-29 18:39:32 -0800767 sp<AudioTrackThread> t = mAudioTrackThread;
768 if (t != 0) {
769 t->wake();
770 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800771 return NO_ERROR;
772}
773
Glenn Kastena5224f32012-01-04 12:41:44 -0800774status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800775{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700776 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100777 return INVALID_OPERATION;
778 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700779 if (marker == NULL) {
780 return BAD_VALUE;
781 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800782
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800783 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800784 *marker = mMarkerPosition;
785
786 return NO_ERROR;
787}
788
789status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
790{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700791 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700792 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700793 return INVALID_OPERATION;
794 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800795
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800796 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700797 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800798 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800799
Andy Hung3c09c782014-12-29 18:39:32 -0800800 sp<AudioTrackThread> t = mAudioTrackThread;
801 if (t != 0) {
802 t->wake();
803 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800804 return NO_ERROR;
805}
806
Glenn Kastena5224f32012-01-04 12:41:44 -0800807status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800808{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700809 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100810 return INVALID_OPERATION;
811 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700812 if (updatePeriod == NULL) {
813 return BAD_VALUE;
814 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800815
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800816 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800817 *updatePeriod = mUpdatePeriod;
818
819 return NO_ERROR;
820}
821
822status_t AudioTrack::setPosition(uint32_t position)
823{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700824 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700825 return INVALID_OPERATION;
826 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800827 if (position > mFrameCount) {
828 return BAD_VALUE;
829 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800830
Eric Laurent1703cdf2011-03-07 14:52:59 -0800831 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800832 // Currently we require that the player is inactive before setting parameters such as position
833 // or loop points. Otherwise, there could be a race condition: the application could read the
834 // current position, compute a new position or loop parameters, and then set that position or
835 // loop parameters but it would do the "wrong" thing since the position has continued to advance
836 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
837 // to specify how it wants to handle such scenarios.
838 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700839 return INVALID_OPERATION;
840 }
Andy Hung9b461582014-12-01 17:56:29 -0800841 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -0700842 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800843 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -0800844
845 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800846 return NO_ERROR;
847}
848
Glenn Kasten200092b2014-08-15 15:13:30 -0700849status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800850{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700851 if (position == NULL) {
852 return BAD_VALUE;
853 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800854
Eric Laurent1703cdf2011-03-07 14:52:59 -0800855 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700856 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100857 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800858
Eric Laurentab5cdba2014-06-09 17:22:27 -0700859 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800860 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
861 *position = mPausedPosition;
862 return NO_ERROR;
863 }
864
Glenn Kasten142f5192014-03-25 17:44:59 -0700865 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100866 uint32_t halFrames;
867 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
868 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700869 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
870 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100871 *position = dspFrames;
872 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -0800873 if (mCblk->mFlags & CBLK_INVALID) {
874 restoreTrack_l("getPosition");
875 }
876
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100877 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700878 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
879 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100880 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800881 return NO_ERROR;
882}
883
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000884status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800885{
886 if (mSharedBuffer == 0 || mIsTimed) {
887 return INVALID_OPERATION;
888 }
889 if (position == NULL) {
890 return BAD_VALUE;
891 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800892
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800893 AutoMutex lock(mLock);
894 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800895 return NO_ERROR;
896}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800897
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800898status_t AudioTrack::reload()
899{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700900 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800901 return INVALID_OPERATION;
902 }
903
Eric Laurent1703cdf2011-03-07 14:52:59 -0800904 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800905 // See setPosition() regarding setting parameters such as loop points or position while active
906 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700907 return INVALID_OPERATION;
908 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800909 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800910 (void) updateAndGetPosition_l();
911 mPosition = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800912#if 0
Andy Hung9b461582014-12-01 17:56:29 -0800913 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -0800914 // of loop count. Historically we have not restored loop count, start, end,
915 // but it makes sense if one desires to repeat playing a particular sound.
916 if (mLoopCount != 0) {
917 mLoopCountNotified = mLoopCount;
918 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
919 }
920#endif
Andy Hung9b461582014-12-01 17:56:29 -0800921 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800922 return NO_ERROR;
923}
924
Glenn Kasten38e905b2014-01-13 10:21:48 -0800925audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700926{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800927 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100928 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800929}
930
Eric Laurentbe916aa2010-06-01 23:49:17 -0700931status_t AudioTrack::attachAuxEffect(int effectId)
932{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800933 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700934 status_t status = mAudioTrack->attachAuxEffect(effectId);
935 if (status == NO_ERROR) {
936 mAuxEffectId = effectId;
937 }
938 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700939}
940
Eric Laurente83b55d2014-11-14 10:06:21 -0800941audio_stream_type_t AudioTrack::streamType() const
942{
943 if (mStreamType == AUDIO_STREAM_DEFAULT) {
944 return audio_attributes_to_stream_type(&mAttributes);
945 }
946 return mStreamType;
947}
948
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800949// -------------------------------------------------------------------------
950
Eric Laurent1703cdf2011-03-07 14:52:59 -0800951// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -0700952status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800953{
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800954 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
955 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700956 ALOGE("Could not get audioflinger");
957 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800958 }
959
Eric Laurente83b55d2014-11-14 10:06:21 -0800960 audio_io_handle_t output;
961 audio_stream_type_t streamType = mStreamType;
962 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
963 status_t status = AudioSystem::getOutputForAttr(attr, &output,
964 (audio_session_t)mSessionId, &streamType,
965 mSampleRate, mFormat, mChannelMask,
966 mFlags, mOffloadInfo);
967
968
969 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700970 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 -0700971 " channel mask %#x, flags %#x",
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700972 mSessionId, streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800973 return BAD_VALUE;
974 }
975 {
976 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
977 // we must release it ourselves if anything goes wrong.
978
Glenn Kastence8828a2013-09-16 18:07:38 -0700979 // Not all of these values are needed under all conditions, but it is easier to get them all
980
Eric Laurentd1b449a2010-05-14 03:26:45 -0700981 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -0700982 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700983 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800984 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800985 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700986 }
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700987 ALOGV("createTrack_l() output %d afLatency %u", output, afLatency);
Eric Laurentd1b449a2010-05-14 03:26:45 -0700988
Glenn Kastence8828a2013-09-16 18:07:38 -0700989 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700990 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -0700991 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700992 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800993 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700994 }
995
996 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700997 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -0700998 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700999 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001000 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001001 }
Eric Laurent0d6db582014-11-12 18:39:44 -08001002 if (mSampleRate == 0) {
1003 mSampleRate = afSampleRate;
1004 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001005 // Client decides whether the track is TIMED (see below), but can only express a preference
1006 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001007 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001008 // either of these use cases:
1009 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -08001010 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001011 // use case 2: callback transfer mode
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001012 (mTransfer == TRANSFER_CALLBACK) ||
1013 // use case 3: obtain/release mode
1014 (mTransfer == TRANSFER_OBTAIN)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001015 // matching sample rate
1016 (mSampleRate == afSampleRate))) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001017 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client; transfer %d, track %u Hz, output %u Hz",
1018 mTransfer, mSampleRate, afSampleRate);
Glenn Kasten093000f2012-05-03 09:35:36 -07001019 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001020 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001021 }
1022
Glenn Kastence8828a2013-09-16 18:07:38 -07001023 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -08001024 // n = 1 fast track with single buffering; nBuffering is ignored
1025 // n = 2 fast track with double buffering
Andy Hung0e48d252015-01-26 11:43:15 -08001026 // n = 2 normal track, (including those with sample rate conversion)
1027 // n >= 3 very high latency or very small notification interval (unused).
1028 const uint32_t nBuffering = 2;
Glenn Kastence8828a2013-09-16 18:07:38 -07001029
Eric Laurentd1b449a2010-05-14 03:26:45 -07001030 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001031
Glenn Kasten363fb752014-01-15 12:27:31 -08001032 size_t frameCount = mReqFrameCount;
1033 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001034
Glenn Kasten363fb752014-01-15 12:27:31 -08001035 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001036 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001037 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001038 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001039 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001040 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001041 if (mNotificationFramesAct != frameCount) {
1042 mNotificationFramesAct = frameCount;
1043 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001044 } else if (mSharedBuffer != 0) {
Andy Hungabdb9902015-01-12 15:08:22 -08001045 // FIXME: Ensure client side memory buffers need
1046 // not have additional alignment beyond sample
1047 // (e.g. 16 bit stereo accessed as 32 bit frame).
1048 size_t alignment = audio_bytes_per_sample(mFormat);
Glenn Kastenb7730382014-04-30 15:50:31 -07001049 if (alignment & 1) {
Andy Hungabdb9902015-01-12 15:08:22 -08001050 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
Glenn Kastenb7730382014-04-30 15:50:31 -07001051 alignment = 1;
1052 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001053 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001054 // More than 2 channels does not require stronger alignment than stereo
1055 alignment <<= 1;
1056 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001057 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001058 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001059 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001060 status = BAD_VALUE;
1061 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001062 }
1063
1064 // When initializing a shared buffer AudioTrack via constructors,
1065 // there's no frameCount parameter.
1066 // But when initializing a shared buffer AudioTrack via set(),
1067 // there _is_ a frameCount parameter. We silently ignore it.
Andy Hungabdb9902015-01-12 15:08:22 -08001068 frameCount = mSharedBuffer->size() / mFrameSize;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001069 } else {
Andy Hung0e48d252015-01-26 11:43:15 -08001070 // For fast and normal streaming tracks,
1071 // the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -07001072 }
1073
Glenn Kastena075db42012-03-06 11:22:44 -08001074 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1075 if (mIsTimed) {
1076 trackFlags |= IAudioFlinger::TRACK_TIMED;
1077 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001078
1079 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001080 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001081 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001082 if (mAudioTrackThread != 0) {
1083 tid = mAudioTrackThread->getTid();
1084 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001085 }
1086
Glenn Kasten363fb752014-01-15 12:27:31 -08001087 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001088 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1089 }
1090
Eric Laurentab5cdba2014-06-09 17:22:27 -07001091 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1092 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1093 }
1094
Glenn Kasten74935e42013-12-19 08:56:45 -08001095 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1096 // but we will still need the original value also
Glenn Kasten138d6f92015-03-20 10:54:51 -07001097 int originalSessionId = mSessionId;
Eric Laurente83b55d2014-11-14 10:06:21 -08001098 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001099 mSampleRate,
Andy Hungabdb9902015-01-12 15:08:22 -08001100 mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001101 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001102 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001103 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001104 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001105 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001106 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001107 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001108 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001109 &status);
Glenn Kasten138d6f92015-03-20 10:54:51 -07001110 ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
1111 "session ID changed from %d to %d", originalSessionId, mSessionId);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001112
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001113 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001114 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001115 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001116 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001117 ALOG_ASSERT(track != 0);
1118
Glenn Kasten38e905b2014-01-13 10:21:48 -08001119 // AudioFlinger now owns the reference to the I/O handle,
1120 // so we are no longer responsible for releasing it.
1121
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001122 sp<IMemory> iMem = track->getCblk();
1123 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001124 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001125 return NO_INIT;
1126 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001127 void *iMemPointer = iMem->pointer();
1128 if (iMemPointer == NULL) {
1129 ALOGE("Could not get control block pointer");
1130 return NO_INIT;
1131 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001132 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001133 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001134 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001135 mDeathNotifier.clear();
1136 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001137 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001138 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001139 IPCThreadState::self()->flushCommands();
1140
Glenn Kasten0cde0762014-01-16 15:06:36 -08001141 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001142 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001143 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001144 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1145 // In current design, AudioTrack client checks and ensures frame count validity before
1146 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1147 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001148 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001149 }
1150 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001151
Glenn Kastena07f17c2013-04-23 12:39:37 -07001152 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001153 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001154 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001155 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001156 mAwaitBoost = true;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001157 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001158 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001159 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001160 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001161 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001162 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001163 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001164 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1165 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1166 } else {
1167 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001168 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001169 // FIXME This is a warning, not an error, so don't return error status
1170 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001171 }
1172 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001173 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1174 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1175 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1176 } else {
1177 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1178 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1179 // FIXME This is a warning, not an error, so don't return error status
1180 //return NO_INIT;
1181 }
1182 }
Andy Hung0e48d252015-01-26 11:43:15 -08001183 // Make sure that application is notified with sufficient margin before underrun
1184 if (mSharedBuffer == 0 && audio_is_linear_pcm(mFormat)) {
1185 // Theoretically double-buffering is not required for fast tracks,
1186 // due to tighter scheduling. But in practice, to accommodate kernels with
1187 // scheduling jitter, and apps with computation jitter, we use double-buffering
1188 // for fast tracks just like normal streaming tracks.
1189 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount / nBuffering) {
1190 mNotificationFramesAct = frameCount / nBuffering;
1191 }
1192 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001193
Glenn Kasten38e905b2014-01-13 10:21:48 -08001194 // We retain a copy of the I/O handle, but don't own the reference
1195 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001196 mRefreshRemaining = true;
1197
1198 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1199 // is the value of pointer() for the shared buffer, otherwise buffers points
1200 // immediately after the control block. This address is for the mapping within client
1201 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1202 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001203 if (mSharedBuffer == 0) {
Glenn Kasten138d6f92015-03-20 10:54:51 -07001204 buffers = cblk + 1;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001205 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001206 buffers = mSharedBuffer->pointer();
Glenn Kasten138d6f92015-03-20 10:54:51 -07001207 if (buffers == NULL) {
1208 ALOGE("Could not get buffer pointer");
1209 return NO_INIT;
1210 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001211 }
1212
Eric Laurent2beeb502010-07-16 07:43:46 -07001213 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001214 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001215 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001216
Glenn Kastenb6037442012-11-14 13:42:25 -08001217 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001218 // If IAudioTrack is re-created, don't let the requested frameCount
1219 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001220 if (frameCount > mReqFrameCount) {
1221 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001222 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001223
1224 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001225 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001226 mStaticProxy.clear();
Andy Hungabdb9902015-01-12 15:08:22 -08001227 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001228 } else {
Andy Hungabdb9902015-01-12 15:08:22 -08001229 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001230 mProxy = mStaticProxy;
1231 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001232
1233 mProxy->setVolumeLR(gain_minifloat_pack(
1234 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1235 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1236
Glenn Kastene3aa6592012-12-04 12:22:46 -08001237 mProxy->setSendLevel(mSendLevel);
1238 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001239 mProxy->setMinimum(mNotificationFramesAct);
1240
1241 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001242 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001243
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001244 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001245 }
1246
1247release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001248 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001249 if (status == NO_ERROR) {
1250 status = NO_INIT;
1251 }
1252 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001253}
1254
Glenn Kastenb46f3942015-03-09 12:00:30 -07001255status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001256{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001257 if (audioBuffer == NULL) {
Glenn Kasten551b5352015-03-20 11:30:28 -07001258 if (nonContig != NULL) {
1259 *nonContig = 0;
1260 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001261 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001262 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001263 if (mTransfer != TRANSFER_OBTAIN) {
1264 audioBuffer->frameCount = 0;
1265 audioBuffer->size = 0;
1266 audioBuffer->raw = NULL;
Glenn Kasten551b5352015-03-20 11:30:28 -07001267 if (nonContig != NULL) {
1268 *nonContig = 0;
1269 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001270 return INVALID_OPERATION;
1271 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001272
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001273 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001274 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001275 if (waitCount == -1) {
1276 requested = &ClientProxy::kForever;
1277 } else if (waitCount == 0) {
1278 requested = &ClientProxy::kNonBlocking;
1279 } else if (waitCount > 0) {
1280 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001281 timeout.tv_sec = ms / 1000;
1282 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1283 requested = &timeout;
1284 } else {
1285 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1286 requested = NULL;
1287 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001288 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001289}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001290
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001291status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1292 struct timespec *elapsed, size_t *nonContig)
1293{
1294 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1295 uint32_t oldSequence = 0;
1296 uint32_t newSequence;
1297
1298 Proxy::Buffer buffer;
1299 status_t status = NO_ERROR;
1300
1301 static const int32_t kMaxTries = 5;
1302 int32_t tryCounter = kMaxTries;
1303
1304 do {
1305 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1306 // keep them from going away if another thread re-creates the track during obtainBuffer()
1307 sp<AudioTrackClientProxy> proxy;
1308 sp<IMemory> iMem;
1309
1310 { // start of lock scope
1311 AutoMutex lock(mLock);
1312
1313 newSequence = mSequence;
1314 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1315 if (status == DEAD_OBJECT) {
1316 // re-create track, unless someone else has already done so
1317 if (newSequence == oldSequence) {
1318 status = restoreTrack_l("obtainBuffer");
1319 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001320 buffer.mFrameCount = 0;
1321 buffer.mRaw = NULL;
1322 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001323 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001324 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001325 }
1326 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001327 oldSequence = newSequence;
1328
1329 // Keep the extra references
1330 proxy = mProxy;
1331 iMem = mCblkMemory;
1332
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001333 if (mState == STATE_STOPPING) {
1334 status = -EINTR;
1335 buffer.mFrameCount = 0;
1336 buffer.mRaw = NULL;
1337 buffer.mNonContig = 0;
1338 break;
1339 }
1340
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001341 // Non-blocking if track is stopped or paused
1342 if (mState != STATE_ACTIVE) {
1343 requested = &ClientProxy::kNonBlocking;
1344 }
1345
1346 } // end of lock scope
1347
1348 buffer.mFrameCount = audioBuffer->frameCount;
1349 // FIXME starts the requested timeout and elapsed over from scratch
1350 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1351
1352 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1353
1354 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001355 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001356 audioBuffer->raw = buffer.mRaw;
1357 if (nonContig != NULL) {
1358 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001359 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001360 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001361}
1362
Glenn Kasten54a8a452015-03-09 12:03:00 -07001363void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001364{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001365 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001366 if (mTransfer == TRANSFER_SHARED) {
1367 return;
1368 }
1369
Andy Hungabdb9902015-01-12 15:08:22 -08001370 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001371 if (stepCount == 0) {
1372 return;
1373 }
1374
1375 Proxy::Buffer buffer;
1376 buffer.mFrameCount = stepCount;
1377 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001378
Eric Laurent1703cdf2011-03-07 14:52:59 -08001379 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001380 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001381 mInUnderrun = false;
1382 mProxy->releaseBuffer(&buffer);
1383
1384 // restart track if it was disabled by audioflinger due to previous underrun
1385 if (mState == STATE_ACTIVE) {
1386 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001387 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001388 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001389 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001390 mAudioTrack->start();
1391 }
1392 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001393}
1394
1395// -------------------------------------------------------------------------
1396
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001397ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001398{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001399 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001400 return INVALID_OPERATION;
1401 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001402
Eric Laurentab5cdba2014-06-09 17:22:27 -07001403 if (isDirect()) {
1404 AutoMutex lock(mLock);
1405 int32_t flags = android_atomic_and(
1406 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1407 &mCblk->mFlags);
1408 if (flags & CBLK_INVALID) {
1409 return DEAD_OBJECT;
1410 }
1411 }
1412
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001413 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001414 // Sanity-check: user is most-likely passing an error code, and it would
1415 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001416 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001417 return BAD_VALUE;
1418 }
1419
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001420 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001421 Buffer audioBuffer;
1422
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001423 while (userSize >= mFrameSize) {
1424 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001425
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001426 status_t err = obtainBuffer(&audioBuffer,
1427 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001428 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001429 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001430 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001431 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001432 return ssize_t(err);
1433 }
1434
Glenn Kastenae4b8792015-03-20 09:04:21 -07001435 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08001436 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001437 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001438 userSize -= toWrite;
1439 written += toWrite;
1440
1441 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001442 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001443
1444 return written;
1445}
1446
1447// -------------------------------------------------------------------------
1448
John Grossman4ff14ba2012-02-08 16:37:41 -08001449TimedAudioTrack::TimedAudioTrack() {
1450 mIsTimed = true;
1451}
1452
1453status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1454{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001455 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001456 status_t result = UNKNOWN_ERROR;
1457
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001458#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001459 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1460 // while we are accessing the cblk
1461 sp<IAudioTrack> audioTrack = mAudioTrack;
1462 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001463#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001464
John Grossman4ff14ba2012-02-08 16:37:41 -08001465 // If the track is not invalid already, try to allocate a buffer. alloc
1466 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001467 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001468 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001469 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001470 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1471 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001472 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001473 }
1474 }
1475
1476 // If the track is invalid at this point, attempt to restore it. and try the
1477 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001478 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001479 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001480
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001481 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001482 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001483 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001484 }
1485
1486 return result;
1487}
1488
1489status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1490 int64_t pts)
1491{
Eric Laurentdf839842012-05-31 14:27:14 -07001492 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1493 {
1494 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001495 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001496 // restart track if it was disabled by audioflinger due to previous underrun
1497 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001498 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1499 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001500 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001501 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001502 mAudioTrack->start();
1503 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001504 }
Eric Laurentdf839842012-05-31 14:27:14 -07001505 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001506}
1507
1508status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1509 TargetTimeline target)
1510{
1511 return mAudioTrack->setMediaTimeTransform(xform, target);
1512}
1513
1514// -------------------------------------------------------------------------
1515
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001516nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001517{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001518 // Currently the AudioTrack thread is not created if there are no callbacks.
1519 // Would it ever make sense to run the thread, even without callbacks?
1520 // If so, then replace this by checks at each use for mCbf != NULL.
1521 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1522
Eric Laurent1703cdf2011-03-07 14:52:59 -08001523 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001524 if (mAwaitBoost) {
1525 mAwaitBoost = false;
1526 mLock.unlock();
1527 static const int32_t kMaxTries = 5;
1528 int32_t tryCounter = kMaxTries;
1529 uint32_t pollUs = 10000;
1530 do {
1531 int policy = sched_getscheduler(0);
1532 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1533 break;
1534 }
1535 usleep(pollUs);
1536 pollUs <<= 1;
1537 } while (tryCounter-- > 0);
1538 if (tryCounter < 0) {
1539 ALOGE("did not receive expected priority boost on time");
1540 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001541 // Run again immediately
1542 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001543 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001544
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001545 // Can only reference mCblk while locked
1546 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001547 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001548
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001549 // Check for track invalidation
1550 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001551 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1552 // AudioSystem cache. We should not exit here but after calling the callback so
1553 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001554 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001555 status_t status = restoreTrack_l("processAudioBuffer");
Andy Hung53c3b5f2014-12-15 16:42:05 -08001556 // after restoration, continue below to make sure that the loop and buffer events
1557 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001558 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001559 }
1560
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001561 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001562 bool active = mState == STATE_ACTIVE;
1563
1564 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1565 bool newUnderrun = false;
1566 if (flags & CBLK_UNDERRUN) {
1567#if 0
1568 // Currently in shared buffer mode, when the server reaches the end of buffer,
1569 // the track stays active in continuous underrun state. It's up to the application
1570 // to pause or stop the track, or set the position to a new offset within buffer.
1571 // This was some experimental code to auto-pause on underrun. Keeping it here
1572 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1573 if (mTransfer == TRANSFER_SHARED) {
1574 mState = STATE_PAUSED;
1575 active = false;
1576 }
1577#endif
1578 if (!mInUnderrun) {
1579 mInUnderrun = true;
1580 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001581 }
1582 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001583
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001584 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001585 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001586
1587 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001588 bool markerReached = false;
1589 size_t markerPosition = mMarkerPosition;
1590 // FIXME fails for wraparound, need 64 bits
1591 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1592 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001593 }
1594
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001595 // Determine number of new position callback(s) that will be needed, while locked
1596 size_t newPosCount = 0;
1597 size_t newPosition = mNewPosition;
1598 size_t updatePeriod = mUpdatePeriod;
1599 // FIXME fails for wraparound, need 64 bits
1600 if (updatePeriod > 0 && position >= newPosition) {
1601 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1602 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001603 }
1604
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001605 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001606 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001607 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001608 if (mRefreshRemaining) {
1609 mRefreshRemaining = false;
1610 mRemainingFrames = notificationFrames;
1611 mRetryOnPartialBuffer = false;
1612 }
1613 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001614 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001615 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001616
Andy Hung53c3b5f2014-12-15 16:42:05 -08001617 // Determine the number of new loop callback(s) that will be needed, while locked.
1618 int loopCountNotifications = 0;
1619 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1620
1621 if (mLoopCount > 0) {
1622 int loopCount;
1623 size_t bufferPosition;
1624 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1625 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1626 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1627 mLoopCountNotified = loopCount; // discard any excess notifications
1628 } else if (mLoopCount < 0) {
1629 // FIXME: We're not accurate with notification count and position with infinite looping
1630 // since loopCount from server side will always return -1 (we could decrement it).
1631 size_t bufferPosition = mStaticProxy->getBufferPosition();
1632 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1633 loopPeriod = mLoopEnd - bufferPosition;
1634 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1635 size_t bufferPosition = mStaticProxy->getBufferPosition();
1636 loopPeriod = mFrameCount - bufferPosition;
1637 }
1638
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001639 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08001640 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001641 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1642
1643 mLock.unlock();
1644
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001645 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001646 struct timespec timeout;
1647 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1648 timeout.tv_nsec = 0;
1649
Glenn Kasten96f04882013-09-20 09:28:56 -07001650 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001651 switch (status) {
1652 case NO_ERROR:
1653 case DEAD_OBJECT:
1654 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001655 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001656 {
1657 AutoMutex lock(mLock);
1658 // The previously assigned value of waitStreamEnd is no longer valid,
1659 // since the mutex has been unlocked and either the callback handler
1660 // or another thread could have re-started the AudioTrack during that time.
1661 waitStreamEnd = mState == STATE_STOPPING;
1662 if (waitStreamEnd) {
1663 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001664 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001665 }
1666 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001667 if (waitStreamEnd && status != DEAD_OBJECT) {
1668 return NS_INACTIVE;
1669 }
1670 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001671 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001672 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001673 }
1674
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001675 // perform callbacks while unlocked
1676 if (newUnderrun) {
1677 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1678 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001679 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001680 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001681 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001682 }
1683 if (flags & CBLK_BUFFER_END) {
1684 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1685 }
1686 if (markerReached) {
1687 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1688 }
1689 while (newPosCount > 0) {
1690 size_t temp = newPosition;
1691 mCbf(EVENT_NEW_POS, mUserData, &temp);
1692 newPosition += updatePeriod;
1693 newPosCount--;
1694 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001695
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001696 if (mObservedSequence != sequence) {
1697 mObservedSequence = sequence;
1698 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001699 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001700 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001701 return NS_INACTIVE;
1702 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001703 }
1704
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001705 // if inactive, then don't run me again until re-started
1706 if (!active) {
1707 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001708 }
1709
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001710 // Compute the estimated time until the next timed event (position, markers, loops)
1711 // FIXME only for non-compressed audio
1712 uint32_t minFrames = ~0;
1713 if (!markerReached && position < markerPosition) {
1714 minFrames = markerPosition - position;
1715 }
1716 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08001717 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001718 minFrames = loopPeriod;
1719 }
Andy Hung2d85f092015-01-07 12:45:13 -08001720 if (updatePeriod > 0) {
1721 minFrames = min(minFrames, uint32_t(newPosition - position));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001722 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001723
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001724 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1725 static const uint32_t kPoll = 0;
1726 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1727 minFrames = kPoll * notificationFrames;
1728 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001729
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001730 // Convert frame units to time units
1731 nsecs_t ns = NS_WHENEVER;
1732 if (minFrames != (uint32_t) ~0) {
1733 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1734 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1735 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1736 }
1737
1738 // If not supplying data by EVENT_MORE_DATA, then we're done
1739 if (mTransfer != TRANSFER_CALLBACK) {
1740 return ns;
1741 }
1742
1743 struct timespec timeout;
1744 const struct timespec *requested = &ClientProxy::kForever;
1745 if (ns != NS_WHENEVER) {
1746 timeout.tv_sec = ns / 1000000000LL;
1747 timeout.tv_nsec = ns % 1000000000LL;
1748 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1749 requested = &timeout;
1750 }
1751
1752 while (mRemainingFrames > 0) {
1753
1754 Buffer audioBuffer;
1755 audioBuffer.frameCount = mRemainingFrames;
1756 size_t nonContig;
1757 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1758 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001759 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001760 requested = &ClientProxy::kNonBlocking;
1761 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001762 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001763 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001764 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001765 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1766 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001767 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001768 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001769 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1770 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001771 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001772
Eric Laurent42a6f422013-08-29 14:35:05 -07001773 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001774 mRetryOnPartialBuffer = false;
1775 if (avail < mRemainingFrames) {
1776 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1777 if (ns < 0 || myns < ns) {
1778 ns = myns;
1779 }
1780 return ns;
1781 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001782 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001783
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001784 size_t reqSize = audioBuffer.size;
1785 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001786 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001787
1788 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001789 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001790 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1791 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001792 return NS_NEVER;
1793 }
1794
1795 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001796 // The callback is done filling buffers
1797 // Keep this thread going to handle timed events and
1798 // still try to get more data in intervals of WAIT_PERIOD_MS
1799 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001800 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001801 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001802
Glenn Kasten138d6f92015-03-20 10:54:51 -07001803 size_t releasedFrames = writtenSize / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001804 audioBuffer.frameCount = releasedFrames;
1805 mRemainingFrames -= releasedFrames;
1806 if (misalignment >= releasedFrames) {
1807 misalignment -= releasedFrames;
1808 } else {
1809 misalignment = 0;
1810 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001811
1812 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001813
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001814 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1815 // if callback doesn't like to accept the full chunk
1816 if (writtenSize < reqSize) {
1817 continue;
1818 }
1819
1820 // There could be enough non-contiguous frames available to satisfy the remaining request
1821 if (mRemainingFrames <= nonContig) {
1822 continue;
1823 }
1824
1825#if 0
1826 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1827 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1828 // that total to a sum == notificationFrames.
1829 if (0 < misalignment && misalignment <= mRemainingFrames) {
1830 mRemainingFrames = misalignment;
1831 return (mRemainingFrames * 1100000000LL) / sampleRate;
1832 }
1833#endif
1834
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001835 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001836 mRemainingFrames = notificationFrames;
1837 mRetryOnPartialBuffer = true;
1838
1839 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1840 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001841}
1842
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001843status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001844{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001845 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001846 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001847 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001848
Glenn Kastena47f3162012-11-07 10:13:08 -08001849 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08001850 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001851 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001852
Eric Laurentab5cdba2014-06-09 17:22:27 -07001853 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001854 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001855 return DEAD_OBJECT;
1856 }
1857
Glenn Kasten200092b2014-08-15 15:13:30 -07001858 // save the old static buffer position
Andy Hung4ede21d2014-12-12 15:37:34 -08001859 size_t bufferPosition = 0;
1860 int loopCount = 0;
1861 if (mStaticProxy != 0) {
1862 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1863 }
Glenn Kasten200092b2014-08-15 15:13:30 -07001864
1865 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001866 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001867 // It will also delete the strong references on previous IAudioTrack and IMemory.
1868 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Glenn Kastenae4b8792015-03-20 09:04:21 -07001869 status_t result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001870
1871 // take the frames that will be lost by track recreation into account in saved position
Andy Hung9b461582014-12-01 17:56:29 -08001872 // For streaming tracks, this is the amount we obtained from the user/client
1873 // (not the number actually consumed at the server - those are already lost).
Glenn Kasten200092b2014-08-15 15:13:30 -07001874 (void) updateAndGetPosition_l();
Andy Hung7ccdaad2015-03-20 00:38:32 -07001875 if (mStaticProxy == 0) {
Andy Hung9b461582014-12-01 17:56:29 -08001876 mPosition = mReleased;
1877 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001878
Glenn Kastena47f3162012-11-07 10:13:08 -08001879 if (result == NO_ERROR) {
Andy Hung4ede21d2014-12-12 15:37:34 -08001880 // Continue playback from last known position and restore loop.
1881 if (mStaticProxy != 0) {
1882 if (loopCount != 0) {
1883 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
1884 mLoopStart, mLoopEnd, loopCount);
1885 } else {
1886 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001887 if (bufferPosition == mFrameCount) {
1888 ALOGD("restoring track at end of static buffer");
1889 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001890 }
1891 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001892 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001893 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001894 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001895 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001896 if (result != NO_ERROR) {
1897 ALOGW("restoreTrack_l() failed status %d", result);
1898 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001899 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001900 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001901
1902 return result;
1903}
1904
Glenn Kasten200092b2014-08-15 15:13:30 -07001905uint32_t AudioTrack::updateAndGetPosition_l()
1906{
1907 // This is the sole place to read server consumed frames
1908 uint32_t newServer = mProxy->getPosition();
1909 int32_t delta = newServer - mServer;
1910 mServer = newServer;
1911 // TODO There is controversy about whether there can be "negative jitter" in server position.
1912 // This should be investigated further, and if possible, it should be addressed.
1913 // A more definite failure mode is infrequent polling by client.
1914 // One could call (void)getPosition_l() in releaseBuffer(),
1915 // so mReleased and mPosition are always lock-step as best possible.
1916 // That should ensure delta never goes negative for infrequent polling
1917 // unless the server has more than 2^31 frames in its buffer,
1918 // in which case the use of uint32_t for these counters has bigger issues.
1919 if (delta < 0) {
1920 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
1921 delta = 0;
1922 }
1923 return mPosition += (uint32_t) delta;
1924}
1925
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001926status_t AudioTrack::setParameters(const String8& keyValuePairs)
1927{
1928 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001929 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001930}
1931
Glenn Kastence703742013-07-19 16:33:58 -07001932status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1933{
Glenn Kasten53cec222013-08-29 09:01:02 -07001934 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001935 // FIXME not implemented for fast tracks; should use proxy and SSQ
1936 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1937 return INVALID_OPERATION;
1938 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001939
1940 switch (mState) {
1941 case STATE_ACTIVE:
1942 case STATE_PAUSED:
1943 break; // handle below
1944 case STATE_FLUSHED:
1945 case STATE_STOPPED:
1946 return WOULD_BLOCK;
1947 case STATE_STOPPING:
1948 case STATE_PAUSED_STOPPING:
1949 if (!isOffloaded_l()) {
1950 return INVALID_OPERATION;
1951 }
1952 break; // offloaded tracks handled below
1953 default:
1954 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
1955 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07001956 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001957
Eric Laurent275e8e92014-11-30 15:14:47 -08001958 if (mCblk->mFlags & CBLK_INVALID) {
1959 restoreTrack_l("getTimestamp");
1960 }
1961
Glenn Kasten200092b2014-08-15 15:13:30 -07001962 // The presented frame count must always lag behind the consumed frame count.
1963 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07001964 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001965 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07001966 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001967 return status;
1968 }
1969 if (isOffloadedOrDirect_l()) {
1970 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
1971 // use cached paused position in case another offloaded track is running.
1972 timestamp.mPosition = mPausedPosition;
1973 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
1974 return NO_ERROR;
1975 }
1976
1977 // Check whether a pending flush or stop has completed, as those commands may
1978 // be asynchronous or return near finish.
1979 if (mStartUs != 0 && mSampleRate != 0) {
1980 static const int kTimeJitterUs = 100000; // 100 ms
1981 static const int k1SecUs = 1000000;
1982
1983 const int64_t timeNow = getNowUs();
1984
1985 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
1986 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
1987 if (timestampTimeUs < mStartUs) {
1988 return WOULD_BLOCK; // stale timestamp time, occurs before start.
1989 }
1990 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
1991 const int64_t deltaPositionByUs = timestamp.mPosition * 1000000LL / mSampleRate;
1992
1993 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
1994 // Verify that the counter can't count faster than the sample rate
1995 // since the start time. If greater, then that means we have failed
1996 // to completely flush or stop the previous playing track.
1997 ALOGW("incomplete flush or stop:"
1998 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
1999 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2000 timestamp.mPosition);
2001 return WOULD_BLOCK;
2002 }
2003 }
2004 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
2005 }
2006 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002007 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2008 (void) updateAndGetPosition_l();
2009 // Server consumed (mServer) and presented both use the same server time base,
2010 // and server consumed is always >= presented.
2011 // The delta between these represents the number of frames in the buffer pipeline.
2012 // If this delta between these is greater than the client position, it means that
2013 // actually presented is still stuck at the starting line (figuratively speaking),
2014 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
2015 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2016 return INVALID_OPERATION;
2017 }
2018 // Convert timestamp position from server time base to client time base.
2019 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2020 // But if we change it to 64-bit then this could fail.
2021 // If (mPosition - mServer) can be negative then should use:
2022 // (int32_t)(mPosition - mServer)
2023 timestamp.mPosition += mPosition - mServer;
2024 // Immediately after a call to getPosition_l(), mPosition and
2025 // mServer both represent the same frame position. mPosition is
2026 // in client's point of view, and mServer is in server's point of
2027 // view. So the difference between them is the "fudge factor"
2028 // between client and server views due to stop() and/or new
2029 // IAudioTrack. And timestamp.mPosition is initially in server's
2030 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002031 }
2032 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002033}
2034
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002035String8 AudioTrack::getParameters(const String8& keys)
2036{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002037 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002038 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002039 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002040 } else {
2041 return String8::empty();
2042 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002043}
2044
Glenn Kasten23a75452014-01-13 10:37:17 -08002045bool AudioTrack::isOffloaded() const
2046{
2047 AutoMutex lock(mLock);
2048 return isOffloaded_l();
2049}
2050
Eric Laurentab5cdba2014-06-09 17:22:27 -07002051bool AudioTrack::isDirect() const
2052{
2053 AutoMutex lock(mLock);
2054 return isDirect_l();
2055}
2056
2057bool AudioTrack::isOffloadedOrDirect() const
2058{
2059 AutoMutex lock(mLock);
2060 return isOffloadedOrDirect_l();
2061}
2062
2063
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002064status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002065{
2066
2067 const size_t SIZE = 256;
2068 char buffer[SIZE];
2069 String8 result;
2070
2071 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002072 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002073 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002074 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002075 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002076 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002077 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08002078 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002079 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002080 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002081 result.append(buffer);
2082 ::write(fd, result.string(), result.size());
2083 return NO_ERROR;
2084}
2085
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002086uint32_t AudioTrack::getUnderrunFrames() const
2087{
2088 AutoMutex lock(mLock);
2089 return mProxy->getUnderrunFrames();
2090}
2091
2092// =========================================================================
2093
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002094void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002095{
2096 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2097 if (audioTrack != 0) {
2098 AutoMutex lock(audioTrack->mLock);
2099 audioTrack->mProxy->binderDied();
2100 }
2101}
2102
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002103// =========================================================================
2104
2105AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002106 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2107 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002108{
2109}
2110
2111AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002112{
2113}
2114
2115bool AudioTrack::AudioTrackThread::threadLoop()
2116{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002117 {
2118 AutoMutex _l(mMyLock);
2119 if (mPaused) {
2120 mMyCond.wait(mMyLock);
2121 // caller will check for exitPending()
2122 return true;
2123 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002124 if (mIgnoreNextPausedInt) {
2125 mIgnoreNextPausedInt = false;
2126 mPausedInt = false;
2127 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002128 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002129 if (mPausedNs > 0) {
2130 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2131 } else {
2132 mMyCond.wait(mMyLock);
2133 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002134 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002135 return true;
2136 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002137 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002138 if (exitPending()) {
2139 return false;
2140 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002141 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002142 switch (ns) {
2143 case 0:
2144 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002145 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002146 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002147 return true;
2148 case NS_NEVER:
2149 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002150 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08002151 // Event driven: call wake() when callback notifications conditions change.
2152 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002153 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002154 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002155 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002156 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002157 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002158 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002159}
2160
Glenn Kasten3acbd052012-02-28 10:39:56 -08002161void AudioTrack::AudioTrackThread::requestExit()
2162{
2163 // must be in this order to avoid a race condition
2164 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002165 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002166}
2167
2168void AudioTrack::AudioTrackThread::pause()
2169{
2170 AutoMutex _l(mMyLock);
2171 mPaused = true;
2172}
2173
2174void AudioTrack::AudioTrackThread::resume()
2175{
2176 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002177 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002178 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002179 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002180 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002181 mMyCond.signal();
2182 }
2183}
2184
Andy Hung3c09c782014-12-29 18:39:32 -08002185void AudioTrack::AudioTrackThread::wake()
2186{
2187 AutoMutex _l(mMyLock);
2188 if (!mPaused && mPausedInt && mPausedNs > 0) {
2189 // audio track is active and internally paused with timeout.
2190 mIgnoreNextPausedInt = true;
2191 mPausedInt = false;
2192 mMyCond.signal();
2193 }
2194}
2195
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002196void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2197{
2198 AutoMutex _l(mMyLock);
2199 mPausedInt = true;
2200 mPausedNs = ns;
2201}
2202
Glenn Kasten40bc9062015-03-20 09:09:33 -07002203} // namespace android