blob: 46025c0dc17f86972d19402f77b9fbf402a72a67 [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
18
19//#define LOG_NDEBUG 0
20#define LOG_TAG "AudioTrack"
21
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080022#include <sys/resource.h>
Glenn Kasten9f80dd22012-12-18 15:57:32 -080023#include <audio_utils/primitives.h>
24#include <binder/IPCThreadState.h>
25#include <media/AudioTrack.h>
26#include <utils/Log.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080027#include <private/media/AudioTrackShared.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070028#include <media/IAudioFlinger.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080029
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010030#define WAIT_PERIOD_MS 10
31#define WAIT_STREAM_END_TIMEOUT_SEC 120
32
Glenn Kasten511754b2012-01-11 09:52:19 -080033
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080034namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080035// ---------------------------------------------------------------------------
36
37// static
38status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080039 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080040 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080041 uint32_t sampleRate)
42{
Glenn Kastend65d73c2012-06-22 17:21:07 -070043 if (frameCount == NULL) {
44 return BAD_VALUE;
45 }
Glenn Kasten04cd0182012-06-25 11:49:27 -070046
Glenn Kastene0fa4672012-04-24 14:35:14 -070047 // FIXME merge with similar code in createTrack_l(), except we're missing
48 // some information here that is available in createTrack_l():
49 // audio_io_handle_t output
50 // audio_format_t format
51 // audio_channel_mask_t channelMask
52 // audio_output_flags_t flags
Glenn Kasten3b16c762012-11-14 08:44:39 -080053 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080054 status_t status;
55 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
56 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080057 ALOGE("Unable to query output sample rate for stream type %d; status %d",
58 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080059 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080060 }
Glenn Kastene33054e2012-11-14 12:54:39 -080061 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -080062 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
63 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080064 ALOGE("Unable to query output frame count for stream type %d; status %d",
65 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080066 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080067 }
68 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -080069 status = AudioSystem::getOutputLatency(&afLatency, streamType);
70 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080071 ALOGE("Unable to query output latency for stream type %d; status %d",
72 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080073 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080074 }
75
76 // Ensure that buffer depth covers at least audio hardware latency
77 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080078 if (minBufCount < 2) {
79 minBufCount = 2;
80 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +080081
82 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
Glenn Kastene53b9ea2012-03-12 16:29:55 -070083 afFrameCount * minBufCount * sampleRate / afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080084 // The formula above should always produce a non-zero value, but return an error
85 // in the unlikely event that it does not, as that's part of the API contract.
86 if (*frameCount == 0) {
87 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %d",
88 streamType, sampleRate);
89 return BAD_VALUE;
90 }
Glenn Kasten3acbd052012-02-28 10:39:56 -080091 ALOGV("getMinFrameCount=%d: afFrameCount=%d, minBufCount=%d, afSampleRate=%d, afLatency=%d",
92 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +080093 return NO_ERROR;
94}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080095
96// ---------------------------------------------------------------------------
97
98AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -070099 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800100 mIsTimed(false),
101 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800102 mPreviousSchedulingGroup(SP_DEFAULT)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800103{
104}
105
106AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800107 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800108 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800109 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700110 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800111 int frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700112 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800113 callback_t cbf,
114 void* user,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700115 int notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800116 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000117 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800118 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800119 int uid,
120 pid_t pid)
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),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800124 mPreviousSchedulingGroup(SP_DEFAULT)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800125{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700126 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700127 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800128 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Marco Nelissend457c972014-02-11 08:47:07 -0800129 offloadInfo, uid, pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800130}
131
Andreas Huberc8139852012-01-18 10:51:55 -0800132AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800133 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800134 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800135 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700136 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800137 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700138 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800139 callback_t cbf,
140 void* user,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700141 int notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800142 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000143 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800144 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800145 int uid,
146 pid_t pid)
Glenn Kasten87913512011-06-22 16:15:25 -0700147 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800148 mIsTimed(false),
149 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800150 mPreviousSchedulingGroup(SP_DEFAULT)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800151{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700152 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800153 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800154 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
155 uid, pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800156}
157
158AudioTrack::~AudioTrack()
159{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800160 if (mStatus == NO_ERROR) {
161 // Make sure that callback function exits in the case where
162 // it is looping on buffer full condition in obtainBuffer().
163 // Otherwise the callback thread will never exit.
164 stop();
165 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100166 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800167 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800168 mAudioTrackThread->requestExitAndWait();
169 mAudioTrackThread.clear();
170 }
Glenn Kasten53cec222013-08-29 09:01:02 -0700171 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
172 mAudioTrack.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800173 IPCThreadState::self()->flushCommands();
Marco Nelissend457c972014-02-11 08:47:07 -0800174 ALOGV("~AudioTrack, releasing session id from %d on behalf of %d",
175 IPCThreadState::self()->getCallingPid(), mClientPid);
176 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800177 }
178}
179
180status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800181 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800182 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800183 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700184 audio_channel_mask_t channelMask,
Glenn Kastene33054e2012-11-14 12:54:39 -0800185 int frameCountInt,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700186 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800187 callback_t cbf,
188 void* user,
189 int notificationFrames,
190 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700191 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800192 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000193 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800194 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800195 int uid,
196 pid_t pid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800197{
Glenn Kasten86f04662014-02-24 15:13:05 -0800198 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %d, "
199 "flags #%x, notificationFrames %d, sessionId %d, transferType %d",
200 streamType, sampleRate, format, channelMask, frameCountInt, flags, notificationFrames,
201 sessionId, transferType);
202
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800203 switch (transferType) {
204 case TRANSFER_DEFAULT:
205 if (sharedBuffer != 0) {
206 transferType = TRANSFER_SHARED;
207 } else if (cbf == NULL || threadCanCallJava) {
208 transferType = TRANSFER_SYNC;
209 } else {
210 transferType = TRANSFER_CALLBACK;
211 }
212 break;
213 case TRANSFER_CALLBACK:
214 if (cbf == NULL || sharedBuffer != 0) {
215 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
216 return BAD_VALUE;
217 }
218 break;
219 case TRANSFER_OBTAIN:
220 case TRANSFER_SYNC:
221 if (sharedBuffer != 0) {
222 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
223 return BAD_VALUE;
224 }
225 break;
226 case TRANSFER_SHARED:
227 if (sharedBuffer == 0) {
228 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
229 return BAD_VALUE;
230 }
231 break;
232 default:
233 ALOGE("Invalid transfer type %d", transferType);
234 return BAD_VALUE;
235 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800236 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800237 mTransfer = transferType;
238
Glenn Kastene33054e2012-11-14 12:54:39 -0800239 // FIXME "int" here is legacy and will be replaced by size_t later
240 if (frameCountInt < 0) {
241 ALOGE("Invalid frame count %d", frameCountInt);
242 return BAD_VALUE;
243 }
244 size_t frameCount = frameCountInt;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800245
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700246 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
247 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800248
Glenn Kastene33054e2012-11-14 12:54:39 -0800249 ALOGV("set() streamType %d frameCount %u flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700250
Eric Laurent1703cdf2011-03-07 14:52:59 -0800251 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800252
Glenn Kasten53cec222013-08-29 09:01:02 -0700253 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700254 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000255 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800256 return INVALID_OPERATION;
257 }
258
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800259 // handle default values first.
Dima Zavinfce7a472011-04-19 22:30:36 -0700260 if (streamType == AUDIO_STREAM_DEFAULT) {
261 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800262 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800263 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
264 ALOGE("Invalid stream type %d", streamType);
265 return BAD_VALUE;
266 }
267 mStreamType = streamType;
Glenn Kastenea7939a2012-03-14 12:56:26 -0700268
Glenn Kastenb1bef512014-01-13 10:25:53 -0800269 status_t status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800270 if (sampleRate == 0) {
Glenn Kastenb1bef512014-01-13 10:25:53 -0800271 status = AudioSystem::getOutputSamplingRate(&sampleRate, streamType);
272 if (status != NO_ERROR) {
273 ALOGE("Could not get output sample rate for stream type %d; status %d",
274 streamType, status);
275 return status;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700276 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800277 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800278 mSampleRate = sampleRate;
Glenn Kastenea7939a2012-03-14 12:56:26 -0700279
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800280 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800281 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700282 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800283 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800284
285 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700286 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800287 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800288 return BAD_VALUE;
289 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800290 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700291
Glenn Kasten8ba90322013-10-30 11:29:27 -0700292 if (!audio_is_output_channel(channelMask)) {
293 ALOGE("Invalid channel mask %#x", channelMask);
294 return BAD_VALUE;
295 }
296
Glenn Kastene0fa4672012-04-24 14:35:14 -0700297 // AudioFlinger does not currently support 8-bit data in shared memory
298 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
299 ALOGE("8-bit data in shared memory is not supported");
300 return BAD_VALUE;
301 }
302
Eric Laurentc2f1f072009-07-17 12:17:14 -0700303 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100304 // or offload was requested
305 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
306 || !audio_is_linear_pcm(format)) {
307 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
308 ? "Offload request, forcing to Direct Output"
309 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700310 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800311 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700312 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700313 }
Eric Laurent1948eb32012-04-13 16:50:19 -0700314 // only allow deep buffering for music stream type
315 if (streamType != AUDIO_STREAM_MUSIC) {
316 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
317 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700318
Glenn Kastena42ff002012-11-14 12:47:55 -0800319 mChannelMask = channelMask;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700320 uint32_t channelCount = popcount(channelMask);
Glenn Kastena42ff002012-11-14 12:47:55 -0800321 mChannelCount = channelCount;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700322
Glenn Kastene3aa6592012-12-04 12:22:46 -0800323 if (audio_is_linear_pcm(format)) {
324 mFrameSize = channelCount * audio_bytes_per_sample(format);
325 mFrameSizeAF = channelCount * sizeof(int16_t);
326 } else {
327 mFrameSize = sizeof(uint8_t);
328 mFrameSizeAF = sizeof(uint8_t);
329 }
330
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800331 // Make copy of input parameter offloadInfo so that in the future:
332 // (a) createTrack_l doesn't need it as an input parameter
333 // (b) we can support re-creation of offloaded tracks
334 if (offloadInfo != NULL) {
335 mOffloadInfoCopy = *offloadInfo;
336 mOffloadInfo = &mOffloadInfoCopy;
337 } else {
338 mOffloadInfo = NULL;
339 }
340
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800341 mVolume[LEFT] = 1.0f;
342 mVolume[RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800343 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800344 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800345 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700346 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800347 mNotificationFramesAct = 0;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700348 mSessionId = sessionId;
Marco Nelissend457c972014-02-11 08:47:07 -0800349 int callingpid = IPCThreadState::self()->getCallingPid();
350 int mypid = getpid();
351 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800352 mClientUid = IPCThreadState::self()->getCallingUid();
353 } else {
354 mClientUid = uid;
355 }
Marco Nelissend457c972014-02-11 08:47:07 -0800356 if (pid == -1 || (callingpid != mypid)) {
357 mClientPid = callingpid;
358 } else {
359 mClientPid = pid;
360 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700361 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700362 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700363 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700364
Glenn Kastena997e7a2012-08-07 09:44:19 -0700365 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700366 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700367 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
368 }
369
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800370 // create the IAudioTrack
Glenn Kasten363fb752014-01-15 12:27:31 -0800371 status = createTrack_l(0 /*epoch*/);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800372
Glenn Kastena997e7a2012-08-07 09:44:19 -0700373 if (status != NO_ERROR) {
374 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100375 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
376 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700377 mAudioTrackThread.clear();
378 }
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800379 // Use of direct and offloaded output streams is ref counted by audio policy manager.
Glenn Kasten38e905b2014-01-13 10:21:48 -0800380#if 0 // FIXME This should no longer be needed
381 //Use of direct and offloaded output streams is ref counted by audio policy manager.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100382 // As getOutput was called above and resulted in an output stream to be opened,
383 // we need to release it.
Glenn Kasten38e905b2014-01-13 10:21:48 -0800384 if (mOutput != 0) {
385 AudioSystem::releaseOutput(mOutput);
386 mOutput = 0;
387 }
388#endif
Glenn Kastena997e7a2012-08-07 09:44:19 -0700389 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700390 }
391
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800392 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800393 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800394 mUserData = user;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800395 mLoopPeriod = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800396 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700397 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800398 mNewPosition = 0;
399 mUpdatePeriod = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800400 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800401 mSequence = 1;
402 mObservedSequence = mSequence;
403 mInUnderrun = false;
404
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800405 return NO_ERROR;
406}
407
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800408// -------------------------------------------------------------------------
409
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100410status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800411{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800412 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100413
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800414 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100415 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800416 }
417
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800418 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800419
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800420 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100421 if (previousState == STATE_PAUSED_STOPPING) {
422 mState = STATE_STOPPING;
423 } else {
424 mState = STATE_ACTIVE;
425 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800426 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
427 // reset current position as seen by client to 0
428 mProxy->setEpoch(mProxy->getEpoch() - mProxy->getPosition());
Eric Laurentec9a0322013-08-28 10:23:01 -0700429 // force refresh of remaining frames by processAudioBuffer() as last
430 // write before stop could be partial.
431 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800432 }
433 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700434 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800435
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800436 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800437 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100438 if (previousState == STATE_STOPPING) {
439 mProxy->interrupt();
440 } else {
441 t->resume();
442 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800443 } else {
444 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
445 get_sched_policy(0, &mPreviousSchedulingGroup);
446 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
447 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800448
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800449 status_t status = NO_ERROR;
450 if (!(flags & CBLK_INVALID)) {
451 status = mAudioTrack->start();
452 if (status == DEAD_OBJECT) {
453 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800454 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800455 }
456 if (flags & CBLK_INVALID) {
457 status = restoreTrack_l("start");
458 }
459
460 if (status != NO_ERROR) {
461 ALOGE("start() status %d", status);
462 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800463 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100464 if (previousState != STATE_STOPPING) {
465 t->pause();
466 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800467 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700468 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700469 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800470 }
471 }
472
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100473 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800474}
475
476void AudioTrack::stop()
477{
478 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700479 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800480 return;
481 }
482
Glenn Kasten23a75452014-01-13 10:37:17 -0800483 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100484 mState = STATE_STOPPING;
485 } else {
486 mState = STATE_STOPPED;
487 }
488
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800489 mProxy->interrupt();
490 mAudioTrack->stop();
491 // the playback head position will reset to 0, so if a marker is set, we need
492 // to activate it again
493 mMarkerReached = false;
494#if 0
495 // Force flush if a shared buffer is used otherwise audioflinger
496 // will not stop before end of buffer is reached.
497 // It may be needed to make sure that we stop playback, likely in case looping is on.
498 if (mSharedBuffer != 0) {
499 flush_l();
500 }
501#endif
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100502
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800503 sp<AudioTrackThread> t = mAudioTrackThread;
504 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800505 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100506 t->pause();
507 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800508 } else {
509 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
510 set_sched_policy(0, mPreviousSchedulingGroup);
511 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800512}
513
514bool AudioTrack::stopped() const
515{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800516 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800517 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800518}
519
520void AudioTrack::flush()
521{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800522 if (mSharedBuffer != 0) {
523 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800524 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800525 AutoMutex lock(mLock);
526 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
527 return;
528 }
529 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800530}
531
Eric Laurent1703cdf2011-03-07 14:52:59 -0800532void AudioTrack::flush_l()
533{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800534 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700535
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700536 // clear playback marker and periodic update counter
537 mMarkerPosition = 0;
538 mMarkerReached = false;
539 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100540 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700541
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800542 mState = STATE_FLUSHED;
Glenn Kasten23a75452014-01-13 10:37:17 -0800543 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100544 mProxy->interrupt();
545 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800546 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800547 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800548}
549
550void AudioTrack::pause()
551{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800552 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100553 if (mState == STATE_ACTIVE) {
554 mState = STATE_PAUSED;
555 } else if (mState == STATE_STOPPING) {
556 mState = STATE_PAUSED_STOPPING;
557 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800558 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800559 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800560 mProxy->interrupt();
561 mAudioTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800562}
563
Eric Laurentbe916aa2010-06-01 23:49:17 -0700564status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800565{
Glenn Kastenf0c49502011-11-30 09:46:04 -0800566 if (left < 0.0f || left > 1.0f || right < 0.0f || right > 1.0f) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700567 return BAD_VALUE;
568 }
569
Eric Laurent1703cdf2011-03-07 14:52:59 -0800570 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800571 mVolume[LEFT] = left;
572 mVolume[RIGHT] = right;
573
Glenn Kastene3aa6592012-12-04 12:22:46 -0800574 mProxy->setVolumeLR((uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700575
Glenn Kasten23a75452014-01-13 10:37:17 -0800576 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700577 mAudioTrack->signal();
578 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700579 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800580}
581
Glenn Kastenb1c09932012-02-27 16:21:04 -0800582status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800583{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800584 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700585}
586
Eric Laurent2beeb502010-07-16 07:43:46 -0700587status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700588{
Glenn Kasten05632a52012-01-03 14:22:33 -0800589 if (level < 0.0f || level > 1.0f) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700590 return BAD_VALUE;
591 }
592
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800593 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700594 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800595 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700596
597 return NO_ERROR;
598}
599
Glenn Kastena5224f32012-01-04 12:41:44 -0800600void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700601{
602 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800603 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700604 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800605}
606
Glenn Kasten3b16c762012-11-14 08:44:39 -0800607status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800608{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100609 if (mIsTimed || isOffloaded()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800610 return INVALID_OPERATION;
611 }
612
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800613 uint32_t afSamplingRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800614 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700615 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800616 }
617 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Glenn Kastend65d73c2012-06-22 17:21:07 -0700618 if (rate == 0 || rate > afSamplingRate*2 ) {
619 return BAD_VALUE;
620 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800621
Eric Laurent1703cdf2011-03-07 14:52:59 -0800622 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800623 mSampleRate = rate;
624 mProxy->setSampleRate(rate);
625
Eric Laurent57326622009-07-07 07:10:45 -0700626 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800627}
628
Glenn Kastena5224f32012-01-04 12:41:44 -0800629uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800630{
John Grossman4ff14ba2012-02-08 16:37:41 -0800631 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800632 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800633 }
634
Eric Laurent1703cdf2011-03-07 14:52:59 -0800635 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700636
637 // sample rate can be updated during playback by the offloaded decoder so we need to
638 // query the HAL and update if needed.
639// FIXME use Proxy return channel to update the rate from server and avoid polling here
Glenn Kasten23a75452014-01-13 10:37:17 -0800640 if (isOffloaded_l()) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700641 if (mOutput != 0) {
642 uint32_t sampleRate = 0;
643 status_t status = AudioSystem::getSamplingRate(mOutput, mStreamType, &sampleRate);
644 if (status == NO_ERROR) {
645 mSampleRate = sampleRate;
646 }
647 }
648 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800649 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800650}
651
652status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
653{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100654 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800655 return INVALID_OPERATION;
656 }
657
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800658 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800659 ;
660 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
661 loopEnd - loopStart >= MIN_LOOP) {
662 ;
663 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800664 return BAD_VALUE;
665 }
666
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800667 AutoMutex lock(mLock);
668 // See setPosition() regarding setting parameters such as loop points or position while active
669 if (mState == STATE_ACTIVE) {
670 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700671 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800672 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800673 return NO_ERROR;
674}
675
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800676void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
677{
678 // FIXME If setting a loop also sets position to start of loop, then
679 // this is correct. Otherwise it should be removed.
680 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
681 mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0;
682 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
683}
684
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800685status_t AudioTrack::setMarkerPosition(uint32_t marker)
686{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700687 // The only purpose of setting marker position is to get a callback
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100688 if (mCbf == NULL || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700689 return INVALID_OPERATION;
690 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800691
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800692 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800693 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700694 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800695
696 return NO_ERROR;
697}
698
Glenn Kastena5224f32012-01-04 12:41:44 -0800699status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800700{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100701 if (isOffloaded()) {
702 return INVALID_OPERATION;
703 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700704 if (marker == NULL) {
705 return BAD_VALUE;
706 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800707
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800708 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800709 *marker = mMarkerPosition;
710
711 return NO_ERROR;
712}
713
714status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
715{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700716 // The only purpose of setting position update period is to get a callback
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100717 if (mCbf == NULL || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700718 return INVALID_OPERATION;
719 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800720
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800721 AutoMutex lock(mLock);
722 mNewPosition = mProxy->getPosition() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800723 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800724
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800725 return NO_ERROR;
726}
727
Glenn Kastena5224f32012-01-04 12:41:44 -0800728status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800729{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100730 if (isOffloaded()) {
731 return INVALID_OPERATION;
732 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700733 if (updatePeriod == NULL) {
734 return BAD_VALUE;
735 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800736
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800737 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800738 *updatePeriod = mUpdatePeriod;
739
740 return NO_ERROR;
741}
742
743status_t AudioTrack::setPosition(uint32_t position)
744{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100745 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700746 return INVALID_OPERATION;
747 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800748 if (position > mFrameCount) {
749 return BAD_VALUE;
750 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800751
Eric Laurent1703cdf2011-03-07 14:52:59 -0800752 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800753 // Currently we require that the player is inactive before setting parameters such as position
754 // or loop points. Otherwise, there could be a race condition: the application could read the
755 // current position, compute a new position or loop parameters, and then set that position or
756 // loop parameters but it would do the "wrong" thing since the position has continued to advance
757 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
758 // to specify how it wants to handle such scenarios.
759 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700760 return INVALID_OPERATION;
761 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800762 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
763 mLoopPeriod = 0;
764 // FIXME Check whether loops and setting position are incompatible in old code.
765 // If we use setLoop for both purposes we lose the capability to set the position while looping.
766 mStaticProxy->setLoop(position, mFrameCount, 0);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700767
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800768 return NO_ERROR;
769}
770
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800771status_t AudioTrack::getPosition(uint32_t *position) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800772{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700773 if (position == NULL) {
774 return BAD_VALUE;
775 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800776
Eric Laurent1703cdf2011-03-07 14:52:59 -0800777 AutoMutex lock(mLock);
Glenn Kasten23a75452014-01-13 10:37:17 -0800778 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100779 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800780
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100781 if (mOutput != 0) {
782 uint32_t halFrames;
783 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
784 }
785 *position = dspFrames;
786 } else {
787 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
788 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ? 0 :
789 mProxy->getPosition();
790 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800791 return NO_ERROR;
792}
793
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000794status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800795{
796 if (mSharedBuffer == 0 || mIsTimed) {
797 return INVALID_OPERATION;
798 }
799 if (position == NULL) {
800 return BAD_VALUE;
801 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800802
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800803 AutoMutex lock(mLock);
804 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800805 return NO_ERROR;
806}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800807
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800808status_t AudioTrack::reload()
809{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100810 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800811 return INVALID_OPERATION;
812 }
813
Eric Laurent1703cdf2011-03-07 14:52:59 -0800814 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800815 // See setPosition() regarding setting parameters such as loop points or position while active
816 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700817 return INVALID_OPERATION;
818 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800819 mNewPosition = mUpdatePeriod;
820 mLoopPeriod = 0;
821 // FIXME The new code cannot reload while keeping a loop specified.
822 // Need to check how the old code handled this, and whether it's a significant change.
823 mStaticProxy->setLoop(0, mFrameCount, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800824 return NO_ERROR;
825}
826
Glenn Kasten38e905b2014-01-13 10:21:48 -0800827audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700828{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800829 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100830 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800831}
832
Eric Laurentbe916aa2010-06-01 23:49:17 -0700833status_t AudioTrack::attachAuxEffect(int effectId)
834{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800835 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700836 status_t status = mAudioTrack->attachAuxEffect(effectId);
837 if (status == NO_ERROR) {
838 mAuxEffectId = effectId;
839 }
840 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700841}
842
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800843// -------------------------------------------------------------------------
844
Eric Laurent1703cdf2011-03-07 14:52:59 -0800845// must be called with mLock held
Glenn Kasten363fb752014-01-15 12:27:31 -0800846status_t AudioTrack::createTrack_l(size_t epoch)
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800847{
848 status_t status;
849 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
850 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700851 ALOGE("Could not get audioflinger");
852 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800853 }
854
Glenn Kasten38e905b2014-01-13 10:21:48 -0800855 audio_io_handle_t output = AudioSystem::getOutput(mStreamType, mSampleRate, mFormat,
856 mChannelMask, mFlags, mOffloadInfo);
857 if (output == 0) {
858 ALOGE("Could not get audio output for stream type %d, sample rate %u, format %#x, "
859 "channel mask %#x, flags %#x",
860 mStreamType, mSampleRate, mFormat, mChannelMask, mFlags);
861 return BAD_VALUE;
862 }
863 {
864 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
865 // we must release it ourselves if anything goes wrong.
866
Glenn Kastence8828a2013-09-16 18:07:38 -0700867 // Not all of these values are needed under all conditions, but it is easier to get them all
868
Eric Laurentd1b449a2010-05-14 03:26:45 -0700869 uint32_t afLatency;
Glenn Kasten363fb752014-01-15 12:27:31 -0800870 status = AudioSystem::getLatency(output, mStreamType, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700871 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800872 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800873 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700874 }
875
Glenn Kastence8828a2013-09-16 18:07:38 -0700876 size_t afFrameCount;
Glenn Kasten363fb752014-01-15 12:27:31 -0800877 status = AudioSystem::getFrameCount(output, mStreamType, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -0700878 if (status != NO_ERROR) {
Glenn Kasten363fb752014-01-15 12:27:31 -0800879 ALOGE("getFrameCount(output=%d, streamType=%d) status %d", output, mStreamType, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800880 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700881 }
882
883 uint32_t afSampleRate;
Glenn Kasten363fb752014-01-15 12:27:31 -0800884 status = AudioSystem::getSamplingRate(output, mStreamType, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -0700885 if (status != NO_ERROR) {
Glenn Kasten363fb752014-01-15 12:27:31 -0800886 ALOGE("getSamplingRate(output=%d, streamType=%d) status %d", output, mStreamType, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800887 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700888 }
889
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700890 // Client decides whether the track is TIMED (see below), but can only express a preference
891 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800892 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700893 // either of these use cases:
894 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -0800895 (mSharedBuffer != 0) ||
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700896 // use case 2: callback handler
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800897 (mCbf != NULL)) &&
898 // matching sample rate
899 (mSampleRate == afSampleRate))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800900 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -0700901 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -0800902 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700903 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700904 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700905
Glenn Kastence8828a2013-09-16 18:07:38 -0700906 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -0800907 // n = 1 fast track with single buffering; nBuffering is ignored
908 // n = 2 fast track with double buffering
Glenn Kastence8828a2013-09-16 18:07:38 -0700909 // n = 2 normal track, no sample rate conversion
910 // n = 3 normal track, with sample rate conversion
911 // (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering)
912 // n > 3 very high latency or very small notification interval; nBuffering is ignored
Glenn Kasten363fb752014-01-15 12:27:31 -0800913 const uint32_t nBuffering = (mSampleRate == afSampleRate) ? 2 : 3;
Glenn Kastence8828a2013-09-16 18:07:38 -0700914
Eric Laurentd1b449a2010-05-14 03:26:45 -0700915 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700916
Glenn Kasten363fb752014-01-15 12:27:31 -0800917 size_t frameCount = mReqFrameCount;
918 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700919
Glenn Kasten363fb752014-01-15 12:27:31 -0800920 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700921 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -0800922 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -0700923 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700924 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700925 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100926 if (mNotificationFramesAct != frameCount) {
927 mNotificationFramesAct = frameCount;
928 }
Glenn Kasten363fb752014-01-15 12:27:31 -0800929 } else if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700930
Glenn Kastena42ff002012-11-14 12:47:55 -0800931 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -0700932 // 8-bit data in shared memory is not currently supported by AudioFlinger
Glenn Kasten363fb752014-01-15 12:27:31 -0800933 size_t alignment = /* mFormat == AUDIO_FORMAT_PCM_8_BIT ? 1 : */ 2;
Glenn Kastena42ff002012-11-14 12:47:55 -0800934 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700935 // More than 2 channels does not require stronger alignment than stereo
936 alignment <<= 1;
937 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000938 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -0800939 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -0800940 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800941 status = BAD_VALUE;
942 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700943 }
944
945 // When initializing a shared buffer AudioTrack via constructors,
946 // there's no frameCount parameter.
947 // But when initializing a shared buffer AudioTrack via set(),
948 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kasten363fb752014-01-15 12:27:31 -0800949 frameCount = mSharedBuffer->size()/mChannelCount/sizeof(int16_t);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700950
Glenn Kasten363fb752014-01-15 12:27:31 -0800951 } else if (!(mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700952
953 // FIXME move these calculations and associated checks to server
Glenn Kastene0fa4672012-04-24 14:35:14 -0700954
Eric Laurentd1b449a2010-05-14 03:26:45 -0700955 // Ensure that buffer depth covers at least audio hardware latency
956 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Glenn Kastenbb6f0a02013-06-03 15:00:29 -0700957 ALOGV("afFrameCount=%d, minBufCount=%d, afSampleRate=%u, afLatency=%d",
958 afFrameCount, minBufCount, afSampleRate, afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700959 if (minBufCount <= nBuffering) {
960 minBufCount = nBuffering;
Glenn Kasten7c027242012-12-26 14:43:16 -0800961 }
Eric Laurentd1b449a2010-05-14 03:26:45 -0700962
Glenn Kasten363fb752014-01-15 12:27:31 -0800963 size_t minFrameCount = (afFrameCount*mSampleRate*minBufCount)/afSampleRate;
Glenn Kastene33054e2012-11-14 12:54:39 -0800964 ALOGV("minFrameCount: %u, afFrameCount=%d, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -0800965 ", afLatency=%d",
Glenn Kasten363fb752014-01-15 12:27:31 -0800966 minFrameCount, afFrameCount, minBufCount, mSampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700967
968 if (frameCount == 0) {
969 frameCount = minFrameCount;
Glenn Kastence8828a2013-09-16 18:07:38 -0700970 } else if (frameCount < minFrameCount) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700971 // not ALOGW because it happens all the time when playing key clicks over A2DP
972 ALOGV("Minimum buffer size corrected from %d to %d",
973 frameCount, minFrameCount);
974 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800975 }
Glenn Kastence8828a2013-09-16 18:07:38 -0700976 // Make sure that application is notified with sufficient margin before underrun
977 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
978 mNotificationFramesAct = frameCount/nBuffering;
979 }
Eric Laurentd1b449a2010-05-14 03:26:45 -0700980
Glenn Kastene0fa4672012-04-24 14:35:14 -0700981 } else {
982 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -0700983 }
984
Glenn Kastena075db42012-03-06 11:22:44 -0800985 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
986 if (mIsTimed) {
987 trackFlags |= IAudioFlinger::TRACK_TIMED;
988 }
Glenn Kasten3acbd052012-02-28 10:39:56 -0800989
990 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -0800991 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700992 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800993 if (mAudioTrackThread != 0) {
994 tid = mAudioTrackThread->getTid();
995 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700996 }
997
Glenn Kasten363fb752014-01-15 12:27:31 -0800998 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100999 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1000 }
1001
Glenn Kasten74935e42013-12-19 08:56:45 -08001002 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1003 // but we will still need the original value also
Glenn Kasten363fb752014-01-15 12:27:31 -08001004 sp<IAudioTrack> track = audioFlinger->createTrack(mStreamType,
1005 mSampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -07001006 // AudioFlinger only sees 16-bit PCM
Glenn Kasten363fb752014-01-15 12:27:31 -08001007 mFormat == AUDIO_FORMAT_PCM_8_BIT ?
1008 AUDIO_FORMAT_PCM_16_BIT : mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001009 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001010 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001011 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001012 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001013 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001014 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001015 &mSessionId,
Glenn Kastend054c322013-07-12 12:59:20 -07001016 mName,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001017 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001018 &status);
1019
1020 if (track == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001021 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001022 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001023 }
Glenn Kasten38e905b2014-01-13 10:21:48 -08001024 // AudioFlinger now owns the reference to the I/O handle,
1025 // so we are no longer responsible for releasing it.
1026
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001027 sp<IMemory> iMem = track->getCblk();
1028 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001029 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001030 return NO_INIT;
1031 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001032 void *iMemPointer = iMem->pointer();
1033 if (iMemPointer == NULL) {
1034 ALOGE("Could not get control block pointer");
1035 return NO_INIT;
1036 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001037 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001038 if (mAudioTrack != 0) {
1039 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
1040 mDeathNotifier.clear();
1041 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001042 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001043 mCblkMemory = iMem;
Glenn Kasten0cde0762014-01-16 15:06:36 -08001044 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001045 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001046 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001047 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1048 // In current design, AudioTrack client checks and ensures frame count validity before
1049 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1050 // for fast track as it uses a special method of assigning frame count.
1051 ALOGW("Requested frameCount %u but received frameCount %u", frameCount, temp);
1052 }
1053 frameCount = temp;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001054 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001055 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001056 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Glenn Kastenb6037442012-11-14 13:42:25 -08001057 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %u", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001058 mAwaitBoost = true;
Glenn Kasten363fb752014-01-15 12:27:31 -08001059 if (mSharedBuffer == 0) {
Glenn Kastenb5fed682013-12-03 09:06:43 -08001060 // Theoretically double-buffering is not required for fast tracks,
1061 // due to tighter scheduling. But in practice, to accommodate kernels with
1062 // scheduling jitter, and apps with computation jitter, we use double-buffering.
1063 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1064 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001065 }
1066 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001067 } else {
Glenn Kastenb6037442012-11-14 13:42:25 -08001068 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %u", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001069 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001070 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1071 if (mSharedBuffer == 0) {
Glenn Kastence8828a2013-09-16 18:07:38 -07001072 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1073 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001074 }
1075 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001076 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001077 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001078 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001079 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1080 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1081 } else {
1082 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001083 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001084 // FIXME This is a warning, not an error, so don't return error status
1085 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001086 }
1087 }
1088
Glenn Kasten38e905b2014-01-13 10:21:48 -08001089 // We retain a copy of the I/O handle, but don't own the reference
1090 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001091 mRefreshRemaining = true;
1092
1093 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1094 // is the value of pointer() for the shared buffer, otherwise buffers points
1095 // immediately after the control block. This address is for the mapping within client
1096 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1097 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001098 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001099 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001100 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001101 buffers = mSharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001102 }
1103
Eric Laurent2beeb502010-07-16 07:43:46 -07001104 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001105 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001106 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kastenb6037442012-11-14 13:42:25 -08001107 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001108 // If IAudioTrack is re-created, don't let the requested frameCount
1109 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001110 if (frameCount > mReqFrameCount) {
1111 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001112 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001113
1114 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001115 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001116 mStaticProxy.clear();
1117 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1118 } else {
1119 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1120 mProxy = mStaticProxy;
1121 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001122 mProxy->setVolumeLR((uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) |
1123 uint16_t(mVolume[LEFT] * 0x1000));
1124 mProxy->setSendLevel(mSendLevel);
1125 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001126 mProxy->setEpoch(epoch);
1127 mProxy->setMinimum(mNotificationFramesAct);
1128
1129 mDeathNotifier = new DeathNotifier(this);
1130 mAudioTrack->asBinder()->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001131
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001132 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001133 }
1134
1135release:
1136 AudioSystem::releaseOutput(output);
1137 if (status == NO_ERROR) {
1138 status = NO_INIT;
1139 }
1140 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001141}
1142
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001143status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1144{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001145 if (audioBuffer == NULL) {
1146 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001147 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001148 if (mTransfer != TRANSFER_OBTAIN) {
1149 audioBuffer->frameCount = 0;
1150 audioBuffer->size = 0;
1151 audioBuffer->raw = NULL;
1152 return INVALID_OPERATION;
1153 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001154
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001155 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001156 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001157 if (waitCount == -1) {
1158 requested = &ClientProxy::kForever;
1159 } else if (waitCount == 0) {
1160 requested = &ClientProxy::kNonBlocking;
1161 } else if (waitCount > 0) {
1162 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001163 timeout.tv_sec = ms / 1000;
1164 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1165 requested = &timeout;
1166 } else {
1167 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1168 requested = NULL;
1169 }
1170 return obtainBuffer(audioBuffer, requested);
1171}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001172
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001173status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1174 struct timespec *elapsed, size_t *nonContig)
1175{
1176 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1177 uint32_t oldSequence = 0;
1178 uint32_t newSequence;
1179
1180 Proxy::Buffer buffer;
1181 status_t status = NO_ERROR;
1182
1183 static const int32_t kMaxTries = 5;
1184 int32_t tryCounter = kMaxTries;
1185
1186 do {
1187 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1188 // keep them from going away if another thread re-creates the track during obtainBuffer()
1189 sp<AudioTrackClientProxy> proxy;
1190 sp<IMemory> iMem;
1191
1192 { // start of lock scope
1193 AutoMutex lock(mLock);
1194
1195 newSequence = mSequence;
1196 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1197 if (status == DEAD_OBJECT) {
1198 // re-create track, unless someone else has already done so
1199 if (newSequence == oldSequence) {
1200 status = restoreTrack_l("obtainBuffer");
1201 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001202 buffer.mFrameCount = 0;
1203 buffer.mRaw = NULL;
1204 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001205 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001206 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001207 }
1208 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001209 oldSequence = newSequence;
1210
1211 // Keep the extra references
1212 proxy = mProxy;
1213 iMem = mCblkMemory;
1214
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001215 if (mState == STATE_STOPPING) {
1216 status = -EINTR;
1217 buffer.mFrameCount = 0;
1218 buffer.mRaw = NULL;
1219 buffer.mNonContig = 0;
1220 break;
1221 }
1222
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001223 // Non-blocking if track is stopped or paused
1224 if (mState != STATE_ACTIVE) {
1225 requested = &ClientProxy::kNonBlocking;
1226 }
1227
1228 } // end of lock scope
1229
1230 buffer.mFrameCount = audioBuffer->frameCount;
1231 // FIXME starts the requested timeout and elapsed over from scratch
1232 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1233
1234 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1235
1236 audioBuffer->frameCount = buffer.mFrameCount;
1237 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1238 audioBuffer->raw = buffer.mRaw;
1239 if (nonContig != NULL) {
1240 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001241 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001242 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001243}
1244
1245void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1246{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001247 if (mTransfer == TRANSFER_SHARED) {
1248 return;
1249 }
1250
1251 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1252 if (stepCount == 0) {
1253 return;
1254 }
1255
1256 Proxy::Buffer buffer;
1257 buffer.mFrameCount = stepCount;
1258 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001259
Eric Laurent1703cdf2011-03-07 14:52:59 -08001260 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001261 mInUnderrun = false;
1262 mProxy->releaseBuffer(&buffer);
1263
1264 // restart track if it was disabled by audioflinger due to previous underrun
1265 if (mState == STATE_ACTIVE) {
1266 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001267 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastend054c322013-07-12 12:59:20 -07001268 ALOGW("releaseBuffer() track %p name=%s disabled due to previous underrun, restarting",
1269 this, mName.string());
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001270 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001271 mAudioTrack->start();
1272 }
1273 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001274}
1275
1276// -------------------------------------------------------------------------
1277
1278ssize_t AudioTrack::write(const void* buffer, size_t userSize)
1279{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001280 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001281 return INVALID_OPERATION;
1282 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001283
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001284 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001285 // Sanity-check: user is most-likely passing an error code, and it would
1286 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001287 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001288 return BAD_VALUE;
1289 }
1290
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001291 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001292 Buffer audioBuffer;
1293
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001294 while (userSize >= mFrameSize) {
1295 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001296
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001297 status_t err = obtainBuffer(&audioBuffer, &ClientProxy::kForever);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001298 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001299 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001300 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001301 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001302 return ssize_t(err);
1303 }
1304
1305 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001306 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001307 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001308 toWrite = audioBuffer.size >> 1;
1309 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001310 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001311 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001312 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001313 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001314 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001315 userSize -= toWrite;
1316 written += toWrite;
1317
1318 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001319 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001320
1321 return written;
1322}
1323
1324// -------------------------------------------------------------------------
1325
John Grossman4ff14ba2012-02-08 16:37:41 -08001326TimedAudioTrack::TimedAudioTrack() {
1327 mIsTimed = true;
1328}
1329
1330status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1331{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001332 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001333 status_t result = UNKNOWN_ERROR;
1334
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001335#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001336 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1337 // while we are accessing the cblk
1338 sp<IAudioTrack> audioTrack = mAudioTrack;
1339 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001340#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001341
John Grossman4ff14ba2012-02-08 16:37:41 -08001342 // If the track is not invalid already, try to allocate a buffer. alloc
1343 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001344 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001345 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001346 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001347 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1348 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001349 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001350 }
1351 }
1352
1353 // If the track is invalid at this point, attempt to restore it. and try the
1354 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001355 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001356 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001357
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001358 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001359 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001360 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001361 }
1362
1363 return result;
1364}
1365
1366status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1367 int64_t pts)
1368{
Eric Laurentdf839842012-05-31 14:27:14 -07001369 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1370 {
1371 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001372 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001373 // restart track if it was disabled by audioflinger due to previous underrun
1374 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001375 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1376 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001377 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001378 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001379 mAudioTrack->start();
1380 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001381 }
Eric Laurentdf839842012-05-31 14:27:14 -07001382 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001383}
1384
1385status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1386 TargetTimeline target)
1387{
1388 return mAudioTrack->setMediaTimeTransform(xform, target);
1389}
1390
1391// -------------------------------------------------------------------------
1392
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001393nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001394{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001395 // Currently the AudioTrack thread is not created if there are no callbacks.
1396 // Would it ever make sense to run the thread, even without callbacks?
1397 // If so, then replace this by checks at each use for mCbf != NULL.
1398 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1399
Eric Laurent1703cdf2011-03-07 14:52:59 -08001400 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001401 if (mAwaitBoost) {
1402 mAwaitBoost = false;
1403 mLock.unlock();
1404 static const int32_t kMaxTries = 5;
1405 int32_t tryCounter = kMaxTries;
1406 uint32_t pollUs = 10000;
1407 do {
1408 int policy = sched_getscheduler(0);
1409 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1410 break;
1411 }
1412 usleep(pollUs);
1413 pollUs <<= 1;
1414 } while (tryCounter-- > 0);
1415 if (tryCounter < 0) {
1416 ALOGE("did not receive expected priority boost on time");
1417 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001418 // Run again immediately
1419 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001420 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001421
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001422 // Can only reference mCblk while locked
1423 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001424 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001425
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001426 // Check for track invalidation
1427 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001428 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1429 // AudioSystem cache. We should not exit here but after calling the callback so
1430 // that the upper layers can recreate the track
Glenn Kasten23a75452014-01-13 10:37:17 -08001431 if (!isOffloaded_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001432 status_t status = restoreTrack_l("processAudioBuffer");
1433 mLock.unlock();
1434 // Run again immediately, but with a new IAudioTrack
1435 return 0;
1436 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001437 }
1438
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001439 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001440 bool active = mState == STATE_ACTIVE;
1441
1442 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1443 bool newUnderrun = false;
1444 if (flags & CBLK_UNDERRUN) {
1445#if 0
1446 // Currently in shared buffer mode, when the server reaches the end of buffer,
1447 // the track stays active in continuous underrun state. It's up to the application
1448 // to pause or stop the track, or set the position to a new offset within buffer.
1449 // This was some experimental code to auto-pause on underrun. Keeping it here
1450 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1451 if (mTransfer == TRANSFER_SHARED) {
1452 mState = STATE_PAUSED;
1453 active = false;
1454 }
1455#endif
1456 if (!mInUnderrun) {
1457 mInUnderrun = true;
1458 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001459 }
1460 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001461
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001462 // Get current position of server
1463 size_t position = mProxy->getPosition();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001464
1465 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001466 bool markerReached = false;
1467 size_t markerPosition = mMarkerPosition;
1468 // FIXME fails for wraparound, need 64 bits
1469 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1470 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001471 }
1472
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001473 // Determine number of new position callback(s) that will be needed, while locked
1474 size_t newPosCount = 0;
1475 size_t newPosition = mNewPosition;
1476 size_t updatePeriod = mUpdatePeriod;
1477 // FIXME fails for wraparound, need 64 bits
1478 if (updatePeriod > 0 && position >= newPosition) {
1479 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1480 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001481 }
1482
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001483 // Cache other fields that will be needed soon
1484 uint32_t loopPeriod = mLoopPeriod;
1485 uint32_t sampleRate = mSampleRate;
1486 size_t notificationFrames = mNotificationFramesAct;
1487 if (mRefreshRemaining) {
1488 mRefreshRemaining = false;
1489 mRemainingFrames = notificationFrames;
1490 mRetryOnPartialBuffer = false;
1491 }
1492 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001493 uint32_t sequence = mSequence;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001494
1495 // These fields don't need to be cached, because they are assigned only by set():
1496 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1497 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1498
1499 mLock.unlock();
1500
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001501 if (waitStreamEnd) {
1502 AutoMutex lock(mLock);
1503
1504 sp<AudioTrackClientProxy> proxy = mProxy;
1505 sp<IMemory> iMem = mCblkMemory;
1506
1507 struct timespec timeout;
1508 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1509 timeout.tv_nsec = 0;
1510
1511 mLock.unlock();
1512 status_t status = mProxy->waitStreamEndDone(&timeout);
1513 mLock.lock();
1514 switch (status) {
1515 case NO_ERROR:
1516 case DEAD_OBJECT:
1517 case TIMED_OUT:
1518 mLock.unlock();
1519 mCbf(EVENT_STREAM_END, mUserData, NULL);
1520 mLock.lock();
1521 if (mState == STATE_STOPPING) {
1522 mState = STATE_STOPPED;
1523 if (status != DEAD_OBJECT) {
1524 return NS_INACTIVE;
1525 }
1526 }
1527 return 0;
1528 default:
1529 return 0;
1530 }
1531 }
1532
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001533 // perform callbacks while unlocked
1534 if (newUnderrun) {
1535 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1536 }
1537 // FIXME we will miss loops if loop cycle was signaled several times since last call
1538 // to processAudioBuffer()
1539 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1540 mCbf(EVENT_LOOP_END, mUserData, NULL);
1541 }
1542 if (flags & CBLK_BUFFER_END) {
1543 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1544 }
1545 if (markerReached) {
1546 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1547 }
1548 while (newPosCount > 0) {
1549 size_t temp = newPosition;
1550 mCbf(EVENT_NEW_POS, mUserData, &temp);
1551 newPosition += updatePeriod;
1552 newPosCount--;
1553 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001554
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001555 if (mObservedSequence != sequence) {
1556 mObservedSequence = sequence;
1557 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001558 // for offloaded tracks, just wait for the upper layers to recreate the track
1559 if (isOffloaded()) {
1560 return NS_INACTIVE;
1561 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001562 }
1563
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001564 // if inactive, then don't run me again until re-started
1565 if (!active) {
1566 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001567 }
1568
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001569 // Compute the estimated time until the next timed event (position, markers, loops)
1570 // FIXME only for non-compressed audio
1571 uint32_t minFrames = ~0;
1572 if (!markerReached && position < markerPosition) {
1573 minFrames = markerPosition - position;
1574 }
1575 if (loopPeriod > 0 && loopPeriod < minFrames) {
1576 minFrames = loopPeriod;
1577 }
1578 if (updatePeriod > 0 && updatePeriod < minFrames) {
1579 minFrames = updatePeriod;
1580 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001581
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001582 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1583 static const uint32_t kPoll = 0;
1584 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1585 minFrames = kPoll * notificationFrames;
1586 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001587
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001588 // Convert frame units to time units
1589 nsecs_t ns = NS_WHENEVER;
1590 if (minFrames != (uint32_t) ~0) {
1591 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1592 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1593 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1594 }
1595
1596 // If not supplying data by EVENT_MORE_DATA, then we're done
1597 if (mTransfer != TRANSFER_CALLBACK) {
1598 return ns;
1599 }
1600
1601 struct timespec timeout;
1602 const struct timespec *requested = &ClientProxy::kForever;
1603 if (ns != NS_WHENEVER) {
1604 timeout.tv_sec = ns / 1000000000LL;
1605 timeout.tv_nsec = ns % 1000000000LL;
1606 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1607 requested = &timeout;
1608 }
1609
1610 while (mRemainingFrames > 0) {
1611
1612 Buffer audioBuffer;
1613 audioBuffer.frameCount = mRemainingFrames;
1614 size_t nonContig;
1615 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1616 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1617 "obtainBuffer() err=%d frameCount=%u", err, audioBuffer.frameCount);
1618 requested = &ClientProxy::kNonBlocking;
1619 size_t avail = audioBuffer.frameCount + nonContig;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001620 ALOGV("obtainBuffer(%u) returned %u = %u + %u err %d",
1621 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001622 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001623 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1624 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001625 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001626 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001627 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1628 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001629 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001630
Eric Laurent42a6f422013-08-29 14:35:05 -07001631 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001632 mRetryOnPartialBuffer = false;
1633 if (avail < mRemainingFrames) {
1634 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1635 if (ns < 0 || myns < ns) {
1636 ns = myns;
1637 }
1638 return ns;
1639 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001640 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001641
1642 // Divide buffer size by 2 to take into account the expansion
1643 // due to 8 to 16 bit conversion: the callback must fill only half
1644 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001645 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001646 audioBuffer.size >>= 1;
1647 }
1648
1649 size_t reqSize = audioBuffer.size;
1650 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001651 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001652
1653 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001654 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
1655 ALOGE("EVENT_MORE_DATA requested %u bytes but callback returned %d bytes",
1656 reqSize, (int) writtenSize);
1657 return NS_NEVER;
1658 }
1659
1660 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001661 // The callback is done filling buffers
1662 // Keep this thread going to handle timed events and
1663 // still try to get more data in intervals of WAIT_PERIOD_MS
1664 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001665 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001666 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001667
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001668 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001669 // 8 to 16 bit conversion, note that source and destination are the same address
1670 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001671 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001672 }
1673
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001674 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1675 audioBuffer.frameCount = releasedFrames;
1676 mRemainingFrames -= releasedFrames;
1677 if (misalignment >= releasedFrames) {
1678 misalignment -= releasedFrames;
1679 } else {
1680 misalignment = 0;
1681 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001682
1683 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001684
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001685 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1686 // if callback doesn't like to accept the full chunk
1687 if (writtenSize < reqSize) {
1688 continue;
1689 }
1690
1691 // There could be enough non-contiguous frames available to satisfy the remaining request
1692 if (mRemainingFrames <= nonContig) {
1693 continue;
1694 }
1695
1696#if 0
1697 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1698 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1699 // that total to a sum == notificationFrames.
1700 if (0 < misalignment && misalignment <= mRemainingFrames) {
1701 mRemainingFrames = misalignment;
1702 return (mRemainingFrames * 1100000000LL) / sampleRate;
1703 }
1704#endif
1705
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001706 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001707 mRemainingFrames = notificationFrames;
1708 mRetryOnPartialBuffer = true;
1709
1710 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1711 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001712}
1713
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001714status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001715{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001716 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Glenn Kasten23a75452014-01-13 10:37:17 -08001717 isOffloaded_l() ? "Offloaded" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001718 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001719 status_t result;
1720
Glenn Kastena47f3162012-11-07 10:13:08 -08001721 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kasten38e905b2014-01-13 10:21:48 -08001722 // output parameters in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001723 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001724
Glenn Kasten23a75452014-01-13 10:37:17 -08001725 if (isOffloaded_l()) {
1726 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001727 return DEAD_OBJECT;
1728 }
1729
Glenn Kastena47f3162012-11-07 10:13:08 -08001730 // if the new IAudioTrack is created, createTrack_l() will modify the
1731 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1732 // It will also delete the strong references on previous IAudioTrack and IMemory
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001733
1734 // take the frames that will be lost by track recreation into account in saved position
1735 size_t position = mProxy->getPosition() + mProxy->getFramesFilled();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001736 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
Glenn Kasten363fb752014-01-15 12:27:31 -08001737 result = createTrack_l(position /*epoch*/);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001738
Glenn Kastena47f3162012-11-07 10:13:08 -08001739 if (result == NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001740 // continue playback from last known position, but
1741 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1742 if (mStaticProxy != NULL) {
1743 mLoopPeriod = 0;
1744 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1745 }
1746 // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1747 // track destruction have been played? This is critical for SoundPool implementation
1748 // This must be broken, and needs to be tested/debugged.
1749#if 0
Glenn Kastena47f3162012-11-07 10:13:08 -08001750 // restore write index and set other indexes to reflect empty buffer status
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001751 if (!strcmp(from, "start")) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001752 // Make sure that a client relying on callback events indicating underrun or
1753 // the actual amount of audio frames played (e.g SoundPool) receives them.
1754 if (mSharedBuffer == 0) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001755 // restart playback even if buffer is not completely filled.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001756 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001757 }
1758 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001759#endif
1760 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001761 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001762 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001763 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001764 if (result != NO_ERROR) {
Glenn Kasten2b2165c2014-01-13 08:53:36 -08001765 // Use of direct and offloaded output streams is ref counted by audio policy manager.
Glenn Kasten38e905b2014-01-13 10:21:48 -08001766#if 0 // FIXME This should no longer be needed
1767 //Use of direct and offloaded output streams is ref counted by audio policy manager.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001768 // As getOutput was called above and resulted in an output stream to be opened,
1769 // we need to release it.
Glenn Kasten38e905b2014-01-13 10:21:48 -08001770 if (mOutput != 0) {
1771 AudioSystem::releaseOutput(mOutput);
1772 mOutput = 0;
1773 }
1774#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001775 ALOGW("restoreTrack_l() failed status %d", result);
1776 mState = STATE_STOPPED;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001777 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001778
1779 return result;
1780}
1781
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001782status_t AudioTrack::setParameters(const String8& keyValuePairs)
1783{
1784 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001785 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001786}
1787
Glenn Kastence703742013-07-19 16:33:58 -07001788status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1789{
Glenn Kasten53cec222013-08-29 09:01:02 -07001790 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001791 // FIXME not implemented for fast tracks; should use proxy and SSQ
1792 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1793 return INVALID_OPERATION;
1794 }
1795 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
1796 return INVALID_OPERATION;
1797 }
1798 status_t status = mAudioTrack->getTimestamp(timestamp);
1799 if (status == NO_ERROR) {
1800 timestamp.mPosition += mProxy->getEpoch();
1801 }
1802 return status;
Glenn Kastence703742013-07-19 16:33:58 -07001803}
1804
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001805String8 AudioTrack::getParameters(const String8& keys)
1806{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08001807 audio_io_handle_t output = getOutput();
1808 if (output != 0) {
1809 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001810 } else {
1811 return String8::empty();
1812 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001813}
1814
Glenn Kasten23a75452014-01-13 10:37:17 -08001815bool AudioTrack::isOffloaded() const
1816{
1817 AutoMutex lock(mLock);
1818 return isOffloaded_l();
1819}
1820
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001821status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001822{
1823
1824 const size_t SIZE = 256;
1825 char buffer[SIZE];
1826 String8 result;
1827
1828 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001829 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
1830 mVolume[0], mVolume[1]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001831 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001832 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001833 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001834 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001835 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001836 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001837 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001838 result.append(buffer);
1839 ::write(fd, result.string(), result.size());
1840 return NO_ERROR;
1841}
1842
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001843uint32_t AudioTrack::getUnderrunFrames() const
1844{
1845 AutoMutex lock(mLock);
1846 return mProxy->getUnderrunFrames();
1847}
1848
1849// =========================================================================
1850
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001851void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001852{
1853 sp<AudioTrack> audioTrack = mAudioTrack.promote();
1854 if (audioTrack != 0) {
1855 AutoMutex lock(audioTrack->mLock);
1856 audioTrack->mProxy->binderDied();
1857 }
1858}
1859
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001860// =========================================================================
1861
1862AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07001863 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
1864 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08001865{
1866}
1867
1868AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001869{
1870}
1871
1872bool AudioTrack::AudioTrackThread::threadLoop()
1873{
Glenn Kasten3acbd052012-02-28 10:39:56 -08001874 {
1875 AutoMutex _l(mMyLock);
1876 if (mPaused) {
1877 mMyCond.wait(mMyLock);
1878 // caller will check for exitPending()
1879 return true;
1880 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07001881 if (mIgnoreNextPausedInt) {
1882 mIgnoreNextPausedInt = false;
1883 mPausedInt = false;
1884 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001885 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001886 if (mPausedNs > 0) {
1887 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
1888 } else {
1889 mMyCond.wait(mMyLock);
1890 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07001891 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001892 return true;
1893 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001894 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001895 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001896 switch (ns) {
1897 case 0:
1898 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001899 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001900 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001901 return true;
1902 case NS_NEVER:
1903 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001904 case NS_WHENEVER:
1905 // FIXME increase poll interval, or make event-driven
1906 ns = 1000000000LL;
1907 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001908 default:
1909 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001910 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001911 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07001912 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001913}
1914
Glenn Kasten3acbd052012-02-28 10:39:56 -08001915void AudioTrack::AudioTrackThread::requestExit()
1916{
1917 // must be in this order to avoid a race condition
1918 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07001919 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08001920}
1921
1922void AudioTrack::AudioTrackThread::pause()
1923{
1924 AutoMutex _l(mMyLock);
1925 mPaused = true;
1926}
1927
1928void AudioTrack::AudioTrackThread::resume()
1929{
1930 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07001931 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07001932 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08001933 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07001934 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001935 mMyCond.signal();
1936 }
1937}
1938
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001939void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
1940{
1941 AutoMutex _l(mMyLock);
1942 mPausedInt = true;
1943 mPausedNs = ns;
1944}
1945
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001946}; // namespace android