blob: d4bacc087c3c2b989dc184566593675108e6d311 [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
Glenn Kastene0fa4672012-04-24 14:35:14 -070069 // FIXME merge with similar code in createTrack_l(), except we're missing
70 // some information here that is available in createTrack_l():
71 // audio_io_handle_t output
72 // audio_format_t format
73 // audio_channel_mask_t channelMask
74 // audio_output_flags_t flags
Glenn Kasten3b16c762012-11-14 08:44:39 -080075 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080076 status_t status;
77 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
78 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080079 ALOGE("Unable to query output sample rate for stream type %d; status %d",
80 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080081 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080082 }
Glenn Kastene33054e2012-11-14 12:54:39 -080083 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -080084 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
85 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080086 ALOGE("Unable to query output frame count for stream type %d; status %d",
87 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080088 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080089 }
90 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -080091 status = AudioSystem::getOutputLatency(&afLatency, streamType);
92 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080093 ALOGE("Unable to query output latency for stream type %d; status %d",
94 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080095 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080096 }
97
98 // Ensure that buffer depth covers at least audio hardware latency
99 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800100 if (minBufCount < 2) {
101 minBufCount = 2;
102 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800103
104 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
Andy Hungcd044842014-08-07 11:04:34 -0700105 afFrameCount * minBufCount * uint64_t(sampleRate) / afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -0800106 // The formula above should always produce a non-zero value, but return an error
107 // in the unlikely event that it does not, as that's part of the API contract.
108 if (*frameCount == 0) {
109 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %d",
110 streamType, sampleRate);
111 return BAD_VALUE;
112 }
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700113 ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, minBufCount=%d, afSampleRate=%d, afLatency=%d",
Glenn Kasten3acbd052012-02-28 10:39:56 -0800114 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800115 return NO_ERROR;
116}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800117
118// ---------------------------------------------------------------------------
119
120AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700121 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800122 mIsTimed(false),
123 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800124 mPreviousSchedulingGroup(SP_DEFAULT),
125 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800126{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700127 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
128 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
129 mAttributes.flags = 0x0;
130 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800131}
132
133AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800134 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800135 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800136 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700137 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800138 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700139 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800140 callback_t cbf,
141 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800142 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800143 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000144 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800145 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800146 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700147 pid_t pid,
148 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700149 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800150 mIsTimed(false),
151 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800152 mPreviousSchedulingGroup(SP_DEFAULT),
153 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800154{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700155 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700156 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800157 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700158 offloadInfo, uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800159}
160
Andreas Huberc8139852012-01-18 10:51:55 -0800161AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800162 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800163 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800164 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700165 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800166 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700167 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800168 callback_t cbf,
169 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800170 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800171 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000172 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800173 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800174 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700175 pid_t pid,
176 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700177 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800178 mIsTimed(false),
179 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800180 mPreviousSchedulingGroup(SP_DEFAULT),
181 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800182{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700183 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800184 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800185 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700186 uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800187}
188
189AudioTrack::~AudioTrack()
190{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800191 if (mStatus == NO_ERROR) {
192 // Make sure that callback function exits in the case where
193 // it is looping on buffer full condition in obtainBuffer().
194 // Otherwise the callback thread will never exit.
195 stop();
196 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100197 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800198 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800199 mAudioTrackThread->requestExitAndWait();
200 mAudioTrackThread.clear();
201 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800202 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700203 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700204 mCblkMemory.clear();
205 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800206 IPCThreadState::self()->flushCommands();
Marco Nelissend457c972014-02-11 08:47:07 -0800207 ALOGV("~AudioTrack, releasing session id from %d on behalf of %d",
208 IPCThreadState::self()->getCallingPid(), mClientPid);
209 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800210 }
211}
212
213status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800214 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800215 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800216 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700217 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800218 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700219 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800220 callback_t cbf,
221 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800222 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800223 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700224 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800225 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000226 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800227 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800228 int uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700229 pid_t pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700230 const audio_attributes_t* pAttributes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800231{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800232 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten838b3d82014-02-27 15:30:41 -0800233 "flags #%x, notificationFrames %u, sessionId %d, transferType %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800234 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten86f04662014-02-24 15:13:05 -0800235 sessionId, transferType);
236
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800237 switch (transferType) {
238 case TRANSFER_DEFAULT:
239 if (sharedBuffer != 0) {
240 transferType = TRANSFER_SHARED;
241 } else if (cbf == NULL || threadCanCallJava) {
242 transferType = TRANSFER_SYNC;
243 } else {
244 transferType = TRANSFER_CALLBACK;
245 }
246 break;
247 case TRANSFER_CALLBACK:
248 if (cbf == NULL || sharedBuffer != 0) {
249 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
250 return BAD_VALUE;
251 }
252 break;
253 case TRANSFER_OBTAIN:
254 case TRANSFER_SYNC:
255 if (sharedBuffer != 0) {
256 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
257 return BAD_VALUE;
258 }
259 break;
260 case TRANSFER_SHARED:
261 if (sharedBuffer == 0) {
262 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
263 return BAD_VALUE;
264 }
265 break;
266 default:
267 ALOGE("Invalid transfer type %d", transferType);
268 return BAD_VALUE;
269 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800270 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800271 mTransfer = transferType;
272
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700273 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
274 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800275
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700276 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700277
Eric Laurent1703cdf2011-03-07 14:52:59 -0800278 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800279
Glenn Kasten53cec222013-08-29 09:01:02 -0700280 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700281 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000282 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800283 return INVALID_OPERATION;
284 }
285
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800286 // handle default values first.
Eric Laurente83b55d2014-11-14 10:06:21 -0800287 if (streamType == AUDIO_STREAM_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700288 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800289 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700290 if (pAttributes == NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800291 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700292 ALOGE("Invalid stream type %d", streamType);
293 return BAD_VALUE;
294 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700295 mStreamType = streamType;
Eric Laurente83b55d2014-11-14 10:06:21 -0800296
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700297 } else {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700298 // stream type shouldn't be looked at, this track has audio attributes
299 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700300 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
301 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800302 mStreamType = AUDIO_STREAM_DEFAULT;
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800303 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700304
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800305 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800306 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700307 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800308 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800309
310 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700311 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800312 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800313 return BAD_VALUE;
314 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800315 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700316
Glenn Kasten8ba90322013-10-30 11:29:27 -0700317 if (!audio_is_output_channel(channelMask)) {
318 ALOGE("Invalid channel mask %#x", channelMask);
319 return BAD_VALUE;
320 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800321 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700322 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800323 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700324
Eric Laurentc2f1f072009-07-17 12:17:14 -0700325 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100326 // or offload was requested
327 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
328 || !audio_is_linear_pcm(format)) {
329 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
330 ? "Offload request, forcing to Direct Output"
331 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700332 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800333 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700334 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700335 }
336
Eric Laurentd1f69b02014-12-15 14:33:13 -0800337 // force direct flag if HW A/V sync requested
338 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
339 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
340 }
341
Glenn Kastenb7730382014-04-30 15:50:31 -0700342 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
343 if (audio_is_linear_pcm(format)) {
344 mFrameSize = channelCount * audio_bytes_per_sample(format);
345 } else {
346 mFrameSize = sizeof(uint8_t);
347 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800348 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700349 ALOG_ASSERT(audio_is_linear_pcm(format));
350 mFrameSize = channelCount * audio_bytes_per_sample(format);
Glenn Kastenb7730382014-04-30 15:50:31 -0700351 // createTrack will return an error if PCM format is not supported by server,
352 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800353 }
354
Eric Laurent0d6db582014-11-12 18:39:44 -0800355 // sampling rate must be specified for direct outputs
356 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
357 return BAD_VALUE;
358 }
359 mSampleRate = sampleRate;
360
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800361 // Make copy of input parameter offloadInfo so that in the future:
362 // (a) createTrack_l doesn't need it as an input parameter
363 // (b) we can support re-creation of offloaded tracks
364 if (offloadInfo != NULL) {
365 mOffloadInfoCopy = *offloadInfo;
366 mOffloadInfo = &mOffloadInfoCopy;
367 } else {
368 mOffloadInfo = NULL;
369 }
370
Glenn Kasten66e46352014-01-16 17:44:23 -0800371 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
372 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800373 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800374 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800375 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700376 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800377 mNotificationFramesAct = 0;
Eric Laurentcaf7f482014-11-25 17:50:47 -0800378 if (sessionId == AUDIO_SESSION_ALLOCATE) {
379 mSessionId = AudioSystem::newAudioUniqueId();
380 } else {
381 mSessionId = sessionId;
382 }
Marco Nelissend457c972014-02-11 08:47:07 -0800383 int callingpid = IPCThreadState::self()->getCallingPid();
384 int mypid = getpid();
385 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800386 mClientUid = IPCThreadState::self()->getCallingUid();
387 } else {
388 mClientUid = uid;
389 }
Marco Nelissend457c972014-02-11 08:47:07 -0800390 if (pid == -1 || (callingpid != mypid)) {
391 mClientPid = callingpid;
392 } else {
393 mClientPid = pid;
394 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700395 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700396 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700397 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700398
Glenn Kastena997e7a2012-08-07 09:44:19 -0700399 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700400 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700401 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
402 }
403
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800404 // create the IAudioTrack
Eric Laurent0d6db582014-11-12 18:39:44 -0800405 status_t status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800406
Glenn Kastena997e7a2012-08-07 09:44:19 -0700407 if (status != NO_ERROR) {
408 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100409 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
410 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700411 mAudioTrackThread.clear();
412 }
413 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700414 }
415
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800416 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800417 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800418 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800419 mLoopCount = 0;
420 mLoopStart = 0;
421 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800422 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800423 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700424 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800425 mNewPosition = 0;
426 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700427 mServer = 0;
428 mPosition = 0;
429 mReleased = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700430 mStartUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800431 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800432 mSequence = 1;
433 mObservedSequence = mSequence;
434 mInUnderrun = false;
435
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800436 return NO_ERROR;
437}
438
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800439// -------------------------------------------------------------------------
440
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100441status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800442{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800443 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100444
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800445 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100446 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800447 }
448
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800449 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800450
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800451 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100452 if (previousState == STATE_PAUSED_STOPPING) {
453 mState = STATE_STOPPING;
454 } else {
455 mState = STATE_ACTIVE;
456 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700457 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800458 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
459 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700460 mPosition = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700461 // For offloaded tracks, we don't know if the hardware counters are really zero here,
462 // since the flush is asynchronous and stop may not fully drain.
463 // We save the time when the track is started to later verify whether
464 // the counters are realistic (i.e. start from zero after this time).
465 mStartUs = getNowUs();
466
Eric Laurentec9a0322013-08-28 10:23:01 -0700467 // force refresh of remaining frames by processAudioBuffer() as last
468 // write before stop could be partial.
469 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800470 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700471 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700472 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800473
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800474 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800475 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100476 if (previousState == STATE_STOPPING) {
477 mProxy->interrupt();
478 } else {
479 t->resume();
480 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800481 } else {
482 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
483 get_sched_policy(0, &mPreviousSchedulingGroup);
484 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
485 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800486
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800487 status_t status = NO_ERROR;
488 if (!(flags & CBLK_INVALID)) {
489 status = mAudioTrack->start();
490 if (status == DEAD_OBJECT) {
491 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800492 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800493 }
494 if (flags & CBLK_INVALID) {
495 status = restoreTrack_l("start");
496 }
497
498 if (status != NO_ERROR) {
499 ALOGE("start() status %d", status);
500 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800501 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100502 if (previousState != STATE_STOPPING) {
503 t->pause();
504 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800505 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700506 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700507 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800508 }
509 }
510
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100511 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800512}
513
514void AudioTrack::stop()
515{
516 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700517 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800518 return;
519 }
520
Glenn Kasten23a75452014-01-13 10:37:17 -0800521 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100522 mState = STATE_STOPPING;
523 } else {
524 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -0700525 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100526 }
527
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800528 mProxy->interrupt();
529 mAudioTrack->stop();
530 // the playback head position will reset to 0, so if a marker is set, we need
531 // to activate it again
532 mMarkerReached = false;
Andy Hung9b461582014-12-01 17:56:29 -0800533
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800534 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800535 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800536 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
537 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800538 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100539
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800540 sp<AudioTrackThread> t = mAudioTrackThread;
541 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800542 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100543 t->pause();
544 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800545 } else {
546 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
547 set_sched_policy(0, mPreviousSchedulingGroup);
548 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800549}
550
551bool AudioTrack::stopped() const
552{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800553 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800554 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800555}
556
557void AudioTrack::flush()
558{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800559 if (mSharedBuffer != 0) {
560 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800561 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800562 AutoMutex lock(mLock);
563 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
564 return;
565 }
566 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800567}
568
Eric Laurent1703cdf2011-03-07 14:52:59 -0800569void AudioTrack::flush_l()
570{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800571 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700572
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700573 // clear playback marker and periodic update counter
574 mMarkerPosition = 0;
575 mMarkerReached = false;
576 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100577 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700578
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800579 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700580 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800581 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100582 mProxy->interrupt();
583 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800584 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800585 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800586}
587
588void AudioTrack::pause()
589{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800590 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100591 if (mState == STATE_ACTIVE) {
592 mState = STATE_PAUSED;
593 } else if (mState == STATE_STOPPING) {
594 mState = STATE_PAUSED_STOPPING;
595 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800596 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800597 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800598 mProxy->interrupt();
599 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800600
Marco Nelissen3a90f282014-03-10 11:21:43 -0700601 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700602 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700603 // An offload output can be re-used between two audio tracks having
604 // the same configuration. A timestamp query for a paused track
605 // while the other is running would return an incorrect time.
606 // To fix this, cache the playback position on a pause() and return
607 // this time when requested until the track is resumed.
608
609 // OffloadThread sends HAL pause in its threadLoop. Time saved
610 // here can be slightly off.
611
612 // TODO: check return code for getRenderPosition.
613
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800614 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800615 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
616 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
617 }
618 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800619}
620
Eric Laurentbe916aa2010-06-01 23:49:17 -0700621status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800622{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700623 // This duplicates a test by AudioTrack JNI, but that is not the only caller
624 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
625 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700626 return BAD_VALUE;
627 }
628
Eric Laurent1703cdf2011-03-07 14:52:59 -0800629 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800630 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
631 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800632
Glenn Kastenc56f3422014-03-21 17:53:17 -0700633 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700634
Glenn Kasten23a75452014-01-13 10:37:17 -0800635 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700636 mAudioTrack->signal();
637 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700638 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800639}
640
Glenn Kastenb1c09932012-02-27 16:21:04 -0800641status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800642{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800643 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700644}
645
Eric Laurent2beeb502010-07-16 07:43:46 -0700646status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700647{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700648 // This duplicates a test by AudioTrack JNI, but that is not the only caller
649 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700650 return BAD_VALUE;
651 }
652
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800653 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700654 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800655 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700656
657 return NO_ERROR;
658}
659
Glenn Kastena5224f32012-01-04 12:41:44 -0800660void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700661{
662 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800663 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700664 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800665}
666
Glenn Kasten3b16c762012-11-14 08:44:39 -0800667status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800668{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700669 if (mIsTimed || isOffloadedOrDirect()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800670 return INVALID_OPERATION;
671 }
672
Eric Laurent0d6db582014-11-12 18:39:44 -0800673 AutoMutex lock(mLock);
674 if (mOutput == AUDIO_IO_HANDLE_NONE) {
675 return NO_INIT;
676 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800677 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800678 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700679 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800680 }
Andy Hungcd044842014-08-07 11:04:34 -0700681 if (rate == 0 || rate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700682 return BAD_VALUE;
683 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800684
Glenn Kastene3aa6592012-12-04 12:22:46 -0800685 mSampleRate = rate;
686 mProxy->setSampleRate(rate);
687
Eric Laurent57326622009-07-07 07:10:45 -0700688 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800689}
690
Glenn Kastena5224f32012-01-04 12:41:44 -0800691uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800692{
John Grossman4ff14ba2012-02-08 16:37:41 -0800693 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800694 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800695 }
696
Eric Laurent1703cdf2011-03-07 14:52:59 -0800697 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700698
699 // sample rate can be updated during playback by the offloaded decoder so we need to
700 // query the HAL and update if needed.
701// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700702 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700703 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700704 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700705 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700706 if (status == NO_ERROR) {
707 mSampleRate = sampleRate;
708 }
709 }
710 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800711 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800712}
713
714status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
715{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700716 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800717 return INVALID_OPERATION;
718 }
719
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800720 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800721 ;
722 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
723 loopEnd - loopStart >= MIN_LOOP) {
724 ;
725 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800726 return BAD_VALUE;
727 }
728
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800729 AutoMutex lock(mLock);
730 // See setPosition() regarding setting parameters such as loop points or position while active
731 if (mState == STATE_ACTIVE) {
732 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700733 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800734 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800735 return NO_ERROR;
736}
737
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800738void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
739{
Andy Hung4ede21d2014-12-12 15:37:34 -0800740 // We do not update the periodic notification point.
741 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
742 mLoopCount = loopCount;
743 mLoopEnd = loopEnd;
744 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800745 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800746 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -0800747
748 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800749}
750
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800751status_t AudioTrack::setMarkerPosition(uint32_t marker)
752{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700753 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700754 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700755 return INVALID_OPERATION;
756 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800757
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800758 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800759 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700760 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800761
Andy Hung3c09c782014-12-29 18:39:32 -0800762 sp<AudioTrackThread> t = mAudioTrackThread;
763 if (t != 0) {
764 t->wake();
765 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800766 return NO_ERROR;
767}
768
Glenn Kastena5224f32012-01-04 12:41:44 -0800769status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800770{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700771 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100772 return INVALID_OPERATION;
773 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700774 if (marker == NULL) {
775 return BAD_VALUE;
776 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800777
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800778 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800779 *marker = mMarkerPosition;
780
781 return NO_ERROR;
782}
783
784status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
785{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700786 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700787 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700788 return INVALID_OPERATION;
789 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800790
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800791 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700792 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800793 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800794
Andy Hung3c09c782014-12-29 18:39:32 -0800795 sp<AudioTrackThread> t = mAudioTrackThread;
796 if (t != 0) {
797 t->wake();
798 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800799 return NO_ERROR;
800}
801
Glenn Kastena5224f32012-01-04 12:41:44 -0800802status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800803{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700804 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100805 return INVALID_OPERATION;
806 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700807 if (updatePeriod == NULL) {
808 return BAD_VALUE;
809 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800810
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800811 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800812 *updatePeriod = mUpdatePeriod;
813
814 return NO_ERROR;
815}
816
817status_t AudioTrack::setPosition(uint32_t position)
818{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700819 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700820 return INVALID_OPERATION;
821 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800822 if (position > mFrameCount) {
823 return BAD_VALUE;
824 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800825
Eric Laurent1703cdf2011-03-07 14:52:59 -0800826 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800827 // Currently we require that the player is inactive before setting parameters such as position
828 // or loop points. Otherwise, there could be a race condition: the application could read the
829 // current position, compute a new position or loop parameters, and then set that position or
830 // loop parameters but it would do the "wrong" thing since the position has continued to advance
831 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
832 // to specify how it wants to handle such scenarios.
833 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700834 return INVALID_OPERATION;
835 }
Andy Hung9b461582014-12-01 17:56:29 -0800836 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -0700837 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800838 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -0800839
840 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800841 return NO_ERROR;
842}
843
Glenn Kasten200092b2014-08-15 15:13:30 -0700844status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800845{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700846 if (position == NULL) {
847 return BAD_VALUE;
848 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800849
Eric Laurent1703cdf2011-03-07 14:52:59 -0800850 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700851 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100852 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800853
Eric Laurentab5cdba2014-06-09 17:22:27 -0700854 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800855 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
856 *position = mPausedPosition;
857 return NO_ERROR;
858 }
859
Glenn Kasten142f5192014-03-25 17:44:59 -0700860 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100861 uint32_t halFrames;
862 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
863 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700864 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
865 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100866 *position = dspFrames;
867 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -0800868 if (mCblk->mFlags & CBLK_INVALID) {
869 restoreTrack_l("getPosition");
870 }
871
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100872 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700873 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
874 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100875 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800876 return NO_ERROR;
877}
878
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000879status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800880{
881 if (mSharedBuffer == 0 || mIsTimed) {
882 return INVALID_OPERATION;
883 }
884 if (position == NULL) {
885 return BAD_VALUE;
886 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800887
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800888 AutoMutex lock(mLock);
889 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800890 return NO_ERROR;
891}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800892
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800893status_t AudioTrack::reload()
894{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700895 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800896 return INVALID_OPERATION;
897 }
898
Eric Laurent1703cdf2011-03-07 14:52:59 -0800899 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800900 // See setPosition() regarding setting parameters such as loop points or position while active
901 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700902 return INVALID_OPERATION;
903 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800904 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800905 (void) updateAndGetPosition_l();
906 mPosition = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800907#if 0
Andy Hung9b461582014-12-01 17:56:29 -0800908 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -0800909 // of loop count. Historically we have not restored loop count, start, end,
910 // but it makes sense if one desires to repeat playing a particular sound.
911 if (mLoopCount != 0) {
912 mLoopCountNotified = mLoopCount;
913 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
914 }
915#endif
Andy Hung9b461582014-12-01 17:56:29 -0800916 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800917 return NO_ERROR;
918}
919
Glenn Kasten38e905b2014-01-13 10:21:48 -0800920audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700921{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800922 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100923 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800924}
925
Eric Laurentbe916aa2010-06-01 23:49:17 -0700926status_t AudioTrack::attachAuxEffect(int effectId)
927{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800928 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700929 status_t status = mAudioTrack->attachAuxEffect(effectId);
930 if (status == NO_ERROR) {
931 mAuxEffectId = effectId;
932 }
933 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700934}
935
Eric Laurente83b55d2014-11-14 10:06:21 -0800936audio_stream_type_t AudioTrack::streamType() const
937{
938 if (mStreamType == AUDIO_STREAM_DEFAULT) {
939 return audio_attributes_to_stream_type(&mAttributes);
940 }
941 return mStreamType;
942}
943
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800944// -------------------------------------------------------------------------
945
Eric Laurent1703cdf2011-03-07 14:52:59 -0800946// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -0700947status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800948{
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800949 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
950 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700951 ALOGE("Could not get audioflinger");
952 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800953 }
954
Eric Laurente83b55d2014-11-14 10:06:21 -0800955 audio_io_handle_t output;
956 audio_stream_type_t streamType = mStreamType;
957 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
958 status_t status = AudioSystem::getOutputForAttr(attr, &output,
959 (audio_session_t)mSessionId, &streamType,
960 mSampleRate, mFormat, mChannelMask,
961 mFlags, mOffloadInfo);
962
963
964 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700965 ALOGE("Could not get audio output for stream type %d, usage %d, sample rate %u, format %#x,"
966 " channel mask %#x, flags %#x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800967 streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800968 return BAD_VALUE;
969 }
970 {
971 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
972 // we must release it ourselves if anything goes wrong.
973
Glenn Kastence8828a2013-09-16 18:07:38 -0700974 // Not all of these values are needed under all conditions, but it is easier to get them all
975
Eric Laurentd1b449a2010-05-14 03:26:45 -0700976 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -0700977 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700978 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800979 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800980 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700981 }
982
Glenn Kastence8828a2013-09-16 18:07:38 -0700983 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700984 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -0700985 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700986 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800987 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700988 }
989
990 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700991 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -0700992 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700993 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800994 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700995 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800996 if (mSampleRate == 0) {
997 mSampleRate = afSampleRate;
998 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700999 // Client decides whether the track is TIMED (see below), but can only express a preference
1000 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001001 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001002 // either of these use cases:
1003 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -08001004 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001005 // use case 2: callback transfer mode
1006 (mTransfer == TRANSFER_CALLBACK)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001007 // matching sample rate
1008 (mSampleRate == afSampleRate))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08001009 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -07001010 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001011 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001012 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001013 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001014
Glenn Kastence8828a2013-09-16 18:07:38 -07001015 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -08001016 // n = 1 fast track with single buffering; nBuffering is ignored
1017 // n = 2 fast track with double buffering
Glenn Kastence8828a2013-09-16 18:07:38 -07001018 // n = 2 normal track, no sample rate conversion
1019 // n = 3 normal track, with sample rate conversion
1020 // (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering)
1021 // n > 3 very high latency or very small notification interval; nBuffering is ignored
Glenn Kasten363fb752014-01-15 12:27:31 -08001022 const uint32_t nBuffering = (mSampleRate == afSampleRate) ? 2 : 3;
Glenn Kastence8828a2013-09-16 18:07:38 -07001023
Eric Laurentd1b449a2010-05-14 03:26:45 -07001024 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001025
Glenn Kasten363fb752014-01-15 12:27:31 -08001026 size_t frameCount = mReqFrameCount;
1027 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001028
Glenn Kasten363fb752014-01-15 12:27:31 -08001029 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001030 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001031 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001032 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001033 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001034 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001035 if (mNotificationFramesAct != frameCount) {
1036 mNotificationFramesAct = frameCount;
1037 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001038 } else if (mSharedBuffer != 0) {
Andy Hungabdb9902015-01-12 15:08:22 -08001039 // FIXME: Ensure client side memory buffers need
1040 // not have additional alignment beyond sample
1041 // (e.g. 16 bit stereo accessed as 32 bit frame).
1042 size_t alignment = audio_bytes_per_sample(mFormat);
Glenn Kastenb7730382014-04-30 15:50:31 -07001043 if (alignment & 1) {
Andy Hungabdb9902015-01-12 15:08:22 -08001044 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
Glenn Kastenb7730382014-04-30 15:50:31 -07001045 alignment = 1;
1046 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001047 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001048 // More than 2 channels does not require stronger alignment than stereo
1049 alignment <<= 1;
1050 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001051 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001052 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001053 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001054 status = BAD_VALUE;
1055 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001056 }
1057
1058 // When initializing a shared buffer AudioTrack via constructors,
1059 // there's no frameCount parameter.
1060 // But when initializing a shared buffer AudioTrack via set(),
1061 // there _is_ a frameCount parameter. We silently ignore it.
Andy Hungabdb9902015-01-12 15:08:22 -08001062 frameCount = mSharedBuffer->size() / mFrameSize;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001063
Glenn Kasten363fb752014-01-15 12:27:31 -08001064 } else if (!(mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001065
1066 // FIXME move these calculations and associated checks to server
Glenn Kastene0fa4672012-04-24 14:35:14 -07001067
Eric Laurentd1b449a2010-05-14 03:26:45 -07001068 // Ensure that buffer depth covers at least audio hardware latency
1069 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001070 ALOGV("afFrameCount=%zu, minBufCount=%d, afSampleRate=%u, afLatency=%d",
Glenn Kastenbb6f0a02013-06-03 15:00:29 -07001071 afFrameCount, minBufCount, afSampleRate, afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001072 if (minBufCount <= nBuffering) {
1073 minBufCount = nBuffering;
Glenn Kasten7c027242012-12-26 14:43:16 -08001074 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001075
Andy Hungcd044842014-08-07 11:04:34 -07001076 size_t minFrameCount = afFrameCount * minBufCount * uint64_t(mSampleRate) / afSampleRate;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001077 ALOGV("minFrameCount: %zu, afFrameCount=%zu, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -08001078 ", afLatency=%d",
Glenn Kasten363fb752014-01-15 12:27:31 -08001079 minFrameCount, afFrameCount, minBufCount, mSampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001080
1081 if (frameCount == 0) {
1082 frameCount = minFrameCount;
Glenn Kastence8828a2013-09-16 18:07:38 -07001083 } else if (frameCount < minFrameCount) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001084 // not ALOGW because it happens all the time when playing key clicks over A2DP
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001085 ALOGV("Minimum buffer size corrected from %zu to %zu",
Glenn Kastene0fa4672012-04-24 14:35:14 -07001086 frameCount, minFrameCount);
1087 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001088 }
Glenn Kastence8828a2013-09-16 18:07:38 -07001089 // Make sure that application is notified with sufficient margin before underrun
1090 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1091 mNotificationFramesAct = frameCount/nBuffering;
1092 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001093
Glenn Kastene0fa4672012-04-24 14:35:14 -07001094 } else {
1095 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -07001096 }
1097
Glenn Kastena075db42012-03-06 11:22:44 -08001098 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1099 if (mIsTimed) {
1100 trackFlags |= IAudioFlinger::TRACK_TIMED;
1101 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001102
1103 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001104 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001105 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001106 if (mAudioTrackThread != 0) {
1107 tid = mAudioTrackThread->getTid();
1108 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001109 }
1110
Glenn Kasten363fb752014-01-15 12:27:31 -08001111 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001112 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1113 }
1114
Eric Laurentab5cdba2014-06-09 17:22:27 -07001115 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1116 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1117 }
1118
Glenn Kasten74935e42013-12-19 08:56:45 -08001119 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1120 // but we will still need the original value also
Eric Laurente83b55d2014-11-14 10:06:21 -08001121 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001122 mSampleRate,
Andy Hungabdb9902015-01-12 15:08:22 -08001123 mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001124 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001125 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001126 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001127 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001128 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001129 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001130 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001131 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001132 &status);
1133
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001134 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001135 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001136 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001137 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001138 ALOG_ASSERT(track != 0);
1139
Glenn Kasten38e905b2014-01-13 10:21:48 -08001140 // AudioFlinger now owns the reference to the I/O handle,
1141 // so we are no longer responsible for releasing it.
1142
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001143 sp<IMemory> iMem = track->getCblk();
1144 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001145 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001146 return NO_INIT;
1147 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001148 void *iMemPointer = iMem->pointer();
1149 if (iMemPointer == NULL) {
1150 ALOGE("Could not get control block pointer");
1151 return NO_INIT;
1152 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001153 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001154 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001155 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001156 mDeathNotifier.clear();
1157 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001158 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001159 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001160 IPCThreadState::self()->flushCommands();
1161
Glenn Kasten0cde0762014-01-16 15:06:36 -08001162 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001163 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001164 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001165 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1166 // In current design, AudioTrack client checks and ensures frame count validity before
1167 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1168 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001169 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001170 }
1171 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001172
Glenn Kastena07f17c2013-04-23 12:39:37 -07001173 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001174 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001175 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001176 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001177 mAwaitBoost = true;
Glenn Kasten363fb752014-01-15 12:27:31 -08001178 if (mSharedBuffer == 0) {
Glenn Kastenb5fed682013-12-03 09:06:43 -08001179 // Theoretically double-buffering is not required for fast tracks,
1180 // due to tighter scheduling. But in practice, to accommodate kernels with
1181 // scheduling jitter, and apps with computation jitter, we use double-buffering.
1182 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1183 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001184 }
1185 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001186 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001187 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001188 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001189 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1190 if (mSharedBuffer == 0) {
Glenn Kastence8828a2013-09-16 18:07:38 -07001191 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1192 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001193 }
1194 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001195 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001196 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001197 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001198 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1199 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1200 } else {
1201 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001202 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001203 // FIXME This is a warning, not an error, so don't return error status
1204 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001205 }
1206 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001207 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1208 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1209 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1210 } else {
1211 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1212 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1213 // FIXME This is a warning, not an error, so don't return error status
1214 //return NO_INIT;
1215 }
1216 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001217
Glenn Kasten38e905b2014-01-13 10:21:48 -08001218 // We retain a copy of the I/O handle, but don't own the reference
1219 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001220 mRefreshRemaining = true;
1221
1222 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1223 // is the value of pointer() for the shared buffer, otherwise buffers points
1224 // immediately after the control block. This address is for the mapping within client
1225 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1226 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001227 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001228 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001229 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001230 buffers = mSharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001231 }
1232
Eric Laurent2beeb502010-07-16 07:43:46 -07001233 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001234 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001235 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001236
Glenn Kastenb6037442012-11-14 13:42:25 -08001237 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001238 // If IAudioTrack is re-created, don't let the requested frameCount
1239 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001240 if (frameCount > mReqFrameCount) {
1241 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001242 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001243
1244 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001245 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001246 mStaticProxy.clear();
Andy Hungabdb9902015-01-12 15:08:22 -08001247 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001248 } else {
Andy Hungabdb9902015-01-12 15:08:22 -08001249 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001250 mProxy = mStaticProxy;
1251 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001252
1253 mProxy->setVolumeLR(gain_minifloat_pack(
1254 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1255 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1256
Glenn Kastene3aa6592012-12-04 12:22:46 -08001257 mProxy->setSendLevel(mSendLevel);
1258 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001259 mProxy->setMinimum(mNotificationFramesAct);
1260
1261 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001262 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001263
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001264 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001265 }
1266
1267release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001268 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001269 if (status == NO_ERROR) {
1270 status = NO_INIT;
1271 }
1272 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001273}
1274
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001275status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1276{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001277 if (audioBuffer == NULL) {
1278 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001279 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001280 if (mTransfer != TRANSFER_OBTAIN) {
1281 audioBuffer->frameCount = 0;
1282 audioBuffer->size = 0;
1283 audioBuffer->raw = NULL;
1284 return INVALID_OPERATION;
1285 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001286
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001287 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001288 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001289 if (waitCount == -1) {
1290 requested = &ClientProxy::kForever;
1291 } else if (waitCount == 0) {
1292 requested = &ClientProxy::kNonBlocking;
1293 } else if (waitCount > 0) {
1294 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001295 timeout.tv_sec = ms / 1000;
1296 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1297 requested = &timeout;
1298 } else {
1299 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1300 requested = NULL;
1301 }
1302 return obtainBuffer(audioBuffer, requested);
1303}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001304
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001305status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1306 struct timespec *elapsed, size_t *nonContig)
1307{
1308 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1309 uint32_t oldSequence = 0;
1310 uint32_t newSequence;
1311
1312 Proxy::Buffer buffer;
1313 status_t status = NO_ERROR;
1314
1315 static const int32_t kMaxTries = 5;
1316 int32_t tryCounter = kMaxTries;
1317
1318 do {
1319 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1320 // keep them from going away if another thread re-creates the track during obtainBuffer()
1321 sp<AudioTrackClientProxy> proxy;
1322 sp<IMemory> iMem;
1323
1324 { // start of lock scope
1325 AutoMutex lock(mLock);
1326
1327 newSequence = mSequence;
1328 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1329 if (status == DEAD_OBJECT) {
1330 // re-create track, unless someone else has already done so
1331 if (newSequence == oldSequence) {
1332 status = restoreTrack_l("obtainBuffer");
1333 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001334 buffer.mFrameCount = 0;
1335 buffer.mRaw = NULL;
1336 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001337 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001338 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001339 }
1340 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001341 oldSequence = newSequence;
1342
1343 // Keep the extra references
1344 proxy = mProxy;
1345 iMem = mCblkMemory;
1346
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001347 if (mState == STATE_STOPPING) {
1348 status = -EINTR;
1349 buffer.mFrameCount = 0;
1350 buffer.mRaw = NULL;
1351 buffer.mNonContig = 0;
1352 break;
1353 }
1354
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001355 // Non-blocking if track is stopped or paused
1356 if (mState != STATE_ACTIVE) {
1357 requested = &ClientProxy::kNonBlocking;
1358 }
1359
1360 } // end of lock scope
1361
1362 buffer.mFrameCount = audioBuffer->frameCount;
1363 // FIXME starts the requested timeout and elapsed over from scratch
1364 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1365
1366 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1367
1368 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001369 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001370 audioBuffer->raw = buffer.mRaw;
1371 if (nonContig != NULL) {
1372 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001373 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001374 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001375}
1376
1377void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1378{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001379 if (mTransfer == TRANSFER_SHARED) {
1380 return;
1381 }
1382
Andy Hungabdb9902015-01-12 15:08:22 -08001383 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001384 if (stepCount == 0) {
1385 return;
1386 }
1387
1388 Proxy::Buffer buffer;
1389 buffer.mFrameCount = stepCount;
1390 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001391
Eric Laurent1703cdf2011-03-07 14:52:59 -08001392 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001393 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001394 mInUnderrun = false;
1395 mProxy->releaseBuffer(&buffer);
1396
1397 // restart track if it was disabled by audioflinger due to previous underrun
1398 if (mState == STATE_ACTIVE) {
1399 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001400 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001401 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001402 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001403 mAudioTrack->start();
1404 }
1405 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001406}
1407
1408// -------------------------------------------------------------------------
1409
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001410ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001411{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001412 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001413 return INVALID_OPERATION;
1414 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001415
Eric Laurentab5cdba2014-06-09 17:22:27 -07001416 if (isDirect()) {
1417 AutoMutex lock(mLock);
1418 int32_t flags = android_atomic_and(
1419 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1420 &mCblk->mFlags);
1421 if (flags & CBLK_INVALID) {
1422 return DEAD_OBJECT;
1423 }
1424 }
1425
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001426 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001427 // Sanity-check: user is most-likely passing an error code, and it would
1428 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001429 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001430 return BAD_VALUE;
1431 }
1432
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001433 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001434 Buffer audioBuffer;
1435
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001436 while (userSize >= mFrameSize) {
1437 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001438
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001439 status_t err = obtainBuffer(&audioBuffer,
1440 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001441 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001442 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001443 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001444 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001445 return ssize_t(err);
1446 }
1447
1448 size_t toWrite;
Andy Hungabdb9902015-01-12 15:08:22 -08001449 toWrite = audioBuffer.size;
1450 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001451 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001452 userSize -= toWrite;
1453 written += toWrite;
1454
1455 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001456 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001457
1458 return written;
1459}
1460
1461// -------------------------------------------------------------------------
1462
John Grossman4ff14ba2012-02-08 16:37:41 -08001463TimedAudioTrack::TimedAudioTrack() {
1464 mIsTimed = true;
1465}
1466
1467status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1468{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001469 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001470 status_t result = UNKNOWN_ERROR;
1471
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001472#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001473 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1474 // while we are accessing the cblk
1475 sp<IAudioTrack> audioTrack = mAudioTrack;
1476 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001477#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001478
John Grossman4ff14ba2012-02-08 16:37:41 -08001479 // If the track is not invalid already, try to allocate a buffer. alloc
1480 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001481 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001482 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001483 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001484 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1485 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001486 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001487 }
1488 }
1489
1490 // If the track is invalid at this point, attempt to restore it. and try the
1491 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001492 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001493 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001494
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001495 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001496 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001497 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001498 }
1499
1500 return result;
1501}
1502
1503status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1504 int64_t pts)
1505{
Eric Laurentdf839842012-05-31 14:27:14 -07001506 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1507 {
1508 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001509 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001510 // restart track if it was disabled by audioflinger due to previous underrun
1511 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001512 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1513 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001514 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001515 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001516 mAudioTrack->start();
1517 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001518 }
Eric Laurentdf839842012-05-31 14:27:14 -07001519 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001520}
1521
1522status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1523 TargetTimeline target)
1524{
1525 return mAudioTrack->setMediaTimeTransform(xform, target);
1526}
1527
1528// -------------------------------------------------------------------------
1529
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001530nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001531{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001532 // Currently the AudioTrack thread is not created if there are no callbacks.
1533 // Would it ever make sense to run the thread, even without callbacks?
1534 // If so, then replace this by checks at each use for mCbf != NULL.
1535 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1536
Eric Laurent1703cdf2011-03-07 14:52:59 -08001537 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001538 if (mAwaitBoost) {
1539 mAwaitBoost = false;
1540 mLock.unlock();
1541 static const int32_t kMaxTries = 5;
1542 int32_t tryCounter = kMaxTries;
1543 uint32_t pollUs = 10000;
1544 do {
1545 int policy = sched_getscheduler(0);
1546 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1547 break;
1548 }
1549 usleep(pollUs);
1550 pollUs <<= 1;
1551 } while (tryCounter-- > 0);
1552 if (tryCounter < 0) {
1553 ALOGE("did not receive expected priority boost on time");
1554 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001555 // Run again immediately
1556 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001557 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001558
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001559 // Can only reference mCblk while locked
1560 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001561 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001562
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001563 // Check for track invalidation
1564 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001565 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1566 // AudioSystem cache. We should not exit here but after calling the callback so
1567 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001568 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001569 status_t status = restoreTrack_l("processAudioBuffer");
Andy Hung53c3b5f2014-12-15 16:42:05 -08001570 // after restoration, continue below to make sure that the loop and buffer events
1571 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001572 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001573 }
1574
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001575 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001576 bool active = mState == STATE_ACTIVE;
1577
1578 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1579 bool newUnderrun = false;
1580 if (flags & CBLK_UNDERRUN) {
1581#if 0
1582 // Currently in shared buffer mode, when the server reaches the end of buffer,
1583 // the track stays active in continuous underrun state. It's up to the application
1584 // to pause or stop the track, or set the position to a new offset within buffer.
1585 // This was some experimental code to auto-pause on underrun. Keeping it here
1586 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1587 if (mTransfer == TRANSFER_SHARED) {
1588 mState = STATE_PAUSED;
1589 active = false;
1590 }
1591#endif
1592 if (!mInUnderrun) {
1593 mInUnderrun = true;
1594 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001595 }
1596 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001597
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001598 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001599 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001600
1601 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001602 bool markerReached = false;
1603 size_t markerPosition = mMarkerPosition;
1604 // FIXME fails for wraparound, need 64 bits
1605 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1606 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001607 }
1608
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001609 // Determine number of new position callback(s) that will be needed, while locked
1610 size_t newPosCount = 0;
1611 size_t newPosition = mNewPosition;
1612 size_t updatePeriod = mUpdatePeriod;
1613 // FIXME fails for wraparound, need 64 bits
1614 if (updatePeriod > 0 && position >= newPosition) {
1615 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1616 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001617 }
1618
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001619 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001620 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001621 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001622 if (mRefreshRemaining) {
1623 mRefreshRemaining = false;
1624 mRemainingFrames = notificationFrames;
1625 mRetryOnPartialBuffer = false;
1626 }
1627 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001628 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001629 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001630
Andy Hung53c3b5f2014-12-15 16:42:05 -08001631 // Determine the number of new loop callback(s) that will be needed, while locked.
1632 int loopCountNotifications = 0;
1633 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1634
1635 if (mLoopCount > 0) {
1636 int loopCount;
1637 size_t bufferPosition;
1638 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1639 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1640 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1641 mLoopCountNotified = loopCount; // discard any excess notifications
1642 } else if (mLoopCount < 0) {
1643 // FIXME: We're not accurate with notification count and position with infinite looping
1644 // since loopCount from server side will always return -1 (we could decrement it).
1645 size_t bufferPosition = mStaticProxy->getBufferPosition();
1646 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1647 loopPeriod = mLoopEnd - bufferPosition;
1648 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1649 size_t bufferPosition = mStaticProxy->getBufferPosition();
1650 loopPeriod = mFrameCount - bufferPosition;
1651 }
1652
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001653 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08001654 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001655 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1656
1657 mLock.unlock();
1658
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001659 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001660 struct timespec timeout;
1661 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1662 timeout.tv_nsec = 0;
1663
Glenn Kasten96f04882013-09-20 09:28:56 -07001664 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001665 switch (status) {
1666 case NO_ERROR:
1667 case DEAD_OBJECT:
1668 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001669 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001670 {
1671 AutoMutex lock(mLock);
1672 // The previously assigned value of waitStreamEnd is no longer valid,
1673 // since the mutex has been unlocked and either the callback handler
1674 // or another thread could have re-started the AudioTrack during that time.
1675 waitStreamEnd = mState == STATE_STOPPING;
1676 if (waitStreamEnd) {
1677 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001678 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001679 }
1680 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001681 if (waitStreamEnd && status != DEAD_OBJECT) {
1682 return NS_INACTIVE;
1683 }
1684 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001685 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001686 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001687 }
1688
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001689 // perform callbacks while unlocked
1690 if (newUnderrun) {
1691 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1692 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001693 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001694 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001695 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001696 }
1697 if (flags & CBLK_BUFFER_END) {
1698 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1699 }
1700 if (markerReached) {
1701 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1702 }
1703 while (newPosCount > 0) {
1704 size_t temp = newPosition;
1705 mCbf(EVENT_NEW_POS, mUserData, &temp);
1706 newPosition += updatePeriod;
1707 newPosCount--;
1708 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001709
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001710 if (mObservedSequence != sequence) {
1711 mObservedSequence = sequence;
1712 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001713 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001714 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001715 return NS_INACTIVE;
1716 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001717 }
1718
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001719 // if inactive, then don't run me again until re-started
1720 if (!active) {
1721 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001722 }
1723
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001724 // Compute the estimated time until the next timed event (position, markers, loops)
1725 // FIXME only for non-compressed audio
1726 uint32_t minFrames = ~0;
1727 if (!markerReached && position < markerPosition) {
1728 minFrames = markerPosition - position;
1729 }
1730 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08001731 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001732 minFrames = loopPeriod;
1733 }
Andy Hung2d85f092015-01-07 12:45:13 -08001734 if (updatePeriod > 0) {
1735 minFrames = min(minFrames, uint32_t(newPosition - position));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001736 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001737
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001738 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1739 static const uint32_t kPoll = 0;
1740 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1741 minFrames = kPoll * notificationFrames;
1742 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001743
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001744 // Convert frame units to time units
1745 nsecs_t ns = NS_WHENEVER;
1746 if (minFrames != (uint32_t) ~0) {
1747 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1748 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1749 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1750 }
1751
1752 // If not supplying data by EVENT_MORE_DATA, then we're done
1753 if (mTransfer != TRANSFER_CALLBACK) {
1754 return ns;
1755 }
1756
1757 struct timespec timeout;
1758 const struct timespec *requested = &ClientProxy::kForever;
1759 if (ns != NS_WHENEVER) {
1760 timeout.tv_sec = ns / 1000000000LL;
1761 timeout.tv_nsec = ns % 1000000000LL;
1762 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1763 requested = &timeout;
1764 }
1765
1766 while (mRemainingFrames > 0) {
1767
1768 Buffer audioBuffer;
1769 audioBuffer.frameCount = mRemainingFrames;
1770 size_t nonContig;
1771 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1772 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001773 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001774 requested = &ClientProxy::kNonBlocking;
1775 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001776 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001777 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001778 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001779 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1780 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001781 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001782 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001783 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1784 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001785 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001786
Eric Laurent42a6f422013-08-29 14:35:05 -07001787 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001788 mRetryOnPartialBuffer = false;
1789 if (avail < mRemainingFrames) {
1790 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1791 if (ns < 0 || myns < ns) {
1792 ns = myns;
1793 }
1794 return ns;
1795 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001796 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001797
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001798 size_t reqSize = audioBuffer.size;
1799 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001800 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001801
1802 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001803 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001804 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1805 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001806 return NS_NEVER;
1807 }
1808
1809 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001810 // The callback is done filling buffers
1811 // Keep this thread going to handle timed events and
1812 // still try to get more data in intervals of WAIT_PERIOD_MS
1813 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001814 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001815 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001816
Andy Hungabdb9902015-01-12 15:08:22 -08001817 size_t releasedFrames = audioBuffer.size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001818 audioBuffer.frameCount = releasedFrames;
1819 mRemainingFrames -= releasedFrames;
1820 if (misalignment >= releasedFrames) {
1821 misalignment -= releasedFrames;
1822 } else {
1823 misalignment = 0;
1824 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001825
1826 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001827
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001828 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1829 // if callback doesn't like to accept the full chunk
1830 if (writtenSize < reqSize) {
1831 continue;
1832 }
1833
1834 // There could be enough non-contiguous frames available to satisfy the remaining request
1835 if (mRemainingFrames <= nonContig) {
1836 continue;
1837 }
1838
1839#if 0
1840 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1841 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1842 // that total to a sum == notificationFrames.
1843 if (0 < misalignment && misalignment <= mRemainingFrames) {
1844 mRemainingFrames = misalignment;
1845 return (mRemainingFrames * 1100000000LL) / sampleRate;
1846 }
1847#endif
1848
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001849 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001850 mRemainingFrames = notificationFrames;
1851 mRetryOnPartialBuffer = true;
1852
1853 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1854 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001855}
1856
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001857status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001858{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001859 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001860 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001861 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001862 status_t result;
1863
Glenn Kastena47f3162012-11-07 10:13:08 -08001864 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08001865 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001866 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001867
Eric Laurentab5cdba2014-06-09 17:22:27 -07001868 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001869 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001870 return DEAD_OBJECT;
1871 }
1872
Glenn Kasten200092b2014-08-15 15:13:30 -07001873 // save the old static buffer position
Andy Hung4ede21d2014-12-12 15:37:34 -08001874 size_t bufferPosition = 0;
1875 int loopCount = 0;
1876 if (mStaticProxy != 0) {
1877 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1878 }
Glenn Kasten200092b2014-08-15 15:13:30 -07001879
1880 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001881 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001882 // It will also delete the strong references on previous IAudioTrack and IMemory.
1883 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
1884 result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001885
1886 // take the frames that will be lost by track recreation into account in saved position
Andy Hung9b461582014-12-01 17:56:29 -08001887 // For streaming tracks, this is the amount we obtained from the user/client
1888 // (not the number actually consumed at the server - those are already lost).
Glenn Kasten200092b2014-08-15 15:13:30 -07001889 (void) updateAndGetPosition_l();
Andy Hung9b461582014-12-01 17:56:29 -08001890 if (mStaticProxy != 0) {
1891 mPosition = mReleased;
1892 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001893
Glenn Kastena47f3162012-11-07 10:13:08 -08001894 if (result == NO_ERROR) {
Andy Hung4ede21d2014-12-12 15:37:34 -08001895 // Continue playback from last known position and restore loop.
1896 if (mStaticProxy != 0) {
1897 if (loopCount != 0) {
1898 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
1899 mLoopStart, mLoopEnd, loopCount);
1900 } else {
1901 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001902 if (bufferPosition == mFrameCount) {
1903 ALOGD("restoring track at end of static buffer");
1904 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001905 }
1906 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001907 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001908 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001909 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001910 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001911 if (result != NO_ERROR) {
1912 ALOGW("restoreTrack_l() failed status %d", result);
1913 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001914 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001915 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001916
1917 return result;
1918}
1919
Glenn Kasten200092b2014-08-15 15:13:30 -07001920uint32_t AudioTrack::updateAndGetPosition_l()
1921{
1922 // This is the sole place to read server consumed frames
1923 uint32_t newServer = mProxy->getPosition();
1924 int32_t delta = newServer - mServer;
1925 mServer = newServer;
1926 // TODO There is controversy about whether there can be "negative jitter" in server position.
1927 // This should be investigated further, and if possible, it should be addressed.
1928 // A more definite failure mode is infrequent polling by client.
1929 // One could call (void)getPosition_l() in releaseBuffer(),
1930 // so mReleased and mPosition are always lock-step as best possible.
1931 // That should ensure delta never goes negative for infrequent polling
1932 // unless the server has more than 2^31 frames in its buffer,
1933 // in which case the use of uint32_t for these counters has bigger issues.
1934 if (delta < 0) {
1935 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
1936 delta = 0;
1937 }
1938 return mPosition += (uint32_t) delta;
1939}
1940
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001941status_t AudioTrack::setParameters(const String8& keyValuePairs)
1942{
1943 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001944 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001945}
1946
Glenn Kastence703742013-07-19 16:33:58 -07001947status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1948{
Glenn Kasten53cec222013-08-29 09:01:02 -07001949 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001950 // FIXME not implemented for fast tracks; should use proxy and SSQ
1951 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1952 return INVALID_OPERATION;
1953 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001954
1955 switch (mState) {
1956 case STATE_ACTIVE:
1957 case STATE_PAUSED:
1958 break; // handle below
1959 case STATE_FLUSHED:
1960 case STATE_STOPPED:
1961 return WOULD_BLOCK;
1962 case STATE_STOPPING:
1963 case STATE_PAUSED_STOPPING:
1964 if (!isOffloaded_l()) {
1965 return INVALID_OPERATION;
1966 }
1967 break; // offloaded tracks handled below
1968 default:
1969 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
1970 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07001971 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001972
Eric Laurent275e8e92014-11-30 15:14:47 -08001973 if (mCblk->mFlags & CBLK_INVALID) {
1974 restoreTrack_l("getTimestamp");
1975 }
1976
Glenn Kasten200092b2014-08-15 15:13:30 -07001977 // The presented frame count must always lag behind the consumed frame count.
1978 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07001979 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001980 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07001981 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001982 return status;
1983 }
1984 if (isOffloadedOrDirect_l()) {
1985 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
1986 // use cached paused position in case another offloaded track is running.
1987 timestamp.mPosition = mPausedPosition;
1988 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
1989 return NO_ERROR;
1990 }
1991
1992 // Check whether a pending flush or stop has completed, as those commands may
1993 // be asynchronous or return near finish.
1994 if (mStartUs != 0 && mSampleRate != 0) {
1995 static const int kTimeJitterUs = 100000; // 100 ms
1996 static const int k1SecUs = 1000000;
1997
1998 const int64_t timeNow = getNowUs();
1999
2000 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
2001 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
2002 if (timestampTimeUs < mStartUs) {
2003 return WOULD_BLOCK; // stale timestamp time, occurs before start.
2004 }
2005 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
2006 const int64_t deltaPositionByUs = timestamp.mPosition * 1000000LL / mSampleRate;
2007
2008 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2009 // Verify that the counter can't count faster than the sample rate
2010 // since the start time. If greater, then that means we have failed
2011 // to completely flush or stop the previous playing track.
2012 ALOGW("incomplete flush or stop:"
2013 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2014 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2015 timestamp.mPosition);
2016 return WOULD_BLOCK;
2017 }
2018 }
2019 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
2020 }
2021 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002022 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2023 (void) updateAndGetPosition_l();
2024 // Server consumed (mServer) and presented both use the same server time base,
2025 // and server consumed is always >= presented.
2026 // The delta between these represents the number of frames in the buffer pipeline.
2027 // If this delta between these is greater than the client position, it means that
2028 // actually presented is still stuck at the starting line (figuratively speaking),
2029 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
2030 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2031 return INVALID_OPERATION;
2032 }
2033 // Convert timestamp position from server time base to client time base.
2034 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2035 // But if we change it to 64-bit then this could fail.
2036 // If (mPosition - mServer) can be negative then should use:
2037 // (int32_t)(mPosition - mServer)
2038 timestamp.mPosition += mPosition - mServer;
2039 // Immediately after a call to getPosition_l(), mPosition and
2040 // mServer both represent the same frame position. mPosition is
2041 // in client's point of view, and mServer is in server's point of
2042 // view. So the difference between them is the "fudge factor"
2043 // between client and server views due to stop() and/or new
2044 // IAudioTrack. And timestamp.mPosition is initially in server's
2045 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002046 }
2047 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002048}
2049
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002050String8 AudioTrack::getParameters(const String8& keys)
2051{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002052 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002053 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002054 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002055 } else {
2056 return String8::empty();
2057 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002058}
2059
Glenn Kasten23a75452014-01-13 10:37:17 -08002060bool AudioTrack::isOffloaded() const
2061{
2062 AutoMutex lock(mLock);
2063 return isOffloaded_l();
2064}
2065
Eric Laurentab5cdba2014-06-09 17:22:27 -07002066bool AudioTrack::isDirect() const
2067{
2068 AutoMutex lock(mLock);
2069 return isDirect_l();
2070}
2071
2072bool AudioTrack::isOffloadedOrDirect() const
2073{
2074 AutoMutex lock(mLock);
2075 return isOffloadedOrDirect_l();
2076}
2077
2078
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002079status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002080{
2081
2082 const size_t SIZE = 256;
2083 char buffer[SIZE];
2084 String8 result;
2085
2086 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002087 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002088 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002089 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002090 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002091 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002092 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08002093 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002094 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002095 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002096 result.append(buffer);
2097 ::write(fd, result.string(), result.size());
2098 return NO_ERROR;
2099}
2100
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002101uint32_t AudioTrack::getUnderrunFrames() const
2102{
2103 AutoMutex lock(mLock);
2104 return mProxy->getUnderrunFrames();
2105}
2106
2107// =========================================================================
2108
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002109void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002110{
2111 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2112 if (audioTrack != 0) {
2113 AutoMutex lock(audioTrack->mLock);
2114 audioTrack->mProxy->binderDied();
2115 }
2116}
2117
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002118// =========================================================================
2119
2120AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002121 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2122 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002123{
2124}
2125
2126AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002127{
2128}
2129
2130bool AudioTrack::AudioTrackThread::threadLoop()
2131{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002132 {
2133 AutoMutex _l(mMyLock);
2134 if (mPaused) {
2135 mMyCond.wait(mMyLock);
2136 // caller will check for exitPending()
2137 return true;
2138 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002139 if (mIgnoreNextPausedInt) {
2140 mIgnoreNextPausedInt = false;
2141 mPausedInt = false;
2142 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002143 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002144 if (mPausedNs > 0) {
2145 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2146 } else {
2147 mMyCond.wait(mMyLock);
2148 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002149 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002150 return true;
2151 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002152 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002153 if (exitPending()) {
2154 return false;
2155 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002156 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002157 switch (ns) {
2158 case 0:
2159 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002160 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002161 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002162 return true;
2163 case NS_NEVER:
2164 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002165 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08002166 // Event driven: call wake() when callback notifications conditions change.
2167 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002168 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002169 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002170 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002171 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002172 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002173 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002174}
2175
Glenn Kasten3acbd052012-02-28 10:39:56 -08002176void AudioTrack::AudioTrackThread::requestExit()
2177{
2178 // must be in this order to avoid a race condition
2179 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002180 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002181}
2182
2183void AudioTrack::AudioTrackThread::pause()
2184{
2185 AutoMutex _l(mMyLock);
2186 mPaused = true;
2187}
2188
2189void AudioTrack::AudioTrackThread::resume()
2190{
2191 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002192 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002193 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002194 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002195 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002196 mMyCond.signal();
2197 }
2198}
2199
Andy Hung3c09c782014-12-29 18:39:32 -08002200void AudioTrack::AudioTrackThread::wake()
2201{
2202 AutoMutex _l(mMyLock);
2203 if (!mPaused && mPausedInt && mPausedNs > 0) {
2204 // audio track is active and internally paused with timeout.
2205 mIgnoreNextPausedInt = true;
2206 mPausedInt = false;
2207 mMyCond.signal();
2208 }
2209}
2210
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002211void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2212{
2213 AutoMutex _l(mMyLock);
2214 mPausedInt = true;
2215 mPausedNs = ns;
2216}
2217
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002218}; // namespace android