blob: 422ead1ee8e29a42de0bb20008965543b5c6bf36 [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
36
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
Glenn Kastene0fa4672012-04-24 14:35:14 -0700325 // AudioFlinger does not currently support 8-bit data in shared memory
326 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
327 ALOGE("8-bit data in shared memory is not supported");
328 return BAD_VALUE;
329 }
330
Eric Laurentc2f1f072009-07-17 12:17:14 -0700331 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100332 // or offload was requested
333 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
334 || !audio_is_linear_pcm(format)) {
335 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
336 ? "Offload request, forcing to Direct Output"
337 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700338 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800339 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700340 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700341 }
342
Eric Laurentd1f69b02014-12-15 14:33:13 -0800343 // force direct flag if HW A/V sync requested
344 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
345 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
346 }
347
Glenn Kastenb7730382014-04-30 15:50:31 -0700348 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
349 if (audio_is_linear_pcm(format)) {
350 mFrameSize = channelCount * audio_bytes_per_sample(format);
351 } else {
352 mFrameSize = sizeof(uint8_t);
353 }
354 mFrameSizeAF = mFrameSize;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800355 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700356 ALOG_ASSERT(audio_is_linear_pcm(format));
357 mFrameSize = channelCount * audio_bytes_per_sample(format);
358 mFrameSizeAF = channelCount * audio_bytes_per_sample(
359 format == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : format);
360 // createTrack will return an error if PCM format is not supported by server,
361 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800362 }
363
Eric Laurent0d6db582014-11-12 18:39:44 -0800364 // sampling rate must be specified for direct outputs
365 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
366 return BAD_VALUE;
367 }
368 mSampleRate = sampleRate;
369
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800370 // Make copy of input parameter offloadInfo so that in the future:
371 // (a) createTrack_l doesn't need it as an input parameter
372 // (b) we can support re-creation of offloaded tracks
373 if (offloadInfo != NULL) {
374 mOffloadInfoCopy = *offloadInfo;
375 mOffloadInfo = &mOffloadInfoCopy;
376 } else {
377 mOffloadInfo = NULL;
378 }
379
Glenn Kasten66e46352014-01-16 17:44:23 -0800380 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
381 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800382 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800383 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800384 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700385 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800386 mNotificationFramesAct = 0;
Eric Laurentcaf7f482014-11-25 17:50:47 -0800387 if (sessionId == AUDIO_SESSION_ALLOCATE) {
388 mSessionId = AudioSystem::newAudioUniqueId();
389 } else {
390 mSessionId = sessionId;
391 }
Marco Nelissend457c972014-02-11 08:47:07 -0800392 int callingpid = IPCThreadState::self()->getCallingPid();
393 int mypid = getpid();
394 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800395 mClientUid = IPCThreadState::self()->getCallingUid();
396 } else {
397 mClientUid = uid;
398 }
Marco Nelissend457c972014-02-11 08:47:07 -0800399 if (pid == -1 || (callingpid != mypid)) {
400 mClientPid = callingpid;
401 } else {
402 mClientPid = pid;
403 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700404 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700405 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700406 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700407
Glenn Kastena997e7a2012-08-07 09:44:19 -0700408 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700409 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700410 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
411 }
412
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800413 // create the IAudioTrack
Eric Laurent0d6db582014-11-12 18:39:44 -0800414 status_t status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800415
Glenn Kastena997e7a2012-08-07 09:44:19 -0700416 if (status != NO_ERROR) {
417 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100418 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
419 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700420 mAudioTrackThread.clear();
421 }
422 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700423 }
424
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800425 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800426 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800427 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800428 mLoopCount = 0;
429 mLoopStart = 0;
430 mLoopEnd = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800431 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700432 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800433 mNewPosition = 0;
434 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700435 mServer = 0;
436 mPosition = 0;
437 mReleased = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700438 mStartUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800439 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800440 mSequence = 1;
441 mObservedSequence = mSequence;
442 mInUnderrun = false;
443
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800444 return NO_ERROR;
445}
446
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800447// -------------------------------------------------------------------------
448
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100449status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800450{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800451 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100452
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800453 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100454 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800455 }
456
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800457 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800458
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800459 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100460 if (previousState == STATE_PAUSED_STOPPING) {
461 mState = STATE_STOPPING;
462 } else {
463 mState = STATE_ACTIVE;
464 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700465 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800466 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
467 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700468 mPosition = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700469 // For offloaded tracks, we don't know if the hardware counters are really zero here,
470 // since the flush is asynchronous and stop may not fully drain.
471 // We save the time when the track is started to later verify whether
472 // the counters are realistic (i.e. start from zero after this time).
473 mStartUs = getNowUs();
474
Eric Laurentec9a0322013-08-28 10:23:01 -0700475 // force refresh of remaining frames by processAudioBuffer() as last
476 // write before stop could be partial.
477 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800478 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700479 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700480 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800481
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800482 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800483 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100484 if (previousState == STATE_STOPPING) {
485 mProxy->interrupt();
486 } else {
487 t->resume();
488 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800489 } else {
490 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
491 get_sched_policy(0, &mPreviousSchedulingGroup);
492 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
493 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800494
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800495 status_t status = NO_ERROR;
496 if (!(flags & CBLK_INVALID)) {
497 status = mAudioTrack->start();
498 if (status == DEAD_OBJECT) {
499 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800500 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800501 }
502 if (flags & CBLK_INVALID) {
503 status = restoreTrack_l("start");
504 }
505
506 if (status != NO_ERROR) {
507 ALOGE("start() status %d", status);
508 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800509 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100510 if (previousState != STATE_STOPPING) {
511 t->pause();
512 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800513 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700514 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700515 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800516 }
517 }
518
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100519 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800520}
521
522void AudioTrack::stop()
523{
524 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700525 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800526 return;
527 }
528
Glenn Kasten23a75452014-01-13 10:37:17 -0800529 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100530 mState = STATE_STOPPING;
531 } else {
532 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -0700533 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100534 }
535
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800536 mProxy->interrupt();
537 mAudioTrack->stop();
538 // the playback head position will reset to 0, so if a marker is set, we need
539 // to activate it again
540 mMarkerReached = false;
Andy Hung9b461582014-12-01 17:56:29 -0800541
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800542 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800543 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800544 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
545 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800546 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100547
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800548 sp<AudioTrackThread> t = mAudioTrackThread;
549 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800550 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100551 t->pause();
552 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800553 } else {
554 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
555 set_sched_policy(0, mPreviousSchedulingGroup);
556 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800557}
558
559bool AudioTrack::stopped() const
560{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800561 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800562 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800563}
564
565void AudioTrack::flush()
566{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800567 if (mSharedBuffer != 0) {
568 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800569 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800570 AutoMutex lock(mLock);
571 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
572 return;
573 }
574 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800575}
576
Eric Laurent1703cdf2011-03-07 14:52:59 -0800577void AudioTrack::flush_l()
578{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800579 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700580
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700581 // clear playback marker and periodic update counter
582 mMarkerPosition = 0;
583 mMarkerReached = false;
584 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100585 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700586
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800587 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700588 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800589 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100590 mProxy->interrupt();
591 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800592 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800593 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800594}
595
596void AudioTrack::pause()
597{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800598 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100599 if (mState == STATE_ACTIVE) {
600 mState = STATE_PAUSED;
601 } else if (mState == STATE_STOPPING) {
602 mState = STATE_PAUSED_STOPPING;
603 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800604 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800605 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800606 mProxy->interrupt();
607 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800608
Marco Nelissen3a90f282014-03-10 11:21:43 -0700609 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700610 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700611 // An offload output can be re-used between two audio tracks having
612 // the same configuration. A timestamp query for a paused track
613 // while the other is running would return an incorrect time.
614 // To fix this, cache the playback position on a pause() and return
615 // this time when requested until the track is resumed.
616
617 // OffloadThread sends HAL pause in its threadLoop. Time saved
618 // here can be slightly off.
619
620 // TODO: check return code for getRenderPosition.
621
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800622 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800623 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
624 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
625 }
626 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800627}
628
Eric Laurentbe916aa2010-06-01 23:49:17 -0700629status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800630{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700631 // This duplicates a test by AudioTrack JNI, but that is not the only caller
632 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
633 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700634 return BAD_VALUE;
635 }
636
Eric Laurent1703cdf2011-03-07 14:52:59 -0800637 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800638 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
639 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800640
Glenn Kastenc56f3422014-03-21 17:53:17 -0700641 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700642
Glenn Kasten23a75452014-01-13 10:37:17 -0800643 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700644 mAudioTrack->signal();
645 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700646 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800647}
648
Glenn Kastenb1c09932012-02-27 16:21:04 -0800649status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800650{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800651 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700652}
653
Eric Laurent2beeb502010-07-16 07:43:46 -0700654status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700655{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700656 // This duplicates a test by AudioTrack JNI, but that is not the only caller
657 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700658 return BAD_VALUE;
659 }
660
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800661 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700662 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800663 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700664
665 return NO_ERROR;
666}
667
Glenn Kastena5224f32012-01-04 12:41:44 -0800668void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700669{
670 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800671 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700672 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800673}
674
Glenn Kasten3b16c762012-11-14 08:44:39 -0800675status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800676{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700677 if (mIsTimed || isOffloadedOrDirect()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800678 return INVALID_OPERATION;
679 }
680
Eric Laurent0d6db582014-11-12 18:39:44 -0800681 AutoMutex lock(mLock);
682 if (mOutput == AUDIO_IO_HANDLE_NONE) {
683 return NO_INIT;
684 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800685 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800686 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700687 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800688 }
Andy Hungcd044842014-08-07 11:04:34 -0700689 if (rate == 0 || rate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700690 return BAD_VALUE;
691 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800692
Glenn Kastene3aa6592012-12-04 12:22:46 -0800693 mSampleRate = rate;
694 mProxy->setSampleRate(rate);
695
Eric Laurent57326622009-07-07 07:10:45 -0700696 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800697}
698
Glenn Kastena5224f32012-01-04 12:41:44 -0800699uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800700{
John Grossman4ff14ba2012-02-08 16:37:41 -0800701 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800702 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800703 }
704
Eric Laurent1703cdf2011-03-07 14:52:59 -0800705 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700706
707 // sample rate can be updated during playback by the offloaded decoder so we need to
708 // query the HAL and update if needed.
709// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700710 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700711 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700712 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700713 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700714 if (status == NO_ERROR) {
715 mSampleRate = sampleRate;
716 }
717 }
718 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800719 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800720}
721
722status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
723{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700724 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800725 return INVALID_OPERATION;
726 }
727
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800728 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800729 ;
730 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
731 loopEnd - loopStart >= MIN_LOOP) {
732 ;
733 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800734 return BAD_VALUE;
735 }
736
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800737 AutoMutex lock(mLock);
738 // See setPosition() regarding setting parameters such as loop points or position while active
739 if (mState == STATE_ACTIVE) {
740 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700741 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800742 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800743 return NO_ERROR;
744}
745
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800746void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
747{
Andy Hung4ede21d2014-12-12 15:37:34 -0800748 // We do not update the periodic notification point.
749 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
750 mLoopCount = loopCount;
751 mLoopEnd = loopEnd;
752 mLoopStart = loopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800753 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
754}
755
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800756status_t AudioTrack::setMarkerPosition(uint32_t marker)
757{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700758 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700759 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700760 return INVALID_OPERATION;
761 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800762
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800763 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800764 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700765 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800766
767 return NO_ERROR;
768}
769
Glenn Kastena5224f32012-01-04 12:41:44 -0800770status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800771{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700772 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100773 return INVALID_OPERATION;
774 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700775 if (marker == NULL) {
776 return BAD_VALUE;
777 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800778
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800779 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800780 *marker = mMarkerPosition;
781
782 return NO_ERROR;
783}
784
785status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
786{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700787 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700788 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700789 return INVALID_OPERATION;
790 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800791
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800792 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700793 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800794 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800795
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800796 return NO_ERROR;
797}
798
Glenn Kastena5224f32012-01-04 12:41:44 -0800799status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800800{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700801 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100802 return INVALID_OPERATION;
803 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700804 if (updatePeriod == NULL) {
805 return BAD_VALUE;
806 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800807
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800808 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800809 *updatePeriod = mUpdatePeriod;
810
811 return NO_ERROR;
812}
813
814status_t AudioTrack::setPosition(uint32_t position)
815{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700816 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700817 return INVALID_OPERATION;
818 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800819 if (position > mFrameCount) {
820 return BAD_VALUE;
821 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800822
Eric Laurent1703cdf2011-03-07 14:52:59 -0800823 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800824 // Currently we require that the player is inactive before setting parameters such as position
825 // or loop points. Otherwise, there could be a race condition: the application could read the
826 // current position, compute a new position or loop parameters, and then set that position or
827 // loop parameters but it would do the "wrong" thing since the position has continued to advance
828 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
829 // to specify how it wants to handle such scenarios.
830 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700831 return INVALID_OPERATION;
832 }
Andy Hung9b461582014-12-01 17:56:29 -0800833 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -0700834 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800835 mStaticProxy->setBufferPosition(position);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800836 return NO_ERROR;
837}
838
Glenn Kasten200092b2014-08-15 15:13:30 -0700839status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800840{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700841 if (position == NULL) {
842 return BAD_VALUE;
843 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800844
Eric Laurent1703cdf2011-03-07 14:52:59 -0800845 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700846 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100847 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800848
Eric Laurentab5cdba2014-06-09 17:22:27 -0700849 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800850 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
851 *position = mPausedPosition;
852 return NO_ERROR;
853 }
854
Glenn Kasten142f5192014-03-25 17:44:59 -0700855 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100856 uint32_t halFrames;
857 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
858 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700859 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
860 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100861 *position = dspFrames;
862 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -0800863 if (mCblk->mFlags & CBLK_INVALID) {
864 restoreTrack_l("getPosition");
865 }
866
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100867 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700868 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
869 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100870 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800871 return NO_ERROR;
872}
873
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000874status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800875{
876 if (mSharedBuffer == 0 || mIsTimed) {
877 return INVALID_OPERATION;
878 }
879 if (position == NULL) {
880 return BAD_VALUE;
881 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800882
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800883 AutoMutex lock(mLock);
884 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800885 return NO_ERROR;
886}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800887
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800888status_t AudioTrack::reload()
889{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700890 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800891 return INVALID_OPERATION;
892 }
893
Eric Laurent1703cdf2011-03-07 14:52:59 -0800894 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800895 // See setPosition() regarding setting parameters such as loop points or position while active
896 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700897 return INVALID_OPERATION;
898 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800899 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800900 (void) updateAndGetPosition_l();
901 mPosition = 0;
902 // The documentation is not clear on the behavior of reload() and the restoration
903 // of loop count. Historically we have not restored loop count, start, end;
904 // rather we just reset the buffer position. However, restoring the last setLoop
905 // information makes sense if one desires to repeat playing a particular sound.
906 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800907 return NO_ERROR;
908}
909
Glenn Kasten38e905b2014-01-13 10:21:48 -0800910audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700911{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800912 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100913 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800914}
915
Eric Laurentbe916aa2010-06-01 23:49:17 -0700916status_t AudioTrack::attachAuxEffect(int effectId)
917{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800918 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700919 status_t status = mAudioTrack->attachAuxEffect(effectId);
920 if (status == NO_ERROR) {
921 mAuxEffectId = effectId;
922 }
923 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700924}
925
Eric Laurente83b55d2014-11-14 10:06:21 -0800926audio_stream_type_t AudioTrack::streamType() const
927{
928 if (mStreamType == AUDIO_STREAM_DEFAULT) {
929 return audio_attributes_to_stream_type(&mAttributes);
930 }
931 return mStreamType;
932}
933
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800934// -------------------------------------------------------------------------
935
Eric Laurent1703cdf2011-03-07 14:52:59 -0800936// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -0700937status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800938{
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800939 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
940 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700941 ALOGE("Could not get audioflinger");
942 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800943 }
944
Eric Laurente83b55d2014-11-14 10:06:21 -0800945 audio_io_handle_t output;
946 audio_stream_type_t streamType = mStreamType;
947 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
948 status_t status = AudioSystem::getOutputForAttr(attr, &output,
949 (audio_session_t)mSessionId, &streamType,
950 mSampleRate, mFormat, mChannelMask,
951 mFlags, mOffloadInfo);
952
953
954 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700955 ALOGE("Could not get audio output for stream type %d, usage %d, sample rate %u, format %#x,"
956 " channel mask %#x, flags %#x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800957 streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800958 return BAD_VALUE;
959 }
960 {
961 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
962 // we must release it ourselves if anything goes wrong.
963
Glenn Kastence8828a2013-09-16 18:07:38 -0700964 // Not all of these values are needed under all conditions, but it is easier to get them all
965
Eric Laurentd1b449a2010-05-14 03:26:45 -0700966 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -0700967 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700968 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800969 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800970 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700971 }
972
Glenn Kastence8828a2013-09-16 18:07:38 -0700973 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700974 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -0700975 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700976 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800977 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700978 }
979
980 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700981 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -0700982 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700983 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800984 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700985 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800986 if (mSampleRate == 0) {
987 mSampleRate = afSampleRate;
988 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700989 // Client decides whether the track is TIMED (see below), but can only express a preference
990 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800991 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700992 // either of these use cases:
993 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -0800994 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -0800995 // use case 2: callback transfer mode
996 (mTransfer == TRANSFER_CALLBACK)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800997 // matching sample rate
998 (mSampleRate == afSampleRate))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800999 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -07001000 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001001 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001002 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001003 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001004
Glenn Kastence8828a2013-09-16 18:07:38 -07001005 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -08001006 // n = 1 fast track with single buffering; nBuffering is ignored
1007 // n = 2 fast track with double buffering
Glenn Kastence8828a2013-09-16 18:07:38 -07001008 // n = 2 normal track, no sample rate conversion
1009 // n = 3 normal track, with sample rate conversion
1010 // (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering)
1011 // n > 3 very high latency or very small notification interval; nBuffering is ignored
Glenn Kasten363fb752014-01-15 12:27:31 -08001012 const uint32_t nBuffering = (mSampleRate == afSampleRate) ? 2 : 3;
Glenn Kastence8828a2013-09-16 18:07:38 -07001013
Eric Laurentd1b449a2010-05-14 03:26:45 -07001014 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001015
Glenn Kasten363fb752014-01-15 12:27:31 -08001016 size_t frameCount = mReqFrameCount;
1017 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001018
Glenn Kasten363fb752014-01-15 12:27:31 -08001019 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001020 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001021 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001022 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001023 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001024 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001025 if (mNotificationFramesAct != frameCount) {
1026 mNotificationFramesAct = frameCount;
1027 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001028 } else if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001029
Glenn Kastena42ff002012-11-14 12:47:55 -08001030 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -07001031 // 8-bit data in shared memory is not currently supported by AudioFlinger
Glenn Kastenb7730382014-04-30 15:50:31 -07001032 size_t alignment = audio_bytes_per_sample(
1033 mFormat == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : mFormat);
1034 if (alignment & 1) {
1035 alignment = 1;
1036 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001037 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001038 // More than 2 channels does not require stronger alignment than stereo
1039 alignment <<= 1;
1040 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001041 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001042 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001043 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001044 status = BAD_VALUE;
1045 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001046 }
1047
1048 // When initializing a shared buffer AudioTrack via constructors,
1049 // there's no frameCount parameter.
1050 // But when initializing a shared buffer AudioTrack via set(),
1051 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kastenb7730382014-04-30 15:50:31 -07001052 frameCount = mSharedBuffer->size() / mFrameSizeAF;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001053
Glenn Kasten363fb752014-01-15 12:27:31 -08001054 } else if (!(mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001055
1056 // FIXME move these calculations and associated checks to server
Glenn Kastene0fa4672012-04-24 14:35:14 -07001057
Eric Laurentd1b449a2010-05-14 03:26:45 -07001058 // Ensure that buffer depth covers at least audio hardware latency
1059 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001060 ALOGV("afFrameCount=%zu, minBufCount=%d, afSampleRate=%u, afLatency=%d",
Glenn Kastenbb6f0a02013-06-03 15:00:29 -07001061 afFrameCount, minBufCount, afSampleRate, afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001062 if (minBufCount <= nBuffering) {
1063 minBufCount = nBuffering;
Glenn Kasten7c027242012-12-26 14:43:16 -08001064 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001065
Andy Hungcd044842014-08-07 11:04:34 -07001066 size_t minFrameCount = afFrameCount * minBufCount * uint64_t(mSampleRate) / afSampleRate;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001067 ALOGV("minFrameCount: %zu, afFrameCount=%zu, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -08001068 ", afLatency=%d",
Glenn Kasten363fb752014-01-15 12:27:31 -08001069 minFrameCount, afFrameCount, minBufCount, mSampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001070
1071 if (frameCount == 0) {
1072 frameCount = minFrameCount;
Glenn Kastence8828a2013-09-16 18:07:38 -07001073 } else if (frameCount < minFrameCount) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001074 // not ALOGW because it happens all the time when playing key clicks over A2DP
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001075 ALOGV("Minimum buffer size corrected from %zu to %zu",
Glenn Kastene0fa4672012-04-24 14:35:14 -07001076 frameCount, minFrameCount);
1077 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001078 }
Glenn Kastence8828a2013-09-16 18:07:38 -07001079 // Make sure that application is notified with sufficient margin before underrun
1080 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1081 mNotificationFramesAct = frameCount/nBuffering;
1082 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001083
Glenn Kastene0fa4672012-04-24 14:35:14 -07001084 } else {
1085 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -07001086 }
1087
Glenn Kastena075db42012-03-06 11:22:44 -08001088 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1089 if (mIsTimed) {
1090 trackFlags |= IAudioFlinger::TRACK_TIMED;
1091 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001092
1093 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001094 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001095 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001096 if (mAudioTrackThread != 0) {
1097 tid = mAudioTrackThread->getTid();
1098 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001099 }
1100
Glenn Kasten363fb752014-01-15 12:27:31 -08001101 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001102 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1103 }
1104
Eric Laurentab5cdba2014-06-09 17:22:27 -07001105 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1106 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1107 }
1108
Glenn Kasten74935e42013-12-19 08:56:45 -08001109 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1110 // but we will still need the original value also
Eric Laurente83b55d2014-11-14 10:06:21 -08001111 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001112 mSampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -07001113 // AudioFlinger only sees 16-bit PCM
Glenn Kastenc4b88a82014-04-30 16:54:30 -07001114 mFormat == AUDIO_FORMAT_PCM_8_BIT &&
1115 !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ?
Glenn Kasten363fb752014-01-15 12:27:31 -08001116 AUDIO_FORMAT_PCM_16_BIT : mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001117 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001118 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001119 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001120 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001121 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001122 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001123 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001124 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001125 &status);
1126
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001127 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001128 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001129 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001130 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001131 ALOG_ASSERT(track != 0);
1132
Glenn Kasten38e905b2014-01-13 10:21:48 -08001133 // AudioFlinger now owns the reference to the I/O handle,
1134 // so we are no longer responsible for releasing it.
1135
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001136 sp<IMemory> iMem = track->getCblk();
1137 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001138 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001139 return NO_INIT;
1140 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001141 void *iMemPointer = iMem->pointer();
1142 if (iMemPointer == NULL) {
1143 ALOGE("Could not get control block pointer");
1144 return NO_INIT;
1145 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001146 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001147 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001148 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001149 mDeathNotifier.clear();
1150 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001151 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001152 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001153 IPCThreadState::self()->flushCommands();
1154
Glenn Kasten0cde0762014-01-16 15:06:36 -08001155 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001156 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001157 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001158 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1159 // In current design, AudioTrack client checks and ensures frame count validity before
1160 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1161 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001162 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001163 }
1164 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001165
Glenn Kastena07f17c2013-04-23 12:39:37 -07001166 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001167 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001168 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001169 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001170 mAwaitBoost = true;
Glenn Kasten363fb752014-01-15 12:27:31 -08001171 if (mSharedBuffer == 0) {
Glenn Kastenb5fed682013-12-03 09:06:43 -08001172 // Theoretically double-buffering is not required for fast tracks,
1173 // due to tighter scheduling. But in practice, to accommodate kernels with
1174 // scheduling jitter, and apps with computation jitter, we use double-buffering.
1175 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1176 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001177 }
1178 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001179 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001180 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001181 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001182 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1183 if (mSharedBuffer == 0) {
Glenn Kastence8828a2013-09-16 18:07:38 -07001184 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1185 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001186 }
1187 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001188 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001189 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001190 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001191 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1192 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1193 } else {
1194 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001195 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001196 // FIXME This is a warning, not an error, so don't return error status
1197 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001198 }
1199 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001200 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1201 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1202 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1203 } else {
1204 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1205 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1206 // FIXME This is a warning, not an error, so don't return error status
1207 //return NO_INIT;
1208 }
1209 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001210
Glenn Kasten38e905b2014-01-13 10:21:48 -08001211 // We retain a copy of the I/O handle, but don't own the reference
1212 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001213 mRefreshRemaining = true;
1214
1215 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1216 // is the value of pointer() for the shared buffer, otherwise buffers points
1217 // immediately after the control block. This address is for the mapping within client
1218 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1219 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001220 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001221 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001222 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001223 buffers = mSharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001224 }
1225
Eric Laurent2beeb502010-07-16 07:43:46 -07001226 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001227 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001228 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001229
Glenn Kastenb6037442012-11-14 13:42:25 -08001230 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001231 // If IAudioTrack is re-created, don't let the requested frameCount
1232 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001233 if (frameCount > mReqFrameCount) {
1234 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001235 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001236
1237 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001238 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001239 mStaticProxy.clear();
1240 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1241 } else {
1242 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1243 mProxy = mStaticProxy;
1244 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001245
1246 mProxy->setVolumeLR(gain_minifloat_pack(
1247 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1248 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1249
Glenn Kastene3aa6592012-12-04 12:22:46 -08001250 mProxy->setSendLevel(mSendLevel);
1251 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001252 mProxy->setMinimum(mNotificationFramesAct);
1253
1254 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001255 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001256
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001257 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001258 }
1259
1260release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001261 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001262 if (status == NO_ERROR) {
1263 status = NO_INIT;
1264 }
1265 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001266}
1267
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001268status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1269{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001270 if (audioBuffer == NULL) {
1271 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001272 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001273 if (mTransfer != TRANSFER_OBTAIN) {
1274 audioBuffer->frameCount = 0;
1275 audioBuffer->size = 0;
1276 audioBuffer->raw = NULL;
1277 return INVALID_OPERATION;
1278 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001279
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001280 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001281 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001282 if (waitCount == -1) {
1283 requested = &ClientProxy::kForever;
1284 } else if (waitCount == 0) {
1285 requested = &ClientProxy::kNonBlocking;
1286 } else if (waitCount > 0) {
1287 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001288 timeout.tv_sec = ms / 1000;
1289 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1290 requested = &timeout;
1291 } else {
1292 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1293 requested = NULL;
1294 }
1295 return obtainBuffer(audioBuffer, requested);
1296}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001297
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001298status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1299 struct timespec *elapsed, size_t *nonContig)
1300{
1301 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1302 uint32_t oldSequence = 0;
1303 uint32_t newSequence;
1304
1305 Proxy::Buffer buffer;
1306 status_t status = NO_ERROR;
1307
1308 static const int32_t kMaxTries = 5;
1309 int32_t tryCounter = kMaxTries;
1310
1311 do {
1312 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1313 // keep them from going away if another thread re-creates the track during obtainBuffer()
1314 sp<AudioTrackClientProxy> proxy;
1315 sp<IMemory> iMem;
1316
1317 { // start of lock scope
1318 AutoMutex lock(mLock);
1319
1320 newSequence = mSequence;
1321 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1322 if (status == DEAD_OBJECT) {
1323 // re-create track, unless someone else has already done so
1324 if (newSequence == oldSequence) {
1325 status = restoreTrack_l("obtainBuffer");
1326 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001327 buffer.mFrameCount = 0;
1328 buffer.mRaw = NULL;
1329 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001330 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001331 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001332 }
1333 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001334 oldSequence = newSequence;
1335
1336 // Keep the extra references
1337 proxy = mProxy;
1338 iMem = mCblkMemory;
1339
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001340 if (mState == STATE_STOPPING) {
1341 status = -EINTR;
1342 buffer.mFrameCount = 0;
1343 buffer.mRaw = NULL;
1344 buffer.mNonContig = 0;
1345 break;
1346 }
1347
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001348 // Non-blocking if track is stopped or paused
1349 if (mState != STATE_ACTIVE) {
1350 requested = &ClientProxy::kNonBlocking;
1351 }
1352
1353 } // end of lock scope
1354
1355 buffer.mFrameCount = audioBuffer->frameCount;
1356 // FIXME starts the requested timeout and elapsed over from scratch
1357 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1358
1359 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1360
1361 audioBuffer->frameCount = buffer.mFrameCount;
1362 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1363 audioBuffer->raw = buffer.mRaw;
1364 if (nonContig != NULL) {
1365 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001366 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001367 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001368}
1369
1370void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1371{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001372 if (mTransfer == TRANSFER_SHARED) {
1373 return;
1374 }
1375
1376 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1377 if (stepCount == 0) {
1378 return;
1379 }
1380
1381 Proxy::Buffer buffer;
1382 buffer.mFrameCount = stepCount;
1383 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001384
Eric Laurent1703cdf2011-03-07 14:52:59 -08001385 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001386 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001387 mInUnderrun = false;
1388 mProxy->releaseBuffer(&buffer);
1389
1390 // restart track if it was disabled by audioflinger due to previous underrun
1391 if (mState == STATE_ACTIVE) {
1392 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001393 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001394 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001395 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001396 mAudioTrack->start();
1397 }
1398 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001399}
1400
1401// -------------------------------------------------------------------------
1402
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001403ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001404{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001405 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001406 return INVALID_OPERATION;
1407 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001408
Eric Laurentab5cdba2014-06-09 17:22:27 -07001409 if (isDirect()) {
1410 AutoMutex lock(mLock);
1411 int32_t flags = android_atomic_and(
1412 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1413 &mCblk->mFlags);
1414 if (flags & CBLK_INVALID) {
1415 return DEAD_OBJECT;
1416 }
1417 }
1418
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001419 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001420 // Sanity-check: user is most-likely passing an error code, and it would
1421 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001422 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001423 return BAD_VALUE;
1424 }
1425
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001426 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001427 Buffer audioBuffer;
1428
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001429 while (userSize >= mFrameSize) {
1430 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001431
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001432 status_t err = obtainBuffer(&audioBuffer,
1433 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001434 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001435 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001436 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001437 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001438 return ssize_t(err);
1439 }
1440
1441 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001442 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001443 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001444 toWrite = audioBuffer.size >> 1;
1445 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001446 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001447 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001448 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001449 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001450 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001451 userSize -= toWrite;
1452 written += toWrite;
1453
1454 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001455 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001456
1457 return written;
1458}
1459
1460// -------------------------------------------------------------------------
1461
John Grossman4ff14ba2012-02-08 16:37:41 -08001462TimedAudioTrack::TimedAudioTrack() {
1463 mIsTimed = true;
1464}
1465
1466status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1467{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001468 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001469 status_t result = UNKNOWN_ERROR;
1470
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001471#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001472 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1473 // while we are accessing the cblk
1474 sp<IAudioTrack> audioTrack = mAudioTrack;
1475 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001476#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001477
John Grossman4ff14ba2012-02-08 16:37:41 -08001478 // If the track is not invalid already, try to allocate a buffer. alloc
1479 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001480 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001481 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001482 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001483 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1484 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001485 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001486 }
1487 }
1488
1489 // If the track is invalid at this point, attempt to restore it. and try the
1490 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001491 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001492 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001493
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001494 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001495 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001496 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001497 }
1498
1499 return result;
1500}
1501
1502status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1503 int64_t pts)
1504{
Eric Laurentdf839842012-05-31 14:27:14 -07001505 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1506 {
1507 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001508 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001509 // restart track if it was disabled by audioflinger due to previous underrun
1510 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001511 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1512 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001513 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001514 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001515 mAudioTrack->start();
1516 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001517 }
Eric Laurentdf839842012-05-31 14:27:14 -07001518 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001519}
1520
1521status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1522 TargetTimeline target)
1523{
1524 return mAudioTrack->setMediaTimeTransform(xform, target);
1525}
1526
1527// -------------------------------------------------------------------------
1528
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001529nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001530{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001531 // Currently the AudioTrack thread is not created if there are no callbacks.
1532 // Would it ever make sense to run the thread, even without callbacks?
1533 // If so, then replace this by checks at each use for mCbf != NULL.
1534 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1535
Eric Laurent1703cdf2011-03-07 14:52:59 -08001536 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001537 if (mAwaitBoost) {
1538 mAwaitBoost = false;
1539 mLock.unlock();
1540 static const int32_t kMaxTries = 5;
1541 int32_t tryCounter = kMaxTries;
1542 uint32_t pollUs = 10000;
1543 do {
1544 int policy = sched_getscheduler(0);
1545 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1546 break;
1547 }
1548 usleep(pollUs);
1549 pollUs <<= 1;
1550 } while (tryCounter-- > 0);
1551 if (tryCounter < 0) {
1552 ALOGE("did not receive expected priority boost on time");
1553 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001554 // Run again immediately
1555 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001556 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001557
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001558 // Can only reference mCblk while locked
1559 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001560 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001561
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001562 // Check for track invalidation
1563 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001564 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1565 // AudioSystem cache. We should not exit here but after calling the callback so
1566 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001567 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001568 status_t status = restoreTrack_l("processAudioBuffer");
1569 mLock.unlock();
1570 // Run again immediately, but with a new IAudioTrack
1571 return 0;
1572 }
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
Andy Hung4ede21d2014-12-12 15:37:34 -08001620 uint32_t loopPeriod = mLoopCount != 0 ? mLoopEnd - mLoopStart : 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001621 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001622 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001623 if (mRefreshRemaining) {
1624 mRefreshRemaining = false;
1625 mRemainingFrames = notificationFrames;
1626 mRetryOnPartialBuffer = false;
1627 }
1628 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001629 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001630 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001631
1632 // These fields don't need to be cached, because they are assigned only by set():
1633 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1634 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1635
1636 mLock.unlock();
1637
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001638 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001639 struct timespec timeout;
1640 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1641 timeout.tv_nsec = 0;
1642
Glenn Kasten96f04882013-09-20 09:28:56 -07001643 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001644 switch (status) {
1645 case NO_ERROR:
1646 case DEAD_OBJECT:
1647 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001648 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001649 {
1650 AutoMutex lock(mLock);
1651 // The previously assigned value of waitStreamEnd is no longer valid,
1652 // since the mutex has been unlocked and either the callback handler
1653 // or another thread could have re-started the AudioTrack during that time.
1654 waitStreamEnd = mState == STATE_STOPPING;
1655 if (waitStreamEnd) {
1656 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001657 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001658 }
1659 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001660 if (waitStreamEnd && status != DEAD_OBJECT) {
1661 return NS_INACTIVE;
1662 }
1663 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001664 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001665 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001666 }
1667
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001668 // perform callbacks while unlocked
1669 if (newUnderrun) {
1670 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1671 }
1672 // FIXME we will miss loops if loop cycle was signaled several times since last call
1673 // to processAudioBuffer()
1674 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1675 mCbf(EVENT_LOOP_END, mUserData, NULL);
1676 }
1677 if (flags & CBLK_BUFFER_END) {
1678 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1679 }
1680 if (markerReached) {
1681 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1682 }
1683 while (newPosCount > 0) {
1684 size_t temp = newPosition;
1685 mCbf(EVENT_NEW_POS, mUserData, &temp);
1686 newPosition += updatePeriod;
1687 newPosCount--;
1688 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001689
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001690 if (mObservedSequence != sequence) {
1691 mObservedSequence = sequence;
1692 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001693 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001694 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001695 return NS_INACTIVE;
1696 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001697 }
1698
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001699 // if inactive, then don't run me again until re-started
1700 if (!active) {
1701 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001702 }
1703
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001704 // Compute the estimated time until the next timed event (position, markers, loops)
1705 // FIXME only for non-compressed audio
1706 uint32_t minFrames = ~0;
1707 if (!markerReached && position < markerPosition) {
1708 minFrames = markerPosition - position;
1709 }
1710 if (loopPeriod > 0 && loopPeriod < minFrames) {
1711 minFrames = loopPeriod;
1712 }
1713 if (updatePeriod > 0 && updatePeriod < minFrames) {
1714 minFrames = updatePeriod;
1715 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001716
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001717 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1718 static const uint32_t kPoll = 0;
1719 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1720 minFrames = kPoll * notificationFrames;
1721 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001722
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001723 // Convert frame units to time units
1724 nsecs_t ns = NS_WHENEVER;
1725 if (minFrames != (uint32_t) ~0) {
1726 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1727 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1728 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1729 }
1730
1731 // If not supplying data by EVENT_MORE_DATA, then we're done
1732 if (mTransfer != TRANSFER_CALLBACK) {
1733 return ns;
1734 }
1735
1736 struct timespec timeout;
1737 const struct timespec *requested = &ClientProxy::kForever;
1738 if (ns != NS_WHENEVER) {
1739 timeout.tv_sec = ns / 1000000000LL;
1740 timeout.tv_nsec = ns % 1000000000LL;
1741 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1742 requested = &timeout;
1743 }
1744
1745 while (mRemainingFrames > 0) {
1746
1747 Buffer audioBuffer;
1748 audioBuffer.frameCount = mRemainingFrames;
1749 size_t nonContig;
1750 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1751 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001752 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001753 requested = &ClientProxy::kNonBlocking;
1754 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001755 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001756 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001757 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001758 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1759 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001760 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001761 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001762 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1763 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001764 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001765
Eric Laurent42a6f422013-08-29 14:35:05 -07001766 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001767 mRetryOnPartialBuffer = false;
1768 if (avail < mRemainingFrames) {
1769 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1770 if (ns < 0 || myns < ns) {
1771 ns = myns;
1772 }
1773 return ns;
1774 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001775 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001776
1777 // Divide buffer size by 2 to take into account the expansion
1778 // due to 8 to 16 bit conversion: the callback must fill only half
1779 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001780 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001781 audioBuffer.size >>= 1;
1782 }
1783
1784 size_t reqSize = audioBuffer.size;
1785 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001786 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001787
1788 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001789 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001790 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1791 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001792 return NS_NEVER;
1793 }
1794
1795 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001796 // The callback is done filling buffers
1797 // Keep this thread going to handle timed events and
1798 // still try to get more data in intervals of WAIT_PERIOD_MS
1799 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001800 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001801 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001802
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001803 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001804 // 8 to 16 bit conversion, note that source and destination are the same address
1805 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001806 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001807 }
1808
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001809 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1810 audioBuffer.frameCount = releasedFrames;
1811 mRemainingFrames -= releasedFrames;
1812 if (misalignment >= releasedFrames) {
1813 misalignment -= releasedFrames;
1814 } else {
1815 misalignment = 0;
1816 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001817
1818 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001819
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001820 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1821 // if callback doesn't like to accept the full chunk
1822 if (writtenSize < reqSize) {
1823 continue;
1824 }
1825
1826 // There could be enough non-contiguous frames available to satisfy the remaining request
1827 if (mRemainingFrames <= nonContig) {
1828 continue;
1829 }
1830
1831#if 0
1832 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1833 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1834 // that total to a sum == notificationFrames.
1835 if (0 < misalignment && misalignment <= mRemainingFrames) {
1836 mRemainingFrames = misalignment;
1837 return (mRemainingFrames * 1100000000LL) / sampleRate;
1838 }
1839#endif
1840
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001841 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001842 mRemainingFrames = notificationFrames;
1843 mRetryOnPartialBuffer = true;
1844
1845 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1846 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001847}
1848
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001849status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001850{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001851 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001852 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001853 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001854 status_t result;
1855
Glenn Kastena47f3162012-11-07 10:13:08 -08001856 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08001857 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001858 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001859
Eric Laurentab5cdba2014-06-09 17:22:27 -07001860 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001861 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001862 return DEAD_OBJECT;
1863 }
1864
Glenn Kasten200092b2014-08-15 15:13:30 -07001865 // save the old static buffer position
Andy Hung4ede21d2014-12-12 15:37:34 -08001866 size_t bufferPosition = 0;
1867 int loopCount = 0;
1868 if (mStaticProxy != 0) {
1869 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1870 }
Glenn Kasten200092b2014-08-15 15:13:30 -07001871
1872 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001873 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001874 // It will also delete the strong references on previous IAudioTrack and IMemory.
1875 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
1876 result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001877
1878 // take the frames that will be lost by track recreation into account in saved position
Andy Hung9b461582014-12-01 17:56:29 -08001879 // For streaming tracks, this is the amount we obtained from the user/client
1880 // (not the number actually consumed at the server - those are already lost).
Glenn Kasten200092b2014-08-15 15:13:30 -07001881 (void) updateAndGetPosition_l();
Andy Hung9b461582014-12-01 17:56:29 -08001882 if (mStaticProxy != 0) {
1883 mPosition = mReleased;
1884 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001885
Glenn Kastena47f3162012-11-07 10:13:08 -08001886 if (result == NO_ERROR) {
Andy Hung4ede21d2014-12-12 15:37:34 -08001887 // Continue playback from last known position and restore loop.
1888 if (mStaticProxy != 0) {
1889 if (loopCount != 0) {
1890 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
1891 mLoopStart, mLoopEnd, loopCount);
1892 } else {
1893 mStaticProxy->setBufferPosition(bufferPosition);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001894 }
1895 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001896 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001897 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001898 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001899 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001900 if (result != NO_ERROR) {
1901 ALOGW("restoreTrack_l() failed status %d", result);
1902 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001903 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001904 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001905
1906 return result;
1907}
1908
Glenn Kasten200092b2014-08-15 15:13:30 -07001909uint32_t AudioTrack::updateAndGetPosition_l()
1910{
1911 // This is the sole place to read server consumed frames
1912 uint32_t newServer = mProxy->getPosition();
1913 int32_t delta = newServer - mServer;
1914 mServer = newServer;
1915 // TODO There is controversy about whether there can be "negative jitter" in server position.
1916 // This should be investigated further, and if possible, it should be addressed.
1917 // A more definite failure mode is infrequent polling by client.
1918 // One could call (void)getPosition_l() in releaseBuffer(),
1919 // so mReleased and mPosition are always lock-step as best possible.
1920 // That should ensure delta never goes negative for infrequent polling
1921 // unless the server has more than 2^31 frames in its buffer,
1922 // in which case the use of uint32_t for these counters has bigger issues.
1923 if (delta < 0) {
1924 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
1925 delta = 0;
1926 }
1927 return mPosition += (uint32_t) delta;
1928}
1929
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001930status_t AudioTrack::setParameters(const String8& keyValuePairs)
1931{
1932 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001933 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001934}
1935
Glenn Kastence703742013-07-19 16:33:58 -07001936status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1937{
Glenn Kasten53cec222013-08-29 09:01:02 -07001938 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001939 // FIXME not implemented for fast tracks; should use proxy and SSQ
1940 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1941 return INVALID_OPERATION;
1942 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001943
1944 switch (mState) {
1945 case STATE_ACTIVE:
1946 case STATE_PAUSED:
1947 break; // handle below
1948 case STATE_FLUSHED:
1949 case STATE_STOPPED:
1950 return WOULD_BLOCK;
1951 case STATE_STOPPING:
1952 case STATE_PAUSED_STOPPING:
1953 if (!isOffloaded_l()) {
1954 return INVALID_OPERATION;
1955 }
1956 break; // offloaded tracks handled below
1957 default:
1958 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
1959 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07001960 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001961
Eric Laurent275e8e92014-11-30 15:14:47 -08001962 if (mCblk->mFlags & CBLK_INVALID) {
1963 restoreTrack_l("getTimestamp");
1964 }
1965
Glenn Kasten200092b2014-08-15 15:13:30 -07001966 // The presented frame count must always lag behind the consumed frame count.
1967 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07001968 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001969 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07001970 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001971 return status;
1972 }
1973 if (isOffloadedOrDirect_l()) {
1974 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
1975 // use cached paused position in case another offloaded track is running.
1976 timestamp.mPosition = mPausedPosition;
1977 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
1978 return NO_ERROR;
1979 }
1980
1981 // Check whether a pending flush or stop has completed, as those commands may
1982 // be asynchronous or return near finish.
1983 if (mStartUs != 0 && mSampleRate != 0) {
1984 static const int kTimeJitterUs = 100000; // 100 ms
1985 static const int k1SecUs = 1000000;
1986
1987 const int64_t timeNow = getNowUs();
1988
1989 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
1990 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
1991 if (timestampTimeUs < mStartUs) {
1992 return WOULD_BLOCK; // stale timestamp time, occurs before start.
1993 }
1994 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
1995 const int64_t deltaPositionByUs = timestamp.mPosition * 1000000LL / mSampleRate;
1996
1997 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
1998 // Verify that the counter can't count faster than the sample rate
1999 // since the start time. If greater, then that means we have failed
2000 // to completely flush or stop the previous playing track.
2001 ALOGW("incomplete flush or stop:"
2002 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2003 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2004 timestamp.mPosition);
2005 return WOULD_BLOCK;
2006 }
2007 }
2008 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
2009 }
2010 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002011 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2012 (void) updateAndGetPosition_l();
2013 // Server consumed (mServer) and presented both use the same server time base,
2014 // and server consumed is always >= presented.
2015 // The delta between these represents the number of frames in the buffer pipeline.
2016 // If this delta between these is greater than the client position, it means that
2017 // actually presented is still stuck at the starting line (figuratively speaking),
2018 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
2019 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2020 return INVALID_OPERATION;
2021 }
2022 // Convert timestamp position from server time base to client time base.
2023 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2024 // But if we change it to 64-bit then this could fail.
2025 // If (mPosition - mServer) can be negative then should use:
2026 // (int32_t)(mPosition - mServer)
2027 timestamp.mPosition += mPosition - mServer;
2028 // Immediately after a call to getPosition_l(), mPosition and
2029 // mServer both represent the same frame position. mPosition is
2030 // in client's point of view, and mServer is in server's point of
2031 // view. So the difference between them is the "fudge factor"
2032 // between client and server views due to stop() and/or new
2033 // IAudioTrack. And timestamp.mPosition is initially in server's
2034 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002035 }
2036 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002037}
2038
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002039String8 AudioTrack::getParameters(const String8& keys)
2040{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002041 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002042 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002043 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002044 } else {
2045 return String8::empty();
2046 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002047}
2048
Glenn Kasten23a75452014-01-13 10:37:17 -08002049bool AudioTrack::isOffloaded() const
2050{
2051 AutoMutex lock(mLock);
2052 return isOffloaded_l();
2053}
2054
Eric Laurentab5cdba2014-06-09 17:22:27 -07002055bool AudioTrack::isDirect() const
2056{
2057 AutoMutex lock(mLock);
2058 return isDirect_l();
2059}
2060
2061bool AudioTrack::isOffloadedOrDirect() const
2062{
2063 AutoMutex lock(mLock);
2064 return isOffloadedOrDirect_l();
2065}
2066
2067
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002068status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002069{
2070
2071 const size_t SIZE = 256;
2072 char buffer[SIZE];
2073 String8 result;
2074
2075 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002076 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002077 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002078 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002079 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002080 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002081 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08002082 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002083 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002084 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002085 result.append(buffer);
2086 ::write(fd, result.string(), result.size());
2087 return NO_ERROR;
2088}
2089
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002090uint32_t AudioTrack::getUnderrunFrames() const
2091{
2092 AutoMutex lock(mLock);
2093 return mProxy->getUnderrunFrames();
2094}
2095
2096// =========================================================================
2097
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002098void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002099{
2100 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2101 if (audioTrack != 0) {
2102 AutoMutex lock(audioTrack->mLock);
2103 audioTrack->mProxy->binderDied();
2104 }
2105}
2106
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002107// =========================================================================
2108
2109AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002110 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2111 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002112{
2113}
2114
2115AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002116{
2117}
2118
2119bool AudioTrack::AudioTrackThread::threadLoop()
2120{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002121 {
2122 AutoMutex _l(mMyLock);
2123 if (mPaused) {
2124 mMyCond.wait(mMyLock);
2125 // caller will check for exitPending()
2126 return true;
2127 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002128 if (mIgnoreNextPausedInt) {
2129 mIgnoreNextPausedInt = false;
2130 mPausedInt = false;
2131 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002132 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002133 if (mPausedNs > 0) {
2134 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2135 } else {
2136 mMyCond.wait(mMyLock);
2137 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002138 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002139 return true;
2140 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002141 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002142 if (exitPending()) {
2143 return false;
2144 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002145 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002146 switch (ns) {
2147 case 0:
2148 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002149 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002150 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002151 return true;
2152 case NS_NEVER:
2153 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002154 case NS_WHENEVER:
2155 // FIXME increase poll interval, or make event-driven
2156 ns = 1000000000LL;
2157 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002158 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002159 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002160 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002161 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002162 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002163}
2164
Glenn Kasten3acbd052012-02-28 10:39:56 -08002165void AudioTrack::AudioTrackThread::requestExit()
2166{
2167 // must be in this order to avoid a race condition
2168 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002169 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002170}
2171
2172void AudioTrack::AudioTrackThread::pause()
2173{
2174 AutoMutex _l(mMyLock);
2175 mPaused = true;
2176}
2177
2178void AudioTrack::AudioTrackThread::resume()
2179{
2180 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002181 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002182 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002183 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002184 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002185 mMyCond.signal();
2186 }
2187}
2188
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002189void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2190{
2191 AutoMutex _l(mMyLock);
2192 mPausedInt = true;
2193 mPausedNs = ns;
2194}
2195
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002196}; // namespace android