blob: 0ad9cc04a31a9d51de026f3e8cffe982293135ae [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080018//#define LOG_NDEBUG 0
19#define LOG_TAG "AudioTrack"
20
Mark Salyzyn34fb2962014-06-18 16:30:56 -070021#include <inttypes.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070022#include <math.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080023#include <sys/resource.h>
Mark Salyzyn34fb2962014-06-18 16:30:56 -070024
Glenn Kasten9f80dd22012-12-18 15:57:32 -080025#include <audio_utils/primitives.h>
26#include <binder/IPCThreadState.h>
27#include <media/AudioTrack.h>
28#include <utils/Log.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080029#include <private/media/AudioTrackShared.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/IAudioFlinger.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080031#include <media/AudioPolicyHelper.h>
Andy Hungcd044842014-08-07 11:04:34 -070032#include <media/AudioResamplerPublic.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080033
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010034#define WAIT_PERIOD_MS 10
35#define WAIT_STREAM_END_TIMEOUT_SEC 120
Andy Hung53c3b5f2014-12-15 16:42:05 -080036static const int kMaxLoopCountNotifications = 32;
Glenn Kasten511754b2012-01-11 09:52:19 -080037
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080038namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080039// ---------------------------------------------------------------------------
40
Andy Hung4ede21d2014-12-12 15:37:34 -080041template <typename T>
42const T &min(const T &x, const T &y) {
43 return x < y ? x : y;
44}
45
Andy Hung7f1bc8a2014-09-12 14:43:11 -070046static int64_t convertTimespecToUs(const struct timespec &tv)
47{
48 return tv.tv_sec * 1000000ll + tv.tv_nsec / 1000;
49}
50
51// current monotonic time in microseconds.
52static int64_t getNowUs()
53{
54 struct timespec tv;
55 (void) clock_gettime(CLOCK_MONOTONIC, &tv);
56 return convertTimespecToUs(tv);
57}
58
Chia-chi Yeh33005a92010-06-16 06:33:13 +080059// static
60status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080061 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080062 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080063 uint32_t sampleRate)
64{
Glenn Kastend65d73c2012-06-22 17:21:07 -070065 if (frameCount == NULL) {
66 return BAD_VALUE;
67 }
Glenn Kasten04cd0182012-06-25 11:49:27 -070068
Andy Hung0e48d252015-01-26 11:43:15 -080069 // FIXME handle in server, like createTrack_l(), possible missing info:
Glenn Kastene0fa4672012-04-24 14:35:14 -070070 // audio_io_handle_t output
71 // audio_format_t format
72 // audio_channel_mask_t channelMask
Andy Hung0e48d252015-01-26 11:43:15 -080073 // audio_output_flags_t flags (FAST)
Glenn Kasten3b16c762012-11-14 08:44:39 -080074 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080075 status_t status;
76 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
77 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080078 ALOGE("Unable to query output sample rate for stream type %d; status %d",
79 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080080 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080081 }
Glenn Kastene33054e2012-11-14 12:54:39 -080082 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -080083 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
84 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080085 ALOGE("Unable to query output frame count for stream type %d; status %d",
86 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080087 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080088 }
89 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -080090 status = AudioSystem::getOutputLatency(&afLatency, streamType);
91 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080092 ALOGE("Unable to query output latency for stream type %d; status %d",
93 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080094 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080095 }
96
97 // Ensure that buffer depth covers at least audio hardware latency
98 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080099 if (minBufCount < 2) {
100 minBufCount = 2;
101 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800102
Andy Hung0e48d252015-01-26 11:43:15 -0800103 *frameCount = minBufCount * sourceFramesNeeded(sampleRate, afFrameCount, afSampleRate);
104 // The formula above should always produce a non-zero value under normal circumstances:
105 // AudioTrack.SAMPLE_RATE_HZ_MIN <= sampleRate <= AudioTrack.SAMPLE_RATE_HZ_MAX.
106 // Return error in the unlikely event that it does not, as that's part of the API contract.
Glenn Kasten66a04672014-01-08 08:53:44 -0800107 if (*frameCount == 0) {
Andy Hung0e48d252015-01-26 11:43:15 -0800108 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %u",
Glenn Kasten66a04672014-01-08 08:53:44 -0800109 streamType, sampleRate);
110 return BAD_VALUE;
111 }
Andy Hung0e48d252015-01-26 11:43:15 -0800112 ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, minBufCount=%u, afSampleRate=%u, afLatency=%u",
Glenn Kasten3acbd052012-02-28 10:39:56 -0800113 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800114 return NO_ERROR;
115}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800116
117// ---------------------------------------------------------------------------
118
119AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700120 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800121 mIsTimed(false),
122 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800123 mPreviousSchedulingGroup(SP_DEFAULT),
124 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800125{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700126 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
127 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
128 mAttributes.flags = 0x0;
129 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800130}
131
132AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800133 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800134 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800135 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700136 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800137 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700138 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800139 callback_t cbf,
140 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800141 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800142 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000143 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800144 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800145 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700146 pid_t pid,
147 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700148 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800149 mIsTimed(false),
150 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800151 mPreviousSchedulingGroup(SP_DEFAULT),
152 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800153{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700154 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700155 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800156 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700157 offloadInfo, uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800158}
159
Andreas Huberc8139852012-01-18 10:51:55 -0800160AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800161 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800162 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800163 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700164 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800165 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700166 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800167 callback_t cbf,
168 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800169 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800170 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000171 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800172 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800173 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700174 pid_t pid,
175 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700176 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800177 mIsTimed(false),
178 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800179 mPreviousSchedulingGroup(SP_DEFAULT),
180 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800181{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700182 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800183 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800184 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700185 uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800186}
187
188AudioTrack::~AudioTrack()
189{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800190 if (mStatus == NO_ERROR) {
191 // Make sure that callback function exits in the case where
192 // it is looping on buffer full condition in obtainBuffer().
193 // Otherwise the callback thread will never exit.
194 stop();
195 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100196 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800197 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800198 mAudioTrackThread->requestExitAndWait();
199 mAudioTrackThread.clear();
200 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800201 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700202 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700203 mCblkMemory.clear();
204 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800205 IPCThreadState::self()->flushCommands();
Marco Nelissend457c972014-02-11 08:47:07 -0800206 ALOGV("~AudioTrack, releasing session id from %d on behalf of %d",
207 IPCThreadState::self()->getCallingPid(), mClientPid);
208 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800209 }
210}
211
212status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800213 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800214 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800215 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700216 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800217 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700218 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800219 callback_t cbf,
220 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800221 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800222 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700223 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800224 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000225 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800226 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800227 int uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700228 pid_t pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700229 const audio_attributes_t* pAttributes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800230{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800231 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten838b3d82014-02-27 15:30:41 -0800232 "flags #%x, notificationFrames %u, sessionId %d, transferType %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800233 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten86f04662014-02-24 15:13:05 -0800234 sessionId, transferType);
235
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800236 switch (transferType) {
237 case TRANSFER_DEFAULT:
238 if (sharedBuffer != 0) {
239 transferType = TRANSFER_SHARED;
240 } else if (cbf == NULL || threadCanCallJava) {
241 transferType = TRANSFER_SYNC;
242 } else {
243 transferType = TRANSFER_CALLBACK;
244 }
245 break;
246 case TRANSFER_CALLBACK:
247 if (cbf == NULL || sharedBuffer != 0) {
248 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
249 return BAD_VALUE;
250 }
251 break;
252 case TRANSFER_OBTAIN:
253 case TRANSFER_SYNC:
254 if (sharedBuffer != 0) {
255 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
256 return BAD_VALUE;
257 }
258 break;
259 case TRANSFER_SHARED:
260 if (sharedBuffer == 0) {
261 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
262 return BAD_VALUE;
263 }
264 break;
265 default:
266 ALOGE("Invalid transfer type %d", transferType);
267 return BAD_VALUE;
268 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800269 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800270 mTransfer = transferType;
271
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700272 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
273 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800274
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700275 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700276
Eric Laurent1703cdf2011-03-07 14:52:59 -0800277 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800278
Glenn Kasten53cec222013-08-29 09:01:02 -0700279 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700280 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000281 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800282 return INVALID_OPERATION;
283 }
284
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800285 // handle default values first.
Eric Laurente83b55d2014-11-14 10:06:21 -0800286 if (streamType == AUDIO_STREAM_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700287 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800288 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700289 if (pAttributes == NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800290 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700291 ALOGE("Invalid stream type %d", streamType);
292 return BAD_VALUE;
293 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700294 mStreamType = streamType;
Eric Laurente83b55d2014-11-14 10:06:21 -0800295
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700296 } else {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700297 // stream type shouldn't be looked at, this track has audio attributes
298 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700299 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
300 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800301 mStreamType = AUDIO_STREAM_DEFAULT;
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800302 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700303
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800304 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800305 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700306 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800307 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800308
309 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700310 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800311 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800312 return BAD_VALUE;
313 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800314 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700315
Glenn Kasten8ba90322013-10-30 11:29:27 -0700316 if (!audio_is_output_channel(channelMask)) {
317 ALOGE("Invalid channel mask %#x", channelMask);
318 return BAD_VALUE;
319 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800320 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700321 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800322 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700323
Eric Laurentc2f1f072009-07-17 12:17:14 -0700324 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100325 // or offload was requested
326 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
327 || !audio_is_linear_pcm(format)) {
328 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
329 ? "Offload request, forcing to Direct Output"
330 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700331 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800332 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700333 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700334 }
335
Eric Laurentd1f69b02014-12-15 14:33:13 -0800336 // force direct flag if HW A/V sync requested
337 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
338 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
339 }
340
Glenn Kastenb7730382014-04-30 15:50:31 -0700341 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
342 if (audio_is_linear_pcm(format)) {
343 mFrameSize = channelCount * audio_bytes_per_sample(format);
344 } else {
345 mFrameSize = sizeof(uint8_t);
346 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800347 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700348 ALOG_ASSERT(audio_is_linear_pcm(format));
349 mFrameSize = channelCount * audio_bytes_per_sample(format);
Glenn Kastenb7730382014-04-30 15:50:31 -0700350 // createTrack will return an error if PCM format is not supported by server,
351 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800352 }
353
Eric Laurent0d6db582014-11-12 18:39:44 -0800354 // sampling rate must be specified for direct outputs
355 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
356 return BAD_VALUE;
357 }
358 mSampleRate = sampleRate;
359
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800360 // Make copy of input parameter offloadInfo so that in the future:
361 // (a) createTrack_l doesn't need it as an input parameter
362 // (b) we can support re-creation of offloaded tracks
363 if (offloadInfo != NULL) {
364 mOffloadInfoCopy = *offloadInfo;
365 mOffloadInfo = &mOffloadInfoCopy;
366 } else {
367 mOffloadInfo = NULL;
368 }
369
Glenn Kasten66e46352014-01-16 17:44:23 -0800370 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
371 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800372 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800373 // mFrameCount is initialized in createTrack_l
Glenn Kastenb603744e2012-11-14 13:42:25 -0800374 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700375 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800376 mNotificationFramesAct = 0;
Eric Laurentcaf7f482014-11-25 17:50:47 -0800377 if (sessionId == AUDIO_SESSION_ALLOCATE) {
378 mSessionId = AudioSystem::newAudioUniqueId();
379 } else {
380 mSessionId = sessionId;
381 }
Marco Nelissend457c972014-02-11 08:47:07 -0800382 int callingpid = IPCThreadState::self()->getCallingPid();
383 int mypid = getpid();
384 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800385 mClientUid = IPCThreadState::self()->getCallingUid();
386 } else {
387 mClientUid = uid;
388 }
Marco Nelissend457c972014-02-11 08:47:07 -0800389 if (pid == -1 || (callingpid != mypid)) {
390 mClientPid = callingpid;
391 } else {
392 mClientPid = pid;
393 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700394 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700395 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700396 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700397
Glenn Kastena997e7a2012-08-07 09:44:19 -0700398 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700399 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700400 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
401 }
402
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800403 // create the IAudioTrack
Eric Laurent0d6db582014-11-12 18:39:44 -0800404 status_t status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800405
Glenn Kastena997e7a2012-08-07 09:44:19 -0700406 if (status != NO_ERROR) {
407 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100408 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
409 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700410 mAudioTrackThread.clear();
411 }
412 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700413 }
414
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800415 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800416 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800417 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800418 mLoopCount = 0;
419 mLoopStart = 0;
420 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800421 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800422 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700423 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800424 mNewPosition = 0;
425 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700426 mServer = 0;
427 mPosition = 0;
428 mReleased = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700429 mStartUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800430 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800431 mSequence = 1;
432 mObservedSequence = mSequence;
433 mInUnderrun = false;
434
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800435 return NO_ERROR;
436}
437
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800438// -------------------------------------------------------------------------
439
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100440status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800441{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800442 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100443
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800444 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100445 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800446 }
447
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800448 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800449
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800450 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100451 if (previousState == STATE_PAUSED_STOPPING) {
452 mState = STATE_STOPPING;
453 } else {
454 mState = STATE_ACTIVE;
455 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700456 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800457 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
458 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700459 mPosition = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700460 // For offloaded tracks, we don't know if the hardware counters are really zero here,
461 // since the flush is asynchronous and stop may not fully drain.
462 // We save the time when the track is started to later verify whether
463 // the counters are realistic (i.e. start from zero after this time).
464 mStartUs = getNowUs();
465
Eric Laurentec9a0322013-08-28 10:23:01 -0700466 // force refresh of remaining frames by processAudioBuffer() as last
467 // write before stop could be partial.
468 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800469 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700470 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700471 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800472
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800473 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800474 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100475 if (previousState == STATE_STOPPING) {
476 mProxy->interrupt();
477 } else {
478 t->resume();
479 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800480 } else {
481 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
482 get_sched_policy(0, &mPreviousSchedulingGroup);
483 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
484 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800485
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800486 status_t status = NO_ERROR;
487 if (!(flags & CBLK_INVALID)) {
488 status = mAudioTrack->start();
489 if (status == DEAD_OBJECT) {
490 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800491 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800492 }
493 if (flags & CBLK_INVALID) {
494 status = restoreTrack_l("start");
495 }
496
497 if (status != NO_ERROR) {
498 ALOGE("start() status %d", status);
499 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800500 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100501 if (previousState != STATE_STOPPING) {
502 t->pause();
503 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800504 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700505 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700506 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800507 }
508 }
509
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100510 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800511}
512
513void AudioTrack::stop()
514{
515 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700516 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800517 return;
518 }
519
Glenn Kasten23a75452014-01-13 10:37:17 -0800520 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100521 mState = STATE_STOPPING;
522 } else {
523 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -0700524 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100525 }
526
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800527 mProxy->interrupt();
528 mAudioTrack->stop();
529 // the playback head position will reset to 0, so if a marker is set, we need
530 // to activate it again
531 mMarkerReached = false;
Andy Hung9b461582014-12-01 17:56:29 -0800532
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800533 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800534 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800535 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
536 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800537 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100538
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800539 sp<AudioTrackThread> t = mAudioTrackThread;
540 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800541 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100542 t->pause();
543 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800544 } else {
545 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
546 set_sched_policy(0, mPreviousSchedulingGroup);
547 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800548}
549
550bool AudioTrack::stopped() const
551{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800552 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800553 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800554}
555
556void AudioTrack::flush()
557{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800558 if (mSharedBuffer != 0) {
559 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800560 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800561 AutoMutex lock(mLock);
562 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
563 return;
564 }
565 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800566}
567
Eric Laurent1703cdf2011-03-07 14:52:59 -0800568void AudioTrack::flush_l()
569{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800570 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700571
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700572 // clear playback marker and periodic update counter
573 mMarkerPosition = 0;
574 mMarkerReached = false;
575 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100576 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700577
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800578 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700579 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800580 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100581 mProxy->interrupt();
582 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800583 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800584 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800585}
586
587void AudioTrack::pause()
588{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800589 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100590 if (mState == STATE_ACTIVE) {
591 mState = STATE_PAUSED;
592 } else if (mState == STATE_STOPPING) {
593 mState = STATE_PAUSED_STOPPING;
594 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800595 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800596 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800597 mProxy->interrupt();
598 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800599
Marco Nelissen3a90f282014-03-10 11:21:43 -0700600 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700601 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700602 // An offload output can be re-used between two audio tracks having
603 // the same configuration. A timestamp query for a paused track
604 // while the other is running would return an incorrect time.
605 // To fix this, cache the playback position on a pause() and return
606 // this time when requested until the track is resumed.
607
608 // OffloadThread sends HAL pause in its threadLoop. Time saved
609 // here can be slightly off.
610
611 // TODO: check return code for getRenderPosition.
612
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800613 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800614 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
615 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
616 }
617 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800618}
619
Eric Laurentbe916aa2010-06-01 23:49:17 -0700620status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800621{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700622 // This duplicates a test by AudioTrack JNI, but that is not the only caller
623 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
624 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700625 return BAD_VALUE;
626 }
627
Eric Laurent1703cdf2011-03-07 14:52:59 -0800628 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800629 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
630 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800631
Glenn Kastenc56f3422014-03-21 17:53:17 -0700632 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700633
Glenn Kasten23a75452014-01-13 10:37:17 -0800634 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700635 mAudioTrack->signal();
636 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700637 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800638}
639
Glenn Kastenb1c09932012-02-27 16:21:04 -0800640status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800641{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800642 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700643}
644
Eric Laurent2beeb502010-07-16 07:43:46 -0700645status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700646{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700647 // This duplicates a test by AudioTrack JNI, but that is not the only caller
648 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700649 return BAD_VALUE;
650 }
651
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800652 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700653 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800654 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700655
656 return NO_ERROR;
657}
658
Glenn Kastena5224f32012-01-04 12:41:44 -0800659void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700660{
661 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800662 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700663 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800664}
665
Glenn Kasten3b16c762012-11-14 08:44:39 -0800666status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800667{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700668 if (mIsTimed || isOffloadedOrDirect()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800669 return INVALID_OPERATION;
670 }
671
Eric Laurent0d6db582014-11-12 18:39:44 -0800672 AutoMutex lock(mLock);
673 if (mOutput == AUDIO_IO_HANDLE_NONE) {
674 return NO_INIT;
675 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800676 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800677 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700678 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800679 }
Andy Hungcd044842014-08-07 11:04:34 -0700680 if (rate == 0 || rate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700681 return BAD_VALUE;
682 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800683
Glenn Kastene3aa6592012-12-04 12:22:46 -0800684 mSampleRate = rate;
685 mProxy->setSampleRate(rate);
686
Eric Laurent57326622009-07-07 07:10:45 -0700687 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800688}
689
Glenn Kastena5224f32012-01-04 12:41:44 -0800690uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800691{
John Grossman4ff14ba2012-02-08 16:37:41 -0800692 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800693 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800694 }
695
Eric Laurent1703cdf2011-03-07 14:52:59 -0800696 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700697
698 // sample rate can be updated during playback by the offloaded decoder so we need to
699 // query the HAL and update if needed.
700// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700701 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700702 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700703 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700704 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700705 if (status == NO_ERROR) {
706 mSampleRate = sampleRate;
707 }
708 }
709 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800710 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800711}
712
713status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
714{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700715 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800716 return INVALID_OPERATION;
717 }
718
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800719 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800720 ;
721 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
722 loopEnd - loopStart >= MIN_LOOP) {
723 ;
724 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800725 return BAD_VALUE;
726 }
727
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800728 AutoMutex lock(mLock);
729 // See setPosition() regarding setting parameters such as loop points or position while active
730 if (mState == STATE_ACTIVE) {
731 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700732 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800733 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800734 return NO_ERROR;
735}
736
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800737void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
738{
Andy Hung4ede21d2014-12-12 15:37:34 -0800739 // We do not update the periodic notification point.
740 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
741 mLoopCount = loopCount;
742 mLoopEnd = loopEnd;
743 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800744 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800745 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -0800746
747 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800748}
749
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800750status_t AudioTrack::setMarkerPosition(uint32_t marker)
751{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700752 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700753 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700754 return INVALID_OPERATION;
755 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800756
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800757 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800758 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700759 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800760
Andy Hung3c09c782014-12-29 18:39:32 -0800761 sp<AudioTrackThread> t = mAudioTrackThread;
762 if (t != 0) {
763 t->wake();
764 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800765 return NO_ERROR;
766}
767
Glenn Kastena5224f32012-01-04 12:41:44 -0800768status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800769{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700770 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100771 return INVALID_OPERATION;
772 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700773 if (marker == NULL) {
774 return BAD_VALUE;
775 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800776
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800777 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800778 *marker = mMarkerPosition;
779
780 return NO_ERROR;
781}
782
783status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
784{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700785 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700786 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700787 return INVALID_OPERATION;
788 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800789
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800790 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700791 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800792 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800793
Andy Hung3c09c782014-12-29 18:39:32 -0800794 sp<AudioTrackThread> t = mAudioTrackThread;
795 if (t != 0) {
796 t->wake();
797 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800798 return NO_ERROR;
799}
800
Glenn Kastena5224f32012-01-04 12:41:44 -0800801status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800802{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700803 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100804 return INVALID_OPERATION;
805 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700806 if (updatePeriod == NULL) {
807 return BAD_VALUE;
808 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800809
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800810 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800811 *updatePeriod = mUpdatePeriod;
812
813 return NO_ERROR;
814}
815
816status_t AudioTrack::setPosition(uint32_t position)
817{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700818 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700819 return INVALID_OPERATION;
820 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800821 if (position > mFrameCount) {
822 return BAD_VALUE;
823 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800824
Eric Laurent1703cdf2011-03-07 14:52:59 -0800825 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800826 // Currently we require that the player is inactive before setting parameters such as position
827 // or loop points. Otherwise, there could be a race condition: the application could read the
828 // current position, compute a new position or loop parameters, and then set that position or
829 // loop parameters but it would do the "wrong" thing since the position has continued to advance
830 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
831 // to specify how it wants to handle such scenarios.
832 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700833 return INVALID_OPERATION;
834 }
Andy Hung9b461582014-12-01 17:56:29 -0800835 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -0700836 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800837 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -0800838
839 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800840 return NO_ERROR;
841}
842
Glenn Kasten200092b2014-08-15 15:13:30 -0700843status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800844{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700845 if (position == NULL) {
846 return BAD_VALUE;
847 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800848
Eric Laurent1703cdf2011-03-07 14:52:59 -0800849 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700850 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100851 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800852
Eric Laurentab5cdba2014-06-09 17:22:27 -0700853 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800854 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
855 *position = mPausedPosition;
856 return NO_ERROR;
857 }
858
Glenn Kasten142f5192014-03-25 17:44:59 -0700859 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100860 uint32_t halFrames;
861 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
862 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700863 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
864 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100865 *position = dspFrames;
866 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -0800867 if (mCblk->mFlags & CBLK_INVALID) {
868 restoreTrack_l("getPosition");
869 }
870
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100871 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700872 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
873 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100874 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800875 return NO_ERROR;
876}
877
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000878status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800879{
880 if (mSharedBuffer == 0 || mIsTimed) {
881 return INVALID_OPERATION;
882 }
883 if (position == NULL) {
884 return BAD_VALUE;
885 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800886
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800887 AutoMutex lock(mLock);
888 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800889 return NO_ERROR;
890}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800891
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800892status_t AudioTrack::reload()
893{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700894 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800895 return INVALID_OPERATION;
896 }
897
Eric Laurent1703cdf2011-03-07 14:52:59 -0800898 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800899 // See setPosition() regarding setting parameters such as loop points or position while active
900 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700901 return INVALID_OPERATION;
902 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800903 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800904 (void) updateAndGetPosition_l();
905 mPosition = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800906#if 0
Andy Hung9b461582014-12-01 17:56:29 -0800907 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -0800908 // of loop count. Historically we have not restored loop count, start, end,
909 // but it makes sense if one desires to repeat playing a particular sound.
910 if (mLoopCount != 0) {
911 mLoopCountNotified = mLoopCount;
912 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
913 }
914#endif
Andy Hung9b461582014-12-01 17:56:29 -0800915 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800916 return NO_ERROR;
917}
918
Glenn Kasten38e905b2014-01-13 10:21:48 -0800919audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700920{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800921 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100922 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800923}
924
Eric Laurentbe916aa2010-06-01 23:49:17 -0700925status_t AudioTrack::attachAuxEffect(int effectId)
926{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800927 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700928 status_t status = mAudioTrack->attachAuxEffect(effectId);
929 if (status == NO_ERROR) {
930 mAuxEffectId = effectId;
931 }
932 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700933}
934
Eric Laurente83b55d2014-11-14 10:06:21 -0800935audio_stream_type_t AudioTrack::streamType() const
936{
937 if (mStreamType == AUDIO_STREAM_DEFAULT) {
938 return audio_attributes_to_stream_type(&mAttributes);
939 }
940 return mStreamType;
941}
942
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800943// -------------------------------------------------------------------------
944
Eric Laurent1703cdf2011-03-07 14:52:59 -0800945// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -0700946status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800947{
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800948 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
949 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700950 ALOGE("Could not get audioflinger");
951 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800952 }
953
Eric Laurente83b55d2014-11-14 10:06:21 -0800954 audio_io_handle_t output;
955 audio_stream_type_t streamType = mStreamType;
956 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
957 status_t status = AudioSystem::getOutputForAttr(attr, &output,
958 (audio_session_t)mSessionId, &streamType,
959 mSampleRate, mFormat, mChannelMask,
960 mFlags, mOffloadInfo);
961
962
963 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700964 ALOGE("Could not get audio output for stream type %d, usage %d, sample rate %u, format %#x,"
965 " channel mask %#x, flags %#x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800966 streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800967 return BAD_VALUE;
968 }
969 {
970 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
971 // we must release it ourselves if anything goes wrong.
972
Glenn Kastence8828a2013-09-16 18:07:38 -0700973 // Not all of these values are needed under all conditions, but it is easier to get them all
974
Eric Laurentd1b449a2010-05-14 03:26:45 -0700975 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -0700976 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700977 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800978 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800979 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700980 }
981
Glenn Kastence8828a2013-09-16 18:07:38 -0700982 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700983 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -0700984 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700985 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800986 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700987 }
988
989 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700990 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -0700991 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700992 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800993 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700994 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800995 if (mSampleRate == 0) {
996 mSampleRate = afSampleRate;
997 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700998 // Client decides whether the track is TIMED (see below), but can only express a preference
999 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001000 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001001 // either of these use cases:
1002 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -08001003 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001004 // use case 2: callback transfer mode
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001005 (mTransfer == TRANSFER_CALLBACK) ||
1006 // use case 3: obtain/release mode
1007 (mTransfer == TRANSFER_OBTAIN)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001008 // matching sample rate
1009 (mSampleRate == afSampleRate))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08001010 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -07001011 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001012 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001013 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001014 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001015
Glenn Kastence8828a2013-09-16 18:07:38 -07001016 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -08001017 // n = 1 fast track with single buffering; nBuffering is ignored
1018 // n = 2 fast track with double buffering
Andy Hung0e48d252015-01-26 11:43:15 -08001019 // n = 2 normal track, (including those with sample rate conversion)
1020 // n >= 3 very high latency or very small notification interval (unused).
1021 const uint32_t nBuffering = 2;
Glenn Kastence8828a2013-09-16 18:07:38 -07001022
Eric Laurentd1b449a2010-05-14 03:26:45 -07001023 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001024
Glenn Kasten363fb752014-01-15 12:27:31 -08001025 size_t frameCount = mReqFrameCount;
1026 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001027
Glenn Kasten363fb752014-01-15 12:27:31 -08001028 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001029 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001030 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001031 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001032 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001033 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001034 if (mNotificationFramesAct != frameCount) {
1035 mNotificationFramesAct = frameCount;
1036 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001037 } else if (mSharedBuffer != 0) {
Andy Hungabdb9902015-01-12 15:08:22 -08001038 // FIXME: Ensure client side memory buffers need
1039 // not have additional alignment beyond sample
1040 // (e.g. 16 bit stereo accessed as 32 bit frame).
1041 size_t alignment = audio_bytes_per_sample(mFormat);
Glenn Kastenb7730382014-04-30 15:50:31 -07001042 if (alignment & 1) {
Andy Hungabdb9902015-01-12 15:08:22 -08001043 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
Glenn Kastenb7730382014-04-30 15:50:31 -07001044 alignment = 1;
1045 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001046 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001047 // More than 2 channels does not require stronger alignment than stereo
1048 alignment <<= 1;
1049 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001050 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001051 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001052 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001053 status = BAD_VALUE;
1054 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001055 }
1056
1057 // When initializing a shared buffer AudioTrack via constructors,
1058 // there's no frameCount parameter.
1059 // But when initializing a shared buffer AudioTrack via set(),
1060 // there _is_ a frameCount parameter. We silently ignore it.
Andy Hungabdb9902015-01-12 15:08:22 -08001061 frameCount = mSharedBuffer->size() / mFrameSize;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001062 } else {
Andy Hung0e48d252015-01-26 11:43:15 -08001063 // For fast and normal streaming tracks,
1064 // the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -07001065 }
1066
Glenn Kastena075db42012-03-06 11:22:44 -08001067 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1068 if (mIsTimed) {
1069 trackFlags |= IAudioFlinger::TRACK_TIMED;
1070 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001071
1072 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001073 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001074 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001075 if (mAudioTrackThread != 0) {
1076 tid = mAudioTrackThread->getTid();
1077 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001078 }
1079
Glenn Kasten363fb752014-01-15 12:27:31 -08001080 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001081 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1082 }
1083
Eric Laurentab5cdba2014-06-09 17:22:27 -07001084 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1085 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1086 }
1087
Glenn Kasten74935e42013-12-19 08:56:45 -08001088 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1089 // but we will still need the original value also
Eric Laurente83b55d2014-11-14 10:06:21 -08001090 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001091 mSampleRate,
Andy Hungabdb9902015-01-12 15:08:22 -08001092 mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001093 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001094 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001095 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001096 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001097 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001098 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001099 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001100 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001101 &status);
1102
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001103 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001104 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001105 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001106 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001107 ALOG_ASSERT(track != 0);
1108
Glenn Kasten38e905b2014-01-13 10:21:48 -08001109 // AudioFlinger now owns the reference to the I/O handle,
1110 // so we are no longer responsible for releasing it.
1111
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001112 sp<IMemory> iMem = track->getCblk();
1113 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001114 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001115 return NO_INIT;
1116 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001117 void *iMemPointer = iMem->pointer();
1118 if (iMemPointer == NULL) {
1119 ALOGE("Could not get control block pointer");
1120 return NO_INIT;
1121 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001122 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001123 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001124 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001125 mDeathNotifier.clear();
1126 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001127 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001128 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001129 IPCThreadState::self()->flushCommands();
1130
Glenn Kasten0cde0762014-01-16 15:06:36 -08001131 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001132 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001133 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb603744e2012-11-14 13:42:25 -08001134 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1135 // In current design, AudioTrack client checks and ensures frame count validity before
1136 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1137 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001138 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb603744e2012-11-14 13:42:25 -08001139 }
1140 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001141
Glenn Kastena07f17c2013-04-23 12:39:37 -07001142 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001143 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001144 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001145 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001146 mAwaitBoost = true;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001147 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001148 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001149 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001150 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001151 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001152 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001153 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001154 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1155 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1156 } else {
1157 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001158 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001159 // FIXME This is a warning, not an error, so don't return error status
1160 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001161 }
1162 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001163 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1164 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1165 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1166 } else {
1167 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1168 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1169 // FIXME This is a warning, not an error, so don't return error status
1170 //return NO_INIT;
1171 }
1172 }
Andy Hung0e48d252015-01-26 11:43:15 -08001173 // Make sure that application is notified with sufficient margin before underrun
1174 if (mSharedBuffer == 0 && audio_is_linear_pcm(mFormat)) {
1175 // Theoretically double-buffering is not required for fast tracks,
1176 // due to tighter scheduling. But in practice, to accommodate kernels with
1177 // scheduling jitter, and apps with computation jitter, we use double-buffering
1178 // for fast tracks just like normal streaming tracks.
1179 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount / nBuffering) {
1180 mNotificationFramesAct = frameCount / nBuffering;
1181 }
1182 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001183
Glenn Kasten38e905b2014-01-13 10:21:48 -08001184 // We retain a copy of the I/O handle, but don't own the reference
1185 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001186 mRefreshRemaining = true;
1187
1188 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1189 // is the value of pointer() for the shared buffer, otherwise buffers points
1190 // immediately after the control block. This address is for the mapping within client
1191 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1192 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001193 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001194 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001195 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001196 buffers = mSharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001197 }
1198
Eric Laurent2beeb502010-07-16 07:43:46 -07001199 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001200 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001201 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001202
Glenn Kastenb603744e2012-11-14 13:42:25 -08001203 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001204 // If IAudioTrack is re-created, don't let the requested frameCount
1205 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb603744e2012-11-14 13:42:25 -08001206 if (frameCount > mReqFrameCount) {
1207 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001208 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001209
1210 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001211 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001212 mStaticProxy.clear();
Andy Hungabdb9902015-01-12 15:08:22 -08001213 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001214 } else {
Andy Hungabdb9902015-01-12 15:08:22 -08001215 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001216 mProxy = mStaticProxy;
1217 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001218
1219 mProxy->setVolumeLR(gain_minifloat_pack(
1220 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1221 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1222
Glenn Kastene3aa6592012-12-04 12:22:46 -08001223 mProxy->setSendLevel(mSendLevel);
1224 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001225 mProxy->setMinimum(mNotificationFramesAct);
1226
1227 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001228 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001229
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001230 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001231 }
1232
1233release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001234 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001235 if (status == NO_ERROR) {
1236 status = NO_INIT;
1237 }
1238 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001239}
1240
Glenn Kastenb46f3942015-03-09 12:00:30 -07001241status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001242{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001243 if (audioBuffer == NULL) {
1244 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001245 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001246 if (mTransfer != TRANSFER_OBTAIN) {
1247 audioBuffer->frameCount = 0;
1248 audioBuffer->size = 0;
1249 audioBuffer->raw = NULL;
1250 return INVALID_OPERATION;
1251 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001252
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001253 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001254 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001255 if (waitCount == -1) {
1256 requested = &ClientProxy::kForever;
1257 } else if (waitCount == 0) {
1258 requested = &ClientProxy::kNonBlocking;
1259 } else if (waitCount > 0) {
1260 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001261 timeout.tv_sec = ms / 1000;
1262 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1263 requested = &timeout;
1264 } else {
1265 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1266 requested = NULL;
1267 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001268 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001269}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001270
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001271status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1272 struct timespec *elapsed, size_t *nonContig)
1273{
1274 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1275 uint32_t oldSequence = 0;
1276 uint32_t newSequence;
1277
1278 Proxy::Buffer buffer;
1279 status_t status = NO_ERROR;
1280
1281 static const int32_t kMaxTries = 5;
1282 int32_t tryCounter = kMaxTries;
1283
1284 do {
1285 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1286 // keep them from going away if another thread re-creates the track during obtainBuffer()
1287 sp<AudioTrackClientProxy> proxy;
1288 sp<IMemory> iMem;
1289
1290 { // start of lock scope
1291 AutoMutex lock(mLock);
1292
1293 newSequence = mSequence;
1294 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1295 if (status == DEAD_OBJECT) {
1296 // re-create track, unless someone else has already done so
1297 if (newSequence == oldSequence) {
1298 status = restoreTrack_l("obtainBuffer");
1299 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001300 buffer.mFrameCount = 0;
1301 buffer.mRaw = NULL;
1302 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001303 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001304 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001305 }
1306 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001307 oldSequence = newSequence;
1308
1309 // Keep the extra references
1310 proxy = mProxy;
1311 iMem = mCblkMemory;
1312
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001313 if (mState == STATE_STOPPING) {
1314 status = -EINTR;
1315 buffer.mFrameCount = 0;
1316 buffer.mRaw = NULL;
1317 buffer.mNonContig = 0;
1318 break;
1319 }
1320
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001321 // Non-blocking if track is stopped or paused
1322 if (mState != STATE_ACTIVE) {
1323 requested = &ClientProxy::kNonBlocking;
1324 }
1325
1326 } // end of lock scope
1327
1328 buffer.mFrameCount = audioBuffer->frameCount;
1329 // FIXME starts the requested timeout and elapsed over from scratch
1330 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1331
1332 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1333
1334 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001335 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001336 audioBuffer->raw = buffer.mRaw;
1337 if (nonContig != NULL) {
1338 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001339 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001340 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001341}
1342
Glenn Kasten54a8a452015-03-09 12:03:00 -07001343void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001344{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001345 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001346 if (mTransfer == TRANSFER_SHARED) {
1347 return;
1348 }
1349
Andy Hungabdb9902015-01-12 15:08:22 -08001350 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001351 if (stepCount == 0) {
1352 return;
1353 }
1354
1355 Proxy::Buffer buffer;
1356 buffer.mFrameCount = stepCount;
1357 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001358
Eric Laurent1703cdf2011-03-07 14:52:59 -08001359 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001360 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001361 mInUnderrun = false;
1362 mProxy->releaseBuffer(&buffer);
1363
1364 // restart track if it was disabled by audioflinger due to previous underrun
1365 if (mState == STATE_ACTIVE) {
1366 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001367 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001368 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001369 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001370 mAudioTrack->start();
1371 }
1372 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001373}
1374
1375// -------------------------------------------------------------------------
1376
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001377ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001378{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001379 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001380 return INVALID_OPERATION;
1381 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001382
Eric Laurentab5cdba2014-06-09 17:22:27 -07001383 if (isDirect()) {
1384 AutoMutex lock(mLock);
1385 int32_t flags = android_atomic_and(
1386 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1387 &mCblk->mFlags);
1388 if (flags & CBLK_INVALID) {
1389 return DEAD_OBJECT;
1390 }
1391 }
1392
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001393 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001394 // Sanity-check: user is most-likely passing an error code, and it would
1395 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001396 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001397 return BAD_VALUE;
1398 }
1399
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001400 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001401 Buffer audioBuffer;
1402
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001403 while (userSize >= mFrameSize) {
1404 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001405
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001406 status_t err = obtainBuffer(&audioBuffer,
1407 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001408 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001409 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001410 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001411 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001412 return ssize_t(err);
1413 }
1414
1415 size_t toWrite;
Andy Hungabdb9902015-01-12 15:08:22 -08001416 toWrite = audioBuffer.size;
1417 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001418 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001419 userSize -= toWrite;
1420 written += toWrite;
1421
1422 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001423 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001424
1425 return written;
1426}
1427
1428// -------------------------------------------------------------------------
1429
John Grossman4ff14ba2012-02-08 16:37:41 -08001430TimedAudioTrack::TimedAudioTrack() {
1431 mIsTimed = true;
1432}
1433
1434status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1435{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001436 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001437 status_t result = UNKNOWN_ERROR;
1438
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001439#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001440 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1441 // while we are accessing the cblk
1442 sp<IAudioTrack> audioTrack = mAudioTrack;
1443 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001444#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001445
John Grossman4ff14ba2012-02-08 16:37:41 -08001446 // If the track is not invalid already, try to allocate a buffer. alloc
1447 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001448 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001449 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001450 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001451 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1452 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001453 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001454 }
1455 }
1456
1457 // If the track is invalid at this point, attempt to restore it. and try the
1458 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001459 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001460 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001461
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001462 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001463 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001464 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001465 }
1466
1467 return result;
1468}
1469
1470status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1471 int64_t pts)
1472{
Eric Laurentdf839842012-05-31 14:27:14 -07001473 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1474 {
1475 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001476 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001477 // restart track if it was disabled by audioflinger due to previous underrun
1478 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001479 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1480 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001481 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001482 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001483 mAudioTrack->start();
1484 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001485 }
Eric Laurentdf839842012-05-31 14:27:14 -07001486 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001487}
1488
1489status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1490 TargetTimeline target)
1491{
1492 return mAudioTrack->setMediaTimeTransform(xform, target);
1493}
1494
1495// -------------------------------------------------------------------------
1496
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001497nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001498{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001499 // Currently the AudioTrack thread is not created if there are no callbacks.
1500 // Would it ever make sense to run the thread, even without callbacks?
1501 // If so, then replace this by checks at each use for mCbf != NULL.
1502 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1503
Eric Laurent1703cdf2011-03-07 14:52:59 -08001504 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001505 if (mAwaitBoost) {
1506 mAwaitBoost = false;
1507 mLock.unlock();
1508 static const int32_t kMaxTries = 5;
1509 int32_t tryCounter = kMaxTries;
1510 uint32_t pollUs = 10000;
1511 do {
1512 int policy = sched_getscheduler(0);
1513 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1514 break;
1515 }
1516 usleep(pollUs);
1517 pollUs <<= 1;
1518 } while (tryCounter-- > 0);
1519 if (tryCounter < 0) {
1520 ALOGE("did not receive expected priority boost on time");
1521 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001522 // Run again immediately
1523 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001524 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001525
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001526 // Can only reference mCblk while locked
1527 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001528 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001529
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001530 // Check for track invalidation
1531 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001532 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1533 // AudioSystem cache. We should not exit here but after calling the callback so
1534 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001535 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001536 status_t status = restoreTrack_l("processAudioBuffer");
Andy Hung53c3b5f2014-12-15 16:42:05 -08001537 // after restoration, continue below to make sure that the loop and buffer events
1538 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001539 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001540 }
1541
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001542 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001543 bool active = mState == STATE_ACTIVE;
1544
1545 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1546 bool newUnderrun = false;
1547 if (flags & CBLK_UNDERRUN) {
1548#if 0
1549 // Currently in shared buffer mode, when the server reaches the end of buffer,
1550 // the track stays active in continuous underrun state. It's up to the application
1551 // to pause or stop the track, or set the position to a new offset within buffer.
1552 // This was some experimental code to auto-pause on underrun. Keeping it here
1553 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1554 if (mTransfer == TRANSFER_SHARED) {
1555 mState = STATE_PAUSED;
1556 active = false;
1557 }
1558#endif
1559 if (!mInUnderrun) {
1560 mInUnderrun = true;
1561 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001562 }
1563 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001564
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001565 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001566 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001567
1568 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001569 bool markerReached = false;
1570 size_t markerPosition = mMarkerPosition;
1571 // FIXME fails for wraparound, need 64 bits
1572 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1573 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001574 }
1575
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001576 // Determine number of new position callback(s) that will be needed, while locked
1577 size_t newPosCount = 0;
1578 size_t newPosition = mNewPosition;
1579 size_t updatePeriod = mUpdatePeriod;
1580 // FIXME fails for wraparound, need 64 bits
1581 if (updatePeriod > 0 && position >= newPosition) {
1582 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1583 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001584 }
1585
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001586 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001587 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001588 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001589 if (mRefreshRemaining) {
1590 mRefreshRemaining = false;
1591 mRemainingFrames = notificationFrames;
1592 mRetryOnPartialBuffer = false;
1593 }
1594 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001595 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001596 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001597
Andy Hung53c3b5f2014-12-15 16:42:05 -08001598 // Determine the number of new loop callback(s) that will be needed, while locked.
1599 int loopCountNotifications = 0;
1600 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1601
1602 if (mLoopCount > 0) {
1603 int loopCount;
1604 size_t bufferPosition;
1605 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1606 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1607 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1608 mLoopCountNotified = loopCount; // discard any excess notifications
1609 } else if (mLoopCount < 0) {
1610 // FIXME: We're not accurate with notification count and position with infinite looping
1611 // since loopCount from server side will always return -1 (we could decrement it).
1612 size_t bufferPosition = mStaticProxy->getBufferPosition();
1613 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1614 loopPeriod = mLoopEnd - bufferPosition;
1615 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1616 size_t bufferPosition = mStaticProxy->getBufferPosition();
1617 loopPeriod = mFrameCount - bufferPosition;
1618 }
1619
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001620 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08001621 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001622 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1623
1624 mLock.unlock();
1625
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001626 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001627 struct timespec timeout;
1628 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1629 timeout.tv_nsec = 0;
1630
Glenn Kasten96f04882013-09-20 09:28:56 -07001631 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001632 switch (status) {
1633 case NO_ERROR:
1634 case DEAD_OBJECT:
1635 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001636 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001637 {
1638 AutoMutex lock(mLock);
1639 // The previously assigned value of waitStreamEnd is no longer valid,
1640 // since the mutex has been unlocked and either the callback handler
1641 // or another thread could have re-started the AudioTrack during that time.
1642 waitStreamEnd = mState == STATE_STOPPING;
1643 if (waitStreamEnd) {
1644 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001645 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001646 }
1647 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001648 if (waitStreamEnd && status != DEAD_OBJECT) {
1649 return NS_INACTIVE;
1650 }
1651 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001652 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001653 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001654 }
1655
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001656 // perform callbacks while unlocked
1657 if (newUnderrun) {
1658 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1659 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001660 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001661 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001662 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001663 }
1664 if (flags & CBLK_BUFFER_END) {
1665 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1666 }
1667 if (markerReached) {
1668 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1669 }
1670 while (newPosCount > 0) {
1671 size_t temp = newPosition;
1672 mCbf(EVENT_NEW_POS, mUserData, &temp);
1673 newPosition += updatePeriod;
1674 newPosCount--;
1675 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001676
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001677 if (mObservedSequence != sequence) {
1678 mObservedSequence = sequence;
1679 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001680 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001681 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001682 return NS_INACTIVE;
1683 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001684 }
1685
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001686 // if inactive, then don't run me again until re-started
1687 if (!active) {
1688 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001689 }
1690
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001691 // Compute the estimated time until the next timed event (position, markers, loops)
1692 // FIXME only for non-compressed audio
1693 uint32_t minFrames = ~0;
1694 if (!markerReached && position < markerPosition) {
1695 minFrames = markerPosition - position;
1696 }
1697 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08001698 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001699 minFrames = loopPeriod;
1700 }
Andy Hung2d85f092015-01-07 12:45:13 -08001701 if (updatePeriod > 0) {
1702 minFrames = min(minFrames, uint32_t(newPosition - position));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001703 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001704
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001705 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1706 static const uint32_t kPoll = 0;
1707 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1708 minFrames = kPoll * notificationFrames;
1709 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001710
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001711 // Convert frame units to time units
1712 nsecs_t ns = NS_WHENEVER;
1713 if (minFrames != (uint32_t) ~0) {
1714 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1715 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1716 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1717 }
1718
1719 // If not supplying data by EVENT_MORE_DATA, then we're done
1720 if (mTransfer != TRANSFER_CALLBACK) {
1721 return ns;
1722 }
1723
1724 struct timespec timeout;
1725 const struct timespec *requested = &ClientProxy::kForever;
1726 if (ns != NS_WHENEVER) {
1727 timeout.tv_sec = ns / 1000000000LL;
1728 timeout.tv_nsec = ns % 1000000000LL;
1729 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1730 requested = &timeout;
1731 }
1732
1733 while (mRemainingFrames > 0) {
1734
1735 Buffer audioBuffer;
1736 audioBuffer.frameCount = mRemainingFrames;
1737 size_t nonContig;
1738 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1739 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001740 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001741 requested = &ClientProxy::kNonBlocking;
1742 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001743 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001744 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001745 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001746 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1747 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001748 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001749 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001750 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1751 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001752 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001753
Eric Laurent42a6f422013-08-29 14:35:05 -07001754 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001755 mRetryOnPartialBuffer = false;
1756 if (avail < mRemainingFrames) {
1757 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1758 if (ns < 0 || myns < ns) {
1759 ns = myns;
1760 }
1761 return ns;
1762 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001763 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001764
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001765 size_t reqSize = audioBuffer.size;
1766 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001767 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001768
1769 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001770 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001771 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1772 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001773 return NS_NEVER;
1774 }
1775
1776 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001777 // The callback is done filling buffers
1778 // Keep this thread going to handle timed events and
1779 // still try to get more data in intervals of WAIT_PERIOD_MS
1780 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001781 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001782 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001783
Andy Hungabdb9902015-01-12 15:08:22 -08001784 size_t releasedFrames = audioBuffer.size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001785 audioBuffer.frameCount = releasedFrames;
1786 mRemainingFrames -= releasedFrames;
1787 if (misalignment >= releasedFrames) {
1788 misalignment -= releasedFrames;
1789 } else {
1790 misalignment = 0;
1791 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001792
1793 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001794
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001795 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1796 // if callback doesn't like to accept the full chunk
1797 if (writtenSize < reqSize) {
1798 continue;
1799 }
1800
1801 // There could be enough non-contiguous frames available to satisfy the remaining request
1802 if (mRemainingFrames <= nonContig) {
1803 continue;
1804 }
1805
1806#if 0
1807 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1808 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1809 // that total to a sum == notificationFrames.
1810 if (0 < misalignment && misalignment <= mRemainingFrames) {
1811 mRemainingFrames = misalignment;
1812 return (mRemainingFrames * 1100000000LL) / sampleRate;
1813 }
1814#endif
1815
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001816 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001817 mRemainingFrames = notificationFrames;
1818 mRetryOnPartialBuffer = true;
1819
1820 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1821 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001822}
1823
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001824status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001825{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001826 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001827 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001828 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001829 status_t result;
1830
Glenn Kastena47f3162012-11-07 10:13:08 -08001831 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08001832 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001833 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001834
Eric Laurentab5cdba2014-06-09 17:22:27 -07001835 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001836 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001837 return DEAD_OBJECT;
1838 }
1839
Glenn Kasten200092b2014-08-15 15:13:30 -07001840 // save the old static buffer position
Andy Hung4ede21d2014-12-12 15:37:34 -08001841 size_t bufferPosition = 0;
1842 int loopCount = 0;
1843 if (mStaticProxy != 0) {
1844 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1845 }
Glenn Kasten200092b2014-08-15 15:13:30 -07001846
1847 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001848 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001849 // It will also delete the strong references on previous IAudioTrack and IMemory.
1850 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
1851 result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001852
1853 // take the frames that will be lost by track recreation into account in saved position
Andy Hung9b461582014-12-01 17:56:29 -08001854 // For streaming tracks, this is the amount we obtained from the user/client
1855 // (not the number actually consumed at the server - those are already lost).
Glenn Kasten200092b2014-08-15 15:13:30 -07001856 (void) updateAndGetPosition_l();
Andy Hung9b461582014-12-01 17:56:29 -08001857 if (mStaticProxy != 0) {
1858 mPosition = mReleased;
1859 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001860
Glenn Kastena47f3162012-11-07 10:13:08 -08001861 if (result == NO_ERROR) {
Andy Hung4ede21d2014-12-12 15:37:34 -08001862 // Continue playback from last known position and restore loop.
1863 if (mStaticProxy != 0) {
1864 if (loopCount != 0) {
1865 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
1866 mLoopStart, mLoopEnd, loopCount);
1867 } else {
1868 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001869 if (bufferPosition == mFrameCount) {
1870 ALOGD("restoring track at end of static buffer");
1871 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001872 }
1873 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001874 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001875 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001876 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001877 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001878 if (result != NO_ERROR) {
1879 ALOGW("restoreTrack_l() failed status %d", result);
1880 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001881 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001882 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001883
1884 return result;
1885}
1886
Glenn Kasten200092b2014-08-15 15:13:30 -07001887uint32_t AudioTrack::updateAndGetPosition_l()
1888{
1889 // This is the sole place to read server consumed frames
1890 uint32_t newServer = mProxy->getPosition();
1891 int32_t delta = newServer - mServer;
1892 mServer = newServer;
1893 // TODO There is controversy about whether there can be "negative jitter" in server position.
1894 // This should be investigated further, and if possible, it should be addressed.
1895 // A more definite failure mode is infrequent polling by client.
1896 // One could call (void)getPosition_l() in releaseBuffer(),
1897 // so mReleased and mPosition are always lock-step as best possible.
1898 // That should ensure delta never goes negative for infrequent polling
1899 // unless the server has more than 2^31 frames in its buffer,
1900 // in which case the use of uint32_t for these counters has bigger issues.
1901 if (delta < 0) {
1902 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
1903 delta = 0;
1904 }
1905 return mPosition += (uint32_t) delta;
1906}
1907
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001908status_t AudioTrack::setParameters(const String8& keyValuePairs)
1909{
1910 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001911 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001912}
1913
Glenn Kastence703742013-07-19 16:33:58 -07001914status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1915{
Glenn Kasten53cec222013-08-29 09:01:02 -07001916 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001917 // FIXME not implemented for fast tracks; should use proxy and SSQ
1918 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1919 return INVALID_OPERATION;
1920 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001921
1922 switch (mState) {
1923 case STATE_ACTIVE:
1924 case STATE_PAUSED:
1925 break; // handle below
1926 case STATE_FLUSHED:
1927 case STATE_STOPPED:
1928 return WOULD_BLOCK;
1929 case STATE_STOPPING:
1930 case STATE_PAUSED_STOPPING:
1931 if (!isOffloaded_l()) {
1932 return INVALID_OPERATION;
1933 }
1934 break; // offloaded tracks handled below
1935 default:
1936 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
1937 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07001938 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001939
Eric Laurent275e8e92014-11-30 15:14:47 -08001940 if (mCblk->mFlags & CBLK_INVALID) {
1941 restoreTrack_l("getTimestamp");
1942 }
1943
Glenn Kasten200092b2014-08-15 15:13:30 -07001944 // The presented frame count must always lag behind the consumed frame count.
1945 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07001946 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001947 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07001948 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001949 return status;
1950 }
1951 if (isOffloadedOrDirect_l()) {
1952 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
1953 // use cached paused position in case another offloaded track is running.
1954 timestamp.mPosition = mPausedPosition;
1955 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
1956 return NO_ERROR;
1957 }
1958
1959 // Check whether a pending flush or stop has completed, as those commands may
1960 // be asynchronous or return near finish.
1961 if (mStartUs != 0 && mSampleRate != 0) {
1962 static const int kTimeJitterUs = 100000; // 100 ms
1963 static const int k1SecUs = 1000000;
1964
1965 const int64_t timeNow = getNowUs();
1966
1967 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
1968 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
1969 if (timestampTimeUs < mStartUs) {
1970 return WOULD_BLOCK; // stale timestamp time, occurs before start.
1971 }
1972 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
1973 const int64_t deltaPositionByUs = timestamp.mPosition * 1000000LL / mSampleRate;
1974
1975 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
1976 // Verify that the counter can't count faster than the sample rate
1977 // since the start time. If greater, then that means we have failed
1978 // to completely flush or stop the previous playing track.
1979 ALOGW("incomplete flush or stop:"
1980 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
1981 (long long)deltaTimeUs, (long long)deltaPositionByUs,
1982 timestamp.mPosition);
1983 return WOULD_BLOCK;
1984 }
1985 }
1986 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
1987 }
1988 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07001989 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
1990 (void) updateAndGetPosition_l();
1991 // Server consumed (mServer) and presented both use the same server time base,
1992 // and server consumed is always >= presented.
1993 // The delta between these represents the number of frames in the buffer pipeline.
1994 // If this delta between these is greater than the client position, it means that
1995 // actually presented is still stuck at the starting line (figuratively speaking),
1996 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
1997 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
1998 return INVALID_OPERATION;
1999 }
2000 // Convert timestamp position from server time base to client time base.
2001 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2002 // But if we change it to 64-bit then this could fail.
2003 // If (mPosition - mServer) can be negative then should use:
2004 // (int32_t)(mPosition - mServer)
2005 timestamp.mPosition += mPosition - mServer;
2006 // Immediately after a call to getPosition_l(), mPosition and
2007 // mServer both represent the same frame position. mPosition is
2008 // in client's point of view, and mServer is in server's point of
2009 // view. So the difference between them is the "fudge factor"
2010 // between client and server views due to stop() and/or new
2011 // IAudioTrack. And timestamp.mPosition is initially in server's
2012 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002013 }
2014 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002015}
2016
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002017String8 AudioTrack::getParameters(const String8& keys)
2018{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002019 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002020 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002021 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002022 } else {
2023 return String8::empty();
2024 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002025}
2026
Glenn Kasten23a75452014-01-13 10:37:17 -08002027bool AudioTrack::isOffloaded() const
2028{
2029 AutoMutex lock(mLock);
2030 return isOffloaded_l();
2031}
2032
Eric Laurentab5cdba2014-06-09 17:22:27 -07002033bool AudioTrack::isDirect() const
2034{
2035 AutoMutex lock(mLock);
2036 return isDirect_l();
2037}
2038
2039bool AudioTrack::isOffloadedOrDirect() const
2040{
2041 AutoMutex lock(mLock);
2042 return isOffloadedOrDirect_l();
2043}
2044
2045
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002046status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002047{
2048
2049 const size_t SIZE = 256;
2050 char buffer[SIZE];
2051 String8 result;
2052
2053 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002054 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002055 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002056 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002057 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb603744e2012-11-14 13:42:25 -08002058 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002059 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08002060 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002061 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002062 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002063 result.append(buffer);
2064 ::write(fd, result.string(), result.size());
2065 return NO_ERROR;
2066}
2067
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002068uint32_t AudioTrack::getUnderrunFrames() const
2069{
2070 AutoMutex lock(mLock);
2071 return mProxy->getUnderrunFrames();
2072}
2073
2074// =========================================================================
2075
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002076void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002077{
2078 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2079 if (audioTrack != 0) {
2080 AutoMutex lock(audioTrack->mLock);
2081 audioTrack->mProxy->binderDied();
2082 }
2083}
2084
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002085// =========================================================================
2086
2087AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002088 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2089 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002090{
2091}
2092
2093AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002094{
2095}
2096
2097bool AudioTrack::AudioTrackThread::threadLoop()
2098{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002099 {
2100 AutoMutex _l(mMyLock);
2101 if (mPaused) {
2102 mMyCond.wait(mMyLock);
2103 // caller will check for exitPending()
2104 return true;
2105 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002106 if (mIgnoreNextPausedInt) {
2107 mIgnoreNextPausedInt = false;
2108 mPausedInt = false;
2109 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002110 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002111 if (mPausedNs > 0) {
2112 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2113 } else {
2114 mMyCond.wait(mMyLock);
2115 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002116 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002117 return true;
2118 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002119 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002120 if (exitPending()) {
2121 return false;
2122 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002123 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002124 switch (ns) {
2125 case 0:
2126 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002127 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002128 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002129 return true;
2130 case NS_NEVER:
2131 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002132 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08002133 // Event driven: call wake() when callback notifications conditions change.
2134 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002135 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002136 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002137 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002138 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002139 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002140 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002141}
2142
Glenn Kasten3acbd052012-02-28 10:39:56 -08002143void AudioTrack::AudioTrackThread::requestExit()
2144{
2145 // must be in this order to avoid a race condition
2146 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002147 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002148}
2149
2150void AudioTrack::AudioTrackThread::pause()
2151{
2152 AutoMutex _l(mMyLock);
2153 mPaused = true;
2154}
2155
2156void AudioTrack::AudioTrackThread::resume()
2157{
2158 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002159 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002160 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002161 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002162 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002163 mMyCond.signal();
2164 }
2165}
2166
Andy Hung3c09c782014-12-29 18:39:32 -08002167void AudioTrack::AudioTrackThread::wake()
2168{
2169 AutoMutex _l(mMyLock);
2170 if (!mPaused && mPausedInt && mPausedNs > 0) {
2171 // audio track is active and internally paused with timeout.
2172 mIgnoreNextPausedInt = true;
2173 mPausedInt = false;
2174 mMyCond.signal();
2175 }
2176}
2177
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002178void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2179{
2180 AutoMutex _l(mMyLock);
2181 mPausedInt = true;
2182 mPausedNs = ns;
2183}
2184
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002185}; // namespace android