blob: fa7249b5e59c2f0c0b03ca4b79291ac3ae718267 [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),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800102 mPreviousSchedulingGroup(SP_DEFAULT),
103 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800104{
105}
106
107AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800108 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800109 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800110 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700111 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800112 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700113 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800114 callback_t cbf,
115 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800116 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800117 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000118 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800119 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800120 int uid,
121 pid_t pid)
Glenn Kasten87913512011-06-22 16:15:25 -0700122 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800123 mIsTimed(false),
124 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800125 mPreviousSchedulingGroup(SP_DEFAULT),
126 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800127{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700128 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700129 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800130 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Marco Nelissend457c972014-02-11 08:47:07 -0800131 offloadInfo, uid, pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800132}
133
Andreas Huberc8139852012-01-18 10:51:55 -0800134AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800135 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800136 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800137 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700138 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800139 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700140 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800141 callback_t cbf,
142 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800143 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800144 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000145 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800146 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800147 int uid,
148 pid_t pid)
Glenn Kasten87913512011-06-22 16:15:25 -0700149 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800150 mIsTimed(false),
151 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800152 mPreviousSchedulingGroup(SP_DEFAULT),
153 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800154{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700155 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800156 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800157 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
158 uid, pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800159}
160
161AudioTrack::~AudioTrack()
162{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800163 if (mStatus == NO_ERROR) {
164 // Make sure that callback function exits in the case where
165 // it is looping on buffer full condition in obtainBuffer().
166 // Otherwise the callback thread will never exit.
167 stop();
168 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100169 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800170 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800171 mAudioTrackThread->requestExitAndWait();
172 mAudioTrackThread.clear();
173 }
Glenn Kasten53cec222013-08-29 09:01:02 -0700174 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
175 mAudioTrack.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800176 IPCThreadState::self()->flushCommands();
Marco Nelissend457c972014-02-11 08:47:07 -0800177 ALOGV("~AudioTrack, releasing session id from %d on behalf of %d",
178 IPCThreadState::self()->getCallingPid(), mClientPid);
179 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800180 }
181}
182
183status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800184 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800185 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800186 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700187 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800188 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700189 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800190 callback_t cbf,
191 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800192 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800193 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700194 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800195 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000196 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800197 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800198 int uid,
199 pid_t pid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800200{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800201 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten838b3d82014-02-27 15:30:41 -0800202 "flags #%x, notificationFrames %u, sessionId %d, transferType %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800203 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten86f04662014-02-24 15:13:05 -0800204 sessionId, transferType);
205
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800206 switch (transferType) {
207 case TRANSFER_DEFAULT:
208 if (sharedBuffer != 0) {
209 transferType = TRANSFER_SHARED;
210 } else if (cbf == NULL || threadCanCallJava) {
211 transferType = TRANSFER_SYNC;
212 } else {
213 transferType = TRANSFER_CALLBACK;
214 }
215 break;
216 case TRANSFER_CALLBACK:
217 if (cbf == NULL || sharedBuffer != 0) {
218 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
219 return BAD_VALUE;
220 }
221 break;
222 case TRANSFER_OBTAIN:
223 case TRANSFER_SYNC:
224 if (sharedBuffer != 0) {
225 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
226 return BAD_VALUE;
227 }
228 break;
229 case TRANSFER_SHARED:
230 if (sharedBuffer == 0) {
231 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
232 return BAD_VALUE;
233 }
234 break;
235 default:
236 ALOGE("Invalid transfer type %d", transferType);
237 return BAD_VALUE;
238 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800239 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800240 mTransfer = transferType;
241
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700242 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
243 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800244
Glenn Kastene33054e2012-11-14 12:54:39 -0800245 ALOGV("set() streamType %d frameCount %u flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700246
Eric Laurent1703cdf2011-03-07 14:52:59 -0800247 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800248
Glenn Kasten53cec222013-08-29 09:01:02 -0700249 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700250 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000251 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800252 return INVALID_OPERATION;
253 }
254
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800255 // handle default values first.
Dima Zavinfce7a472011-04-19 22:30:36 -0700256 if (streamType == AUDIO_STREAM_DEFAULT) {
257 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800258 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800259 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
260 ALOGE("Invalid stream type %d", streamType);
261 return BAD_VALUE;
262 }
263 mStreamType = streamType;
Glenn Kastenea7939a2012-03-14 12:56:26 -0700264
Glenn Kastenb1bef512014-01-13 10:25:53 -0800265 status_t status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800266 if (sampleRate == 0) {
Glenn Kastenb1bef512014-01-13 10:25:53 -0800267 status = AudioSystem::getOutputSamplingRate(&sampleRate, streamType);
268 if (status != NO_ERROR) {
269 ALOGE("Could not get output sample rate for stream type %d; status %d",
270 streamType, status);
271 return status;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700272 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800273 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800274 mSampleRate = sampleRate;
Glenn Kastenea7939a2012-03-14 12:56:26 -0700275
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800276 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800277 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700278 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800279 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800280
281 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700282 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800283 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800284 return BAD_VALUE;
285 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800286 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700287
Glenn Kasten8ba90322013-10-30 11:29:27 -0700288 if (!audio_is_output_channel(channelMask)) {
289 ALOGE("Invalid channel mask %#x", channelMask);
290 return BAD_VALUE;
291 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800292 mChannelMask = channelMask;
293 uint32_t channelCount = popcount(channelMask);
294 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700295
Glenn Kastene0fa4672012-04-24 14:35:14 -0700296 // AudioFlinger does not currently support 8-bit data in shared memory
297 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
298 ALOGE("8-bit data in shared memory is not supported");
299 return BAD_VALUE;
300 }
301
Eric Laurentc2f1f072009-07-17 12:17:14 -0700302 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100303 // or offload was requested
304 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
305 || !audio_is_linear_pcm(format)) {
306 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
307 ? "Offload request, forcing to Direct Output"
308 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700309 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800310 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700311 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700312 }
Eric Laurent1948eb32012-04-13 16:50:19 -0700313 // only allow deep buffering for music stream type
314 if (streamType != AUDIO_STREAM_MUSIC) {
315 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
316 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700317
Glenn Kastene3aa6592012-12-04 12:22:46 -0800318 if (audio_is_linear_pcm(format)) {
319 mFrameSize = channelCount * audio_bytes_per_sample(format);
320 mFrameSizeAF = channelCount * sizeof(int16_t);
321 } else {
322 mFrameSize = sizeof(uint8_t);
323 mFrameSizeAF = sizeof(uint8_t);
324 }
325
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800326 // Make copy of input parameter offloadInfo so that in the future:
327 // (a) createTrack_l doesn't need it as an input parameter
328 // (b) we can support re-creation of offloaded tracks
329 if (offloadInfo != NULL) {
330 mOffloadInfoCopy = *offloadInfo;
331 mOffloadInfo = &mOffloadInfoCopy;
332 } else {
333 mOffloadInfo = NULL;
334 }
335
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800336 mVolume[LEFT] = 1.0f;
337 mVolume[RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800338 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800339 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800340 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700341 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800342 mNotificationFramesAct = 0;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700343 mSessionId = sessionId;
Marco Nelissend457c972014-02-11 08:47:07 -0800344 int callingpid = IPCThreadState::self()->getCallingPid();
345 int mypid = getpid();
346 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800347 mClientUid = IPCThreadState::self()->getCallingUid();
348 } else {
349 mClientUid = uid;
350 }
Marco Nelissend457c972014-02-11 08:47:07 -0800351 if (pid == -1 || (callingpid != mypid)) {
352 mClientPid = callingpid;
353 } else {
354 mClientPid = pid;
355 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700356 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700357 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700358 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700359
Glenn Kastena997e7a2012-08-07 09:44:19 -0700360 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700361 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700362 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
363 }
364
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800365 // create the IAudioTrack
Glenn Kasten363fb752014-01-15 12:27:31 -0800366 status = createTrack_l(0 /*epoch*/);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800367
Glenn Kastena997e7a2012-08-07 09:44:19 -0700368 if (status != NO_ERROR) {
369 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100370 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
371 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700372 mAudioTrackThread.clear();
373 }
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800374 // Use of direct and offloaded output streams is ref counted by audio policy manager.
Glenn Kasten38e905b2014-01-13 10:21:48 -0800375#if 0 // FIXME This should no longer be needed
376 //Use of direct and offloaded output streams is ref counted by audio policy manager.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100377 // As getOutput was called above and resulted in an output stream to be opened,
378 // we need to release it.
Glenn Kasten38e905b2014-01-13 10:21:48 -0800379 if (mOutput != 0) {
380 AudioSystem::releaseOutput(mOutput);
381 mOutput = 0;
382 }
383#endif
Glenn Kastena997e7a2012-08-07 09:44:19 -0700384 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700385 }
386
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800387 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800388 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800389 mUserData = user;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800390 mLoopPeriod = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800391 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700392 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800393 mNewPosition = 0;
394 mUpdatePeriod = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800395 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800396 mSequence = 1;
397 mObservedSequence = mSequence;
398 mInUnderrun = false;
399
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800400 return NO_ERROR;
401}
402
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800403// -------------------------------------------------------------------------
404
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100405status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800406{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800407 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100408
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800409 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100410 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800411 }
412
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800413 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800414
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800415 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100416 if (previousState == STATE_PAUSED_STOPPING) {
417 mState = STATE_STOPPING;
418 } else {
419 mState = STATE_ACTIVE;
420 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800421 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
422 // reset current position as seen by client to 0
423 mProxy->setEpoch(mProxy->getEpoch() - mProxy->getPosition());
Eric Laurentec9a0322013-08-28 10:23:01 -0700424 // force refresh of remaining frames by processAudioBuffer() as last
425 // write before stop could be partial.
426 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800427 }
428 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700429 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800430
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800431 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800432 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100433 if (previousState == STATE_STOPPING) {
434 mProxy->interrupt();
435 } else {
436 t->resume();
437 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800438 } else {
439 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
440 get_sched_policy(0, &mPreviousSchedulingGroup);
441 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
442 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800443
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800444 status_t status = NO_ERROR;
445 if (!(flags & CBLK_INVALID)) {
446 status = mAudioTrack->start();
447 if (status == DEAD_OBJECT) {
448 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800449 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800450 }
451 if (flags & CBLK_INVALID) {
452 status = restoreTrack_l("start");
453 }
454
455 if (status != NO_ERROR) {
456 ALOGE("start() status %d", status);
457 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800458 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100459 if (previousState != STATE_STOPPING) {
460 t->pause();
461 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800462 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700463 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700464 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800465 }
466 }
467
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100468 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800469}
470
471void AudioTrack::stop()
472{
473 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700474 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800475 return;
476 }
477
Glenn Kasten23a75452014-01-13 10:37:17 -0800478 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100479 mState = STATE_STOPPING;
480 } else {
481 mState = STATE_STOPPED;
482 }
483
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800484 mProxy->interrupt();
485 mAudioTrack->stop();
486 // the playback head position will reset to 0, so if a marker is set, we need
487 // to activate it again
488 mMarkerReached = false;
489#if 0
490 // Force flush if a shared buffer is used otherwise audioflinger
491 // will not stop before end of buffer is reached.
492 // It may be needed to make sure that we stop playback, likely in case looping is on.
493 if (mSharedBuffer != 0) {
494 flush_l();
495 }
496#endif
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100497
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800498 sp<AudioTrackThread> t = mAudioTrackThread;
499 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800500 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100501 t->pause();
502 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800503 } else {
504 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
505 set_sched_policy(0, mPreviousSchedulingGroup);
506 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800507}
508
509bool AudioTrack::stopped() const
510{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800511 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800512 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800513}
514
515void AudioTrack::flush()
516{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800517 if (mSharedBuffer != 0) {
518 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800519 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800520 AutoMutex lock(mLock);
521 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
522 return;
523 }
524 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800525}
526
Eric Laurent1703cdf2011-03-07 14:52:59 -0800527void AudioTrack::flush_l()
528{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800529 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700530
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700531 // clear playback marker and periodic update counter
532 mMarkerPosition = 0;
533 mMarkerReached = false;
534 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100535 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700536
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800537 mState = STATE_FLUSHED;
Glenn Kasten23a75452014-01-13 10:37:17 -0800538 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100539 mProxy->interrupt();
540 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800541 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800542 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800543}
544
545void AudioTrack::pause()
546{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800547 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100548 if (mState == STATE_ACTIVE) {
549 mState = STATE_PAUSED;
550 } else if (mState == STATE_STOPPING) {
551 mState = STATE_PAUSED_STOPPING;
552 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800553 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800554 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800555 mProxy->interrupt();
556 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800557
Marco Nelissen3a90f282014-03-10 11:21:43 -0700558 if (isOffloaded_l()) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800559 if (mOutput != 0) {
560 uint32_t halFrames;
561 // OffloadThread sends HAL pause in its threadLoop.. time saved
562 // here can be slightly off
563 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
564 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
565 }
566 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800567}
568
Eric Laurentbe916aa2010-06-01 23:49:17 -0700569status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800570{
Glenn Kastenf0c49502011-11-30 09:46:04 -0800571 if (left < 0.0f || left > 1.0f || right < 0.0f || right > 1.0f) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700572 return BAD_VALUE;
573 }
574
Eric Laurent1703cdf2011-03-07 14:52:59 -0800575 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800576 mVolume[LEFT] = left;
577 mVolume[RIGHT] = right;
578
Glenn Kastene3aa6592012-12-04 12:22:46 -0800579 mProxy->setVolumeLR((uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700580
Glenn Kasten23a75452014-01-13 10:37:17 -0800581 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700582 mAudioTrack->signal();
583 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700584 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800585}
586
Glenn Kastenb1c09932012-02-27 16:21:04 -0800587status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800588{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800589 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700590}
591
Eric Laurent2beeb502010-07-16 07:43:46 -0700592status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700593{
Glenn Kasten05632a52012-01-03 14:22:33 -0800594 if (level < 0.0f || level > 1.0f) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700595 return BAD_VALUE;
596 }
597
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800598 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700599 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800600 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700601
602 return NO_ERROR;
603}
604
Glenn Kastena5224f32012-01-04 12:41:44 -0800605void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700606{
607 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800608 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700609 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800610}
611
Glenn Kasten3b16c762012-11-14 08:44:39 -0800612status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800613{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100614 if (mIsTimed || isOffloaded()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800615 return INVALID_OPERATION;
616 }
617
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800618 uint32_t afSamplingRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800619 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700620 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800621 }
622 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Glenn Kastend65d73c2012-06-22 17:21:07 -0700623 if (rate == 0 || rate > afSamplingRate*2 ) {
624 return BAD_VALUE;
625 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800626
Eric Laurent1703cdf2011-03-07 14:52:59 -0800627 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800628 mSampleRate = rate;
629 mProxy->setSampleRate(rate);
630
Eric Laurent57326622009-07-07 07:10:45 -0700631 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800632}
633
Glenn Kastena5224f32012-01-04 12:41:44 -0800634uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800635{
John Grossman4ff14ba2012-02-08 16:37:41 -0800636 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800637 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800638 }
639
Eric Laurent1703cdf2011-03-07 14:52:59 -0800640 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700641
642 // sample rate can be updated during playback by the offloaded decoder so we need to
643 // query the HAL and update if needed.
644// FIXME use Proxy return channel to update the rate from server and avoid polling here
Glenn Kasten23a75452014-01-13 10:37:17 -0800645 if (isOffloaded_l()) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700646 if (mOutput != 0) {
647 uint32_t sampleRate = 0;
648 status_t status = AudioSystem::getSamplingRate(mOutput, mStreamType, &sampleRate);
649 if (status == NO_ERROR) {
650 mSampleRate = sampleRate;
651 }
652 }
653 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800654 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800655}
656
657status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
658{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100659 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800660 return INVALID_OPERATION;
661 }
662
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800663 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800664 ;
665 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
666 loopEnd - loopStart >= MIN_LOOP) {
667 ;
668 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800669 return BAD_VALUE;
670 }
671
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800672 AutoMutex lock(mLock);
673 // See setPosition() regarding setting parameters such as loop points or position while active
674 if (mState == STATE_ACTIVE) {
675 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700676 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800677 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800678 return NO_ERROR;
679}
680
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800681void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
682{
683 // FIXME If setting a loop also sets position to start of loop, then
684 // this is correct. Otherwise it should be removed.
685 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
686 mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0;
687 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
688}
689
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800690status_t AudioTrack::setMarkerPosition(uint32_t marker)
691{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700692 // The only purpose of setting marker position is to get a callback
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100693 if (mCbf == NULL || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700694 return INVALID_OPERATION;
695 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800696
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800697 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800698 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700699 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800700
701 return NO_ERROR;
702}
703
Glenn Kastena5224f32012-01-04 12:41:44 -0800704status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800705{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100706 if (isOffloaded()) {
707 return INVALID_OPERATION;
708 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700709 if (marker == NULL) {
710 return BAD_VALUE;
711 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800712
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800713 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800714 *marker = mMarkerPosition;
715
716 return NO_ERROR;
717}
718
719status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
720{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700721 // The only purpose of setting position update period is to get a callback
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100722 if (mCbf == NULL || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700723 return INVALID_OPERATION;
724 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800725
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800726 AutoMutex lock(mLock);
727 mNewPosition = mProxy->getPosition() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800728 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800729
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800730 return NO_ERROR;
731}
732
Glenn Kastena5224f32012-01-04 12:41:44 -0800733status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800734{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100735 if (isOffloaded()) {
736 return INVALID_OPERATION;
737 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700738 if (updatePeriod == NULL) {
739 return BAD_VALUE;
740 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800741
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800742 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800743 *updatePeriod = mUpdatePeriod;
744
745 return NO_ERROR;
746}
747
748status_t AudioTrack::setPosition(uint32_t position)
749{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100750 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700751 return INVALID_OPERATION;
752 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800753 if (position > mFrameCount) {
754 return BAD_VALUE;
755 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800756
Eric Laurent1703cdf2011-03-07 14:52:59 -0800757 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800758 // Currently we require that the player is inactive before setting parameters such as position
759 // or loop points. Otherwise, there could be a race condition: the application could read the
760 // current position, compute a new position or loop parameters, and then set that position or
761 // loop parameters but it would do the "wrong" thing since the position has continued to advance
762 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
763 // to specify how it wants to handle such scenarios.
764 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700765 return INVALID_OPERATION;
766 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800767 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
768 mLoopPeriod = 0;
769 // FIXME Check whether loops and setting position are incompatible in old code.
770 // If we use setLoop for both purposes we lose the capability to set the position while looping.
771 mStaticProxy->setLoop(position, mFrameCount, 0);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700772
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800773 return NO_ERROR;
774}
775
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800776status_t AudioTrack::getPosition(uint32_t *position) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800777{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700778 if (position == NULL) {
779 return BAD_VALUE;
780 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800781
Eric Laurent1703cdf2011-03-07 14:52:59 -0800782 AutoMutex lock(mLock);
Glenn Kasten23a75452014-01-13 10:37:17 -0800783 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100784 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800785
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800786 if ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING)) {
787 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
788 *position = mPausedPosition;
789 return NO_ERROR;
790 }
791
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100792 if (mOutput != 0) {
793 uint32_t halFrames;
794 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
795 }
796 *position = dspFrames;
797 } else {
798 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
799 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ? 0 :
800 mProxy->getPosition();
801 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800802 return NO_ERROR;
803}
804
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000805status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800806{
807 if (mSharedBuffer == 0 || mIsTimed) {
808 return INVALID_OPERATION;
809 }
810 if (position == NULL) {
811 return BAD_VALUE;
812 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800813
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800814 AutoMutex lock(mLock);
815 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800816 return NO_ERROR;
817}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800818
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800819status_t AudioTrack::reload()
820{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100821 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800822 return INVALID_OPERATION;
823 }
824
Eric Laurent1703cdf2011-03-07 14:52:59 -0800825 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800826 // See setPosition() regarding setting parameters such as loop points or position while active
827 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700828 return INVALID_OPERATION;
829 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800830 mNewPosition = mUpdatePeriod;
831 mLoopPeriod = 0;
832 // FIXME The new code cannot reload while keeping a loop specified.
833 // Need to check how the old code handled this, and whether it's a significant change.
834 mStaticProxy->setLoop(0, mFrameCount, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800835 return NO_ERROR;
836}
837
Glenn Kasten38e905b2014-01-13 10:21:48 -0800838audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700839{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800840 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100841 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800842}
843
Eric Laurentbe916aa2010-06-01 23:49:17 -0700844status_t AudioTrack::attachAuxEffect(int effectId)
845{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800846 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700847 status_t status = mAudioTrack->attachAuxEffect(effectId);
848 if (status == NO_ERROR) {
849 mAuxEffectId = effectId;
850 }
851 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700852}
853
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800854// -------------------------------------------------------------------------
855
Eric Laurent1703cdf2011-03-07 14:52:59 -0800856// must be called with mLock held
Glenn Kasten363fb752014-01-15 12:27:31 -0800857status_t AudioTrack::createTrack_l(size_t epoch)
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800858{
859 status_t status;
860 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
861 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700862 ALOGE("Could not get audioflinger");
863 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800864 }
865
Glenn Kasten38e905b2014-01-13 10:21:48 -0800866 audio_io_handle_t output = AudioSystem::getOutput(mStreamType, mSampleRate, mFormat,
867 mChannelMask, mFlags, mOffloadInfo);
868 if (output == 0) {
869 ALOGE("Could not get audio output for stream type %d, sample rate %u, format %#x, "
870 "channel mask %#x, flags %#x",
871 mStreamType, mSampleRate, mFormat, mChannelMask, mFlags);
872 return BAD_VALUE;
873 }
874 {
875 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
876 // we must release it ourselves if anything goes wrong.
877
Glenn Kastence8828a2013-09-16 18:07:38 -0700878 // Not all of these values are needed under all conditions, but it is easier to get them all
879
Eric Laurentd1b449a2010-05-14 03:26:45 -0700880 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -0700881 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700882 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800883 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800884 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700885 }
886
Glenn Kastence8828a2013-09-16 18:07:38 -0700887 size_t afFrameCount;
Glenn Kasten363fb752014-01-15 12:27:31 -0800888 status = AudioSystem::getFrameCount(output, mStreamType, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -0700889 if (status != NO_ERROR) {
Glenn Kasten363fb752014-01-15 12:27:31 -0800890 ALOGE("getFrameCount(output=%d, streamType=%d) status %d", output, mStreamType, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800891 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700892 }
893
894 uint32_t afSampleRate;
Glenn Kasten363fb752014-01-15 12:27:31 -0800895 status = AudioSystem::getSamplingRate(output, mStreamType, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -0700896 if (status != NO_ERROR) {
Glenn Kasten363fb752014-01-15 12:27:31 -0800897 ALOGE("getSamplingRate(output=%d, streamType=%d) status %d", output, mStreamType, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800898 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700899 }
900
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700901 // Client decides whether the track is TIMED (see below), but can only express a preference
902 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800903 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700904 // either of these use cases:
905 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -0800906 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -0800907 // use case 2: callback transfer mode
908 (mTransfer == TRANSFER_CALLBACK)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -0800909 // matching sample rate
910 (mSampleRate == afSampleRate))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800911 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -0700912 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -0800913 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700914 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700915 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700916
Glenn Kastence8828a2013-09-16 18:07:38 -0700917 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -0800918 // n = 1 fast track with single buffering; nBuffering is ignored
919 // n = 2 fast track with double buffering
Glenn Kastence8828a2013-09-16 18:07:38 -0700920 // n = 2 normal track, no sample rate conversion
921 // n = 3 normal track, with sample rate conversion
922 // (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering)
923 // n > 3 very high latency or very small notification interval; nBuffering is ignored
Glenn Kasten363fb752014-01-15 12:27:31 -0800924 const uint32_t nBuffering = (mSampleRate == afSampleRate) ? 2 : 3;
Glenn Kastence8828a2013-09-16 18:07:38 -0700925
Eric Laurentd1b449a2010-05-14 03:26:45 -0700926 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700927
Glenn Kasten363fb752014-01-15 12:27:31 -0800928 size_t frameCount = mReqFrameCount;
929 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700930
Glenn Kasten363fb752014-01-15 12:27:31 -0800931 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700932 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -0800933 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -0700934 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700935 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700936 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100937 if (mNotificationFramesAct != frameCount) {
938 mNotificationFramesAct = frameCount;
939 }
Glenn Kasten363fb752014-01-15 12:27:31 -0800940 } else if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700941
Glenn Kastena42ff002012-11-14 12:47:55 -0800942 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -0700943 // 8-bit data in shared memory is not currently supported by AudioFlinger
Glenn Kasten363fb752014-01-15 12:27:31 -0800944 size_t alignment = /* mFormat == AUDIO_FORMAT_PCM_8_BIT ? 1 : */ 2;
Glenn Kastena42ff002012-11-14 12:47:55 -0800945 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700946 // More than 2 channels does not require stronger alignment than stereo
947 alignment <<= 1;
948 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000949 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -0800950 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -0800951 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800952 status = BAD_VALUE;
953 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700954 }
955
956 // When initializing a shared buffer AudioTrack via constructors,
957 // there's no frameCount parameter.
958 // But when initializing a shared buffer AudioTrack via set(),
959 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kasten363fb752014-01-15 12:27:31 -0800960 frameCount = mSharedBuffer->size()/mChannelCount/sizeof(int16_t);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700961
Glenn Kasten363fb752014-01-15 12:27:31 -0800962 } else if (!(mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700963
964 // FIXME move these calculations and associated checks to server
Glenn Kastene0fa4672012-04-24 14:35:14 -0700965
Eric Laurentd1b449a2010-05-14 03:26:45 -0700966 // Ensure that buffer depth covers at least audio hardware latency
967 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Glenn Kastenbb6f0a02013-06-03 15:00:29 -0700968 ALOGV("afFrameCount=%d, minBufCount=%d, afSampleRate=%u, afLatency=%d",
969 afFrameCount, minBufCount, afSampleRate, afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700970 if (minBufCount <= nBuffering) {
971 minBufCount = nBuffering;
Glenn Kasten7c027242012-12-26 14:43:16 -0800972 }
Eric Laurentd1b449a2010-05-14 03:26:45 -0700973
Glenn Kasten363fb752014-01-15 12:27:31 -0800974 size_t minFrameCount = (afFrameCount*mSampleRate*minBufCount)/afSampleRate;
Glenn Kastene33054e2012-11-14 12:54:39 -0800975 ALOGV("minFrameCount: %u, afFrameCount=%d, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -0800976 ", afLatency=%d",
Glenn Kasten363fb752014-01-15 12:27:31 -0800977 minFrameCount, afFrameCount, minBufCount, mSampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700978
979 if (frameCount == 0) {
980 frameCount = minFrameCount;
Glenn Kastence8828a2013-09-16 18:07:38 -0700981 } else if (frameCount < minFrameCount) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700982 // not ALOGW because it happens all the time when playing key clicks over A2DP
983 ALOGV("Minimum buffer size corrected from %d to %d",
984 frameCount, minFrameCount);
985 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800986 }
Glenn Kastence8828a2013-09-16 18:07:38 -0700987 // Make sure that application is notified with sufficient margin before underrun
988 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
989 mNotificationFramesAct = frameCount/nBuffering;
990 }
Eric Laurentd1b449a2010-05-14 03:26:45 -0700991
Glenn Kastene0fa4672012-04-24 14:35:14 -0700992 } else {
993 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -0700994 }
995
Glenn Kastena075db42012-03-06 11:22:44 -0800996 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
997 if (mIsTimed) {
998 trackFlags |= IAudioFlinger::TRACK_TIMED;
999 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001000
1001 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001002 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001003 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001004 if (mAudioTrackThread != 0) {
1005 tid = mAudioTrackThread->getTid();
1006 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001007 }
1008
Glenn Kasten363fb752014-01-15 12:27:31 -08001009 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001010 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1011 }
1012
Glenn Kasten74935e42013-12-19 08:56:45 -08001013 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1014 // but we will still need the original value also
Glenn Kasten363fb752014-01-15 12:27:31 -08001015 sp<IAudioTrack> track = audioFlinger->createTrack(mStreamType,
1016 mSampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -07001017 // AudioFlinger only sees 16-bit PCM
Glenn Kasten363fb752014-01-15 12:27:31 -08001018 mFormat == AUDIO_FORMAT_PCM_8_BIT ?
1019 AUDIO_FORMAT_PCM_16_BIT : mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001020 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001021 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001022 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001023 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001024 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001025 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001026 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001027 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001028 &status);
1029
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001030 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001031 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001032 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001033 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001034 ALOG_ASSERT(track != 0);
1035
Glenn Kasten38e905b2014-01-13 10:21:48 -08001036 // AudioFlinger now owns the reference to the I/O handle,
1037 // so we are no longer responsible for releasing it.
1038
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001039 sp<IMemory> iMem = track->getCblk();
1040 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001041 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001042 return NO_INIT;
1043 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001044 void *iMemPointer = iMem->pointer();
1045 if (iMemPointer == NULL) {
1046 ALOGE("Could not get control block pointer");
1047 return NO_INIT;
1048 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001049 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001050 if (mAudioTrack != 0) {
1051 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
1052 mDeathNotifier.clear();
1053 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001054 mAudioTrack = track;
Glenn Kasten5f631512014-02-24 15:16:07 -08001055
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001056 mCblkMemory = iMem;
Glenn Kasten0cde0762014-01-16 15:06:36 -08001057 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001058 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001059 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001060 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1061 // In current design, AudioTrack client checks and ensures frame count validity before
1062 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1063 // for fast track as it uses a special method of assigning frame count.
1064 ALOGW("Requested frameCount %u but received frameCount %u", frameCount, temp);
1065 }
1066 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001067
Glenn Kastena07f17c2013-04-23 12:39:37 -07001068 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001069 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001070 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Glenn Kastenb6037442012-11-14 13:42:25 -08001071 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %u", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001072 mAwaitBoost = true;
Glenn Kasten363fb752014-01-15 12:27:31 -08001073 if (mSharedBuffer == 0) {
Glenn Kastenb5fed682013-12-03 09:06:43 -08001074 // Theoretically double-buffering is not required for fast tracks,
1075 // due to tighter scheduling. But in practice, to accommodate kernels with
1076 // scheduling jitter, and apps with computation jitter, we use double-buffering.
1077 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1078 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001079 }
1080 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001081 } else {
Glenn Kastenb6037442012-11-14 13:42:25 -08001082 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %u", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001083 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001084 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1085 if (mSharedBuffer == 0) {
Glenn Kastence8828a2013-09-16 18:07:38 -07001086 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1087 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001088 }
1089 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001090 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001091 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001092 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001093 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1094 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1095 } else {
1096 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001097 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001098 // FIXME This is a warning, not an error, so don't return error status
1099 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001100 }
1101 }
1102
Glenn Kasten38e905b2014-01-13 10:21:48 -08001103 // We retain a copy of the I/O handle, but don't own the reference
1104 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001105 mRefreshRemaining = true;
1106
1107 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1108 // is the value of pointer() for the shared buffer, otherwise buffers points
1109 // immediately after the control block. This address is for the mapping within client
1110 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1111 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001112 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001113 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001114 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001115 buffers = mSharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001116 }
1117
Eric Laurent2beeb502010-07-16 07:43:46 -07001118 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001119 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001120 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001121
Glenn Kastenb6037442012-11-14 13:42:25 -08001122 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001123 // If IAudioTrack is re-created, don't let the requested frameCount
1124 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001125 if (frameCount > mReqFrameCount) {
1126 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001127 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001128
1129 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001130 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001131 mStaticProxy.clear();
1132 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1133 } else {
1134 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1135 mProxy = mStaticProxy;
1136 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001137 mProxy->setVolumeLR((uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) |
1138 uint16_t(mVolume[LEFT] * 0x1000));
1139 mProxy->setSendLevel(mSendLevel);
1140 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001141 mProxy->setEpoch(epoch);
1142 mProxy->setMinimum(mNotificationFramesAct);
1143
1144 mDeathNotifier = new DeathNotifier(this);
1145 mAudioTrack->asBinder()->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001146
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001147 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001148 }
1149
1150release:
1151 AudioSystem::releaseOutput(output);
1152 if (status == NO_ERROR) {
1153 status = NO_INIT;
1154 }
1155 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001156}
1157
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001158status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1159{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001160 if (audioBuffer == NULL) {
1161 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001162 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001163 if (mTransfer != TRANSFER_OBTAIN) {
1164 audioBuffer->frameCount = 0;
1165 audioBuffer->size = 0;
1166 audioBuffer->raw = NULL;
1167 return INVALID_OPERATION;
1168 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001169
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001170 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001171 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001172 if (waitCount == -1) {
1173 requested = &ClientProxy::kForever;
1174 } else if (waitCount == 0) {
1175 requested = &ClientProxy::kNonBlocking;
1176 } else if (waitCount > 0) {
1177 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001178 timeout.tv_sec = ms / 1000;
1179 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1180 requested = &timeout;
1181 } else {
1182 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1183 requested = NULL;
1184 }
1185 return obtainBuffer(audioBuffer, requested);
1186}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001187
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001188status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1189 struct timespec *elapsed, size_t *nonContig)
1190{
1191 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1192 uint32_t oldSequence = 0;
1193 uint32_t newSequence;
1194
1195 Proxy::Buffer buffer;
1196 status_t status = NO_ERROR;
1197
1198 static const int32_t kMaxTries = 5;
1199 int32_t tryCounter = kMaxTries;
1200
1201 do {
1202 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1203 // keep them from going away if another thread re-creates the track during obtainBuffer()
1204 sp<AudioTrackClientProxy> proxy;
1205 sp<IMemory> iMem;
1206
1207 { // start of lock scope
1208 AutoMutex lock(mLock);
1209
1210 newSequence = mSequence;
1211 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1212 if (status == DEAD_OBJECT) {
1213 // re-create track, unless someone else has already done so
1214 if (newSequence == oldSequence) {
1215 status = restoreTrack_l("obtainBuffer");
1216 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001217 buffer.mFrameCount = 0;
1218 buffer.mRaw = NULL;
1219 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001220 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001221 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001222 }
1223 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001224 oldSequence = newSequence;
1225
1226 // Keep the extra references
1227 proxy = mProxy;
1228 iMem = mCblkMemory;
1229
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001230 if (mState == STATE_STOPPING) {
1231 status = -EINTR;
1232 buffer.mFrameCount = 0;
1233 buffer.mRaw = NULL;
1234 buffer.mNonContig = 0;
1235 break;
1236 }
1237
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001238 // Non-blocking if track is stopped or paused
1239 if (mState != STATE_ACTIVE) {
1240 requested = &ClientProxy::kNonBlocking;
1241 }
1242
1243 } // end of lock scope
1244
1245 buffer.mFrameCount = audioBuffer->frameCount;
1246 // FIXME starts the requested timeout and elapsed over from scratch
1247 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1248
1249 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1250
1251 audioBuffer->frameCount = buffer.mFrameCount;
1252 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1253 audioBuffer->raw = buffer.mRaw;
1254 if (nonContig != NULL) {
1255 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001256 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001257 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001258}
1259
1260void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1261{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001262 if (mTransfer == TRANSFER_SHARED) {
1263 return;
1264 }
1265
1266 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1267 if (stepCount == 0) {
1268 return;
1269 }
1270
1271 Proxy::Buffer buffer;
1272 buffer.mFrameCount = stepCount;
1273 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001274
Eric Laurent1703cdf2011-03-07 14:52:59 -08001275 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001276 mInUnderrun = false;
1277 mProxy->releaseBuffer(&buffer);
1278
1279 // restart track if it was disabled by audioflinger due to previous underrun
1280 if (mState == STATE_ACTIVE) {
1281 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001282 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001283 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001284 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001285 mAudioTrack->start();
1286 }
1287 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001288}
1289
1290// -------------------------------------------------------------------------
1291
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001292ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001293{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001294 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001295 return INVALID_OPERATION;
1296 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001297
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001298 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001299 // Sanity-check: user is most-likely passing an error code, and it would
1300 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001301 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001302 return BAD_VALUE;
1303 }
1304
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001305 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001306 Buffer audioBuffer;
1307
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001308 while (userSize >= mFrameSize) {
1309 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001310
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001311 status_t err = obtainBuffer(&audioBuffer,
1312 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001313 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001314 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001315 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001316 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001317 return ssize_t(err);
1318 }
1319
1320 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001321 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001322 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001323 toWrite = audioBuffer.size >> 1;
1324 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001325 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001326 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001327 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001328 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001329 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001330 userSize -= toWrite;
1331 written += toWrite;
1332
1333 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001334 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001335
1336 return written;
1337}
1338
1339// -------------------------------------------------------------------------
1340
John Grossman4ff14ba2012-02-08 16:37:41 -08001341TimedAudioTrack::TimedAudioTrack() {
1342 mIsTimed = true;
1343}
1344
1345status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1346{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001347 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001348 status_t result = UNKNOWN_ERROR;
1349
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001350#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001351 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1352 // while we are accessing the cblk
1353 sp<IAudioTrack> audioTrack = mAudioTrack;
1354 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001355#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001356
John Grossman4ff14ba2012-02-08 16:37:41 -08001357 // If the track is not invalid already, try to allocate a buffer. alloc
1358 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001359 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001360 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001361 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001362 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1363 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001364 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001365 }
1366 }
1367
1368 // If the track is invalid at this point, attempt to restore it. and try the
1369 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001370 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001371 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001372
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001373 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001374 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001375 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001376 }
1377
1378 return result;
1379}
1380
1381status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1382 int64_t pts)
1383{
Eric Laurentdf839842012-05-31 14:27:14 -07001384 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1385 {
1386 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001387 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001388 // restart track if it was disabled by audioflinger due to previous underrun
1389 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001390 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1391 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001392 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001393 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001394 mAudioTrack->start();
1395 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001396 }
Eric Laurentdf839842012-05-31 14:27:14 -07001397 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001398}
1399
1400status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1401 TargetTimeline target)
1402{
1403 return mAudioTrack->setMediaTimeTransform(xform, target);
1404}
1405
1406// -------------------------------------------------------------------------
1407
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001408nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001409{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001410 // Currently the AudioTrack thread is not created if there are no callbacks.
1411 // Would it ever make sense to run the thread, even without callbacks?
1412 // If so, then replace this by checks at each use for mCbf != NULL.
1413 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1414
Eric Laurent1703cdf2011-03-07 14:52:59 -08001415 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001416 if (mAwaitBoost) {
1417 mAwaitBoost = false;
1418 mLock.unlock();
1419 static const int32_t kMaxTries = 5;
1420 int32_t tryCounter = kMaxTries;
1421 uint32_t pollUs = 10000;
1422 do {
1423 int policy = sched_getscheduler(0);
1424 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1425 break;
1426 }
1427 usleep(pollUs);
1428 pollUs <<= 1;
1429 } while (tryCounter-- > 0);
1430 if (tryCounter < 0) {
1431 ALOGE("did not receive expected priority boost on time");
1432 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001433 // Run again immediately
1434 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001435 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001436
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001437 // Can only reference mCblk while locked
1438 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001439 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001440
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001441 // Check for track invalidation
1442 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001443 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1444 // AudioSystem cache. We should not exit here but after calling the callback so
1445 // that the upper layers can recreate the track
Glenn Kasten23a75452014-01-13 10:37:17 -08001446 if (!isOffloaded_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001447 status_t status = restoreTrack_l("processAudioBuffer");
1448 mLock.unlock();
1449 // Run again immediately, but with a new IAudioTrack
1450 return 0;
1451 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001452 }
1453
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001454 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001455 bool active = mState == STATE_ACTIVE;
1456
1457 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1458 bool newUnderrun = false;
1459 if (flags & CBLK_UNDERRUN) {
1460#if 0
1461 // Currently in shared buffer mode, when the server reaches the end of buffer,
1462 // the track stays active in continuous underrun state. It's up to the application
1463 // to pause or stop the track, or set the position to a new offset within buffer.
1464 // This was some experimental code to auto-pause on underrun. Keeping it here
1465 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1466 if (mTransfer == TRANSFER_SHARED) {
1467 mState = STATE_PAUSED;
1468 active = false;
1469 }
1470#endif
1471 if (!mInUnderrun) {
1472 mInUnderrun = true;
1473 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001474 }
1475 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001476
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001477 // Get current position of server
1478 size_t position = mProxy->getPosition();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001479
1480 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001481 bool markerReached = false;
1482 size_t markerPosition = mMarkerPosition;
1483 // FIXME fails for wraparound, need 64 bits
1484 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1485 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001486 }
1487
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001488 // Determine number of new position callback(s) that will be needed, while locked
1489 size_t newPosCount = 0;
1490 size_t newPosition = mNewPosition;
1491 size_t updatePeriod = mUpdatePeriod;
1492 // FIXME fails for wraparound, need 64 bits
1493 if (updatePeriod > 0 && position >= newPosition) {
1494 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1495 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001496 }
1497
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001498 // Cache other fields that will be needed soon
1499 uint32_t loopPeriod = mLoopPeriod;
1500 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001501 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001502 if (mRefreshRemaining) {
1503 mRefreshRemaining = false;
1504 mRemainingFrames = notificationFrames;
1505 mRetryOnPartialBuffer = false;
1506 }
1507 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001508 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001509 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001510
1511 // These fields don't need to be cached, because they are assigned only by set():
1512 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1513 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1514
1515 mLock.unlock();
1516
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001517 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001518 struct timespec timeout;
1519 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1520 timeout.tv_nsec = 0;
1521
Glenn Kasten96f04882013-09-20 09:28:56 -07001522 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001523 switch (status) {
1524 case NO_ERROR:
1525 case DEAD_OBJECT:
1526 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001527 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001528 {
1529 AutoMutex lock(mLock);
1530 // The previously assigned value of waitStreamEnd is no longer valid,
1531 // since the mutex has been unlocked and either the callback handler
1532 // or another thread could have re-started the AudioTrack during that time.
1533 waitStreamEnd = mState == STATE_STOPPING;
1534 if (waitStreamEnd) {
1535 mState = STATE_STOPPED;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001536 }
1537 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001538 if (waitStreamEnd && status != DEAD_OBJECT) {
1539 return NS_INACTIVE;
1540 }
1541 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001542 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001543 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001544 }
1545
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001546 // perform callbacks while unlocked
1547 if (newUnderrun) {
1548 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1549 }
1550 // FIXME we will miss loops if loop cycle was signaled several times since last call
1551 // to processAudioBuffer()
1552 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1553 mCbf(EVENT_LOOP_END, mUserData, NULL);
1554 }
1555 if (flags & CBLK_BUFFER_END) {
1556 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1557 }
1558 if (markerReached) {
1559 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1560 }
1561 while (newPosCount > 0) {
1562 size_t temp = newPosition;
1563 mCbf(EVENT_NEW_POS, mUserData, &temp);
1564 newPosition += updatePeriod;
1565 newPosCount--;
1566 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001567
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001568 if (mObservedSequence != sequence) {
1569 mObservedSequence = sequence;
1570 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001571 // for offloaded tracks, just wait for the upper layers to recreate the track
1572 if (isOffloaded()) {
1573 return NS_INACTIVE;
1574 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001575 }
1576
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001577 // if inactive, then don't run me again until re-started
1578 if (!active) {
1579 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001580 }
1581
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001582 // Compute the estimated time until the next timed event (position, markers, loops)
1583 // FIXME only for non-compressed audio
1584 uint32_t minFrames = ~0;
1585 if (!markerReached && position < markerPosition) {
1586 minFrames = markerPosition - position;
1587 }
1588 if (loopPeriod > 0 && loopPeriod < minFrames) {
1589 minFrames = loopPeriod;
1590 }
1591 if (updatePeriod > 0 && updatePeriod < minFrames) {
1592 minFrames = updatePeriod;
1593 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001594
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001595 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1596 static const uint32_t kPoll = 0;
1597 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1598 minFrames = kPoll * notificationFrames;
1599 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001600
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001601 // Convert frame units to time units
1602 nsecs_t ns = NS_WHENEVER;
1603 if (minFrames != (uint32_t) ~0) {
1604 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1605 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1606 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1607 }
1608
1609 // If not supplying data by EVENT_MORE_DATA, then we're done
1610 if (mTransfer != TRANSFER_CALLBACK) {
1611 return ns;
1612 }
1613
1614 struct timespec timeout;
1615 const struct timespec *requested = &ClientProxy::kForever;
1616 if (ns != NS_WHENEVER) {
1617 timeout.tv_sec = ns / 1000000000LL;
1618 timeout.tv_nsec = ns % 1000000000LL;
1619 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1620 requested = &timeout;
1621 }
1622
1623 while (mRemainingFrames > 0) {
1624
1625 Buffer audioBuffer;
1626 audioBuffer.frameCount = mRemainingFrames;
1627 size_t nonContig;
1628 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1629 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1630 "obtainBuffer() err=%d frameCount=%u", err, audioBuffer.frameCount);
1631 requested = &ClientProxy::kNonBlocking;
1632 size_t avail = audioBuffer.frameCount + nonContig;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001633 ALOGV("obtainBuffer(%u) returned %u = %u + %u err %d",
1634 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001635 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001636 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1637 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001638 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001639 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001640 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1641 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001642 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001643
Eric Laurent42a6f422013-08-29 14:35:05 -07001644 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001645 mRetryOnPartialBuffer = false;
1646 if (avail < mRemainingFrames) {
1647 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1648 if (ns < 0 || myns < ns) {
1649 ns = myns;
1650 }
1651 return ns;
1652 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001653 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001654
1655 // Divide buffer size by 2 to take into account the expansion
1656 // due to 8 to 16 bit conversion: the callback must fill only half
1657 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001658 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001659 audioBuffer.size >>= 1;
1660 }
1661
1662 size_t reqSize = audioBuffer.size;
1663 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001664 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001665
1666 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001667 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
1668 ALOGE("EVENT_MORE_DATA requested %u bytes but callback returned %d bytes",
1669 reqSize, (int) writtenSize);
1670 return NS_NEVER;
1671 }
1672
1673 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001674 // The callback is done filling buffers
1675 // Keep this thread going to handle timed events and
1676 // still try to get more data in intervals of WAIT_PERIOD_MS
1677 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001678 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001679 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001680
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001681 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001682 // 8 to 16 bit conversion, note that source and destination are the same address
1683 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001684 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001685 }
1686
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001687 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1688 audioBuffer.frameCount = releasedFrames;
1689 mRemainingFrames -= releasedFrames;
1690 if (misalignment >= releasedFrames) {
1691 misalignment -= releasedFrames;
1692 } else {
1693 misalignment = 0;
1694 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001695
1696 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001697
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001698 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1699 // if callback doesn't like to accept the full chunk
1700 if (writtenSize < reqSize) {
1701 continue;
1702 }
1703
1704 // There could be enough non-contiguous frames available to satisfy the remaining request
1705 if (mRemainingFrames <= nonContig) {
1706 continue;
1707 }
1708
1709#if 0
1710 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1711 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1712 // that total to a sum == notificationFrames.
1713 if (0 < misalignment && misalignment <= mRemainingFrames) {
1714 mRemainingFrames = misalignment;
1715 return (mRemainingFrames * 1100000000LL) / sampleRate;
1716 }
1717#endif
1718
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001719 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001720 mRemainingFrames = notificationFrames;
1721 mRetryOnPartialBuffer = true;
1722
1723 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1724 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001725}
1726
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001727status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001728{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001729 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Glenn Kasten23a75452014-01-13 10:37:17 -08001730 isOffloaded_l() ? "Offloaded" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001731 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001732 status_t result;
1733
Glenn Kastena47f3162012-11-07 10:13:08 -08001734 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kasten38e905b2014-01-13 10:21:48 -08001735 // output parameters in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001736 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001737
Glenn Kasten23a75452014-01-13 10:37:17 -08001738 if (isOffloaded_l()) {
1739 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001740 return DEAD_OBJECT;
1741 }
1742
Glenn Kastena47f3162012-11-07 10:13:08 -08001743 // if the new IAudioTrack is created, createTrack_l() will modify the
1744 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1745 // It will also delete the strong references on previous IAudioTrack and IMemory
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001746
1747 // take the frames that will be lost by track recreation into account in saved position
1748 size_t position = mProxy->getPosition() + mProxy->getFramesFilled();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001749 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
Glenn Kasten363fb752014-01-15 12:27:31 -08001750 result = createTrack_l(position /*epoch*/);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001751
Glenn Kastena47f3162012-11-07 10:13:08 -08001752 if (result == NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001753 // continue playback from last known position, but
1754 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1755 if (mStaticProxy != NULL) {
1756 mLoopPeriod = 0;
1757 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1758 }
1759 // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1760 // track destruction have been played? This is critical for SoundPool implementation
1761 // This must be broken, and needs to be tested/debugged.
1762#if 0
Glenn Kastena47f3162012-11-07 10:13:08 -08001763 // restore write index and set other indexes to reflect empty buffer status
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001764 if (!strcmp(from, "start")) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001765 // Make sure that a client relying on callback events indicating underrun or
1766 // the actual amount of audio frames played (e.g SoundPool) receives them.
1767 if (mSharedBuffer == 0) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001768 // restart playback even if buffer is not completely filled.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001769 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001770 }
1771 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001772#endif
1773 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001774 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001775 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001776 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001777 if (result != NO_ERROR) {
Glenn Kasten2b2165c2014-01-13 08:53:36 -08001778 // Use of direct and offloaded output streams is ref counted by audio policy manager.
Glenn Kasten38e905b2014-01-13 10:21:48 -08001779#if 0 // FIXME This should no longer be needed
1780 //Use of direct and offloaded output streams is ref counted by audio policy manager.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001781 // As getOutput was called above and resulted in an output stream to be opened,
1782 // we need to release it.
Glenn Kasten38e905b2014-01-13 10:21:48 -08001783 if (mOutput != 0) {
1784 AudioSystem::releaseOutput(mOutput);
1785 mOutput = 0;
1786 }
1787#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001788 ALOGW("restoreTrack_l() failed status %d", result);
1789 mState = STATE_STOPPED;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001790 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001791
1792 return result;
1793}
1794
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001795status_t AudioTrack::setParameters(const String8& keyValuePairs)
1796{
1797 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001798 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001799}
1800
Glenn Kastence703742013-07-19 16:33:58 -07001801status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1802{
Glenn Kasten53cec222013-08-29 09:01:02 -07001803 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001804 // FIXME not implemented for fast tracks; should use proxy and SSQ
1805 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1806 return INVALID_OPERATION;
1807 }
1808 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
1809 return INVALID_OPERATION;
1810 }
1811 status_t status = mAudioTrack->getTimestamp(timestamp);
1812 if (status == NO_ERROR) {
1813 timestamp.mPosition += mProxy->getEpoch();
1814 }
1815 return status;
Glenn Kastence703742013-07-19 16:33:58 -07001816}
1817
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001818String8 AudioTrack::getParameters(const String8& keys)
1819{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08001820 audio_io_handle_t output = getOutput();
1821 if (output != 0) {
1822 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001823 } else {
1824 return String8::empty();
1825 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001826}
1827
Glenn Kasten23a75452014-01-13 10:37:17 -08001828bool AudioTrack::isOffloaded() const
1829{
1830 AutoMutex lock(mLock);
1831 return isOffloaded_l();
1832}
1833
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001834status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001835{
1836
1837 const size_t SIZE = 256;
1838 char buffer[SIZE];
1839 String8 result;
1840
1841 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001842 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
1843 mVolume[0], mVolume[1]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001844 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001845 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001846 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001847 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001848 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001849 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001850 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001851 result.append(buffer);
1852 ::write(fd, result.string(), result.size());
1853 return NO_ERROR;
1854}
1855
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001856uint32_t AudioTrack::getUnderrunFrames() const
1857{
1858 AutoMutex lock(mLock);
1859 return mProxy->getUnderrunFrames();
1860}
1861
1862// =========================================================================
1863
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001864void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001865{
1866 sp<AudioTrack> audioTrack = mAudioTrack.promote();
1867 if (audioTrack != 0) {
1868 AutoMutex lock(audioTrack->mLock);
1869 audioTrack->mProxy->binderDied();
1870 }
1871}
1872
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001873// =========================================================================
1874
1875AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07001876 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
1877 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08001878{
1879}
1880
1881AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001882{
1883}
1884
1885bool AudioTrack::AudioTrackThread::threadLoop()
1886{
Glenn Kasten3acbd052012-02-28 10:39:56 -08001887 {
1888 AutoMutex _l(mMyLock);
1889 if (mPaused) {
1890 mMyCond.wait(mMyLock);
1891 // caller will check for exitPending()
1892 return true;
1893 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07001894 if (mIgnoreNextPausedInt) {
1895 mIgnoreNextPausedInt = false;
1896 mPausedInt = false;
1897 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001898 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001899 if (mPausedNs > 0) {
1900 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
1901 } else {
1902 mMyCond.wait(mMyLock);
1903 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07001904 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001905 return true;
1906 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001907 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001908 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001909 switch (ns) {
1910 case 0:
1911 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001912 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001913 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001914 return true;
1915 case NS_NEVER:
1916 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001917 case NS_WHENEVER:
1918 // FIXME increase poll interval, or make event-driven
1919 ns = 1000000000LL;
1920 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001921 default:
1922 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001923 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001924 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07001925 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001926}
1927
Glenn Kasten3acbd052012-02-28 10:39:56 -08001928void AudioTrack::AudioTrackThread::requestExit()
1929{
1930 // must be in this order to avoid a race condition
1931 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07001932 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08001933}
1934
1935void AudioTrack::AudioTrackThread::pause()
1936{
1937 AutoMutex _l(mMyLock);
1938 mPaused = true;
1939}
1940
1941void AudioTrack::AudioTrackThread::resume()
1942{
1943 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07001944 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07001945 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08001946 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07001947 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001948 mMyCond.signal();
1949 }
1950}
1951
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001952void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
1953{
1954 AutoMutex _l(mMyLock);
1955 mPausedInt = true;
1956 mPausedNs = ns;
1957}
1958
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001959}; // namespace android