blob: fdcf9110ff36a3b22b1376c4dab3ec5f09dfc311 [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
47 // default to 0 in case of error
48 *frameCount = 0;
49
Glenn Kastene0fa4672012-04-24 14:35:14 -070050 // FIXME merge with similar code in createTrack_l(), except we're missing
51 // some information here that is available in createTrack_l():
52 // audio_io_handle_t output
53 // audio_format_t format
54 // audio_channel_mask_t channelMask
55 // audio_output_flags_t flags
Glenn Kasten3b16c762012-11-14 08:44:39 -080056 uint32_t afSampleRate;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080057 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
58 return NO_INIT;
59 }
Glenn Kastene33054e2012-11-14 12:54:39 -080060 size_t afFrameCount;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080061 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
62 return NO_INIT;
63 }
64 uint32_t afLatency;
65 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
66 return NO_INIT;
67 }
68
69 // Ensure that buffer depth covers at least audio hardware latency
70 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080071 if (minBufCount < 2) {
72 minBufCount = 2;
73 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +080074
75 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
Glenn Kastene53b9ea2012-03-12 16:29:55 -070076 afFrameCount * minBufCount * sampleRate / afSampleRate;
Glenn Kasten3acbd052012-02-28 10:39:56 -080077 ALOGV("getMinFrameCount=%d: afFrameCount=%d, minBufCount=%d, afSampleRate=%d, afLatency=%d",
78 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +080079 return NO_ERROR;
80}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080081
82// ---------------------------------------------------------------------------
83
84AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -070085 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -080086 mIsTimed(false),
87 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Glenn Kasten9f80dd22012-12-18 15:57:32 -080088 mPreviousSchedulingGroup(SP_DEFAULT)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080089{
90}
91
92AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -080093 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080094 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -080095 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -070096 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080097 int frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -070098 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080099 callback_t cbf,
100 void* user,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700101 int notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800102 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000103 transfer_type transferType,
104 const audio_offload_info_t *offloadInfo)
Glenn Kasten87913512011-06-22 16:15:25 -0700105 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800106 mIsTimed(false),
107 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800108 mPreviousSchedulingGroup(SP_DEFAULT)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800109{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700110 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700111 frameCount, flags, cbf, user, notificationFrames,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000112 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800113}
114
Andreas Huberc8139852012-01-18 10:51:55 -0800115AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800116 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800117 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800118 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700119 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800120 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700121 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800122 callback_t cbf,
123 void* user,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700124 int notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800125 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000126 transfer_type transferType,
127 const audio_offload_info_t *offloadInfo)
Glenn Kasten87913512011-06-22 16:15:25 -0700128 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800129 mIsTimed(false),
130 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800131 mPreviousSchedulingGroup(SP_DEFAULT)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800132{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700133 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800134 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000135 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800136}
137
138AudioTrack::~AudioTrack()
139{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800140 if (mStatus == NO_ERROR) {
141 // Make sure that callback function exits in the case where
142 // it is looping on buffer full condition in obtainBuffer().
143 // Otherwise the callback thread will never exit.
144 stop();
145 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100146 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800147 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800148 mAudioTrackThread->requestExitAndWait();
149 mAudioTrackThread.clear();
150 }
Glenn Kasten53cec222013-08-29 09:01:02 -0700151 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
152 mAudioTrack.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800153 IPCThreadState::self()->flushCommands();
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700154 AudioSystem::releaseAudioSessionId(mSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800155 }
156}
157
158status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800159 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800160 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800161 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700162 audio_channel_mask_t channelMask,
Glenn Kastene33054e2012-11-14 12:54:39 -0800163 int frameCountInt,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700164 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800165 callback_t cbf,
166 void* user,
167 int notificationFrames,
168 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700169 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800170 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000171 transfer_type transferType,
172 const audio_offload_info_t *offloadInfo)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800173{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800174 switch (transferType) {
175 case TRANSFER_DEFAULT:
176 if (sharedBuffer != 0) {
177 transferType = TRANSFER_SHARED;
178 } else if (cbf == NULL || threadCanCallJava) {
179 transferType = TRANSFER_SYNC;
180 } else {
181 transferType = TRANSFER_CALLBACK;
182 }
183 break;
184 case TRANSFER_CALLBACK:
185 if (cbf == NULL || sharedBuffer != 0) {
186 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
187 return BAD_VALUE;
188 }
189 break;
190 case TRANSFER_OBTAIN:
191 case TRANSFER_SYNC:
192 if (sharedBuffer != 0) {
193 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
194 return BAD_VALUE;
195 }
196 break;
197 case TRANSFER_SHARED:
198 if (sharedBuffer == 0) {
199 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
200 return BAD_VALUE;
201 }
202 break;
203 default:
204 ALOGE("Invalid transfer type %d", transferType);
205 return BAD_VALUE;
206 }
207 mTransfer = transferType;
208
Glenn Kastene33054e2012-11-14 12:54:39 -0800209 // FIXME "int" here is legacy and will be replaced by size_t later
210 if (frameCountInt < 0) {
211 ALOGE("Invalid frame count %d", frameCountInt);
212 return BAD_VALUE;
213 }
214 size_t frameCount = frameCountInt;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800215
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700216 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
217 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800218
Glenn Kastene33054e2012-11-14 12:54:39 -0800219 ALOGV("set() streamType %d frameCount %u flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700220
Eric Laurent1703cdf2011-03-07 14:52:59 -0800221 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800222
Glenn Kasten53cec222013-08-29 09:01:02 -0700223 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700224 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000225 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800226 return INVALID_OPERATION;
227 }
228
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100229 mOutput = 0;
230
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800231 // handle default values first.
Dima Zavinfce7a472011-04-19 22:30:36 -0700232 if (streamType == AUDIO_STREAM_DEFAULT) {
233 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800234 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700235
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800236 if (sampleRate == 0) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800237 uint32_t afSampleRate;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700238 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
239 return NO_INIT;
240 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800241 sampleRate = afSampleRate;
242 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800243 mSampleRate = sampleRate;
Glenn Kastenea7939a2012-03-14 12:56:26 -0700244
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800245 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800246 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700247 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800248 }
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700249 if (channelMask == 0) {
250 channelMask = AUDIO_CHANNEL_OUT_STEREO;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800251 }
252
253 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700254 if (!audio_is_valid_format(format)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800255 ALOGE("Invalid format %d", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800256 return BAD_VALUE;
257 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700258
Glenn Kastene0fa4672012-04-24 14:35:14 -0700259 // AudioFlinger does not currently support 8-bit data in shared memory
260 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
261 ALOGE("8-bit data in shared memory is not supported");
262 return BAD_VALUE;
263 }
264
Eric Laurentc2f1f072009-07-17 12:17:14 -0700265 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100266 // or offload was requested
267 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
268 || !audio_is_linear_pcm(format)) {
269 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
270 ? "Offload request, forcing to Direct Output"
271 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700272 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800273 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700274 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700275 }
Eric Laurent1948eb32012-04-13 16:50:19 -0700276 // only allow deep buffering for music stream type
277 if (streamType != AUDIO_STREAM_MUSIC) {
278 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
279 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700280
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700281 if (!audio_is_output_channel(channelMask)) {
Glenn Kasten28b76b32012-07-03 17:24:41 -0700282 ALOGE("Invalid channel mask %#x", channelMask);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700283 return BAD_VALUE;
284 }
Glenn Kastena42ff002012-11-14 12:47:55 -0800285 mChannelMask = channelMask;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700286 uint32_t channelCount = popcount(channelMask);
Glenn Kastena42ff002012-11-14 12:47:55 -0800287 mChannelCount = channelCount;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700288
Glenn Kastene3aa6592012-12-04 12:22:46 -0800289 if (audio_is_linear_pcm(format)) {
290 mFrameSize = channelCount * audio_bytes_per_sample(format);
291 mFrameSizeAF = channelCount * sizeof(int16_t);
292 } else {
293 mFrameSize = sizeof(uint8_t);
294 mFrameSizeAF = sizeof(uint8_t);
295 }
296
Dima Zavinfce7a472011-04-19 22:30:36 -0700297 audio_io_handle_t output = AudioSystem::getOutput(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800298 streamType,
Glenn Kastene1c39622012-01-04 09:36:37 -0800299 sampleRate, format, channelMask,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000300 flags,
301 offloadInfo);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700302
303 if (output == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000304 ALOGE("Could not get audio output for stream type %d", streamType);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800305 return BAD_VALUE;
306 }
307
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800308 mVolume[LEFT] = 1.0f;
309 mVolume[RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800310 mSendLevel = 0.0f;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700311 mFrameCount = frameCount;
Glenn Kastenb6037442012-11-14 13:42:25 -0800312 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700313 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800314 mNotificationFramesAct = 0;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700315 mSessionId = sessionId;
Eric Laurent2beeb502010-07-16 07:43:46 -0700316 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700317 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700318 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700319
Glenn Kastena997e7a2012-08-07 09:44:19 -0700320 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700321 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700322 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
323 }
324
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800325 // create the IAudioTrack
Eric Laurent1703cdf2011-03-07 14:52:59 -0800326 status_t status = createTrack_l(streamType,
327 sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800328 format,
Eric Laurent1703cdf2011-03-07 14:52:59 -0800329 frameCount,
330 flags,
331 sharedBuffer,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800332 output,
333 0 /*epoch*/);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800334
Glenn Kastena997e7a2012-08-07 09:44:19 -0700335 if (status != NO_ERROR) {
336 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100337 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
338 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700339 mAudioTrackThread.clear();
340 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100341 //Use of direct and offloaded output streams is ref counted by audio policy manager.
342 // As getOutput was called above and resulted in an output stream to be opened,
343 // we need to release it.
344 AudioSystem::releaseOutput(output);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700345 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700346 }
347
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800348 mStatus = NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800349 mStreamType = streamType;
Glenn Kastene1c39622012-01-04 09:36:37 -0800350 mFormat = format;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800351 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800352 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800353 mUserData = user;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800354 mLoopPeriod = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800355 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700356 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800357 mNewPosition = 0;
358 mUpdatePeriod = 0;
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700359 AudioSystem::acquireAudioSessionId(mSessionId);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800360 mSequence = 1;
361 mObservedSequence = mSequence;
362 mInUnderrun = false;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100363 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800364
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800365 return NO_ERROR;
366}
367
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800368// -------------------------------------------------------------------------
369
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100370status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800371{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800372 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100373
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800374 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100375 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800376 }
377
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800378 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800379
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800380 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100381 if (previousState == STATE_PAUSED_STOPPING) {
382 mState = STATE_STOPPING;
383 } else {
384 mState = STATE_ACTIVE;
385 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800386 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
387 // reset current position as seen by client to 0
388 mProxy->setEpoch(mProxy->getEpoch() - mProxy->getPosition());
Eric Laurentec9a0322013-08-28 10:23:01 -0700389 // force refresh of remaining frames by processAudioBuffer() as last
390 // write before stop could be partial.
391 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800392 }
393 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700394 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800395
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800396 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800397 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100398 if (previousState == STATE_STOPPING) {
399 mProxy->interrupt();
400 } else {
401 t->resume();
402 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800403 } else {
404 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
405 get_sched_policy(0, &mPreviousSchedulingGroup);
406 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
407 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800408
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800409 status_t status = NO_ERROR;
410 if (!(flags & CBLK_INVALID)) {
411 status = mAudioTrack->start();
412 if (status == DEAD_OBJECT) {
413 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800414 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800415 }
416 if (flags & CBLK_INVALID) {
417 status = restoreTrack_l("start");
418 }
419
420 if (status != NO_ERROR) {
421 ALOGE("start() status %d", status);
422 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800423 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100424 if (previousState != STATE_STOPPING) {
425 t->pause();
426 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800427 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700428 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700429 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800430 }
431 }
432
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100433 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800434}
435
436void AudioTrack::stop()
437{
438 AutoMutex lock(mLock);
439 // FIXME pause then stop should not be a nop
440 if (mState != STATE_ACTIVE) {
441 return;
442 }
443
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100444 if (isOffloaded()) {
445 mState = STATE_STOPPING;
446 } else {
447 mState = STATE_STOPPED;
448 }
449
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800450 mProxy->interrupt();
451 mAudioTrack->stop();
452 // the playback head position will reset to 0, so if a marker is set, we need
453 // to activate it again
454 mMarkerReached = false;
455#if 0
456 // Force flush if a shared buffer is used otherwise audioflinger
457 // will not stop before end of buffer is reached.
458 // It may be needed to make sure that we stop playback, likely in case looping is on.
459 if (mSharedBuffer != 0) {
460 flush_l();
461 }
462#endif
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100463
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800464 sp<AudioTrackThread> t = mAudioTrackThread;
465 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100466 if (!isOffloaded()) {
467 t->pause();
468 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800469 } else {
470 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
471 set_sched_policy(0, mPreviousSchedulingGroup);
472 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800473}
474
475bool AudioTrack::stopped() const
476{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800477 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800478 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800479}
480
481void AudioTrack::flush()
482{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800483 if (mSharedBuffer != 0) {
484 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800485 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800486 AutoMutex lock(mLock);
487 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
488 return;
489 }
490 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800491}
492
Eric Laurent1703cdf2011-03-07 14:52:59 -0800493void AudioTrack::flush_l()
494{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800495 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700496
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700497 // clear playback marker and periodic update counter
498 mMarkerPosition = 0;
499 mMarkerReached = false;
500 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100501 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700502
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800503 mState = STATE_FLUSHED;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100504 if (isOffloaded()) {
505 mProxy->interrupt();
506 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800507 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800508 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800509}
510
511void AudioTrack::pause()
512{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800513 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100514 if (mState == STATE_ACTIVE) {
515 mState = STATE_PAUSED;
516 } else if (mState == STATE_STOPPING) {
517 mState = STATE_PAUSED_STOPPING;
518 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800519 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800520 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800521 mProxy->interrupt();
522 mAudioTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800523}
524
Eric Laurentbe916aa2010-06-01 23:49:17 -0700525status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800526{
Glenn Kastenf0c49502011-11-30 09:46:04 -0800527 if (left < 0.0f || left > 1.0f || right < 0.0f || right > 1.0f) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700528 return BAD_VALUE;
529 }
530
Eric Laurent1703cdf2011-03-07 14:52:59 -0800531 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800532 mVolume[LEFT] = left;
533 mVolume[RIGHT] = right;
534
Glenn Kastene3aa6592012-12-04 12:22:46 -0800535 mProxy->setVolumeLR((uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700536
537 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800538}
539
Glenn Kastenb1c09932012-02-27 16:21:04 -0800540status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800541{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800542 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700543}
544
Eric Laurent2beeb502010-07-16 07:43:46 -0700545status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700546{
Glenn Kasten05632a52012-01-03 14:22:33 -0800547 if (level < 0.0f || level > 1.0f) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700548 return BAD_VALUE;
549 }
550
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800551 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700552 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800553 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700554
555 return NO_ERROR;
556}
557
Glenn Kastena5224f32012-01-04 12:41:44 -0800558void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700559{
560 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800561 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700562 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800563}
564
Glenn Kasten3b16c762012-11-14 08:44:39 -0800565status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800566{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100567 if (mIsTimed || isOffloaded()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800568 return INVALID_OPERATION;
569 }
570
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800571 uint32_t afSamplingRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800572 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700573 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800574 }
575 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Glenn Kastend65d73c2012-06-22 17:21:07 -0700576 if (rate == 0 || rate > afSamplingRate*2 ) {
577 return BAD_VALUE;
578 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800579
Eric Laurent1703cdf2011-03-07 14:52:59 -0800580 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800581 mSampleRate = rate;
582 mProxy->setSampleRate(rate);
583
Eric Laurent57326622009-07-07 07:10:45 -0700584 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800585}
586
Glenn Kastena5224f32012-01-04 12:41:44 -0800587uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800588{
John Grossman4ff14ba2012-02-08 16:37:41 -0800589 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800590 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800591 }
592
Eric Laurent1703cdf2011-03-07 14:52:59 -0800593 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800594 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800595}
596
597status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
598{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100599 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800600 return INVALID_OPERATION;
601 }
602
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800603 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800604 ;
605 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
606 loopEnd - loopStart >= MIN_LOOP) {
607 ;
608 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800609 return BAD_VALUE;
610 }
611
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800612 AutoMutex lock(mLock);
613 // See setPosition() regarding setting parameters such as loop points or position while active
614 if (mState == STATE_ACTIVE) {
615 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700616 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800617 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800618 return NO_ERROR;
619}
620
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800621void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
622{
623 // FIXME If setting a loop also sets position to start of loop, then
624 // this is correct. Otherwise it should be removed.
625 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
626 mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0;
627 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
628}
629
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800630status_t AudioTrack::setMarkerPosition(uint32_t marker)
631{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700632 // The only purpose of setting marker position is to get a callback
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100633 if (mCbf == NULL || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700634 return INVALID_OPERATION;
635 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800636
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800637 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800638 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700639 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800640
641 return NO_ERROR;
642}
643
Glenn Kastena5224f32012-01-04 12:41:44 -0800644status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800645{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100646 if (isOffloaded()) {
647 return INVALID_OPERATION;
648 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700649 if (marker == NULL) {
650 return BAD_VALUE;
651 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800652
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800653 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800654 *marker = mMarkerPosition;
655
656 return NO_ERROR;
657}
658
659status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
660{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700661 // The only purpose of setting position update period is to get a callback
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100662 if (mCbf == NULL || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700663 return INVALID_OPERATION;
664 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800665
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800666 AutoMutex lock(mLock);
667 mNewPosition = mProxy->getPosition() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800668 mUpdatePeriod = updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800669 return NO_ERROR;
670}
671
Glenn Kastena5224f32012-01-04 12:41:44 -0800672status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800673{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100674 if (isOffloaded()) {
675 return INVALID_OPERATION;
676 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700677 if (updatePeriod == NULL) {
678 return BAD_VALUE;
679 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800680
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800681 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800682 *updatePeriod = mUpdatePeriod;
683
684 return NO_ERROR;
685}
686
687status_t AudioTrack::setPosition(uint32_t position)
688{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100689 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700690 return INVALID_OPERATION;
691 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800692 if (position > mFrameCount) {
693 return BAD_VALUE;
694 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800695
Eric Laurent1703cdf2011-03-07 14:52:59 -0800696 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800697 // Currently we require that the player is inactive before setting parameters such as position
698 // or loop points. Otherwise, there could be a race condition: the application could read the
699 // current position, compute a new position or loop parameters, and then set that position or
700 // loop parameters but it would do the "wrong" thing since the position has continued to advance
701 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
702 // to specify how it wants to handle such scenarios.
703 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700704 return INVALID_OPERATION;
705 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800706 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
707 mLoopPeriod = 0;
708 // FIXME Check whether loops and setting position are incompatible in old code.
709 // If we use setLoop for both purposes we lose the capability to set the position while looping.
710 mStaticProxy->setLoop(position, mFrameCount, 0);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700711
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800712 return NO_ERROR;
713}
714
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800715status_t AudioTrack::getPosition(uint32_t *position) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800716{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700717 if (position == NULL) {
718 return BAD_VALUE;
719 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800720
Eric Laurent1703cdf2011-03-07 14:52:59 -0800721 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100722 if (isOffloaded()) {
723 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800724
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100725 if (mOutput != 0) {
726 uint32_t halFrames;
727 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
728 }
729 *position = dspFrames;
730 } else {
731 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
732 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ? 0 :
733 mProxy->getPosition();
734 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800735 return NO_ERROR;
736}
737
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800738status_t AudioTrack::getBufferPosition(size_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800739{
740 if (mSharedBuffer == 0 || mIsTimed) {
741 return INVALID_OPERATION;
742 }
743 if (position == NULL) {
744 return BAD_VALUE;
745 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800746
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800747 AutoMutex lock(mLock);
748 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800749 return NO_ERROR;
750}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800751
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800752status_t AudioTrack::reload()
753{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100754 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800755 return INVALID_OPERATION;
756 }
757
Eric Laurent1703cdf2011-03-07 14:52:59 -0800758 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800759 // See setPosition() regarding setting parameters such as loop points or position while active
760 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700761 return INVALID_OPERATION;
762 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800763 mNewPosition = mUpdatePeriod;
764 mLoopPeriod = 0;
765 // FIXME The new code cannot reload while keeping a loop specified.
766 // Need to check how the old code handled this, and whether it's a significant change.
767 mStaticProxy->setLoop(0, mFrameCount, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800768 return NO_ERROR;
769}
770
Eric Laurentc2f1f072009-07-17 12:17:14 -0700771audio_io_handle_t AudioTrack::getOutput()
772{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800773 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100774 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800775}
776
777// must be called with mLock held
778audio_io_handle_t AudioTrack::getOutput_l()
779{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100780 if (mOutput) {
781 return mOutput;
782 } else {
783 return AudioSystem::getOutput(mStreamType,
784 mSampleRate, mFormat, mChannelMask, mFlags);
785 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700786}
787
Eric Laurentbe916aa2010-06-01 23:49:17 -0700788status_t AudioTrack::attachAuxEffect(int effectId)
789{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800790 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700791 status_t status = mAudioTrack->attachAuxEffect(effectId);
792 if (status == NO_ERROR) {
793 mAuxEffectId = effectId;
794 }
795 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700796}
797
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800798// -------------------------------------------------------------------------
799
Eric Laurent1703cdf2011-03-07 14:52:59 -0800800// must be called with mLock held
801status_t AudioTrack::createTrack_l(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800802 audio_stream_type_t streamType,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800803 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800804 audio_format_t format,
Glenn Kastene33054e2012-11-14 12:54:39 -0800805 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700806 audio_output_flags_t flags,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800807 const sp<IMemory>& sharedBuffer,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800808 audio_io_handle_t output,
809 size_t epoch)
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800810{
811 status_t status;
812 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
813 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700814 ALOGE("Could not get audioflinger");
815 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800816 }
817
Glenn Kastence8828a2013-09-16 18:07:38 -0700818 // Not all of these values are needed under all conditions, but it is easier to get them all
819
Eric Laurentd1b449a2010-05-14 03:26:45 -0700820 uint32_t afLatency;
Glenn Kastence8828a2013-09-16 18:07:38 -0700821 status = AudioSystem::getLatency(output, streamType, &afLatency);
822 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800823 ALOGE("getLatency(%d) failed status %d", output, status);
Eric Laurentd1b449a2010-05-14 03:26:45 -0700824 return NO_INIT;
825 }
826
Glenn Kastence8828a2013-09-16 18:07:38 -0700827 size_t afFrameCount;
828 status = AudioSystem::getFrameCount(output, streamType, &afFrameCount);
829 if (status != NO_ERROR) {
830 ALOGE("getFrameCount(output=%d, streamType=%d) status %d", output, streamType, status);
831 return NO_INIT;
832 }
833
834 uint32_t afSampleRate;
835 status = AudioSystem::getSamplingRate(output, streamType, &afSampleRate);
836 if (status != NO_ERROR) {
837 ALOGE("getSamplingRate(output=%d, streamType=%d) status %d", output, streamType, status);
838 return NO_INIT;
839 }
840
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700841 // Client decides whether the track is TIMED (see below), but can only express a preference
842 // for FAST. Server will perform additional tests.
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700843 if ((flags & AUDIO_OUTPUT_FLAG_FAST) && !(
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700844 // either of these use cases:
845 // use case 1: shared buffer
846 (sharedBuffer != 0) ||
847 // use case 2: callback handler
848 (mCbf != NULL))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800849 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -0700850 // once denied, do not request again if IAudioTrack is re-created
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700851 flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten093000f2012-05-03 09:35:36 -0700852 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700853 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700854 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700855
Glenn Kastence8828a2013-09-16 18:07:38 -0700856 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
857 // n = 1 fast track; nBuffering is ignored
858 // n = 2 normal track, no sample rate conversion
859 // n = 3 normal track, with sample rate conversion
860 // (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering)
861 // n > 3 very high latency or very small notification interval; nBuffering is ignored
862 const uint32_t nBuffering = (sampleRate == afSampleRate) ? 2 : 3;
863
Eric Laurentd1b449a2010-05-14 03:26:45 -0700864 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700865
Dima Zavinfce7a472011-04-19 22:30:36 -0700866 if (!audio_is_linear_pcm(format)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700867
Eric Laurentd1b449a2010-05-14 03:26:45 -0700868 if (sharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700869 // Same comment as below about ignoring frameCount parameter for set()
Eric Laurentd1b449a2010-05-14 03:26:45 -0700870 frameCount = sharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -0700871 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700872 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700873 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100874 if (mNotificationFramesAct != frameCount) {
875 mNotificationFramesAct = frameCount;
876 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700877 } else if (sharedBuffer != 0) {
878
Glenn Kastena42ff002012-11-14 12:47:55 -0800879 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -0700880 // 8-bit data in shared memory is not currently supported by AudioFlinger
881 size_t alignment = /* format == AUDIO_FORMAT_PCM_8_BIT ? 1 : */ 2;
Glenn Kastena42ff002012-11-14 12:47:55 -0800882 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700883 // More than 2 channels does not require stronger alignment than stereo
884 alignment <<= 1;
885 }
Glenn Kastena42ff002012-11-14 12:47:55 -0800886 if (((size_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
887 ALOGE("Invalid buffer alignment: address %p, channel count %u",
888 sharedBuffer->pointer(), mChannelCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700889 return BAD_VALUE;
890 }
891
892 // When initializing a shared buffer AudioTrack via constructors,
893 // there's no frameCount parameter.
894 // But when initializing a shared buffer AudioTrack via set(),
895 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kastena42ff002012-11-14 12:47:55 -0800896 frameCount = sharedBuffer->size()/mChannelCount/sizeof(int16_t);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700897
898 } else if (!(flags & AUDIO_OUTPUT_FLAG_FAST)) {
899
900 // FIXME move these calculations and associated checks to server
Glenn Kastene0fa4672012-04-24 14:35:14 -0700901
Eric Laurentd1b449a2010-05-14 03:26:45 -0700902 // Ensure that buffer depth covers at least audio hardware latency
903 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Glenn Kastenbb6f0a02013-06-03 15:00:29 -0700904 ALOGV("afFrameCount=%d, minBufCount=%d, afSampleRate=%u, afLatency=%d",
905 afFrameCount, minBufCount, afSampleRate, afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700906 if (minBufCount <= nBuffering) {
907 minBufCount = nBuffering;
Glenn Kasten7c027242012-12-26 14:43:16 -0800908 }
Eric Laurentd1b449a2010-05-14 03:26:45 -0700909
Glenn Kastene33054e2012-11-14 12:54:39 -0800910 size_t minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
911 ALOGV("minFrameCount: %u, afFrameCount=%d, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -0800912 ", afLatency=%d",
913 minFrameCount, afFrameCount, minBufCount, sampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700914
915 if (frameCount == 0) {
916 frameCount = minFrameCount;
Glenn Kastence8828a2013-09-16 18:07:38 -0700917 } else if (frameCount < minFrameCount) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700918 // not ALOGW because it happens all the time when playing key clicks over A2DP
919 ALOGV("Minimum buffer size corrected from %d to %d",
920 frameCount, minFrameCount);
921 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800922 }
Glenn Kastence8828a2013-09-16 18:07:38 -0700923 // Make sure that application is notified with sufficient margin before underrun
924 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
925 mNotificationFramesAct = frameCount/nBuffering;
926 }
Eric Laurentd1b449a2010-05-14 03:26:45 -0700927
Glenn Kastene0fa4672012-04-24 14:35:14 -0700928 } else {
929 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -0700930 }
931
Glenn Kastena075db42012-03-06 11:22:44 -0800932 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
933 if (mIsTimed) {
934 trackFlags |= IAudioFlinger::TRACK_TIMED;
935 }
Glenn Kasten3acbd052012-02-28 10:39:56 -0800936
937 pid_t tid = -1;
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700938 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700939 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800940 if (mAudioTrackThread != 0) {
941 tid = mAudioTrackThread->getTid();
942 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700943 }
944
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100945 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
946 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
947 }
948
Glenn Kasten8d6cc842012-02-03 11:06:53 -0800949 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800950 sampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -0700951 // AudioFlinger only sees 16-bit PCM
952 format == AUDIO_FORMAT_PCM_8_BIT ?
953 AUDIO_FORMAT_PCM_16_BIT : format,
Glenn Kastena42ff002012-11-14 12:47:55 -0800954 mChannelMask,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800955 frameCount,
Glenn Kastene0b07172012-11-06 15:03:34 -0800956 &trackFlags,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800957 sharedBuffer,
958 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800959 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700960 &mSessionId,
Glenn Kastend054c322013-07-12 12:59:20 -0700961 mName,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800962 &status);
963
964 if (track == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000965 ALOGE("AudioFlinger could not create track, status: %d", status);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800966 return status;
967 }
Glenn Kastend2c38fc2012-11-01 14:58:02 -0700968 sp<IMemory> iMem = track->getCblk();
969 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000970 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800971 return NO_INIT;
972 }
Glenn Kasten53cec222013-08-29 09:01:02 -0700973 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800974 if (mAudioTrack != 0) {
975 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
976 mDeathNotifier.clear();
977 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800978 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -0700979 mCblkMemory = iMem;
980 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMem->pointer());
981 mCblk = cblk;
Glenn Kastenb6037442012-11-14 13:42:25 -0800982 size_t temp = cblk->frameCount_;
983 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
984 // In current design, AudioTrack client checks and ensures frame count validity before
985 // passing it to AudioFlinger so AudioFlinger should not return a different value except
986 // for fast track as it uses a special method of assigning frame count.
987 ALOGW("Requested frameCount %u but received frameCount %u", frameCount, temp);
988 }
989 frameCount = temp;
Glenn Kastena07f17c2013-04-23 12:39:37 -0700990 mAwaitBoost = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800991 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -0800992 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Glenn Kastenb6037442012-11-14 13:42:25 -0800993 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %u", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -0700994 mAwaitBoost = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800995 if (sharedBuffer == 0) {
996 // double-buffering is not required for fast tracks, due to tighter scheduling
997 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount) {
998 mNotificationFramesAct = frameCount;
999 }
1000 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001001 } else {
Glenn Kastenb6037442012-11-14 13:42:25 -08001002 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %u", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001003 // once denied, do not request again if IAudioTrack is re-created
1004 flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST);
1005 mFlags = flags;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001006 if (sharedBuffer == 0) {
Glenn Kastence8828a2013-09-16 18:07:38 -07001007 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1008 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001009 }
1010 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001011 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001012 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001013 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
1014 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1015 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1016 } else {
1017 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
1018 flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1019 mFlags = flags;
1020 return NO_INIT;
1021 }
1022 }
1023
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001024 mRefreshRemaining = true;
1025
1026 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1027 // is the value of pointer() for the shared buffer, otherwise buffers points
1028 // immediately after the control block. This address is for the mapping within client
1029 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1030 void* buffers;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001031 if (sharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001032 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001033 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001034 buffers = sharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001035 }
1036
Eric Laurent2beeb502010-07-16 07:43:46 -07001037 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001038 // FIXME don't believe this lie
Glenn Kastenb6037442012-11-14 13:42:25 -08001039 mLatency = afLatency + (1000*frameCount) / sampleRate;
1040 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001041 // If IAudioTrack is re-created, don't let the requested frameCount
1042 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001043 if (frameCount > mReqFrameCount) {
1044 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001045 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001046
1047 // update proxy
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001048 if (sharedBuffer == 0) {
1049 mStaticProxy.clear();
1050 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1051 } else {
1052 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1053 mProxy = mStaticProxy;
1054 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001055 mProxy->setVolumeLR((uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) |
1056 uint16_t(mVolume[LEFT] * 0x1000));
1057 mProxy->setSendLevel(mSendLevel);
1058 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001059 mProxy->setEpoch(epoch);
1060 mProxy->setMinimum(mNotificationFramesAct);
1061
1062 mDeathNotifier = new DeathNotifier(this);
1063 mAudioTrack->asBinder()->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001064
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001065 return NO_ERROR;
1066}
1067
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001068status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1069{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001070 if (audioBuffer == NULL) {
1071 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001072 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001073 if (mTransfer != TRANSFER_OBTAIN) {
1074 audioBuffer->frameCount = 0;
1075 audioBuffer->size = 0;
1076 audioBuffer->raw = NULL;
1077 return INVALID_OPERATION;
1078 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001079
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001080 const struct timespec *requested;
1081 if (waitCount == -1) {
1082 requested = &ClientProxy::kForever;
1083 } else if (waitCount == 0) {
1084 requested = &ClientProxy::kNonBlocking;
1085 } else if (waitCount > 0) {
1086 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
1087 struct timespec timeout;
1088 timeout.tv_sec = ms / 1000;
1089 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1090 requested = &timeout;
1091 } else {
1092 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1093 requested = NULL;
1094 }
1095 return obtainBuffer(audioBuffer, requested);
1096}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001097
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001098status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1099 struct timespec *elapsed, size_t *nonContig)
1100{
1101 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1102 uint32_t oldSequence = 0;
1103 uint32_t newSequence;
1104
1105 Proxy::Buffer buffer;
1106 status_t status = NO_ERROR;
1107
1108 static const int32_t kMaxTries = 5;
1109 int32_t tryCounter = kMaxTries;
1110
1111 do {
1112 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1113 // keep them from going away if another thread re-creates the track during obtainBuffer()
1114 sp<AudioTrackClientProxy> proxy;
1115 sp<IMemory> iMem;
1116
1117 { // start of lock scope
1118 AutoMutex lock(mLock);
1119
1120 newSequence = mSequence;
1121 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1122 if (status == DEAD_OBJECT) {
1123 // re-create track, unless someone else has already done so
1124 if (newSequence == oldSequence) {
1125 status = restoreTrack_l("obtainBuffer");
1126 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001127 buffer.mFrameCount = 0;
1128 buffer.mRaw = NULL;
1129 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001130 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001131 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001132 }
1133 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001134 oldSequence = newSequence;
1135
1136 // Keep the extra references
1137 proxy = mProxy;
1138 iMem = mCblkMemory;
1139
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001140 if (mState == STATE_STOPPING) {
1141 status = -EINTR;
1142 buffer.mFrameCount = 0;
1143 buffer.mRaw = NULL;
1144 buffer.mNonContig = 0;
1145 break;
1146 }
1147
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001148 // Non-blocking if track is stopped or paused
1149 if (mState != STATE_ACTIVE) {
1150 requested = &ClientProxy::kNonBlocking;
1151 }
1152
1153 } // end of lock scope
1154
1155 buffer.mFrameCount = audioBuffer->frameCount;
1156 // FIXME starts the requested timeout and elapsed over from scratch
1157 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1158
1159 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1160
1161 audioBuffer->frameCount = buffer.mFrameCount;
1162 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1163 audioBuffer->raw = buffer.mRaw;
1164 if (nonContig != NULL) {
1165 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001166 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001167 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001168}
1169
1170void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1171{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001172 if (mTransfer == TRANSFER_SHARED) {
1173 return;
1174 }
1175
1176 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1177 if (stepCount == 0) {
1178 return;
1179 }
1180
1181 Proxy::Buffer buffer;
1182 buffer.mFrameCount = stepCount;
1183 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001184
Eric Laurent1703cdf2011-03-07 14:52:59 -08001185 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001186 mInUnderrun = false;
1187 mProxy->releaseBuffer(&buffer);
1188
1189 // restart track if it was disabled by audioflinger due to previous underrun
1190 if (mState == STATE_ACTIVE) {
1191 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001192 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastend054c322013-07-12 12:59:20 -07001193 ALOGW("releaseBuffer() track %p name=%s disabled due to previous underrun, restarting",
1194 this, mName.string());
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001195 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001196 mAudioTrack->start();
1197 }
1198 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001199}
1200
1201// -------------------------------------------------------------------------
1202
1203ssize_t AudioTrack::write(const void* buffer, size_t userSize)
1204{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001205 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001206 return INVALID_OPERATION;
1207 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001208
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001209 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001210 // Sanity-check: user is most-likely passing an error code, and it would
1211 // make the return value ambiguous (actualSize vs error).
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001212 ALOGE("AudioTrack::write(buffer=%p, size=%u (%d)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001213 return BAD_VALUE;
1214 }
1215
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001216 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001217 Buffer audioBuffer;
1218
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001219 while (userSize >= mFrameSize) {
1220 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001221
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001222 status_t err = obtainBuffer(&audioBuffer, &ClientProxy::kForever);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001223 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001224 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001225 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001226 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001227 return ssize_t(err);
1228 }
1229
1230 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001231 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001232 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001233 toWrite = audioBuffer.size >> 1;
1234 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001235 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001236 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001237 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001238 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001239 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001240 userSize -= toWrite;
1241 written += toWrite;
1242
1243 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001244 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001245
1246 return written;
1247}
1248
1249// -------------------------------------------------------------------------
1250
John Grossman4ff14ba2012-02-08 16:37:41 -08001251TimedAudioTrack::TimedAudioTrack() {
1252 mIsTimed = true;
1253}
1254
1255status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1256{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001257 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001258 status_t result = UNKNOWN_ERROR;
1259
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001260#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001261 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1262 // while we are accessing the cblk
1263 sp<IAudioTrack> audioTrack = mAudioTrack;
1264 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001265#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001266
John Grossman4ff14ba2012-02-08 16:37:41 -08001267 // If the track is not invalid already, try to allocate a buffer. alloc
1268 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001269 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001270 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001271 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001272 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1273 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001274 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001275 }
1276 }
1277
1278 // If the track is invalid at this point, attempt to restore it. and try the
1279 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001280 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001281 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001282
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001283 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001284 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001285 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001286 }
1287
1288 return result;
1289}
1290
1291status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1292 int64_t pts)
1293{
Eric Laurentdf839842012-05-31 14:27:14 -07001294 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1295 {
1296 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001297 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001298 // restart track if it was disabled by audioflinger due to previous underrun
1299 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001300 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1301 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001302 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001303 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001304 mAudioTrack->start();
1305 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001306 }
Eric Laurentdf839842012-05-31 14:27:14 -07001307 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001308}
1309
1310status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1311 TargetTimeline target)
1312{
1313 return mAudioTrack->setMediaTimeTransform(xform, target);
1314}
1315
1316// -------------------------------------------------------------------------
1317
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001318nsecs_t AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001319{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001320 // Currently the AudioTrack thread is not created if there are no callbacks.
1321 // Would it ever make sense to run the thread, even without callbacks?
1322 // If so, then replace this by checks at each use for mCbf != NULL.
1323 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1324
Eric Laurent1703cdf2011-03-07 14:52:59 -08001325 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001326 if (mAwaitBoost) {
1327 mAwaitBoost = false;
1328 mLock.unlock();
1329 static const int32_t kMaxTries = 5;
1330 int32_t tryCounter = kMaxTries;
1331 uint32_t pollUs = 10000;
1332 do {
1333 int policy = sched_getscheduler(0);
1334 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1335 break;
1336 }
1337 usleep(pollUs);
1338 pollUs <<= 1;
1339 } while (tryCounter-- > 0);
1340 if (tryCounter < 0) {
1341 ALOGE("did not receive expected priority boost on time");
1342 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001343 // Run again immediately
1344 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001345 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001346
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001347 // Can only reference mCblk while locked
1348 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001349 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001350
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001351 // Check for track invalidation
1352 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001353 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1354 // AudioSystem cache. We should not exit here but after calling the callback so
1355 // that the upper layers can recreate the track
1356 if (!isOffloaded() || (mSequence == mObservedSequence)) {
1357 status_t status = restoreTrack_l("processAudioBuffer");
1358 mLock.unlock();
1359 // Run again immediately, but with a new IAudioTrack
1360 return 0;
1361 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001362 }
1363
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001364 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001365 bool active = mState == STATE_ACTIVE;
1366
1367 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1368 bool newUnderrun = false;
1369 if (flags & CBLK_UNDERRUN) {
1370#if 0
1371 // Currently in shared buffer mode, when the server reaches the end of buffer,
1372 // the track stays active in continuous underrun state. It's up to the application
1373 // to pause or stop the track, or set the position to a new offset within buffer.
1374 // This was some experimental code to auto-pause on underrun. Keeping it here
1375 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1376 if (mTransfer == TRANSFER_SHARED) {
1377 mState = STATE_PAUSED;
1378 active = false;
1379 }
1380#endif
1381 if (!mInUnderrun) {
1382 mInUnderrun = true;
1383 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001384 }
1385 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001386
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001387 // Get current position of server
1388 size_t position = mProxy->getPosition();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001389
1390 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001391 bool markerReached = false;
1392 size_t markerPosition = mMarkerPosition;
1393 // FIXME fails for wraparound, need 64 bits
1394 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1395 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001396 }
1397
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001398 // Determine number of new position callback(s) that will be needed, while locked
1399 size_t newPosCount = 0;
1400 size_t newPosition = mNewPosition;
1401 size_t updatePeriod = mUpdatePeriod;
1402 // FIXME fails for wraparound, need 64 bits
1403 if (updatePeriod > 0 && position >= newPosition) {
1404 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1405 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001406 }
1407
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001408 // Cache other fields that will be needed soon
1409 uint32_t loopPeriod = mLoopPeriod;
1410 uint32_t sampleRate = mSampleRate;
1411 size_t notificationFrames = mNotificationFramesAct;
1412 if (mRefreshRemaining) {
1413 mRefreshRemaining = false;
1414 mRemainingFrames = notificationFrames;
1415 mRetryOnPartialBuffer = false;
1416 }
1417 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001418 uint32_t sequence = mSequence;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001419
1420 // These fields don't need to be cached, because they are assigned only by set():
1421 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1422 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1423
1424 mLock.unlock();
1425
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001426 if (waitStreamEnd) {
1427 AutoMutex lock(mLock);
1428
1429 sp<AudioTrackClientProxy> proxy = mProxy;
1430 sp<IMemory> iMem = mCblkMemory;
1431
1432 struct timespec timeout;
1433 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1434 timeout.tv_nsec = 0;
1435
1436 mLock.unlock();
1437 status_t status = mProxy->waitStreamEndDone(&timeout);
1438 mLock.lock();
1439 switch (status) {
1440 case NO_ERROR:
1441 case DEAD_OBJECT:
1442 case TIMED_OUT:
1443 mLock.unlock();
1444 mCbf(EVENT_STREAM_END, mUserData, NULL);
1445 mLock.lock();
1446 if (mState == STATE_STOPPING) {
1447 mState = STATE_STOPPED;
1448 if (status != DEAD_OBJECT) {
1449 return NS_INACTIVE;
1450 }
1451 }
1452 return 0;
1453 default:
1454 return 0;
1455 }
1456 }
1457
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001458 // perform callbacks while unlocked
1459 if (newUnderrun) {
1460 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1461 }
1462 // FIXME we will miss loops if loop cycle was signaled several times since last call
1463 // to processAudioBuffer()
1464 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1465 mCbf(EVENT_LOOP_END, mUserData, NULL);
1466 }
1467 if (flags & CBLK_BUFFER_END) {
1468 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1469 }
1470 if (markerReached) {
1471 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1472 }
1473 while (newPosCount > 0) {
1474 size_t temp = newPosition;
1475 mCbf(EVENT_NEW_POS, mUserData, &temp);
1476 newPosition += updatePeriod;
1477 newPosCount--;
1478 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001479
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001480 if (mObservedSequence != sequence) {
1481 mObservedSequence = sequence;
1482 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001483 // for offloaded tracks, just wait for the upper layers to recreate the track
1484 if (isOffloaded()) {
1485 return NS_INACTIVE;
1486 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001487 }
1488
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001489 // if inactive, then don't run me again until re-started
1490 if (!active) {
1491 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001492 }
1493
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001494 // Compute the estimated time until the next timed event (position, markers, loops)
1495 // FIXME only for non-compressed audio
1496 uint32_t minFrames = ~0;
1497 if (!markerReached && position < markerPosition) {
1498 minFrames = markerPosition - position;
1499 }
1500 if (loopPeriod > 0 && loopPeriod < minFrames) {
1501 minFrames = loopPeriod;
1502 }
1503 if (updatePeriod > 0 && updatePeriod < minFrames) {
1504 minFrames = updatePeriod;
1505 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001506
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001507 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1508 static const uint32_t kPoll = 0;
1509 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1510 minFrames = kPoll * notificationFrames;
1511 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001512
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001513 // Convert frame units to time units
1514 nsecs_t ns = NS_WHENEVER;
1515 if (minFrames != (uint32_t) ~0) {
1516 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1517 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1518 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1519 }
1520
1521 // If not supplying data by EVENT_MORE_DATA, then we're done
1522 if (mTransfer != TRANSFER_CALLBACK) {
1523 return ns;
1524 }
1525
1526 struct timespec timeout;
1527 const struct timespec *requested = &ClientProxy::kForever;
1528 if (ns != NS_WHENEVER) {
1529 timeout.tv_sec = ns / 1000000000LL;
1530 timeout.tv_nsec = ns % 1000000000LL;
1531 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1532 requested = &timeout;
1533 }
1534
1535 while (mRemainingFrames > 0) {
1536
1537 Buffer audioBuffer;
1538 audioBuffer.frameCount = mRemainingFrames;
1539 size_t nonContig;
1540 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1541 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1542 "obtainBuffer() err=%d frameCount=%u", err, audioBuffer.frameCount);
1543 requested = &ClientProxy::kNonBlocking;
1544 size_t avail = audioBuffer.frameCount + nonContig;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001545 ALOGV("obtainBuffer(%u) returned %u = %u + %u err %d",
1546 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001547 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001548 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1549 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001550 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001551 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001552 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1553 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001554 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001555
Eric Laurent42a6f422013-08-29 14:35:05 -07001556 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001557 mRetryOnPartialBuffer = false;
1558 if (avail < mRemainingFrames) {
1559 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1560 if (ns < 0 || myns < ns) {
1561 ns = myns;
1562 }
1563 return ns;
1564 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001565 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001566
1567 // Divide buffer size by 2 to take into account the expansion
1568 // due to 8 to 16 bit conversion: the callback must fill only half
1569 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001570 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001571 audioBuffer.size >>= 1;
1572 }
1573
1574 size_t reqSize = audioBuffer.size;
1575 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001576 size_t writtenSize = audioBuffer.size;
1577 size_t writtenFrames = writtenSize / mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001578
1579 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001580 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
1581 ALOGE("EVENT_MORE_DATA requested %u bytes but callback returned %d bytes",
1582 reqSize, (int) writtenSize);
1583 return NS_NEVER;
1584 }
1585
1586 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001587 // The callback is done filling buffers
1588 // Keep this thread going to handle timed events and
1589 // still try to get more data in intervals of WAIT_PERIOD_MS
1590 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001591 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001592 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001593
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001594 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001595 // 8 to 16 bit conversion, note that source and destination are the same address
1596 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001597 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001598 }
1599
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001600 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1601 audioBuffer.frameCount = releasedFrames;
1602 mRemainingFrames -= releasedFrames;
1603 if (misalignment >= releasedFrames) {
1604 misalignment -= releasedFrames;
1605 } else {
1606 misalignment = 0;
1607 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001608
1609 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001610
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001611 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1612 // if callback doesn't like to accept the full chunk
1613 if (writtenSize < reqSize) {
1614 continue;
1615 }
1616
1617 // There could be enough non-contiguous frames available to satisfy the remaining request
1618 if (mRemainingFrames <= nonContig) {
1619 continue;
1620 }
1621
1622#if 0
1623 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1624 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1625 // that total to a sum == notificationFrames.
1626 if (0 < misalignment && misalignment <= mRemainingFrames) {
1627 mRemainingFrames = misalignment;
1628 return (mRemainingFrames * 1100000000LL) / sampleRate;
1629 }
1630#endif
1631
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001632 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001633 mRemainingFrames = notificationFrames;
1634 mRetryOnPartialBuffer = true;
1635
1636 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1637 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001638}
1639
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001640status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001641{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001642 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
1643 isOffloaded() ? "Offloaded" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001644 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001645 status_t result;
1646
Glenn Kastena47f3162012-11-07 10:13:08 -08001647 // refresh the audio configuration cache in this process to make sure we get new
1648 // output parameters in getOutput_l() and createTrack_l()
1649 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001650
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001651 if (isOffloaded()) {
1652 return DEAD_OBJECT;
1653 }
1654
1655 // force new output query from audio policy manager;
1656 mOutput = 0;
1657 audio_io_handle_t output = getOutput_l();
1658
Glenn Kastena47f3162012-11-07 10:13:08 -08001659 // if the new IAudioTrack is created, createTrack_l() will modify the
1660 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1661 // It will also delete the strong references on previous IAudioTrack and IMemory
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001662 size_t position = mProxy->getPosition();
1663 mNewPosition = position + mUpdatePeriod;
1664 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
Glenn Kastena47f3162012-11-07 10:13:08 -08001665 result = createTrack_l(mStreamType,
Glenn Kastene3aa6592012-12-04 12:22:46 -08001666 mSampleRate,
Glenn Kastena47f3162012-11-07 10:13:08 -08001667 mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001668 mReqFrameCount, // so that frame count never goes down
Glenn Kastena47f3162012-11-07 10:13:08 -08001669 mFlags,
1670 mSharedBuffer,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001671 output,
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001672 position /*epoch*/);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001673
Glenn Kastena47f3162012-11-07 10:13:08 -08001674 if (result == NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001675 // continue playback from last known position, but
1676 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1677 if (mStaticProxy != NULL) {
1678 mLoopPeriod = 0;
1679 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1680 }
1681 // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1682 // track destruction have been played? This is critical for SoundPool implementation
1683 // This must be broken, and needs to be tested/debugged.
1684#if 0
Glenn Kastena47f3162012-11-07 10:13:08 -08001685 // restore write index and set other indexes to reflect empty buffer status
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001686 if (!strcmp(from, "start")) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001687 // Make sure that a client relying on callback events indicating underrun or
1688 // the actual amount of audio frames played (e.g SoundPool) receives them.
1689 if (mSharedBuffer == 0) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001690 // restart playback even if buffer is not completely filled.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001691 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001692 }
1693 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001694#endif
1695 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001696 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001697 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001698 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001699 if (result != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001700 //Use of direct and offloaded output streams is ref counted by audio policy manager.
1701 // As getOutput was called above and resulted in an output stream to be opened,
1702 // we need to release it.
1703 AudioSystem::releaseOutput(output);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001704 ALOGW("restoreTrack_l() failed status %d", result);
1705 mState = STATE_STOPPED;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001706 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001707
1708 return result;
1709}
1710
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001711status_t AudioTrack::setParameters(const String8& keyValuePairs)
1712{
1713 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001714 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001715}
1716
Glenn Kastence703742013-07-19 16:33:58 -07001717status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1718{
Glenn Kasten53cec222013-08-29 09:01:02 -07001719 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001720 // FIXME not implemented for fast tracks; should use proxy and SSQ
1721 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1722 return INVALID_OPERATION;
1723 }
1724 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
1725 return INVALID_OPERATION;
1726 }
1727 status_t status = mAudioTrack->getTimestamp(timestamp);
1728 if (status == NO_ERROR) {
1729 timestamp.mPosition += mProxy->getEpoch();
1730 }
1731 return status;
Glenn Kastence703742013-07-19 16:33:58 -07001732}
1733
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001734String8 AudioTrack::getParameters(const String8& keys)
1735{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001736 if (mOutput) {
1737 return AudioSystem::getParameters(mOutput, keys);
1738 } else {
1739 return String8::empty();
1740 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001741}
1742
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001743status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1744{
1745
1746 const size_t SIZE = 256;
1747 char buffer[SIZE];
1748 String8 result;
1749
1750 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001751 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
1752 mVolume[0], mVolume[1]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001753 result.append(buffer);
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001754 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001755 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001756 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001757 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001758 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001759 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001760 result.append(buffer);
1761 ::write(fd, result.string(), result.size());
1762 return NO_ERROR;
1763}
1764
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001765uint32_t AudioTrack::getUnderrunFrames() const
1766{
1767 AutoMutex lock(mLock);
1768 return mProxy->getUnderrunFrames();
1769}
1770
1771// =========================================================================
1772
1773void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who)
1774{
1775 sp<AudioTrack> audioTrack = mAudioTrack.promote();
1776 if (audioTrack != 0) {
1777 AutoMutex lock(audioTrack->mLock);
1778 audioTrack->mProxy->binderDied();
1779 }
1780}
1781
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001782// =========================================================================
1783
1784AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001785 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL)
Glenn Kasten3acbd052012-02-28 10:39:56 -08001786{
1787}
1788
1789AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001790{
1791}
1792
1793bool AudioTrack::AudioTrackThread::threadLoop()
1794{
Glenn Kasten3acbd052012-02-28 10:39:56 -08001795 {
1796 AutoMutex _l(mMyLock);
1797 if (mPaused) {
1798 mMyCond.wait(mMyLock);
1799 // caller will check for exitPending()
1800 return true;
1801 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001802 if (mPausedInt) {
1803 mPausedInt = false;
1804 if (mPausedNs > 0) {
1805 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
1806 } else {
1807 mMyCond.wait(mMyLock);
1808 }
1809 return true;
1810 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001811 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001812 nsecs_t ns = mReceiver.processAudioBuffer(this);
1813 switch (ns) {
1814 case 0:
1815 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001816 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001817 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001818 return true;
1819 case NS_NEVER:
1820 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001821 case NS_WHENEVER:
1822 // FIXME increase poll interval, or make event-driven
1823 ns = 1000000000LL;
1824 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001825 default:
1826 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001827 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001828 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07001829 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001830}
1831
Glenn Kasten3acbd052012-02-28 10:39:56 -08001832void AudioTrack::AudioTrackThread::requestExit()
1833{
1834 // must be in this order to avoid a race condition
1835 Thread::requestExit();
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001836 AutoMutex _l(mMyLock);
1837 if (mPaused || mPausedInt) {
1838 mPaused = false;
1839 mPausedInt = false;
1840 mMyCond.signal();
1841 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001842}
1843
1844void AudioTrack::AudioTrackThread::pause()
1845{
1846 AutoMutex _l(mMyLock);
1847 mPaused = true;
1848}
1849
1850void AudioTrack::AudioTrackThread::resume()
1851{
1852 AutoMutex _l(mMyLock);
1853 if (mPaused) {
1854 mPaused = false;
1855 mMyCond.signal();
1856 }
1857}
1858
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001859void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
1860{
1861 AutoMutex _l(mMyLock);
1862 mPausedInt = true;
1863 mPausedNs = ns;
1864}
1865
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001866}; // namespace android