blob: 9e9ec5bc970b2793d2eca43a291a4b25c5d0ae91 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080018//#define LOG_NDEBUG 0
19#define LOG_TAG "AudioTrack"
20
Mark Salyzyn34fb2962014-06-18 16:30:56 -070021#include <inttypes.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070022#include <math.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080023#include <sys/resource.h>
Mark Salyzyn34fb2962014-06-18 16:30:56 -070024
Glenn Kasten9f80dd22012-12-18 15:57:32 -080025#include <audio_utils/primitives.h>
26#include <binder/IPCThreadState.h>
27#include <media/AudioTrack.h>
28#include <utils/Log.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080029#include <private/media/AudioTrackShared.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/IAudioFlinger.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080031#include <media/AudioPolicyHelper.h>
Andy Hungcd044842014-08-07 11:04:34 -070032#include <media/AudioResamplerPublic.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080033
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010034#define WAIT_PERIOD_MS 10
35#define WAIT_STREAM_END_TIMEOUT_SEC 120
Andy Hung53c3b5f2014-12-15 16:42:05 -080036static const int kMaxLoopCountNotifications = 32;
Glenn Kasten511754b2012-01-11 09:52:19 -080037
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080038namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080039// ---------------------------------------------------------------------------
40
Andy Hung4ede21d2014-12-12 15:37:34 -080041template <typename T>
42const T &min(const T &x, const T &y) {
43 return x < y ? x : y;
44}
45
Andy Hung7f1bc8a2014-09-12 14:43:11 -070046static int64_t convertTimespecToUs(const struct timespec &tv)
47{
48 return tv.tv_sec * 1000000ll + tv.tv_nsec / 1000;
49}
50
51// current monotonic time in microseconds.
52static int64_t getNowUs()
53{
54 struct timespec tv;
55 (void) clock_gettime(CLOCK_MONOTONIC, &tv);
56 return convertTimespecToUs(tv);
57}
58
Chia-chi Yeh33005a92010-06-16 06:33:13 +080059// static
60status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080061 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080062 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080063 uint32_t sampleRate)
64{
Glenn Kastend65d73c2012-06-22 17:21:07 -070065 if (frameCount == NULL) {
66 return BAD_VALUE;
67 }
Glenn Kasten04cd0182012-06-25 11:49:27 -070068
Andy Hung0e48d252015-01-26 11:43:15 -080069 // FIXME handle in server, like createTrack_l(), possible missing info:
Glenn Kastene0fa4672012-04-24 14:35:14 -070070 // audio_io_handle_t output
71 // audio_format_t format
72 // audio_channel_mask_t channelMask
Andy Hung0e48d252015-01-26 11:43:15 -080073 // audio_output_flags_t flags (FAST)
Glenn Kasten3b16c762012-11-14 08:44:39 -080074 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080075 status_t status;
76 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
77 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080078 ALOGE("Unable to query output sample rate for stream type %d; status %d",
79 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080080 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080081 }
Glenn Kastene33054e2012-11-14 12:54:39 -080082 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -080083 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
84 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080085 ALOGE("Unable to query output frame count for stream type %d; status %d",
86 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080087 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080088 }
89 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -080090 status = AudioSystem::getOutputLatency(&afLatency, streamType);
91 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080092 ALOGE("Unable to query output latency for stream type %d; status %d",
93 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080094 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080095 }
96
97 // Ensure that buffer depth covers at least audio hardware latency
98 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080099 if (minBufCount < 2) {
100 minBufCount = 2;
101 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800102
Andy Hung0e48d252015-01-26 11:43:15 -0800103 *frameCount = minBufCount * sourceFramesNeeded(sampleRate, afFrameCount, afSampleRate);
104 // The formula above should always produce a non-zero value under normal circumstances:
105 // AudioTrack.SAMPLE_RATE_HZ_MIN <= sampleRate <= AudioTrack.SAMPLE_RATE_HZ_MAX.
106 // Return error in the unlikely event that it does not, as that's part of the API contract.
Glenn Kasten66a04672014-01-08 08:53:44 -0800107 if (*frameCount == 0) {
Andy Hung0e48d252015-01-26 11:43:15 -0800108 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %u",
Glenn Kasten66a04672014-01-08 08:53:44 -0800109 streamType, sampleRate);
110 return BAD_VALUE;
111 }
Andy Hung0e48d252015-01-26 11:43:15 -0800112 ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, minBufCount=%u, afSampleRate=%u, afLatency=%u",
Glenn Kasten3acbd052012-02-28 10:39:56 -0800113 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800114 return NO_ERROR;
115}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800116
117// ---------------------------------------------------------------------------
118
119AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700120 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800121 mIsTimed(false),
122 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800123 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700124 mPausedPosition(0),
125 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
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),
Paul McLeanaa981192015-03-21 09:55:15 -0700153 mPausedPosition(0),
154 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800155{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700156 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700157 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800158 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700159 offloadInfo, uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800160}
161
Andreas Huberc8139852012-01-18 10:51:55 -0800162AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800163 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800164 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800165 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700166 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800167 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700168 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800169 callback_t cbf,
170 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800171 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800172 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000173 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800174 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800175 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700176 pid_t pid,
177 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700178 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800179 mIsTimed(false),
180 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800181 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700182 mPausedPosition(0),
183 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800184{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700185 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800186 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800187 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700188 uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800189}
190
191AudioTrack::~AudioTrack()
192{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800193 if (mStatus == NO_ERROR) {
194 // Make sure that callback function exits in the case where
195 // it is looping on buffer full condition in obtainBuffer().
196 // Otherwise the callback thread will never exit.
197 stop();
198 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100199 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800200 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800201 mAudioTrackThread->requestExitAndWait();
202 mAudioTrackThread.clear();
203 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800204 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700205 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700206 mCblkMemory.clear();
207 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800208 IPCThreadState::self()->flushCommands();
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700209 ALOGV("~AudioTrack, releasing session id %d from %d on behalf of %d",
210 mSessionId, IPCThreadState::self()->getCallingPid(), mClientPid);
Marco Nelissend457c972014-02-11 08:47:07 -0800211 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800212 }
213}
214
215status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800216 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800217 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800218 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700219 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800220 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700221 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800222 callback_t cbf,
223 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800224 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800225 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700226 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800227 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000228 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800229 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800230 int uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700231 pid_t pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700232 const audio_attributes_t* pAttributes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800233{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800234 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700235 "flags #%x, notificationFrames %u, sessionId %d, transferType %d, uid %d, pid %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800236 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700237 sessionId, transferType, uid, pid);
Glenn Kasten86f04662014-02-24 15:13:05 -0800238
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800239 switch (transferType) {
240 case TRANSFER_DEFAULT:
241 if (sharedBuffer != 0) {
242 transferType = TRANSFER_SHARED;
243 } else if (cbf == NULL || threadCanCallJava) {
244 transferType = TRANSFER_SYNC;
245 } else {
246 transferType = TRANSFER_CALLBACK;
247 }
248 break;
249 case TRANSFER_CALLBACK:
250 if (cbf == NULL || sharedBuffer != 0) {
251 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
252 return BAD_VALUE;
253 }
254 break;
255 case TRANSFER_OBTAIN:
256 case TRANSFER_SYNC:
257 if (sharedBuffer != 0) {
258 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
259 return BAD_VALUE;
260 }
261 break;
262 case TRANSFER_SHARED:
263 if (sharedBuffer == 0) {
264 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
265 return BAD_VALUE;
266 }
267 break;
268 default:
269 ALOGE("Invalid transfer type %d", transferType);
270 return BAD_VALUE;
271 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800272 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800273 mTransfer = transferType;
274
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700275 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
276 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800277
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700278 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700279
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;
Eric Laurentc6bd5db2015-03-09 16:29:33 -0700303 if ((mAttributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
304 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
305 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800306 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700307
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800308 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800309 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700310 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800311 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800312
313 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700314 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800315 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800316 return BAD_VALUE;
317 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800318 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700319
Glenn Kasten8ba90322013-10-30 11:29:27 -0700320 if (!audio_is_output_channel(channelMask)) {
321 ALOGE("Invalid channel mask %#x", channelMask);
322 return BAD_VALUE;
323 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800324 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700325 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800326 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700327
Eric Laurentc2f1f072009-07-17 12:17:14 -0700328 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100329 // or offload was requested
330 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
331 || !audio_is_linear_pcm(format)) {
332 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
333 ? "Offload request, forcing to Direct Output"
334 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700335 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800336 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700337 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700338 }
339
Eric Laurentd1f69b02014-12-15 14:33:13 -0800340 // force direct flag if HW A/V sync requested
341 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
342 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
343 }
344
Glenn Kastenb7730382014-04-30 15:50:31 -0700345 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
346 if (audio_is_linear_pcm(format)) {
347 mFrameSize = channelCount * audio_bytes_per_sample(format);
348 } else {
349 mFrameSize = sizeof(uint8_t);
350 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800351 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700352 ALOG_ASSERT(audio_is_linear_pcm(format));
353 mFrameSize = channelCount * audio_bytes_per_sample(format);
Glenn Kastenb7730382014-04-30 15:50:31 -0700354 // createTrack will return an error if PCM format is not supported by server,
355 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800356 }
357
Eric Laurent0d6db582014-11-12 18:39:44 -0800358 // sampling rate must be specified for direct outputs
359 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
360 return BAD_VALUE;
361 }
362 mSampleRate = sampleRate;
363
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800364 // Make copy of input parameter offloadInfo so that in the future:
365 // (a) createTrack_l doesn't need it as an input parameter
366 // (b) we can support re-creation of offloaded tracks
367 if (offloadInfo != NULL) {
368 mOffloadInfoCopy = *offloadInfo;
369 mOffloadInfo = &mOffloadInfoCopy;
370 } else {
371 mOffloadInfo = NULL;
372 }
373
Glenn Kasten66e46352014-01-16 17:44:23 -0800374 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
375 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800376 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800377 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800378 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700379 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800380 mNotificationFramesAct = 0;
Eric Laurentcaf7f482014-11-25 17:50:47 -0800381 if (sessionId == AUDIO_SESSION_ALLOCATE) {
382 mSessionId = AudioSystem::newAudioUniqueId();
383 } else {
384 mSessionId = sessionId;
385 }
Marco Nelissend457c972014-02-11 08:47:07 -0800386 int callingpid = IPCThreadState::self()->getCallingPid();
387 int mypid = getpid();
388 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800389 mClientUid = IPCThreadState::self()->getCallingUid();
390 } else {
391 mClientUid = uid;
392 }
Marco Nelissend457c972014-02-11 08:47:07 -0800393 if (pid == -1 || (callingpid != mypid)) {
394 mClientPid = callingpid;
395 } else {
396 mClientPid = pid;
397 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700398 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700399 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700400 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700401
Glenn Kastena997e7a2012-08-07 09:44:19 -0700402 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700403 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700404 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
Glenn Kastenbfd31842015-03-20 09:01:44 -0700405 // thread begins in paused state, and will not reference us until start()
Glenn Kastena997e7a2012-08-07 09:44:19 -0700406 }
407
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800408 // create the IAudioTrack
Eric Laurent0d6db582014-11-12 18:39:44 -0800409 status_t status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800410
Glenn Kastena997e7a2012-08-07 09:44:19 -0700411 if (status != NO_ERROR) {
412 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100413 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
414 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700415 mAudioTrackThread.clear();
416 }
417 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700418 }
419
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800420 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800421 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800422 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800423 mLoopCount = 0;
424 mLoopStart = 0;
425 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800426 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800427 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700428 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800429 mNewPosition = 0;
430 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700431 mServer = 0;
432 mPosition = 0;
433 mReleased = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700434 mStartUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800435 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800436 mSequence = 1;
437 mObservedSequence = mSequence;
438 mInUnderrun = false;
439
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800440 return NO_ERROR;
441}
442
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800443// -------------------------------------------------------------------------
444
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100445status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800446{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800447 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100448
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800449 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100450 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800451 }
452
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800453 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800454
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800455 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100456 if (previousState == STATE_PAUSED_STOPPING) {
457 mState = STATE_STOPPING;
458 } else {
459 mState = STATE_ACTIVE;
460 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700461 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800462 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
463 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700464 mPosition = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700465 // For offloaded tracks, we don't know if the hardware counters are really zero here,
466 // since the flush is asynchronous and stop may not fully drain.
467 // We save the time when the track is started to later verify whether
468 // the counters are realistic (i.e. start from zero after this time).
469 mStartUs = getNowUs();
470
Eric Laurentec9a0322013-08-28 10:23:01 -0700471 // force refresh of remaining frames by processAudioBuffer() as last
472 // write before stop could be partial.
473 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800474 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700475 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700476 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800477
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800478 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800479 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100480 if (previousState == STATE_STOPPING) {
481 mProxy->interrupt();
482 } else {
483 t->resume();
484 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800485 } else {
486 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
487 get_sched_policy(0, &mPreviousSchedulingGroup);
488 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
489 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800490
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800491 status_t status = NO_ERROR;
492 if (!(flags & CBLK_INVALID)) {
493 status = mAudioTrack->start();
494 if (status == DEAD_OBJECT) {
495 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800496 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800497 }
498 if (flags & CBLK_INVALID) {
499 status = restoreTrack_l("start");
500 }
501
502 if (status != NO_ERROR) {
503 ALOGE("start() status %d", status);
504 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800505 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100506 if (previousState != STATE_STOPPING) {
507 t->pause();
508 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800509 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700510 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700511 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800512 }
513 }
514
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100515 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800516}
517
518void AudioTrack::stop()
519{
520 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700521 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800522 return;
523 }
524
Glenn Kasten23a75452014-01-13 10:37:17 -0800525 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100526 mState = STATE_STOPPING;
527 } else {
528 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -0700529 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100530 }
531
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800532 mProxy->interrupt();
533 mAudioTrack->stop();
534 // the playback head position will reset to 0, so if a marker is set, we need
535 // to activate it again
536 mMarkerReached = false;
Andy Hung9b461582014-12-01 17:56:29 -0800537
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800538 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800539 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800540 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
541 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800542 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100543
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800544 sp<AudioTrackThread> t = mAudioTrackThread;
545 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800546 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100547 t->pause();
548 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800549 } else {
550 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
551 set_sched_policy(0, mPreviousSchedulingGroup);
552 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800553}
554
555bool AudioTrack::stopped() const
556{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800557 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800558 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800559}
560
561void AudioTrack::flush()
562{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800563 if (mSharedBuffer != 0) {
564 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800565 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800566 AutoMutex lock(mLock);
567 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
568 return;
569 }
570 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800571}
572
Eric Laurent1703cdf2011-03-07 14:52:59 -0800573void AudioTrack::flush_l()
574{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800575 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700576
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700577 // clear playback marker and periodic update counter
578 mMarkerPosition = 0;
579 mMarkerReached = false;
580 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100581 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700582
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800583 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700584 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800585 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100586 mProxy->interrupt();
587 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800588 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800589 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800590}
591
592void AudioTrack::pause()
593{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800594 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100595 if (mState == STATE_ACTIVE) {
596 mState = STATE_PAUSED;
597 } else if (mState == STATE_STOPPING) {
598 mState = STATE_PAUSED_STOPPING;
599 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800600 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800601 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800602 mProxy->interrupt();
603 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800604
Marco Nelissen3a90f282014-03-10 11:21:43 -0700605 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700606 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700607 // An offload output can be re-used between two audio tracks having
608 // the same configuration. A timestamp query for a paused track
609 // while the other is running would return an incorrect time.
610 // To fix this, cache the playback position on a pause() and return
611 // this time when requested until the track is resumed.
612
613 // OffloadThread sends HAL pause in its threadLoop. Time saved
614 // here can be slightly off.
615
616 // TODO: check return code for getRenderPosition.
617
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800618 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800619 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
620 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
621 }
622 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800623}
624
Eric Laurentbe916aa2010-06-01 23:49:17 -0700625status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800626{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700627 // This duplicates a test by AudioTrack JNI, but that is not the only caller
628 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
629 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700630 return BAD_VALUE;
631 }
632
Eric Laurent1703cdf2011-03-07 14:52:59 -0800633 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800634 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
635 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800636
Glenn Kastenc56f3422014-03-21 17:53:17 -0700637 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700638
Glenn Kasten23a75452014-01-13 10:37:17 -0800639 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700640 mAudioTrack->signal();
641 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700642 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800643}
644
Glenn Kastenb1c09932012-02-27 16:21:04 -0800645status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800646{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800647 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700648}
649
Eric Laurent2beeb502010-07-16 07:43:46 -0700650status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700651{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700652 // This duplicates a test by AudioTrack JNI, but that is not the only caller
653 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700654 return BAD_VALUE;
655 }
656
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800657 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700658 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800659 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700660
661 return NO_ERROR;
662}
663
Glenn Kastena5224f32012-01-04 12:41:44 -0800664void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700665{
666 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800667 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700668 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800669}
670
Glenn Kasten3b16c762012-11-14 08:44:39 -0800671status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800672{
Andy Hung5cbb5782015-03-27 18:39:59 -0700673 AutoMutex lock(mLock);
674 if (rate == mSampleRate) {
675 return NO_ERROR;
676 }
677 if (mIsTimed || isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800678 return INVALID_OPERATION;
679 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800680 if (mOutput == AUDIO_IO_HANDLE_NONE) {
681 return NO_INIT;
682 }
Andy Hung5cbb5782015-03-27 18:39:59 -0700683 // NOTE: it is theoretically possible, but highly unlikely, that a device change
684 // could mean a previously allowed sampling rate is no longer allowed.
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;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800753 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800754 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -0800755
756 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800757}
758
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800759status_t AudioTrack::setMarkerPosition(uint32_t marker)
760{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700761 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700762 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700763 return INVALID_OPERATION;
764 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800765
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800766 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800767 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700768 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800769
Andy Hung3c09c782014-12-29 18:39:32 -0800770 sp<AudioTrackThread> t = mAudioTrackThread;
771 if (t != 0) {
772 t->wake();
773 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800774 return NO_ERROR;
775}
776
Glenn Kastena5224f32012-01-04 12:41:44 -0800777status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800778{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700779 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100780 return INVALID_OPERATION;
781 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700782 if (marker == NULL) {
783 return BAD_VALUE;
784 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800785
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800786 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800787 *marker = mMarkerPosition;
788
789 return NO_ERROR;
790}
791
792status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
793{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700794 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700795 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700796 return INVALID_OPERATION;
797 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800798
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800799 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700800 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800801 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800802
Andy Hung3c09c782014-12-29 18:39:32 -0800803 sp<AudioTrackThread> t = mAudioTrackThread;
804 if (t != 0) {
805 t->wake();
806 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800807 return NO_ERROR;
808}
809
Glenn Kastena5224f32012-01-04 12:41:44 -0800810status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800811{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700812 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100813 return INVALID_OPERATION;
814 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700815 if (updatePeriod == NULL) {
816 return BAD_VALUE;
817 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800818
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800819 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800820 *updatePeriod = mUpdatePeriod;
821
822 return NO_ERROR;
823}
824
825status_t AudioTrack::setPosition(uint32_t position)
826{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700827 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700828 return INVALID_OPERATION;
829 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800830 if (position > mFrameCount) {
831 return BAD_VALUE;
832 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800833
Eric Laurent1703cdf2011-03-07 14:52:59 -0800834 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800835 // Currently we require that the player is inactive before setting parameters such as position
836 // or loop points. Otherwise, there could be a race condition: the application could read the
837 // current position, compute a new position or loop parameters, and then set that position or
838 // loop parameters but it would do the "wrong" thing since the position has continued to advance
839 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
840 // to specify how it wants to handle such scenarios.
841 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700842 return INVALID_OPERATION;
843 }
Andy Hung9b461582014-12-01 17:56:29 -0800844 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -0700845 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800846 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -0800847
848 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800849 return NO_ERROR;
850}
851
Glenn Kasten200092b2014-08-15 15:13:30 -0700852status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800853{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700854 if (position == NULL) {
855 return BAD_VALUE;
856 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800857
Eric Laurent1703cdf2011-03-07 14:52:59 -0800858 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700859 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100860 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800861
Eric Laurentab5cdba2014-06-09 17:22:27 -0700862 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800863 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
864 *position = mPausedPosition;
865 return NO_ERROR;
866 }
867
Glenn Kasten142f5192014-03-25 17:44:59 -0700868 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100869 uint32_t halFrames;
870 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
871 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700872 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
873 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100874 *position = dspFrames;
875 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -0800876 if (mCblk->mFlags & CBLK_INVALID) {
877 restoreTrack_l("getPosition");
878 }
879
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100880 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700881 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
882 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100883 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800884 return NO_ERROR;
885}
886
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000887status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800888{
889 if (mSharedBuffer == 0 || mIsTimed) {
890 return INVALID_OPERATION;
891 }
892 if (position == NULL) {
893 return BAD_VALUE;
894 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800895
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800896 AutoMutex lock(mLock);
897 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800898 return NO_ERROR;
899}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800900
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800901status_t AudioTrack::reload()
902{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700903 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800904 return INVALID_OPERATION;
905 }
906
Eric Laurent1703cdf2011-03-07 14:52:59 -0800907 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800908 // See setPosition() regarding setting parameters such as loop points or position while active
909 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700910 return INVALID_OPERATION;
911 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800912 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800913 (void) updateAndGetPosition_l();
914 mPosition = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800915#if 0
Andy Hung9b461582014-12-01 17:56:29 -0800916 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -0800917 // of loop count. Historically we have not restored loop count, start, end,
918 // but it makes sense if one desires to repeat playing a particular sound.
919 if (mLoopCount != 0) {
920 mLoopCountNotified = mLoopCount;
921 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
922 }
923#endif
Andy Hung9b461582014-12-01 17:56:29 -0800924 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800925 return NO_ERROR;
926}
927
Glenn Kasten38e905b2014-01-13 10:21:48 -0800928audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700929{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800930 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100931 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800932}
933
Paul McLeanaa981192015-03-21 09:55:15 -0700934status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
935 AutoMutex lock(mLock);
936 if (mSelectedDeviceId != deviceId) {
937 mSelectedDeviceId = deviceId;
938 return restoreTrack_l("setOutputDevice() restart");
939 } else {
940 return NO_ERROR;
941 }
942}
943
944audio_port_handle_t AudioTrack::getOutputDevice() {
945 AutoMutex lock(mLock);
946 return mSelectedDeviceId;
947}
948
Eric Laurentbe916aa2010-06-01 23:49:17 -0700949status_t AudioTrack::attachAuxEffect(int effectId)
950{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800951 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700952 status_t status = mAudioTrack->attachAuxEffect(effectId);
953 if (status == NO_ERROR) {
954 mAuxEffectId = effectId;
955 }
956 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700957}
958
Eric Laurente83b55d2014-11-14 10:06:21 -0800959audio_stream_type_t AudioTrack::streamType() const
960{
961 if (mStreamType == AUDIO_STREAM_DEFAULT) {
962 return audio_attributes_to_stream_type(&mAttributes);
963 }
964 return mStreamType;
965}
966
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800967// -------------------------------------------------------------------------
968
Eric Laurent1703cdf2011-03-07 14:52:59 -0800969// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -0700970status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800971{
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800972 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
973 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700974 ALOGE("Could not get audioflinger");
975 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800976 }
977
Eric Laurente83b55d2014-11-14 10:06:21 -0800978 audio_io_handle_t output;
979 audio_stream_type_t streamType = mStreamType;
980 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
Eric Laurente83b55d2014-11-14 10:06:21 -0800981
Paul McLeanaa981192015-03-21 09:55:15 -0700982 status_t status;
983 status = AudioSystem::getOutputForAttr(attr, &output,
984 (audio_session_t)mSessionId, &streamType,
985 mSampleRate, mFormat, mChannelMask,
986 mFlags, mSelectedDeviceId, mOffloadInfo);
Eric Laurente83b55d2014-11-14 10:06:21 -0800987
988 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700989 ALOGE("Could not get audio output for session %d, stream type %d, usage %d, sample rate %u, format %#x,"
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700990 " channel mask %#x, flags %#x",
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700991 mSessionId, streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800992 return BAD_VALUE;
993 }
994 {
995 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
996 // we must release it ourselves if anything goes wrong.
997
Glenn Kastence8828a2013-09-16 18:07:38 -0700998 // Not all of these values are needed under all conditions, but it is easier to get them all
999
Eric Laurentd1b449a2010-05-14 03:26:45 -07001000 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -07001001 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001002 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001003 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001004 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001005 }
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001006 ALOGV("createTrack_l() output %d afLatency %u", output, afLatency);
Eric Laurentd1b449a2010-05-14 03:26:45 -07001007
Glenn Kastence8828a2013-09-16 18:07:38 -07001008 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001009 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -07001010 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001011 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001012 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001013 }
1014
1015 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001016 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -07001017 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001018 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001019 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001020 }
Eric Laurent0d6db582014-11-12 18:39:44 -08001021 if (mSampleRate == 0) {
1022 mSampleRate = afSampleRate;
1023 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001024 // Client decides whether the track is TIMED (see below), but can only express a preference
1025 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001026 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001027 // either of these use cases:
1028 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -08001029 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001030 // use case 2: callback transfer mode
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001031 (mTransfer == TRANSFER_CALLBACK) ||
1032 // use case 3: obtain/release mode
1033 (mTransfer == TRANSFER_OBTAIN)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001034 // matching sample rate
1035 (mSampleRate == afSampleRate))) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001036 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client; transfer %d, track %u Hz, output %u Hz",
1037 mTransfer, mSampleRate, afSampleRate);
Glenn Kasten093000f2012-05-03 09:35:36 -07001038 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001039 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001040 }
1041
Glenn Kastence8828a2013-09-16 18:07:38 -07001042 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -08001043 // n = 1 fast track with single buffering; nBuffering is ignored
1044 // n = 2 fast track with double buffering
Andy Hung0e48d252015-01-26 11:43:15 -08001045 // n = 2 normal track, (including those with sample rate conversion)
1046 // n >= 3 very high latency or very small notification interval (unused).
1047 const uint32_t nBuffering = 2;
Glenn Kastence8828a2013-09-16 18:07:38 -07001048
Eric Laurentd1b449a2010-05-14 03:26:45 -07001049 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001050
Glenn Kasten363fb752014-01-15 12:27:31 -08001051 size_t frameCount = mReqFrameCount;
1052 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001053
Glenn Kasten363fb752014-01-15 12:27:31 -08001054 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001055 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001056 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001057 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001058 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001059 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001060 if (mNotificationFramesAct != frameCount) {
1061 mNotificationFramesAct = frameCount;
1062 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001063 } else if (mSharedBuffer != 0) {
Andy Hungabdb9902015-01-12 15:08:22 -08001064 // FIXME: Ensure client side memory buffers need
1065 // not have additional alignment beyond sample
1066 // (e.g. 16 bit stereo accessed as 32 bit frame).
1067 size_t alignment = audio_bytes_per_sample(mFormat);
Glenn Kastenb7730382014-04-30 15:50:31 -07001068 if (alignment & 1) {
Andy Hungabdb9902015-01-12 15:08:22 -08001069 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
Glenn Kastenb7730382014-04-30 15:50:31 -07001070 alignment = 1;
1071 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001072 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001073 // More than 2 channels does not require stronger alignment than stereo
1074 alignment <<= 1;
1075 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001076 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001077 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001078 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001079 status = BAD_VALUE;
1080 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001081 }
1082
1083 // When initializing a shared buffer AudioTrack via constructors,
1084 // there's no frameCount parameter.
1085 // But when initializing a shared buffer AudioTrack via set(),
1086 // there _is_ a frameCount parameter. We silently ignore it.
Andy Hungabdb9902015-01-12 15:08:22 -08001087 frameCount = mSharedBuffer->size() / mFrameSize;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001088 } else {
Andy Hung0e48d252015-01-26 11:43:15 -08001089 // For fast and normal streaming tracks,
1090 // the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -07001091 }
1092
Glenn Kastena075db42012-03-06 11:22:44 -08001093 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1094 if (mIsTimed) {
1095 trackFlags |= IAudioFlinger::TRACK_TIMED;
1096 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001097
1098 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001099 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001100 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001101 if (mAudioTrackThread != 0) {
1102 tid = mAudioTrackThread->getTid();
1103 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001104 }
1105
Glenn Kasten363fb752014-01-15 12:27:31 -08001106 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001107 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1108 }
1109
Eric Laurentab5cdba2014-06-09 17:22:27 -07001110 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1111 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1112 }
1113
Glenn Kasten74935e42013-12-19 08:56:45 -08001114 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1115 // but we will still need the original value also
Glenn Kasten138d6f92015-03-20 10:54:51 -07001116 int originalSessionId = mSessionId;
Eric Laurente83b55d2014-11-14 10:06:21 -08001117 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001118 mSampleRate,
Andy Hungabdb9902015-01-12 15:08:22 -08001119 mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001120 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001121 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001122 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001123 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001124 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001125 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001126 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001127 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001128 &status);
Glenn Kasten138d6f92015-03-20 10:54:51 -07001129 ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
1130 "session ID changed from %d to %d", originalSessionId, mSessionId);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001131
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001132 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001133 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001134 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001135 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001136 ALOG_ASSERT(track != 0);
1137
Glenn Kasten38e905b2014-01-13 10:21:48 -08001138 // AudioFlinger now owns the reference to the I/O handle,
1139 // so we are no longer responsible for releasing it.
1140
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001141 sp<IMemory> iMem = track->getCblk();
1142 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001143 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001144 return NO_INIT;
1145 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001146 void *iMemPointer = iMem->pointer();
1147 if (iMemPointer == NULL) {
1148 ALOGE("Could not get control block pointer");
1149 return NO_INIT;
1150 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001151 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001152 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001153 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001154 mDeathNotifier.clear();
1155 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001156 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001157 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001158 IPCThreadState::self()->flushCommands();
1159
Glenn Kasten0cde0762014-01-16 15:06:36 -08001160 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001161 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001162 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001163 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1164 // In current design, AudioTrack client checks and ensures frame count validity before
1165 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1166 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001167 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001168 }
1169 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001170
Glenn Kastena07f17c2013-04-23 12:39:37 -07001171 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001172 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001173 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001174 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001175 mAwaitBoost = true;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001176 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001177 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001178 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001179 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001180 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001181 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001182 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001183 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1184 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1185 } else {
1186 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001187 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001188 // FIXME This is a warning, not an error, so don't return error status
1189 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001190 }
1191 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001192 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1193 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1194 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1195 } else {
1196 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1197 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1198 // FIXME This is a warning, not an error, so don't return error status
1199 //return NO_INIT;
1200 }
1201 }
Andy Hung0e48d252015-01-26 11:43:15 -08001202 // Make sure that application is notified with sufficient margin before underrun
1203 if (mSharedBuffer == 0 && audio_is_linear_pcm(mFormat)) {
1204 // Theoretically double-buffering is not required for fast tracks,
1205 // due to tighter scheduling. But in practice, to accommodate kernels with
1206 // scheduling jitter, and apps with computation jitter, we use double-buffering
1207 // for fast tracks just like normal streaming tracks.
1208 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount / nBuffering) {
1209 mNotificationFramesAct = frameCount / nBuffering;
1210 }
1211 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001212
Glenn Kasten38e905b2014-01-13 10:21:48 -08001213 // We retain a copy of the I/O handle, but don't own the reference
1214 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001215 mRefreshRemaining = true;
1216
1217 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1218 // is the value of pointer() for the shared buffer, otherwise buffers points
1219 // immediately after the control block. This address is for the mapping within client
1220 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1221 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001222 if (mSharedBuffer == 0) {
Glenn Kasten138d6f92015-03-20 10:54:51 -07001223 buffers = cblk + 1;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001224 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001225 buffers = mSharedBuffer->pointer();
Glenn Kasten138d6f92015-03-20 10:54:51 -07001226 if (buffers == NULL) {
1227 ALOGE("Could not get buffer pointer");
1228 return NO_INIT;
1229 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001230 }
1231
Eric Laurent2beeb502010-07-16 07:43:46 -07001232 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001233 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001234 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001235
Glenn Kastenb6037442012-11-14 13:42:25 -08001236 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001237 // If IAudioTrack is re-created, don't let the requested frameCount
1238 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001239 if (frameCount > mReqFrameCount) {
1240 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001241 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001242
1243 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001244 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001245 mStaticProxy.clear();
Andy Hungabdb9902015-01-12 15:08:22 -08001246 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001247 } else {
Andy Hungabdb9902015-01-12 15:08:22 -08001248 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001249 mProxy = mStaticProxy;
1250 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001251
1252 mProxy->setVolumeLR(gain_minifloat_pack(
1253 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1254 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1255
Glenn Kastene3aa6592012-12-04 12:22:46 -08001256 mProxy->setSendLevel(mSendLevel);
1257 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001258 mProxy->setMinimum(mNotificationFramesAct);
1259
1260 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001261 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001262
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001263 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001264 }
1265
1266release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001267 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001268 if (status == NO_ERROR) {
1269 status = NO_INIT;
1270 }
1271 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001272}
1273
Glenn Kastenb46f3942015-03-09 12:00:30 -07001274status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001275{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001276 if (audioBuffer == NULL) {
1277 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001278 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001279 if (mTransfer != TRANSFER_OBTAIN) {
1280 audioBuffer->frameCount = 0;
1281 audioBuffer->size = 0;
1282 audioBuffer->raw = NULL;
1283 return INVALID_OPERATION;
1284 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001285
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001286 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001287 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001288 if (waitCount == -1) {
1289 requested = &ClientProxy::kForever;
1290 } else if (waitCount == 0) {
1291 requested = &ClientProxy::kNonBlocking;
1292 } else if (waitCount > 0) {
1293 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001294 timeout.tv_sec = ms / 1000;
1295 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1296 requested = &timeout;
1297 } else {
1298 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1299 requested = NULL;
1300 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001301 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001302}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001303
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001304status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1305 struct timespec *elapsed, size_t *nonContig)
1306{
1307 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1308 uint32_t oldSequence = 0;
1309 uint32_t newSequence;
1310
1311 Proxy::Buffer buffer;
1312 status_t status = NO_ERROR;
1313
1314 static const int32_t kMaxTries = 5;
1315 int32_t tryCounter = kMaxTries;
1316
1317 do {
1318 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1319 // keep them from going away if another thread re-creates the track during obtainBuffer()
1320 sp<AudioTrackClientProxy> proxy;
1321 sp<IMemory> iMem;
1322
1323 { // start of lock scope
1324 AutoMutex lock(mLock);
1325
1326 newSequence = mSequence;
1327 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1328 if (status == DEAD_OBJECT) {
1329 // re-create track, unless someone else has already done so
1330 if (newSequence == oldSequence) {
1331 status = restoreTrack_l("obtainBuffer");
1332 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001333 buffer.mFrameCount = 0;
1334 buffer.mRaw = NULL;
1335 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001336 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001337 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001338 }
1339 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001340 oldSequence = newSequence;
1341
1342 // Keep the extra references
1343 proxy = mProxy;
1344 iMem = mCblkMemory;
1345
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001346 if (mState == STATE_STOPPING) {
1347 status = -EINTR;
1348 buffer.mFrameCount = 0;
1349 buffer.mRaw = NULL;
1350 buffer.mNonContig = 0;
1351 break;
1352 }
1353
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001354 // Non-blocking if track is stopped or paused
1355 if (mState != STATE_ACTIVE) {
1356 requested = &ClientProxy::kNonBlocking;
1357 }
1358
1359 } // end of lock scope
1360
1361 buffer.mFrameCount = audioBuffer->frameCount;
1362 // FIXME starts the requested timeout and elapsed over from scratch
1363 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1364
1365 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1366
1367 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001368 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001369 audioBuffer->raw = buffer.mRaw;
1370 if (nonContig != NULL) {
1371 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001372 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001373 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001374}
1375
Glenn Kasten54a8a452015-03-09 12:03:00 -07001376void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001377{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001378 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001379 if (mTransfer == TRANSFER_SHARED) {
1380 return;
1381 }
1382
Andy Hungabdb9902015-01-12 15:08:22 -08001383 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001384 if (stepCount == 0) {
1385 return;
1386 }
1387
1388 Proxy::Buffer buffer;
1389 buffer.mFrameCount = stepCount;
1390 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001391
Eric Laurent1703cdf2011-03-07 14:52:59 -08001392 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001393 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001394 mInUnderrun = false;
1395 mProxy->releaseBuffer(&buffer);
1396
1397 // restart track if it was disabled by audioflinger due to previous underrun
1398 if (mState == STATE_ACTIVE) {
1399 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001400 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001401 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001402 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001403 mAudioTrack->start();
1404 }
1405 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001406}
1407
1408// -------------------------------------------------------------------------
1409
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001410ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001411{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001412 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001413 return INVALID_OPERATION;
1414 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001415
Eric Laurentab5cdba2014-06-09 17:22:27 -07001416 if (isDirect()) {
1417 AutoMutex lock(mLock);
1418 int32_t flags = android_atomic_and(
1419 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1420 &mCblk->mFlags);
1421 if (flags & CBLK_INVALID) {
1422 return DEAD_OBJECT;
1423 }
1424 }
1425
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001426 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001427 // Sanity-check: user is most-likely passing an error code, and it would
1428 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001429 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001430 return BAD_VALUE;
1431 }
1432
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001433 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001434 Buffer audioBuffer;
1435
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001436 while (userSize >= mFrameSize) {
1437 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001438
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001439 status_t err = obtainBuffer(&audioBuffer,
1440 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001441 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001442 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001443 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001444 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001445 return ssize_t(err);
1446 }
1447
Glenn Kastenae4b8792015-03-20 09:04:21 -07001448 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08001449 memcpy(audioBuffer.i8, buffer, toWrite);
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");
Andy Hung53c3b5f2014-12-15 16:42:05 -08001569 // after restoration, continue below to make sure that the loop and buffer events
1570 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001571 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001572 }
1573
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001574 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001575 bool active = mState == STATE_ACTIVE;
1576
1577 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1578 bool newUnderrun = false;
1579 if (flags & CBLK_UNDERRUN) {
1580#if 0
1581 // Currently in shared buffer mode, when the server reaches the end of buffer,
1582 // the track stays active in continuous underrun state. It's up to the application
1583 // to pause or stop the track, or set the position to a new offset within buffer.
1584 // This was some experimental code to auto-pause on underrun. Keeping it here
1585 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1586 if (mTransfer == TRANSFER_SHARED) {
1587 mState = STATE_PAUSED;
1588 active = false;
1589 }
1590#endif
1591 if (!mInUnderrun) {
1592 mInUnderrun = true;
1593 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001594 }
1595 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001596
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001597 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001598 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001599
1600 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001601 bool markerReached = false;
1602 size_t markerPosition = mMarkerPosition;
1603 // FIXME fails for wraparound, need 64 bits
1604 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1605 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001606 }
1607
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001608 // Determine number of new position callback(s) that will be needed, while locked
1609 size_t newPosCount = 0;
1610 size_t newPosition = mNewPosition;
1611 size_t updatePeriod = mUpdatePeriod;
1612 // FIXME fails for wraparound, need 64 bits
1613 if (updatePeriod > 0 && position >= newPosition) {
1614 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1615 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001616 }
1617
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001618 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001619 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001620 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001621 if (mRefreshRemaining) {
1622 mRefreshRemaining = false;
1623 mRemainingFrames = notificationFrames;
1624 mRetryOnPartialBuffer = false;
1625 }
1626 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001627 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001628 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001629
Andy Hung53c3b5f2014-12-15 16:42:05 -08001630 // Determine the number of new loop callback(s) that will be needed, while locked.
1631 int loopCountNotifications = 0;
1632 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1633
1634 if (mLoopCount > 0) {
1635 int loopCount;
1636 size_t bufferPosition;
1637 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1638 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1639 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1640 mLoopCountNotified = loopCount; // discard any excess notifications
1641 } else if (mLoopCount < 0) {
1642 // FIXME: We're not accurate with notification count and position with infinite looping
1643 // since loopCount from server side will always return -1 (we could decrement it).
1644 size_t bufferPosition = mStaticProxy->getBufferPosition();
1645 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1646 loopPeriod = mLoopEnd - bufferPosition;
1647 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1648 size_t bufferPosition = mStaticProxy->getBufferPosition();
1649 loopPeriod = mFrameCount - bufferPosition;
1650 }
1651
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001652 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08001653 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001654 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1655
1656 mLock.unlock();
1657
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001658 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001659 struct timespec timeout;
1660 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1661 timeout.tv_nsec = 0;
1662
Glenn Kasten96f04882013-09-20 09:28:56 -07001663 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001664 switch (status) {
1665 case NO_ERROR:
1666 case DEAD_OBJECT:
1667 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001668 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001669 {
1670 AutoMutex lock(mLock);
1671 // The previously assigned value of waitStreamEnd is no longer valid,
1672 // since the mutex has been unlocked and either the callback handler
1673 // or another thread could have re-started the AudioTrack during that time.
1674 waitStreamEnd = mState == STATE_STOPPING;
1675 if (waitStreamEnd) {
1676 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001677 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001678 }
1679 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001680 if (waitStreamEnd && status != DEAD_OBJECT) {
1681 return NS_INACTIVE;
1682 }
1683 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001684 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001685 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001686 }
1687
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001688 // perform callbacks while unlocked
1689 if (newUnderrun) {
1690 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1691 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001692 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001693 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001694 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001695 }
1696 if (flags & CBLK_BUFFER_END) {
1697 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1698 }
1699 if (markerReached) {
1700 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1701 }
1702 while (newPosCount > 0) {
1703 size_t temp = newPosition;
1704 mCbf(EVENT_NEW_POS, mUserData, &temp);
1705 newPosition += updatePeriod;
1706 newPosCount--;
1707 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001708
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001709 if (mObservedSequence != sequence) {
1710 mObservedSequence = sequence;
1711 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001712 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001713 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001714 return NS_INACTIVE;
1715 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001716 }
1717
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001718 // if inactive, then don't run me again until re-started
1719 if (!active) {
1720 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001721 }
1722
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001723 // Compute the estimated time until the next timed event (position, markers, loops)
1724 // FIXME only for non-compressed audio
1725 uint32_t minFrames = ~0;
1726 if (!markerReached && position < markerPosition) {
1727 minFrames = markerPosition - position;
1728 }
1729 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08001730 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001731 minFrames = loopPeriod;
1732 }
Andy Hung2d85f092015-01-07 12:45:13 -08001733 if (updatePeriod > 0) {
1734 minFrames = min(minFrames, uint32_t(newPosition - position));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001735 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001736
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001737 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1738 static const uint32_t kPoll = 0;
1739 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1740 minFrames = kPoll * notificationFrames;
1741 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001742
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001743 // Convert frame units to time units
1744 nsecs_t ns = NS_WHENEVER;
1745 if (minFrames != (uint32_t) ~0) {
1746 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1747 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1748 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1749 }
1750
1751 // If not supplying data by EVENT_MORE_DATA, then we're done
1752 if (mTransfer != TRANSFER_CALLBACK) {
1753 return ns;
1754 }
1755
1756 struct timespec timeout;
1757 const struct timespec *requested = &ClientProxy::kForever;
1758 if (ns != NS_WHENEVER) {
1759 timeout.tv_sec = ns / 1000000000LL;
1760 timeout.tv_nsec = ns % 1000000000LL;
1761 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1762 requested = &timeout;
1763 }
1764
1765 while (mRemainingFrames > 0) {
1766
1767 Buffer audioBuffer;
1768 audioBuffer.frameCount = mRemainingFrames;
1769 size_t nonContig;
1770 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1771 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001772 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001773 requested = &ClientProxy::kNonBlocking;
1774 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001775 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001776 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001777 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001778 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1779 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001780 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001781 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001782 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1783 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001784 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001785
Eric Laurent42a6f422013-08-29 14:35:05 -07001786 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001787 mRetryOnPartialBuffer = false;
1788 if (avail < mRemainingFrames) {
1789 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1790 if (ns < 0 || myns < ns) {
1791 ns = myns;
1792 }
1793 return ns;
1794 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001795 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001796
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001797 size_t reqSize = audioBuffer.size;
1798 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001799 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001800
1801 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001802 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001803 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1804 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001805 return NS_NEVER;
1806 }
1807
1808 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001809 // The callback is done filling buffers
1810 // Keep this thread going to handle timed events and
1811 // still try to get more data in intervals of WAIT_PERIOD_MS
1812 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001813 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001814 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001815
Glenn Kasten138d6f92015-03-20 10:54:51 -07001816 size_t releasedFrames = writtenSize / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001817 audioBuffer.frameCount = releasedFrames;
1818 mRemainingFrames -= releasedFrames;
1819 if (misalignment >= releasedFrames) {
1820 misalignment -= releasedFrames;
1821 } else {
1822 misalignment = 0;
1823 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001824
1825 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001826
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001827 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1828 // if callback doesn't like to accept the full chunk
1829 if (writtenSize < reqSize) {
1830 continue;
1831 }
1832
1833 // There could be enough non-contiguous frames available to satisfy the remaining request
1834 if (mRemainingFrames <= nonContig) {
1835 continue;
1836 }
1837
1838#if 0
1839 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1840 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1841 // that total to a sum == notificationFrames.
1842 if (0 < misalignment && misalignment <= mRemainingFrames) {
1843 mRemainingFrames = misalignment;
1844 return (mRemainingFrames * 1100000000LL) / sampleRate;
1845 }
1846#endif
1847
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001848 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001849 mRemainingFrames = notificationFrames;
1850 mRetryOnPartialBuffer = true;
1851
1852 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1853 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001854}
1855
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001856status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001857{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001858 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001859 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001860 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001861
Glenn Kastena47f3162012-11-07 10:13:08 -08001862 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08001863 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001864 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001865
Eric Laurentab5cdba2014-06-09 17:22:27 -07001866 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001867 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001868 return DEAD_OBJECT;
1869 }
1870
Glenn Kasten200092b2014-08-15 15:13:30 -07001871 // save the old static buffer position
Andy Hung4ede21d2014-12-12 15:37:34 -08001872 size_t bufferPosition = 0;
1873 int loopCount = 0;
1874 if (mStaticProxy != 0) {
1875 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1876 }
Glenn Kasten200092b2014-08-15 15:13:30 -07001877
1878 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001879 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001880 // It will also delete the strong references on previous IAudioTrack and IMemory.
1881 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Glenn Kastenae4b8792015-03-20 09:04:21 -07001882 status_t result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001883
1884 // take the frames that will be lost by track recreation into account in saved position
Andy Hung9b461582014-12-01 17:56:29 -08001885 // For streaming tracks, this is the amount we obtained from the user/client
1886 // (not the number actually consumed at the server - those are already lost).
Glenn Kasten200092b2014-08-15 15:13:30 -07001887 (void) updateAndGetPosition_l();
Andy Hung7ccdaad2015-03-20 00:38:32 -07001888 if (mStaticProxy == 0) {
Andy Hung9b461582014-12-01 17:56:29 -08001889 mPosition = mReleased;
1890 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001891
Glenn Kastena47f3162012-11-07 10:13:08 -08001892 if (result == NO_ERROR) {
Andy Hung4ede21d2014-12-12 15:37:34 -08001893 // Continue playback from last known position and restore loop.
1894 if (mStaticProxy != 0) {
1895 if (loopCount != 0) {
1896 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
1897 mLoopStart, mLoopEnd, loopCount);
1898 } else {
1899 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001900 if (bufferPosition == mFrameCount) {
1901 ALOGD("restoring track at end of static buffer");
1902 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001903 }
1904 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001905 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001906 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001907 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001908 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001909 if (result != NO_ERROR) {
1910 ALOGW("restoreTrack_l() failed status %d", result);
1911 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001912 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001913 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001914
1915 return result;
1916}
1917
Glenn Kasten200092b2014-08-15 15:13:30 -07001918uint32_t AudioTrack::updateAndGetPosition_l()
1919{
1920 // This is the sole place to read server consumed frames
1921 uint32_t newServer = mProxy->getPosition();
1922 int32_t delta = newServer - mServer;
1923 mServer = newServer;
1924 // TODO There is controversy about whether there can be "negative jitter" in server position.
1925 // This should be investigated further, and if possible, it should be addressed.
1926 // A more definite failure mode is infrequent polling by client.
1927 // One could call (void)getPosition_l() in releaseBuffer(),
1928 // so mReleased and mPosition are always lock-step as best possible.
1929 // That should ensure delta never goes negative for infrequent polling
1930 // unless the server has more than 2^31 frames in its buffer,
1931 // in which case the use of uint32_t for these counters has bigger issues.
1932 if (delta < 0) {
1933 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
1934 delta = 0;
1935 }
1936 return mPosition += (uint32_t) delta;
1937}
1938
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001939status_t AudioTrack::setParameters(const String8& keyValuePairs)
1940{
1941 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001942 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001943}
1944
Glenn Kastence703742013-07-19 16:33:58 -07001945status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1946{
Glenn Kasten53cec222013-08-29 09:01:02 -07001947 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001948 // FIXME not implemented for fast tracks; should use proxy and SSQ
1949 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1950 return INVALID_OPERATION;
1951 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001952
1953 switch (mState) {
1954 case STATE_ACTIVE:
1955 case STATE_PAUSED:
1956 break; // handle below
1957 case STATE_FLUSHED:
1958 case STATE_STOPPED:
1959 return WOULD_BLOCK;
1960 case STATE_STOPPING:
1961 case STATE_PAUSED_STOPPING:
1962 if (!isOffloaded_l()) {
1963 return INVALID_OPERATION;
1964 }
1965 break; // offloaded tracks handled below
1966 default:
1967 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
1968 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07001969 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001970
Eric Laurent275e8e92014-11-30 15:14:47 -08001971 if (mCblk->mFlags & CBLK_INVALID) {
1972 restoreTrack_l("getTimestamp");
1973 }
1974
Glenn Kasten200092b2014-08-15 15:13:30 -07001975 // The presented frame count must always lag behind the consumed frame count.
1976 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07001977 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001978 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07001979 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001980 return status;
1981 }
1982 if (isOffloadedOrDirect_l()) {
1983 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
1984 // use cached paused position in case another offloaded track is running.
1985 timestamp.mPosition = mPausedPosition;
1986 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
1987 return NO_ERROR;
1988 }
1989
1990 // Check whether a pending flush or stop has completed, as those commands may
1991 // be asynchronous or return near finish.
1992 if (mStartUs != 0 && mSampleRate != 0) {
1993 static const int kTimeJitterUs = 100000; // 100 ms
1994 static const int k1SecUs = 1000000;
1995
1996 const int64_t timeNow = getNowUs();
1997
1998 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
1999 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
2000 if (timestampTimeUs < mStartUs) {
2001 return WOULD_BLOCK; // stale timestamp time, occurs before start.
2002 }
2003 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
2004 const int64_t deltaPositionByUs = timestamp.mPosition * 1000000LL / mSampleRate;
2005
2006 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2007 // Verify that the counter can't count faster than the sample rate
2008 // since the start time. If greater, then that means we have failed
2009 // to completely flush or stop the previous playing track.
2010 ALOGW("incomplete flush or stop:"
2011 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2012 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2013 timestamp.mPosition);
2014 return WOULD_BLOCK;
2015 }
2016 }
2017 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
2018 }
2019 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002020 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2021 (void) updateAndGetPosition_l();
2022 // Server consumed (mServer) and presented both use the same server time base,
2023 // and server consumed is always >= presented.
2024 // The delta between these represents the number of frames in the buffer pipeline.
2025 // If this delta between these is greater than the client position, it means that
2026 // actually presented is still stuck at the starting line (figuratively speaking),
2027 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
2028 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2029 return INVALID_OPERATION;
2030 }
2031 // Convert timestamp position from server time base to client time base.
2032 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2033 // But if we change it to 64-bit then this could fail.
2034 // If (mPosition - mServer) can be negative then should use:
2035 // (int32_t)(mPosition - mServer)
2036 timestamp.mPosition += mPosition - mServer;
2037 // Immediately after a call to getPosition_l(), mPosition and
2038 // mServer both represent the same frame position. mPosition is
2039 // in client's point of view, and mServer is in server's point of
2040 // view. So the difference between them is the "fudge factor"
2041 // between client and server views due to stop() and/or new
2042 // IAudioTrack. And timestamp.mPosition is initially in server's
2043 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002044 }
2045 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002046}
2047
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002048String8 AudioTrack::getParameters(const String8& keys)
2049{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002050 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002051 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002052 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002053 } else {
2054 return String8::empty();
2055 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002056}
2057
Glenn Kasten23a75452014-01-13 10:37:17 -08002058bool AudioTrack::isOffloaded() const
2059{
2060 AutoMutex lock(mLock);
2061 return isOffloaded_l();
2062}
2063
Eric Laurentab5cdba2014-06-09 17:22:27 -07002064bool AudioTrack::isDirect() const
2065{
2066 AutoMutex lock(mLock);
2067 return isDirect_l();
2068}
2069
2070bool AudioTrack::isOffloadedOrDirect() const
2071{
2072 AutoMutex lock(mLock);
2073 return isOffloadedOrDirect_l();
2074}
2075
2076
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002077status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002078{
2079
2080 const size_t SIZE = 256;
2081 char buffer[SIZE];
2082 String8 result;
2083
2084 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002085 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002086 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002087 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002088 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002089 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002090 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08002091 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002092 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002093 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002094 result.append(buffer);
2095 ::write(fd, result.string(), result.size());
2096 return NO_ERROR;
2097}
2098
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002099uint32_t AudioTrack::getUnderrunFrames() const
2100{
2101 AutoMutex lock(mLock);
2102 return mProxy->getUnderrunFrames();
2103}
2104
2105// =========================================================================
2106
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002107void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002108{
2109 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2110 if (audioTrack != 0) {
2111 AutoMutex lock(audioTrack->mLock);
2112 audioTrack->mProxy->binderDied();
2113 }
2114}
2115
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002116// =========================================================================
2117
2118AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002119 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2120 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002121{
2122}
2123
2124AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002125{
2126}
2127
2128bool AudioTrack::AudioTrackThread::threadLoop()
2129{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002130 {
2131 AutoMutex _l(mMyLock);
2132 if (mPaused) {
2133 mMyCond.wait(mMyLock);
2134 // caller will check for exitPending()
2135 return true;
2136 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002137 if (mIgnoreNextPausedInt) {
2138 mIgnoreNextPausedInt = false;
2139 mPausedInt = false;
2140 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002141 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002142 if (mPausedNs > 0) {
2143 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2144 } else {
2145 mMyCond.wait(mMyLock);
2146 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002147 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002148 return true;
2149 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002150 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002151 if (exitPending()) {
2152 return false;
2153 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002154 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002155 switch (ns) {
2156 case 0:
2157 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002158 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002159 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002160 return true;
2161 case NS_NEVER:
2162 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002163 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08002164 // Event driven: call wake() when callback notifications conditions change.
2165 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002166 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002167 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002168 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002169 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002170 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002171 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002172}
2173
Glenn Kasten3acbd052012-02-28 10:39:56 -08002174void AudioTrack::AudioTrackThread::requestExit()
2175{
2176 // must be in this order to avoid a race condition
2177 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002178 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002179}
2180
2181void AudioTrack::AudioTrackThread::pause()
2182{
2183 AutoMutex _l(mMyLock);
2184 mPaused = true;
2185}
2186
2187void AudioTrack::AudioTrackThread::resume()
2188{
2189 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002190 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002191 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002192 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002193 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002194 mMyCond.signal();
2195 }
2196}
2197
Andy Hung3c09c782014-12-29 18:39:32 -08002198void AudioTrack::AudioTrackThread::wake()
2199{
2200 AutoMutex _l(mMyLock);
2201 if (!mPaused && mPausedInt && mPausedNs > 0) {
2202 // audio track is active and internally paused with timeout.
2203 mIgnoreNextPausedInt = true;
2204 mPausedInt = false;
2205 mMyCond.signal();
2206 }
2207}
2208
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002209void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2210{
2211 AutoMutex _l(mMyLock);
2212 mPausedInt = true;
2213 mPausedNs = ns;
2214}
2215
Glenn Kasten40bc9062015-03-20 09:09:33 -07002216} // namespace android