blob: ea7b2df380fd35f469cf9ebd7ce44adf202270cc [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080018//#define LOG_NDEBUG 0
19#define LOG_TAG "AudioTrack"
20
Mark Salyzyn34fb2962014-06-18 16:30:56 -070021#include <inttypes.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070022#include <math.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080023#include <sys/resource.h>
Mark Salyzyn34fb2962014-06-18 16:30:56 -070024
Glenn Kasten9f80dd22012-12-18 15:57:32 -080025#include <audio_utils/primitives.h>
26#include <binder/IPCThreadState.h>
27#include <media/AudioTrack.h>
28#include <utils/Log.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080029#include <private/media/AudioTrackShared.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/IAudioFlinger.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080031#include <media/AudioPolicyHelper.h>
Andy Hungcd044842014-08-07 11:04:34 -070032#include <media/AudioResamplerPublic.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080033
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010034#define WAIT_PERIOD_MS 10
35#define WAIT_STREAM_END_TIMEOUT_SEC 120
Andy Hung53c3b5f2014-12-15 16:42:05 -080036static const int kMaxLoopCountNotifications = 32;
Glenn Kasten511754b2012-01-11 09:52:19 -080037
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080038namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080039// ---------------------------------------------------------------------------
40
Andy Hung4ede21d2014-12-12 15:37:34 -080041template <typename T>
42const T &min(const T &x, const T &y) {
43 return x < y ? x : y;
44}
45
Andy Hung7f1bc8a2014-09-12 14:43:11 -070046static int64_t convertTimespecToUs(const struct timespec &tv)
47{
48 return tv.tv_sec * 1000000ll + tv.tv_nsec / 1000;
49}
50
51// current monotonic time in microseconds.
52static int64_t getNowUs()
53{
54 struct timespec tv;
55 (void) clock_gettime(CLOCK_MONOTONIC, &tv);
56 return convertTimespecToUs(tv);
57}
58
Chia-chi Yeh33005a92010-06-16 06:33:13 +080059// static
60status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080061 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080062 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080063 uint32_t sampleRate)
64{
Glenn Kastend65d73c2012-06-22 17:21:07 -070065 if (frameCount == NULL) {
66 return BAD_VALUE;
67 }
Glenn Kasten04cd0182012-06-25 11:49:27 -070068
Glenn Kastene0fa4672012-04-24 14:35:14 -070069 // FIXME merge with similar code in createTrack_l(), except we're missing
70 // some information here that is available in createTrack_l():
71 // audio_io_handle_t output
72 // audio_format_t format
73 // audio_channel_mask_t channelMask
74 // audio_output_flags_t flags
Glenn Kasten3b16c762012-11-14 08:44:39 -080075 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080076 status_t status;
77 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
78 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080079 ALOGE("Unable to query output sample rate for stream type %d; status %d",
80 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080081 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080082 }
Glenn Kastene33054e2012-11-14 12:54:39 -080083 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -080084 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
85 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080086 ALOGE("Unable to query output frame count for stream type %d; status %d",
87 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080088 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080089 }
90 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -080091 status = AudioSystem::getOutputLatency(&afLatency, streamType);
92 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080093 ALOGE("Unable to query output latency for stream type %d; status %d",
94 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080095 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080096 }
97
98 // Ensure that buffer depth covers at least audio hardware latency
99 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800100 if (minBufCount < 2) {
101 minBufCount = 2;
102 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800103
104 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
Andy Hungcd044842014-08-07 11:04:34 -0700105 afFrameCount * minBufCount * uint64_t(sampleRate) / afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -0800106 // The formula above should always produce a non-zero value, but return an error
107 // in the unlikely event that it does not, as that's part of the API contract.
108 if (*frameCount == 0) {
109 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %d",
110 streamType, sampleRate);
111 return BAD_VALUE;
112 }
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700113 ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, minBufCount=%d, afSampleRate=%d, afLatency=%d",
Glenn Kasten3acbd052012-02-28 10:39:56 -0800114 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800115 return NO_ERROR;
116}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800117
118// ---------------------------------------------------------------------------
119
120AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700121 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800122 mIsTimed(false),
123 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800124 mPreviousSchedulingGroup(SP_DEFAULT),
125 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800126{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700127 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
128 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
129 mAttributes.flags = 0x0;
130 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800131}
132
133AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800134 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800135 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800136 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700137 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800138 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700139 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800140 callback_t cbf,
141 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800142 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800143 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000144 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800145 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800146 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700147 pid_t pid,
148 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700149 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800150 mIsTimed(false),
151 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800152 mPreviousSchedulingGroup(SP_DEFAULT),
153 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800154{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700155 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700156 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800157 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700158 offloadInfo, uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800159}
160
Andreas Huberc8139852012-01-18 10:51:55 -0800161AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800162 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800163 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800164 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700165 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800166 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700167 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800168 callback_t cbf,
169 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800170 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800171 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000172 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800173 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800174 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700175 pid_t pid,
176 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700177 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800178 mIsTimed(false),
179 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800180 mPreviousSchedulingGroup(SP_DEFAULT),
181 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800182{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700183 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800184 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800185 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700186 uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800187}
188
189AudioTrack::~AudioTrack()
190{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800191 if (mStatus == NO_ERROR) {
192 // Make sure that callback function exits in the case where
193 // it is looping on buffer full condition in obtainBuffer().
194 // Otherwise the callback thread will never exit.
195 stop();
196 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100197 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800198 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800199 mAudioTrackThread->requestExitAndWait();
200 mAudioTrackThread.clear();
201 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800202 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700203 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700204 mCblkMemory.clear();
205 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800206 IPCThreadState::self()->flushCommands();
Marco Nelissend457c972014-02-11 08:47:07 -0800207 ALOGV("~AudioTrack, releasing session id from %d on behalf of %d",
208 IPCThreadState::self()->getCallingPid(), mClientPid);
209 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800210 }
211}
212
213status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800214 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800215 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800216 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700217 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800218 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700219 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800220 callback_t cbf,
221 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800222 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800223 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700224 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800225 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000226 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800227 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800228 int uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700229 pid_t pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700230 const audio_attributes_t* pAttributes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800231{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800232 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten838b3d82014-02-27 15:30:41 -0800233 "flags #%x, notificationFrames %u, sessionId %d, transferType %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800234 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten86f04662014-02-24 15:13:05 -0800235 sessionId, transferType);
236
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800237 switch (transferType) {
238 case TRANSFER_DEFAULT:
239 if (sharedBuffer != 0) {
240 transferType = TRANSFER_SHARED;
241 } else if (cbf == NULL || threadCanCallJava) {
242 transferType = TRANSFER_SYNC;
243 } else {
244 transferType = TRANSFER_CALLBACK;
245 }
246 break;
247 case TRANSFER_CALLBACK:
248 if (cbf == NULL || sharedBuffer != 0) {
249 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
250 return BAD_VALUE;
251 }
252 break;
253 case TRANSFER_OBTAIN:
254 case TRANSFER_SYNC:
255 if (sharedBuffer != 0) {
256 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
257 return BAD_VALUE;
258 }
259 break;
260 case TRANSFER_SHARED:
261 if (sharedBuffer == 0) {
262 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
263 return BAD_VALUE;
264 }
265 break;
266 default:
267 ALOGE("Invalid transfer type %d", transferType);
268 return BAD_VALUE;
269 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800270 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800271 mTransfer = transferType;
272
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700273 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
274 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800275
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700276 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700277
Eric Laurent1703cdf2011-03-07 14:52:59 -0800278 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800279
Glenn Kasten53cec222013-08-29 09:01:02 -0700280 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700281 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000282 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800283 return INVALID_OPERATION;
284 }
285
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800286 // handle default values first.
Eric Laurente83b55d2014-11-14 10:06:21 -0800287 if (streamType == AUDIO_STREAM_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700288 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800289 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700290 if (pAttributes == NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800291 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700292 ALOGE("Invalid stream type %d", streamType);
293 return BAD_VALUE;
294 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700295 mStreamType = streamType;
Eric Laurente83b55d2014-11-14 10:06:21 -0800296
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700297 } else {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700298 // stream type shouldn't be looked at, this track has audio attributes
299 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700300 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
301 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800302 mStreamType = AUDIO_STREAM_DEFAULT;
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800303 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700304
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800305 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800306 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700307 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800308 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800309
310 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700311 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800312 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800313 return BAD_VALUE;
314 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800315 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700316
Glenn Kasten8ba90322013-10-30 11:29:27 -0700317 if (!audio_is_output_channel(channelMask)) {
318 ALOGE("Invalid channel mask %#x", channelMask);
319 return BAD_VALUE;
320 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800321 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700322 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800323 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700324
Glenn Kastene0fa4672012-04-24 14:35:14 -0700325 // AudioFlinger does not currently support 8-bit data in shared memory
326 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
327 ALOGE("8-bit data in shared memory is not supported");
328 return BAD_VALUE;
329 }
330
Eric Laurentc2f1f072009-07-17 12:17:14 -0700331 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100332 // or offload was requested
333 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
334 || !audio_is_linear_pcm(format)) {
335 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
336 ? "Offload request, forcing to Direct Output"
337 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700338 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800339 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700340 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700341 }
342
Eric Laurentd1f69b02014-12-15 14:33:13 -0800343 // force direct flag if HW A/V sync requested
344 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
345 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
346 }
347
Glenn Kastenb7730382014-04-30 15:50:31 -0700348 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
349 if (audio_is_linear_pcm(format)) {
350 mFrameSize = channelCount * audio_bytes_per_sample(format);
351 } else {
352 mFrameSize = sizeof(uint8_t);
353 }
354 mFrameSizeAF = mFrameSize;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800355 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700356 ALOG_ASSERT(audio_is_linear_pcm(format));
357 mFrameSize = channelCount * audio_bytes_per_sample(format);
358 mFrameSizeAF = channelCount * audio_bytes_per_sample(
359 format == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : format);
360 // createTrack will return an error if PCM format is not supported by server,
361 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800362 }
363
Eric Laurent0d6db582014-11-12 18:39:44 -0800364 // sampling rate must be specified for direct outputs
365 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
366 return BAD_VALUE;
367 }
368 mSampleRate = sampleRate;
369
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800370 // Make copy of input parameter offloadInfo so that in the future:
371 // (a) createTrack_l doesn't need it as an input parameter
372 // (b) we can support re-creation of offloaded tracks
373 if (offloadInfo != NULL) {
374 mOffloadInfoCopy = *offloadInfo;
375 mOffloadInfo = &mOffloadInfoCopy;
376 } else {
377 mOffloadInfo = NULL;
378 }
379
Glenn Kasten66e46352014-01-16 17:44:23 -0800380 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
381 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800382 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800383 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800384 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700385 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800386 mNotificationFramesAct = 0;
Eric Laurentcaf7f482014-11-25 17:50:47 -0800387 if (sessionId == AUDIO_SESSION_ALLOCATE) {
388 mSessionId = AudioSystem::newAudioUniqueId();
389 } else {
390 mSessionId = sessionId;
391 }
Marco Nelissend457c972014-02-11 08:47:07 -0800392 int callingpid = IPCThreadState::self()->getCallingPid();
393 int mypid = getpid();
394 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800395 mClientUid = IPCThreadState::self()->getCallingUid();
396 } else {
397 mClientUid = uid;
398 }
Marco Nelissend457c972014-02-11 08:47:07 -0800399 if (pid == -1 || (callingpid != mypid)) {
400 mClientPid = callingpid;
401 } else {
402 mClientPid = pid;
403 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700404 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700405 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700406 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700407
Glenn Kastena997e7a2012-08-07 09:44:19 -0700408 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700409 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700410 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
411 }
412
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800413 // create the IAudioTrack
Eric Laurent0d6db582014-11-12 18:39:44 -0800414 status_t status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800415
Glenn Kastena997e7a2012-08-07 09:44:19 -0700416 if (status != NO_ERROR) {
417 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100418 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
419 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700420 mAudioTrackThread.clear();
421 }
422 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700423 }
424
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800425 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800426 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800427 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800428 mLoopCount = 0;
429 mLoopStart = 0;
430 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800431 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800432 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700433 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800434 mNewPosition = 0;
435 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700436 mServer = 0;
437 mPosition = 0;
438 mReleased = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700439 mStartUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800440 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800441 mSequence = 1;
442 mObservedSequence = mSequence;
443 mInUnderrun = false;
444
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800445 return NO_ERROR;
446}
447
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800448// -------------------------------------------------------------------------
449
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100450status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800451{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800452 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100453
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800454 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100455 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800456 }
457
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800458 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800459
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800460 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100461 if (previousState == STATE_PAUSED_STOPPING) {
462 mState = STATE_STOPPING;
463 } else {
464 mState = STATE_ACTIVE;
465 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700466 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800467 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
468 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700469 mPosition = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700470 // For offloaded tracks, we don't know if the hardware counters are really zero here,
471 // since the flush is asynchronous and stop may not fully drain.
472 // We save the time when the track is started to later verify whether
473 // the counters are realistic (i.e. start from zero after this time).
474 mStartUs = getNowUs();
475
Eric Laurentec9a0322013-08-28 10:23:01 -0700476 // force refresh of remaining frames by processAudioBuffer() as last
477 // write before stop could be partial.
478 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800479 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700480 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700481 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800482
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800483 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800484 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100485 if (previousState == STATE_STOPPING) {
486 mProxy->interrupt();
487 } else {
488 t->resume();
489 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800490 } else {
491 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
492 get_sched_policy(0, &mPreviousSchedulingGroup);
493 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
494 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800495
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800496 status_t status = NO_ERROR;
497 if (!(flags & CBLK_INVALID)) {
498 status = mAudioTrack->start();
499 if (status == DEAD_OBJECT) {
500 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800501 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800502 }
503 if (flags & CBLK_INVALID) {
504 status = restoreTrack_l("start");
505 }
506
507 if (status != NO_ERROR) {
508 ALOGE("start() status %d", status);
509 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800510 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100511 if (previousState != STATE_STOPPING) {
512 t->pause();
513 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800514 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700515 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700516 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800517 }
518 }
519
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100520 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800521}
522
523void AudioTrack::stop()
524{
525 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700526 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800527 return;
528 }
529
Glenn Kasten23a75452014-01-13 10:37:17 -0800530 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100531 mState = STATE_STOPPING;
532 } else {
533 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -0700534 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100535 }
536
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800537 mProxy->interrupt();
538 mAudioTrack->stop();
539 // the playback head position will reset to 0, so if a marker is set, we need
540 // to activate it again
541 mMarkerReached = false;
Andy Hung9b461582014-12-01 17:56:29 -0800542
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800543 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800544 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800545 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
546 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800547 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100548
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800549 sp<AudioTrackThread> t = mAudioTrackThread;
550 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800551 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100552 t->pause();
553 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800554 } else {
555 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
556 set_sched_policy(0, mPreviousSchedulingGroup);
557 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800558}
559
560bool AudioTrack::stopped() const
561{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800562 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800563 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800564}
565
566void AudioTrack::flush()
567{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800568 if (mSharedBuffer != 0) {
569 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800570 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800571 AutoMutex lock(mLock);
572 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
573 return;
574 }
575 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800576}
577
Eric Laurent1703cdf2011-03-07 14:52:59 -0800578void AudioTrack::flush_l()
579{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800580 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700581
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700582 // clear playback marker and periodic update counter
583 mMarkerPosition = 0;
584 mMarkerReached = false;
585 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100586 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700587
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800588 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700589 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800590 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100591 mProxy->interrupt();
592 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800593 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800594 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800595}
596
597void AudioTrack::pause()
598{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800599 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100600 if (mState == STATE_ACTIVE) {
601 mState = STATE_PAUSED;
602 } else if (mState == STATE_STOPPING) {
603 mState = STATE_PAUSED_STOPPING;
604 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800605 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800606 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800607 mProxy->interrupt();
608 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800609
Marco Nelissen3a90f282014-03-10 11:21:43 -0700610 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700611 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700612 // An offload output can be re-used between two audio tracks having
613 // the same configuration. A timestamp query for a paused track
614 // while the other is running would return an incorrect time.
615 // To fix this, cache the playback position on a pause() and return
616 // this time when requested until the track is resumed.
617
618 // OffloadThread sends HAL pause in its threadLoop. Time saved
619 // here can be slightly off.
620
621 // TODO: check return code for getRenderPosition.
622
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800623 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800624 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
625 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
626 }
627 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800628}
629
Eric Laurentbe916aa2010-06-01 23:49:17 -0700630status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800631{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700632 // This duplicates a test by AudioTrack JNI, but that is not the only caller
633 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
634 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700635 return BAD_VALUE;
636 }
637
Eric Laurent1703cdf2011-03-07 14:52:59 -0800638 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800639 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
640 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800641
Glenn Kastenc56f3422014-03-21 17:53:17 -0700642 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700643
Glenn Kasten23a75452014-01-13 10:37:17 -0800644 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700645 mAudioTrack->signal();
646 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700647 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800648}
649
Glenn Kastenb1c09932012-02-27 16:21:04 -0800650status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800651{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800652 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700653}
654
Eric Laurent2beeb502010-07-16 07:43:46 -0700655status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700656{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700657 // This duplicates a test by AudioTrack JNI, but that is not the only caller
658 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700659 return BAD_VALUE;
660 }
661
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800662 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700663 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800664 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700665
666 return NO_ERROR;
667}
668
Glenn Kastena5224f32012-01-04 12:41:44 -0800669void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700670{
671 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800672 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700673 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800674}
675
Glenn Kasten3b16c762012-11-14 08:44:39 -0800676status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800677{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700678 if (mIsTimed || isOffloadedOrDirect()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800679 return INVALID_OPERATION;
680 }
681
Eric Laurent0d6db582014-11-12 18:39:44 -0800682 AutoMutex lock(mLock);
683 if (mOutput == AUDIO_IO_HANDLE_NONE) {
684 return NO_INIT;
685 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800686 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800687 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700688 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800689 }
Andy Hungcd044842014-08-07 11:04:34 -0700690 if (rate == 0 || rate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700691 return BAD_VALUE;
692 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800693
Glenn Kastene3aa6592012-12-04 12:22:46 -0800694 mSampleRate = rate;
695 mProxy->setSampleRate(rate);
696
Eric Laurent57326622009-07-07 07:10:45 -0700697 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800698}
699
Glenn Kastena5224f32012-01-04 12:41:44 -0800700uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800701{
John Grossman4ff14ba2012-02-08 16:37:41 -0800702 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800703 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800704 }
705
Eric Laurent1703cdf2011-03-07 14:52:59 -0800706 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700707
708 // sample rate can be updated during playback by the offloaded decoder so we need to
709 // query the HAL and update if needed.
710// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700711 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700712 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700713 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700714 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700715 if (status == NO_ERROR) {
716 mSampleRate = sampleRate;
717 }
718 }
719 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800720 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800721}
722
723status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
724{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700725 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800726 return INVALID_OPERATION;
727 }
728
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800729 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800730 ;
731 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
732 loopEnd - loopStart >= MIN_LOOP) {
733 ;
734 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800735 return BAD_VALUE;
736 }
737
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800738 AutoMutex lock(mLock);
739 // See setPosition() regarding setting parameters such as loop points or position while active
740 if (mState == STATE_ACTIVE) {
741 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700742 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800743 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800744 return NO_ERROR;
745}
746
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800747void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
748{
Andy Hung4ede21d2014-12-12 15:37:34 -0800749 // We do not update the periodic notification point.
750 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
751 mLoopCount = loopCount;
752 mLoopEnd = loopEnd;
753 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800754 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800755 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
756}
757
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800758status_t AudioTrack::setMarkerPosition(uint32_t marker)
759{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700760 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700761 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700762 return INVALID_OPERATION;
763 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800764
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800765 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800766 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700767 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800768
769 return NO_ERROR;
770}
771
Glenn Kastena5224f32012-01-04 12:41:44 -0800772status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800773{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700774 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100775 return INVALID_OPERATION;
776 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700777 if (marker == NULL) {
778 return BAD_VALUE;
779 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800780
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800781 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800782 *marker = mMarkerPosition;
783
784 return NO_ERROR;
785}
786
787status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
788{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700789 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700790 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700791 return INVALID_OPERATION;
792 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800793
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800794 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700795 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800796 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800797
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800798 return NO_ERROR;
799}
800
Glenn Kastena5224f32012-01-04 12:41:44 -0800801status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800802{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700803 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100804 return INVALID_OPERATION;
805 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700806 if (updatePeriod == NULL) {
807 return BAD_VALUE;
808 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800809
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800810 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800811 *updatePeriod = mUpdatePeriod;
812
813 return NO_ERROR;
814}
815
816status_t AudioTrack::setPosition(uint32_t position)
817{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700818 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700819 return INVALID_OPERATION;
820 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800821 if (position > mFrameCount) {
822 return BAD_VALUE;
823 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800824
Eric Laurent1703cdf2011-03-07 14:52:59 -0800825 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800826 // Currently we require that the player is inactive before setting parameters such as position
827 // or loop points. Otherwise, there could be a race condition: the application could read the
828 // current position, compute a new position or loop parameters, and then set that position or
829 // loop parameters but it would do the "wrong" thing since the position has continued to advance
830 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
831 // to specify how it wants to handle such scenarios.
832 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700833 return INVALID_OPERATION;
834 }
Andy Hung9b461582014-12-01 17:56:29 -0800835 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -0700836 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800837 mStaticProxy->setBufferPosition(position);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800838 return NO_ERROR;
839}
840
Glenn Kasten200092b2014-08-15 15:13:30 -0700841status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800842{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700843 if (position == NULL) {
844 return BAD_VALUE;
845 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800846
Eric Laurent1703cdf2011-03-07 14:52:59 -0800847 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700848 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100849 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800850
Eric Laurentab5cdba2014-06-09 17:22:27 -0700851 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800852 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
853 *position = mPausedPosition;
854 return NO_ERROR;
855 }
856
Glenn Kasten142f5192014-03-25 17:44:59 -0700857 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100858 uint32_t halFrames;
859 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
860 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700861 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
862 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100863 *position = dspFrames;
864 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -0800865 if (mCblk->mFlags & CBLK_INVALID) {
866 restoreTrack_l("getPosition");
867 }
868
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100869 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700870 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
871 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100872 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800873 return NO_ERROR;
874}
875
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000876status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800877{
878 if (mSharedBuffer == 0 || mIsTimed) {
879 return INVALID_OPERATION;
880 }
881 if (position == NULL) {
882 return BAD_VALUE;
883 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800884
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800885 AutoMutex lock(mLock);
886 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800887 return NO_ERROR;
888}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800889
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800890status_t AudioTrack::reload()
891{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700892 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800893 return INVALID_OPERATION;
894 }
895
Eric Laurent1703cdf2011-03-07 14:52:59 -0800896 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800897 // See setPosition() regarding setting parameters such as loop points or position while active
898 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700899 return INVALID_OPERATION;
900 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800901 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800902 (void) updateAndGetPosition_l();
903 mPosition = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800904#if 0
Andy Hung9b461582014-12-01 17:56:29 -0800905 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -0800906 // of loop count. Historically we have not restored loop count, start, end,
907 // but it makes sense if one desires to repeat playing a particular sound.
908 if (mLoopCount != 0) {
909 mLoopCountNotified = mLoopCount;
910 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
911 }
912#endif
Andy Hung9b461582014-12-01 17:56:29 -0800913 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800914 return NO_ERROR;
915}
916
Glenn Kasten38e905b2014-01-13 10:21:48 -0800917audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700918{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800919 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100920 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800921}
922
Eric Laurentbe916aa2010-06-01 23:49:17 -0700923status_t AudioTrack::attachAuxEffect(int effectId)
924{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800925 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700926 status_t status = mAudioTrack->attachAuxEffect(effectId);
927 if (status == NO_ERROR) {
928 mAuxEffectId = effectId;
929 }
930 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700931}
932
Eric Laurente83b55d2014-11-14 10:06:21 -0800933audio_stream_type_t AudioTrack::streamType() const
934{
935 if (mStreamType == AUDIO_STREAM_DEFAULT) {
936 return audio_attributes_to_stream_type(&mAttributes);
937 }
938 return mStreamType;
939}
940
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800941// -------------------------------------------------------------------------
942
Eric Laurent1703cdf2011-03-07 14:52:59 -0800943// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -0700944status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800945{
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800946 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
947 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700948 ALOGE("Could not get audioflinger");
949 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800950 }
951
Eric Laurente83b55d2014-11-14 10:06:21 -0800952 audio_io_handle_t output;
953 audio_stream_type_t streamType = mStreamType;
954 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
955 status_t status = AudioSystem::getOutputForAttr(attr, &output,
956 (audio_session_t)mSessionId, &streamType,
957 mSampleRate, mFormat, mChannelMask,
958 mFlags, mOffloadInfo);
959
960
961 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700962 ALOGE("Could not get audio output for stream type %d, usage %d, sample rate %u, format %#x,"
963 " channel mask %#x, flags %#x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800964 streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800965 return BAD_VALUE;
966 }
967 {
968 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
969 // we must release it ourselves if anything goes wrong.
970
Glenn Kastence8828a2013-09-16 18:07:38 -0700971 // Not all of these values are needed under all conditions, but it is easier to get them all
972
Eric Laurentd1b449a2010-05-14 03:26:45 -0700973 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -0700974 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700975 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800976 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800977 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700978 }
979
Glenn Kastence8828a2013-09-16 18:07:38 -0700980 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700981 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -0700982 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700983 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800984 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700985 }
986
987 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700988 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -0700989 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700990 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800991 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700992 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800993 if (mSampleRate == 0) {
994 mSampleRate = afSampleRate;
995 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700996 // Client decides whether the track is TIMED (see below), but can only express a preference
997 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800998 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700999 // either of these use cases:
1000 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -08001001 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001002 // use case 2: callback transfer mode
1003 (mTransfer == TRANSFER_CALLBACK)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001004 // matching sample rate
1005 (mSampleRate == afSampleRate))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08001006 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -07001007 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001008 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001009 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001010 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001011
Glenn Kastence8828a2013-09-16 18:07:38 -07001012 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -08001013 // n = 1 fast track with single buffering; nBuffering is ignored
1014 // n = 2 fast track with double buffering
Glenn Kastence8828a2013-09-16 18:07:38 -07001015 // n = 2 normal track, no sample rate conversion
1016 // n = 3 normal track, with sample rate conversion
1017 // (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering)
1018 // n > 3 very high latency or very small notification interval; nBuffering is ignored
Glenn Kasten363fb752014-01-15 12:27:31 -08001019 const uint32_t nBuffering = (mSampleRate == afSampleRate) ? 2 : 3;
Glenn Kastence8828a2013-09-16 18:07:38 -07001020
Eric Laurentd1b449a2010-05-14 03:26:45 -07001021 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001022
Glenn Kasten363fb752014-01-15 12:27:31 -08001023 size_t frameCount = mReqFrameCount;
1024 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001025
Glenn Kasten363fb752014-01-15 12:27:31 -08001026 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001027 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001028 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001029 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001030 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001031 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001032 if (mNotificationFramesAct != frameCount) {
1033 mNotificationFramesAct = frameCount;
1034 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001035 } else if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001036
Glenn Kastena42ff002012-11-14 12:47:55 -08001037 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -07001038 // 8-bit data in shared memory is not currently supported by AudioFlinger
Glenn Kastenb7730382014-04-30 15:50:31 -07001039 size_t alignment = audio_bytes_per_sample(
1040 mFormat == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : mFormat);
1041 if (alignment & 1) {
1042 alignment = 1;
1043 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001044 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001045 // More than 2 channels does not require stronger alignment than stereo
1046 alignment <<= 1;
1047 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001048 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001049 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001050 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001051 status = BAD_VALUE;
1052 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001053 }
1054
1055 // When initializing a shared buffer AudioTrack via constructors,
1056 // there's no frameCount parameter.
1057 // But when initializing a shared buffer AudioTrack via set(),
1058 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kastenb7730382014-04-30 15:50:31 -07001059 frameCount = mSharedBuffer->size() / mFrameSizeAF;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001060
Glenn Kasten363fb752014-01-15 12:27:31 -08001061 } else if (!(mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001062
1063 // FIXME move these calculations and associated checks to server
Glenn Kastene0fa4672012-04-24 14:35:14 -07001064
Eric Laurentd1b449a2010-05-14 03:26:45 -07001065 // Ensure that buffer depth covers at least audio hardware latency
1066 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001067 ALOGV("afFrameCount=%zu, minBufCount=%d, afSampleRate=%u, afLatency=%d",
Glenn Kastenbb6f0a02013-06-03 15:00:29 -07001068 afFrameCount, minBufCount, afSampleRate, afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001069 if (minBufCount <= nBuffering) {
1070 minBufCount = nBuffering;
Glenn Kasten7c027242012-12-26 14:43:16 -08001071 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001072
Andy Hungcd044842014-08-07 11:04:34 -07001073 size_t minFrameCount = afFrameCount * minBufCount * uint64_t(mSampleRate) / afSampleRate;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001074 ALOGV("minFrameCount: %zu, afFrameCount=%zu, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -08001075 ", afLatency=%d",
Glenn Kasten363fb752014-01-15 12:27:31 -08001076 minFrameCount, afFrameCount, minBufCount, mSampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001077
1078 if (frameCount == 0) {
1079 frameCount = minFrameCount;
Glenn Kastence8828a2013-09-16 18:07:38 -07001080 } else if (frameCount < minFrameCount) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001081 // not ALOGW because it happens all the time when playing key clicks over A2DP
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001082 ALOGV("Minimum buffer size corrected from %zu to %zu",
Glenn Kastene0fa4672012-04-24 14:35:14 -07001083 frameCount, minFrameCount);
1084 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001085 }
Glenn Kastence8828a2013-09-16 18:07:38 -07001086 // Make sure that application is notified with sufficient margin before underrun
1087 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1088 mNotificationFramesAct = frameCount/nBuffering;
1089 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001090
Glenn Kastene0fa4672012-04-24 14:35:14 -07001091 } else {
1092 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -07001093 }
1094
Glenn Kastena075db42012-03-06 11:22:44 -08001095 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1096 if (mIsTimed) {
1097 trackFlags |= IAudioFlinger::TRACK_TIMED;
1098 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001099
1100 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001101 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001102 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001103 if (mAudioTrackThread != 0) {
1104 tid = mAudioTrackThread->getTid();
1105 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001106 }
1107
Glenn Kasten363fb752014-01-15 12:27:31 -08001108 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001109 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1110 }
1111
Eric Laurentab5cdba2014-06-09 17:22:27 -07001112 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1113 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1114 }
1115
Glenn Kasten74935e42013-12-19 08:56:45 -08001116 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1117 // but we will still need the original value also
Eric Laurente83b55d2014-11-14 10:06:21 -08001118 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001119 mSampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -07001120 // AudioFlinger only sees 16-bit PCM
Glenn Kastenc4b88a82014-04-30 16:54:30 -07001121 mFormat == AUDIO_FORMAT_PCM_8_BIT &&
1122 !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ?
Glenn Kasten363fb752014-01-15 12:27:31 -08001123 AUDIO_FORMAT_PCM_16_BIT : mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001124 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001125 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001126 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001127 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001128 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001129 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001130 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001131 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001132 &status);
1133
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001134 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001135 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001136 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001137 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001138 ALOG_ASSERT(track != 0);
1139
Glenn Kasten38e905b2014-01-13 10:21:48 -08001140 // AudioFlinger now owns the reference to the I/O handle,
1141 // so we are no longer responsible for releasing it.
1142
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001143 sp<IMemory> iMem = track->getCblk();
1144 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001145 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001146 return NO_INIT;
1147 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001148 void *iMemPointer = iMem->pointer();
1149 if (iMemPointer == NULL) {
1150 ALOGE("Could not get control block pointer");
1151 return NO_INIT;
1152 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001153 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001154 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001155 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001156 mDeathNotifier.clear();
1157 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001158 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001159 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001160 IPCThreadState::self()->flushCommands();
1161
Glenn Kasten0cde0762014-01-16 15:06:36 -08001162 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001163 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001164 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001165 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1166 // In current design, AudioTrack client checks and ensures frame count validity before
1167 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1168 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001169 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001170 }
1171 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001172
Glenn Kastena07f17c2013-04-23 12:39:37 -07001173 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001174 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001175 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001176 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001177 mAwaitBoost = true;
Glenn Kasten363fb752014-01-15 12:27:31 -08001178 if (mSharedBuffer == 0) {
Glenn Kastenb5fed682013-12-03 09:06:43 -08001179 // Theoretically double-buffering is not required for fast tracks,
1180 // due to tighter scheduling. But in practice, to accommodate kernels with
1181 // scheduling jitter, and apps with computation jitter, we use double-buffering.
1182 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1183 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001184 }
1185 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001186 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001187 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001188 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001189 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1190 if (mSharedBuffer == 0) {
Glenn Kastence8828a2013-09-16 18:07:38 -07001191 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1192 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001193 }
1194 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001195 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001196 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001197 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001198 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1199 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1200 } else {
1201 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001202 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001203 // FIXME This is a warning, not an error, so don't return error status
1204 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001205 }
1206 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001207 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1208 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1209 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1210 } else {
1211 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1212 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1213 // FIXME This is a warning, not an error, so don't return error status
1214 //return NO_INIT;
1215 }
1216 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001217
Glenn Kasten38e905b2014-01-13 10:21:48 -08001218 // We retain a copy of the I/O handle, but don't own the reference
1219 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001220 mRefreshRemaining = true;
1221
1222 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1223 // is the value of pointer() for the shared buffer, otherwise buffers points
1224 // immediately after the control block. This address is for the mapping within client
1225 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1226 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001227 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001228 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001229 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001230 buffers = mSharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001231 }
1232
Eric Laurent2beeb502010-07-16 07:43:46 -07001233 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001234 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001235 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001236
Glenn Kastenb6037442012-11-14 13:42:25 -08001237 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001238 // If IAudioTrack is re-created, don't let the requested frameCount
1239 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001240 if (frameCount > mReqFrameCount) {
1241 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001242 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001243
1244 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001245 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001246 mStaticProxy.clear();
1247 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1248 } else {
1249 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1250 mProxy = mStaticProxy;
1251 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001252
1253 mProxy->setVolumeLR(gain_minifloat_pack(
1254 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1255 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1256
Glenn Kastene3aa6592012-12-04 12:22:46 -08001257 mProxy->setSendLevel(mSendLevel);
1258 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001259 mProxy->setMinimum(mNotificationFramesAct);
1260
1261 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001262 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001263
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001264 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001265 }
1266
1267release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001268 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001269 if (status == NO_ERROR) {
1270 status = NO_INIT;
1271 }
1272 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001273}
1274
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001275status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1276{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001277 if (audioBuffer == NULL) {
1278 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001279 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001280 if (mTransfer != TRANSFER_OBTAIN) {
1281 audioBuffer->frameCount = 0;
1282 audioBuffer->size = 0;
1283 audioBuffer->raw = NULL;
1284 return INVALID_OPERATION;
1285 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001286
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001287 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001288 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001289 if (waitCount == -1) {
1290 requested = &ClientProxy::kForever;
1291 } else if (waitCount == 0) {
1292 requested = &ClientProxy::kNonBlocking;
1293 } else if (waitCount > 0) {
1294 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001295 timeout.tv_sec = ms / 1000;
1296 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1297 requested = &timeout;
1298 } else {
1299 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1300 requested = NULL;
1301 }
1302 return obtainBuffer(audioBuffer, requested);
1303}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001304
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001305status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1306 struct timespec *elapsed, size_t *nonContig)
1307{
1308 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1309 uint32_t oldSequence = 0;
1310 uint32_t newSequence;
1311
1312 Proxy::Buffer buffer;
1313 status_t status = NO_ERROR;
1314
1315 static const int32_t kMaxTries = 5;
1316 int32_t tryCounter = kMaxTries;
1317
1318 do {
1319 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1320 // keep them from going away if another thread re-creates the track during obtainBuffer()
1321 sp<AudioTrackClientProxy> proxy;
1322 sp<IMemory> iMem;
1323
1324 { // start of lock scope
1325 AutoMutex lock(mLock);
1326
1327 newSequence = mSequence;
1328 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1329 if (status == DEAD_OBJECT) {
1330 // re-create track, unless someone else has already done so
1331 if (newSequence == oldSequence) {
1332 status = restoreTrack_l("obtainBuffer");
1333 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001334 buffer.mFrameCount = 0;
1335 buffer.mRaw = NULL;
1336 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001337 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001338 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001339 }
1340 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001341 oldSequence = newSequence;
1342
1343 // Keep the extra references
1344 proxy = mProxy;
1345 iMem = mCblkMemory;
1346
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001347 if (mState == STATE_STOPPING) {
1348 status = -EINTR;
1349 buffer.mFrameCount = 0;
1350 buffer.mRaw = NULL;
1351 buffer.mNonContig = 0;
1352 break;
1353 }
1354
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001355 // Non-blocking if track is stopped or paused
1356 if (mState != STATE_ACTIVE) {
1357 requested = &ClientProxy::kNonBlocking;
1358 }
1359
1360 } // end of lock scope
1361
1362 buffer.mFrameCount = audioBuffer->frameCount;
1363 // FIXME starts the requested timeout and elapsed over from scratch
1364 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1365
1366 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1367
1368 audioBuffer->frameCount = buffer.mFrameCount;
1369 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1370 audioBuffer->raw = buffer.mRaw;
1371 if (nonContig != NULL) {
1372 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001373 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001374 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001375}
1376
1377void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1378{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001379 if (mTransfer == TRANSFER_SHARED) {
1380 return;
1381 }
1382
1383 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1384 if (stepCount == 0) {
1385 return;
1386 }
1387
1388 Proxy::Buffer buffer;
1389 buffer.mFrameCount = stepCount;
1390 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001391
Eric Laurent1703cdf2011-03-07 14:52:59 -08001392 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001393 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001394 mInUnderrun = false;
1395 mProxy->releaseBuffer(&buffer);
1396
1397 // restart track if it was disabled by audioflinger due to previous underrun
1398 if (mState == STATE_ACTIVE) {
1399 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001400 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001401 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001402 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001403 mAudioTrack->start();
1404 }
1405 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001406}
1407
1408// -------------------------------------------------------------------------
1409
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001410ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001411{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001412 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001413 return INVALID_OPERATION;
1414 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001415
Eric Laurentab5cdba2014-06-09 17:22:27 -07001416 if (isDirect()) {
1417 AutoMutex lock(mLock);
1418 int32_t flags = android_atomic_and(
1419 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1420 &mCblk->mFlags);
1421 if (flags & CBLK_INVALID) {
1422 return DEAD_OBJECT;
1423 }
1424 }
1425
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001426 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001427 // Sanity-check: user is most-likely passing an error code, and it would
1428 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001429 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001430 return BAD_VALUE;
1431 }
1432
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001433 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001434 Buffer audioBuffer;
1435
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001436 while (userSize >= mFrameSize) {
1437 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001438
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001439 status_t err = obtainBuffer(&audioBuffer,
1440 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001441 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001442 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001443 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001444 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001445 return ssize_t(err);
1446 }
1447
1448 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001449 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001450 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001451 toWrite = audioBuffer.size >> 1;
1452 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001453 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001454 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001455 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001456 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001457 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001458 userSize -= toWrite;
1459 written += toWrite;
1460
1461 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001462 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001463
1464 return written;
1465}
1466
1467// -------------------------------------------------------------------------
1468
John Grossman4ff14ba2012-02-08 16:37:41 -08001469TimedAudioTrack::TimedAudioTrack() {
1470 mIsTimed = true;
1471}
1472
1473status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1474{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001475 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001476 status_t result = UNKNOWN_ERROR;
1477
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001478#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001479 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1480 // while we are accessing the cblk
1481 sp<IAudioTrack> audioTrack = mAudioTrack;
1482 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001483#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001484
John Grossman4ff14ba2012-02-08 16:37:41 -08001485 // If the track is not invalid already, try to allocate a buffer. alloc
1486 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001487 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001488 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001489 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001490 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1491 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001492 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001493 }
1494 }
1495
1496 // If the track is invalid at this point, attempt to restore it. and try the
1497 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001498 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001499 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001500
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001501 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001502 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001503 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001504 }
1505
1506 return result;
1507}
1508
1509status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1510 int64_t pts)
1511{
Eric Laurentdf839842012-05-31 14:27:14 -07001512 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1513 {
1514 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001515 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001516 // restart track if it was disabled by audioflinger due to previous underrun
1517 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001518 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1519 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001520 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001521 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001522 mAudioTrack->start();
1523 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001524 }
Eric Laurentdf839842012-05-31 14:27:14 -07001525 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001526}
1527
1528status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1529 TargetTimeline target)
1530{
1531 return mAudioTrack->setMediaTimeTransform(xform, target);
1532}
1533
1534// -------------------------------------------------------------------------
1535
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001536nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001537{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001538 // Currently the AudioTrack thread is not created if there are no callbacks.
1539 // Would it ever make sense to run the thread, even without callbacks?
1540 // If so, then replace this by checks at each use for mCbf != NULL.
1541 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1542
Eric Laurent1703cdf2011-03-07 14:52:59 -08001543 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001544 if (mAwaitBoost) {
1545 mAwaitBoost = false;
1546 mLock.unlock();
1547 static const int32_t kMaxTries = 5;
1548 int32_t tryCounter = kMaxTries;
1549 uint32_t pollUs = 10000;
1550 do {
1551 int policy = sched_getscheduler(0);
1552 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1553 break;
1554 }
1555 usleep(pollUs);
1556 pollUs <<= 1;
1557 } while (tryCounter-- > 0);
1558 if (tryCounter < 0) {
1559 ALOGE("did not receive expected priority boost on time");
1560 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001561 // Run again immediately
1562 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001563 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001564
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001565 // Can only reference mCblk while locked
1566 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001567 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001568
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001569 // Check for track invalidation
1570 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001571 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1572 // AudioSystem cache. We should not exit here but after calling the callback so
1573 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001574 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001575 status_t status = restoreTrack_l("processAudioBuffer");
Andy Hung53c3b5f2014-12-15 16:42:05 -08001576 // after restoration, continue below to make sure that the loop and buffer events
1577 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001578 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001579 }
1580
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001581 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001582 bool active = mState == STATE_ACTIVE;
1583
1584 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1585 bool newUnderrun = false;
1586 if (flags & CBLK_UNDERRUN) {
1587#if 0
1588 // Currently in shared buffer mode, when the server reaches the end of buffer,
1589 // the track stays active in continuous underrun state. It's up to the application
1590 // to pause or stop the track, or set the position to a new offset within buffer.
1591 // This was some experimental code to auto-pause on underrun. Keeping it here
1592 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1593 if (mTransfer == TRANSFER_SHARED) {
1594 mState = STATE_PAUSED;
1595 active = false;
1596 }
1597#endif
1598 if (!mInUnderrun) {
1599 mInUnderrun = true;
1600 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001601 }
1602 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001603
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001604 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001605 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001606
1607 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001608 bool markerReached = false;
1609 size_t markerPosition = mMarkerPosition;
1610 // FIXME fails for wraparound, need 64 bits
1611 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1612 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001613 }
1614
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001615 // Determine number of new position callback(s) that will be needed, while locked
1616 size_t newPosCount = 0;
1617 size_t newPosition = mNewPosition;
1618 size_t updatePeriod = mUpdatePeriod;
1619 // FIXME fails for wraparound, need 64 bits
1620 if (updatePeriod > 0 && position >= newPosition) {
1621 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1622 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001623 }
1624
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001625 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001626 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001627 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001628 if (mRefreshRemaining) {
1629 mRefreshRemaining = false;
1630 mRemainingFrames = notificationFrames;
1631 mRetryOnPartialBuffer = false;
1632 }
1633 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001634 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001635 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001636
Andy Hung53c3b5f2014-12-15 16:42:05 -08001637 // Determine the number of new loop callback(s) that will be needed, while locked.
1638 int loopCountNotifications = 0;
1639 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1640
1641 if (mLoopCount > 0) {
1642 int loopCount;
1643 size_t bufferPosition;
1644 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1645 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1646 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1647 mLoopCountNotified = loopCount; // discard any excess notifications
1648 } else if (mLoopCount < 0) {
1649 // FIXME: We're not accurate with notification count and position with infinite looping
1650 // since loopCount from server side will always return -1 (we could decrement it).
1651 size_t bufferPosition = mStaticProxy->getBufferPosition();
1652 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1653 loopPeriod = mLoopEnd - bufferPosition;
1654 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1655 size_t bufferPosition = mStaticProxy->getBufferPosition();
1656 loopPeriod = mFrameCount - bufferPosition;
1657 }
1658
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001659 // These fields don't need to be cached, because they are assigned only by set():
1660 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1661 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1662
1663 mLock.unlock();
1664
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001665 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001666 struct timespec timeout;
1667 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1668 timeout.tv_nsec = 0;
1669
Glenn Kasten96f04882013-09-20 09:28:56 -07001670 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001671 switch (status) {
1672 case NO_ERROR:
1673 case DEAD_OBJECT:
1674 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001675 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001676 {
1677 AutoMutex lock(mLock);
1678 // The previously assigned value of waitStreamEnd is no longer valid,
1679 // since the mutex has been unlocked and either the callback handler
1680 // or another thread could have re-started the AudioTrack during that time.
1681 waitStreamEnd = mState == STATE_STOPPING;
1682 if (waitStreamEnd) {
1683 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001684 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001685 }
1686 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001687 if (waitStreamEnd && status != DEAD_OBJECT) {
1688 return NS_INACTIVE;
1689 }
1690 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001691 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001692 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001693 }
1694
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001695 // perform callbacks while unlocked
1696 if (newUnderrun) {
1697 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1698 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001699 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001700 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001701 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001702 }
1703 if (flags & CBLK_BUFFER_END) {
1704 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1705 }
1706 if (markerReached) {
1707 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1708 }
1709 while (newPosCount > 0) {
1710 size_t temp = newPosition;
1711 mCbf(EVENT_NEW_POS, mUserData, &temp);
1712 newPosition += updatePeriod;
1713 newPosCount--;
1714 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001715
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001716 if (mObservedSequence != sequence) {
1717 mObservedSequence = sequence;
1718 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001719 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001720 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001721 return NS_INACTIVE;
1722 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001723 }
1724
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001725 // if inactive, then don't run me again until re-started
1726 if (!active) {
1727 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001728 }
1729
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001730 // Compute the estimated time until the next timed event (position, markers, loops)
1731 // FIXME only for non-compressed audio
1732 uint32_t minFrames = ~0;
1733 if (!markerReached && position < markerPosition) {
1734 minFrames = markerPosition - position;
1735 }
1736 if (loopPeriod > 0 && loopPeriod < minFrames) {
1737 minFrames = loopPeriod;
1738 }
1739 if (updatePeriod > 0 && updatePeriod < minFrames) {
1740 minFrames = updatePeriod;
1741 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001742
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001743 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1744 static const uint32_t kPoll = 0;
1745 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1746 minFrames = kPoll * notificationFrames;
1747 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001748
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001749 // Convert frame units to time units
1750 nsecs_t ns = NS_WHENEVER;
1751 if (minFrames != (uint32_t) ~0) {
1752 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1753 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1754 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1755 }
1756
1757 // If not supplying data by EVENT_MORE_DATA, then we're done
1758 if (mTransfer != TRANSFER_CALLBACK) {
1759 return ns;
1760 }
1761
1762 struct timespec timeout;
1763 const struct timespec *requested = &ClientProxy::kForever;
1764 if (ns != NS_WHENEVER) {
1765 timeout.tv_sec = ns / 1000000000LL;
1766 timeout.tv_nsec = ns % 1000000000LL;
1767 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1768 requested = &timeout;
1769 }
1770
1771 while (mRemainingFrames > 0) {
1772
1773 Buffer audioBuffer;
1774 audioBuffer.frameCount = mRemainingFrames;
1775 size_t nonContig;
1776 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1777 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001778 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001779 requested = &ClientProxy::kNonBlocking;
1780 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001781 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001782 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001783 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001784 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1785 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001786 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001787 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001788 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1789 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001790 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001791
Eric Laurent42a6f422013-08-29 14:35:05 -07001792 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001793 mRetryOnPartialBuffer = false;
1794 if (avail < mRemainingFrames) {
1795 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1796 if (ns < 0 || myns < ns) {
1797 ns = myns;
1798 }
1799 return ns;
1800 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001801 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001802
1803 // Divide buffer size by 2 to take into account the expansion
1804 // due to 8 to 16 bit conversion: the callback must fill only half
1805 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001806 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001807 audioBuffer.size >>= 1;
1808 }
1809
1810 size_t reqSize = audioBuffer.size;
1811 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001812 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001813
1814 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001815 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001816 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1817 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001818 return NS_NEVER;
1819 }
1820
1821 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001822 // The callback is done filling buffers
1823 // Keep this thread going to handle timed events and
1824 // still try to get more data in intervals of WAIT_PERIOD_MS
1825 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001826 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001827 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001828
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001829 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001830 // 8 to 16 bit conversion, note that source and destination are the same address
1831 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001832 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001833 }
1834
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001835 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1836 audioBuffer.frameCount = releasedFrames;
1837 mRemainingFrames -= releasedFrames;
1838 if (misalignment >= releasedFrames) {
1839 misalignment -= releasedFrames;
1840 } else {
1841 misalignment = 0;
1842 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001843
1844 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001845
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001846 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1847 // if callback doesn't like to accept the full chunk
1848 if (writtenSize < reqSize) {
1849 continue;
1850 }
1851
1852 // There could be enough non-contiguous frames available to satisfy the remaining request
1853 if (mRemainingFrames <= nonContig) {
1854 continue;
1855 }
1856
1857#if 0
1858 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1859 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1860 // that total to a sum == notificationFrames.
1861 if (0 < misalignment && misalignment <= mRemainingFrames) {
1862 mRemainingFrames = misalignment;
1863 return (mRemainingFrames * 1100000000LL) / sampleRate;
1864 }
1865#endif
1866
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001867 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001868 mRemainingFrames = notificationFrames;
1869 mRetryOnPartialBuffer = true;
1870
1871 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1872 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001873}
1874
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001875status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001876{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001877 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001878 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001879 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001880 status_t result;
1881
Glenn Kastena47f3162012-11-07 10:13:08 -08001882 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08001883 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001884 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001885
Eric Laurentab5cdba2014-06-09 17:22:27 -07001886 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001887 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001888 return DEAD_OBJECT;
1889 }
1890
Glenn Kasten200092b2014-08-15 15:13:30 -07001891 // save the old static buffer position
Andy Hung4ede21d2014-12-12 15:37:34 -08001892 size_t bufferPosition = 0;
1893 int loopCount = 0;
1894 if (mStaticProxy != 0) {
1895 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1896 }
Glenn Kasten200092b2014-08-15 15:13:30 -07001897
1898 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001899 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001900 // It will also delete the strong references on previous IAudioTrack and IMemory.
1901 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
1902 result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001903
1904 // take the frames that will be lost by track recreation into account in saved position
Andy Hung9b461582014-12-01 17:56:29 -08001905 // For streaming tracks, this is the amount we obtained from the user/client
1906 // (not the number actually consumed at the server - those are already lost).
Glenn Kasten200092b2014-08-15 15:13:30 -07001907 (void) updateAndGetPosition_l();
Andy Hung9b461582014-12-01 17:56:29 -08001908 if (mStaticProxy != 0) {
1909 mPosition = mReleased;
1910 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001911
Glenn Kastena47f3162012-11-07 10:13:08 -08001912 if (result == NO_ERROR) {
Andy Hung4ede21d2014-12-12 15:37:34 -08001913 // Continue playback from last known position and restore loop.
1914 if (mStaticProxy != 0) {
1915 if (loopCount != 0) {
1916 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
1917 mLoopStart, mLoopEnd, loopCount);
1918 } else {
1919 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001920 if (bufferPosition == mFrameCount) {
1921 ALOGD("restoring track at end of static buffer");
1922 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001923 }
1924 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001925 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001926 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001927 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001928 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001929 if (result != NO_ERROR) {
1930 ALOGW("restoreTrack_l() failed status %d", result);
1931 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001932 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001933 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001934
1935 return result;
1936}
1937
Glenn Kasten200092b2014-08-15 15:13:30 -07001938uint32_t AudioTrack::updateAndGetPosition_l()
1939{
1940 // This is the sole place to read server consumed frames
1941 uint32_t newServer = mProxy->getPosition();
1942 int32_t delta = newServer - mServer;
1943 mServer = newServer;
1944 // TODO There is controversy about whether there can be "negative jitter" in server position.
1945 // This should be investigated further, and if possible, it should be addressed.
1946 // A more definite failure mode is infrequent polling by client.
1947 // One could call (void)getPosition_l() in releaseBuffer(),
1948 // so mReleased and mPosition are always lock-step as best possible.
1949 // That should ensure delta never goes negative for infrequent polling
1950 // unless the server has more than 2^31 frames in its buffer,
1951 // in which case the use of uint32_t for these counters has bigger issues.
1952 if (delta < 0) {
1953 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
1954 delta = 0;
1955 }
1956 return mPosition += (uint32_t) delta;
1957}
1958
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001959status_t AudioTrack::setParameters(const String8& keyValuePairs)
1960{
1961 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001962 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001963}
1964
Glenn Kastence703742013-07-19 16:33:58 -07001965status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1966{
Glenn Kasten53cec222013-08-29 09:01:02 -07001967 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001968 // FIXME not implemented for fast tracks; should use proxy and SSQ
1969 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1970 return INVALID_OPERATION;
1971 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001972
1973 switch (mState) {
1974 case STATE_ACTIVE:
1975 case STATE_PAUSED:
1976 break; // handle below
1977 case STATE_FLUSHED:
1978 case STATE_STOPPED:
1979 return WOULD_BLOCK;
1980 case STATE_STOPPING:
1981 case STATE_PAUSED_STOPPING:
1982 if (!isOffloaded_l()) {
1983 return INVALID_OPERATION;
1984 }
1985 break; // offloaded tracks handled below
1986 default:
1987 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
1988 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07001989 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001990
Eric Laurent275e8e92014-11-30 15:14:47 -08001991 if (mCblk->mFlags & CBLK_INVALID) {
1992 restoreTrack_l("getTimestamp");
1993 }
1994
Glenn Kasten200092b2014-08-15 15:13:30 -07001995 // The presented frame count must always lag behind the consumed frame count.
1996 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07001997 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001998 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07001999 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002000 return status;
2001 }
2002 if (isOffloadedOrDirect_l()) {
2003 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
2004 // use cached paused position in case another offloaded track is running.
2005 timestamp.mPosition = mPausedPosition;
2006 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
2007 return NO_ERROR;
2008 }
2009
2010 // Check whether a pending flush or stop has completed, as those commands may
2011 // be asynchronous or return near finish.
2012 if (mStartUs != 0 && mSampleRate != 0) {
2013 static const int kTimeJitterUs = 100000; // 100 ms
2014 static const int k1SecUs = 1000000;
2015
2016 const int64_t timeNow = getNowUs();
2017
2018 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
2019 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
2020 if (timestampTimeUs < mStartUs) {
2021 return WOULD_BLOCK; // stale timestamp time, occurs before start.
2022 }
2023 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
2024 const int64_t deltaPositionByUs = timestamp.mPosition * 1000000LL / mSampleRate;
2025
2026 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2027 // Verify that the counter can't count faster than the sample rate
2028 // since the start time. If greater, then that means we have failed
2029 // to completely flush or stop the previous playing track.
2030 ALOGW("incomplete flush or stop:"
2031 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2032 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2033 timestamp.mPosition);
2034 return WOULD_BLOCK;
2035 }
2036 }
2037 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
2038 }
2039 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002040 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2041 (void) updateAndGetPosition_l();
2042 // Server consumed (mServer) and presented both use the same server time base,
2043 // and server consumed is always >= presented.
2044 // The delta between these represents the number of frames in the buffer pipeline.
2045 // If this delta between these is greater than the client position, it means that
2046 // actually presented is still stuck at the starting line (figuratively speaking),
2047 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
2048 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2049 return INVALID_OPERATION;
2050 }
2051 // Convert timestamp position from server time base to client time base.
2052 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2053 // But if we change it to 64-bit then this could fail.
2054 // If (mPosition - mServer) can be negative then should use:
2055 // (int32_t)(mPosition - mServer)
2056 timestamp.mPosition += mPosition - mServer;
2057 // Immediately after a call to getPosition_l(), mPosition and
2058 // mServer both represent the same frame position. mPosition is
2059 // in client's point of view, and mServer is in server's point of
2060 // view. So the difference between them is the "fudge factor"
2061 // between client and server views due to stop() and/or new
2062 // IAudioTrack. And timestamp.mPosition is initially in server's
2063 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002064 }
2065 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002066}
2067
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002068String8 AudioTrack::getParameters(const String8& keys)
2069{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002070 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002071 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002072 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002073 } else {
2074 return String8::empty();
2075 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002076}
2077
Glenn Kasten23a75452014-01-13 10:37:17 -08002078bool AudioTrack::isOffloaded() const
2079{
2080 AutoMutex lock(mLock);
2081 return isOffloaded_l();
2082}
2083
Eric Laurentab5cdba2014-06-09 17:22:27 -07002084bool AudioTrack::isDirect() const
2085{
2086 AutoMutex lock(mLock);
2087 return isDirect_l();
2088}
2089
2090bool AudioTrack::isOffloadedOrDirect() const
2091{
2092 AutoMutex lock(mLock);
2093 return isOffloadedOrDirect_l();
2094}
2095
2096
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002097status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002098{
2099
2100 const size_t SIZE = 256;
2101 char buffer[SIZE];
2102 String8 result;
2103
2104 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002105 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002106 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002107 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002108 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002109 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002110 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08002111 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002112 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002113 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002114 result.append(buffer);
2115 ::write(fd, result.string(), result.size());
2116 return NO_ERROR;
2117}
2118
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002119uint32_t AudioTrack::getUnderrunFrames() const
2120{
2121 AutoMutex lock(mLock);
2122 return mProxy->getUnderrunFrames();
2123}
2124
2125// =========================================================================
2126
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002127void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002128{
2129 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2130 if (audioTrack != 0) {
2131 AutoMutex lock(audioTrack->mLock);
2132 audioTrack->mProxy->binderDied();
2133 }
2134}
2135
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002136// =========================================================================
2137
2138AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002139 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2140 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002141{
2142}
2143
2144AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002145{
2146}
2147
2148bool AudioTrack::AudioTrackThread::threadLoop()
2149{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002150 {
2151 AutoMutex _l(mMyLock);
2152 if (mPaused) {
2153 mMyCond.wait(mMyLock);
2154 // caller will check for exitPending()
2155 return true;
2156 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002157 if (mIgnoreNextPausedInt) {
2158 mIgnoreNextPausedInt = false;
2159 mPausedInt = false;
2160 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002161 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002162 if (mPausedNs > 0) {
2163 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2164 } else {
2165 mMyCond.wait(mMyLock);
2166 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002167 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002168 return true;
2169 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002170 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002171 if (exitPending()) {
2172 return false;
2173 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002174 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002175 switch (ns) {
2176 case 0:
2177 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002178 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002179 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002180 return true;
2181 case NS_NEVER:
2182 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002183 case NS_WHENEVER:
2184 // FIXME increase poll interval, or make event-driven
2185 ns = 1000000000LL;
2186 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002187 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002188 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002189 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002190 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002191 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002192}
2193
Glenn Kasten3acbd052012-02-28 10:39:56 -08002194void AudioTrack::AudioTrackThread::requestExit()
2195{
2196 // must be in this order to avoid a race condition
2197 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002198 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002199}
2200
2201void AudioTrack::AudioTrackThread::pause()
2202{
2203 AutoMutex _l(mMyLock);
2204 mPaused = true;
2205}
2206
2207void AudioTrack::AudioTrackThread::resume()
2208{
2209 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002210 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002211 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002212 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002213 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002214 mMyCond.signal();
2215 }
2216}
2217
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002218void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2219{
2220 AutoMutex _l(mMyLock);
2221 mPausedInt = true;
2222 mPausedNs = ns;
2223}
2224
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002225}; // namespace android