blob: 3653b7faae14b1cfbc8a312f7146daabc2e38a1d [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 Kasten9f80dd22012-12-18 15:57:32 -0800151 if (mAudioTrack != 0) {
152 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
153 mAudioTrack.clear();
154 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800155 IPCThreadState::self()->flushCommands();
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700156 AudioSystem::releaseAudioSessionId(mSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800157 }
158}
159
160status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800161 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800162 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800163 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700164 audio_channel_mask_t channelMask,
Glenn Kastene33054e2012-11-14 12:54:39 -0800165 int frameCountInt,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700166 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800167 callback_t cbf,
168 void* user,
169 int notificationFrames,
170 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700171 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800172 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000173 transfer_type transferType,
174 const audio_offload_info_t *offloadInfo)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800175{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800176 switch (transferType) {
177 case TRANSFER_DEFAULT:
178 if (sharedBuffer != 0) {
179 transferType = TRANSFER_SHARED;
180 } else if (cbf == NULL || threadCanCallJava) {
181 transferType = TRANSFER_SYNC;
182 } else {
183 transferType = TRANSFER_CALLBACK;
184 }
185 break;
186 case TRANSFER_CALLBACK:
187 if (cbf == NULL || sharedBuffer != 0) {
188 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
189 return BAD_VALUE;
190 }
191 break;
192 case TRANSFER_OBTAIN:
193 case TRANSFER_SYNC:
194 if (sharedBuffer != 0) {
195 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
196 return BAD_VALUE;
197 }
198 break;
199 case TRANSFER_SHARED:
200 if (sharedBuffer == 0) {
201 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
202 return BAD_VALUE;
203 }
204 break;
205 default:
206 ALOGE("Invalid transfer type %d", transferType);
207 return BAD_VALUE;
208 }
209 mTransfer = transferType;
210
Glenn Kastene33054e2012-11-14 12:54:39 -0800211 // FIXME "int" here is legacy and will be replaced by size_t later
212 if (frameCountInt < 0) {
213 ALOGE("Invalid frame count %d", frameCountInt);
214 return BAD_VALUE;
215 }
216 size_t frameCount = frameCountInt;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800217
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700218 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
219 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800220
Glenn Kastene33054e2012-11-14 12:54:39 -0800221 ALOGV("set() streamType %d frameCount %u flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700222
Eric Laurent1703cdf2011-03-07 14:52:59 -0800223 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800224
Eric Laurent1dd70b92009-04-21 07:56:33 -0700225 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000226 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800227 return INVALID_OPERATION;
228 }
229
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100230 mOutput = 0;
231
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800232 // handle default values first.
Dima Zavinfce7a472011-04-19 22:30:36 -0700233 if (streamType == AUDIO_STREAM_DEFAULT) {
234 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800235 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700236
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800237 if (sampleRate == 0) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800238 uint32_t afSampleRate;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700239 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
240 return NO_INIT;
241 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800242 sampleRate = afSampleRate;
243 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800244 mSampleRate = sampleRate;
Glenn Kastenea7939a2012-03-14 12:56:26 -0700245
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800246 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800247 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700248 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800249 }
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700250 if (channelMask == 0) {
251 channelMask = AUDIO_CHANNEL_OUT_STEREO;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800252 }
253
254 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700255 if (!audio_is_valid_format(format)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800256 ALOGE("Invalid format %d", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800257 return BAD_VALUE;
258 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700259
Glenn Kastene0fa4672012-04-24 14:35:14 -0700260 // AudioFlinger does not currently support 8-bit data in shared memory
261 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
262 ALOGE("8-bit data in shared memory is not supported");
263 return BAD_VALUE;
264 }
265
Eric Laurentc2f1f072009-07-17 12:17:14 -0700266 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100267 // or offload was requested
268 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
269 || !audio_is_linear_pcm(format)) {
270 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
271 ? "Offload request, forcing to Direct Output"
272 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700273 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800274 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700275 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700276 }
Eric Laurent1948eb32012-04-13 16:50:19 -0700277 // only allow deep buffering for music stream type
278 if (streamType != AUDIO_STREAM_MUSIC) {
279 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
280 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700281
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700282 if (!audio_is_output_channel(channelMask)) {
Glenn Kasten28b76b32012-07-03 17:24:41 -0700283 ALOGE("Invalid channel mask %#x", channelMask);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700284 return BAD_VALUE;
285 }
Glenn Kastena42ff002012-11-14 12:47:55 -0800286 mChannelMask = channelMask;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700287 uint32_t channelCount = popcount(channelMask);
Glenn Kastena42ff002012-11-14 12:47:55 -0800288 mChannelCount = channelCount;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700289
Glenn Kastene3aa6592012-12-04 12:22:46 -0800290 if (audio_is_linear_pcm(format)) {
291 mFrameSize = channelCount * audio_bytes_per_sample(format);
292 mFrameSizeAF = channelCount * sizeof(int16_t);
293 } else {
294 mFrameSize = sizeof(uint8_t);
295 mFrameSizeAF = sizeof(uint8_t);
296 }
297
Dima Zavinfce7a472011-04-19 22:30:36 -0700298 audio_io_handle_t output = AudioSystem::getOutput(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800299 streamType,
Glenn Kastene1c39622012-01-04 09:36:37 -0800300 sampleRate, format, channelMask,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000301 flags,
302 offloadInfo);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700303
304 if (output == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000305 ALOGE("Could not get audio output for stream type %d", streamType);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800306 return BAD_VALUE;
307 }
308
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800309 mVolume[LEFT] = 1.0f;
310 mVolume[RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800311 mSendLevel = 0.0f;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700312 mFrameCount = frameCount;
Glenn Kastenb6037442012-11-14 13:42:25 -0800313 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700314 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800315 mNotificationFramesAct = 0;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700316 mSessionId = sessionId;
Eric Laurent2beeb502010-07-16 07:43:46 -0700317 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700318 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700319 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700320
Glenn Kastena997e7a2012-08-07 09:44:19 -0700321 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700322 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700323 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
324 }
325
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800326 // create the IAudioTrack
Eric Laurent1703cdf2011-03-07 14:52:59 -0800327 status_t status = createTrack_l(streamType,
328 sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800329 format,
Eric Laurent1703cdf2011-03-07 14:52:59 -0800330 frameCount,
331 flags,
332 sharedBuffer,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800333 output,
334 0 /*epoch*/);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800335
Glenn Kastena997e7a2012-08-07 09:44:19 -0700336 if (status != NO_ERROR) {
337 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100338 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
339 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700340 mAudioTrackThread.clear();
341 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100342 //Use of direct and offloaded output streams is ref counted by audio policy manager.
343 // As getOutput was called above and resulted in an output stream to be opened,
344 // we need to release it.
345 AudioSystem::releaseOutput(output);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700346 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700347 }
348
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800349 mStatus = NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800350 mStreamType = streamType;
Glenn Kastene1c39622012-01-04 09:36:37 -0800351 mFormat = format;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800352 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800353 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800354 mUserData = user;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800355 mLoopPeriod = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800356 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700357 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800358 mNewPosition = 0;
359 mUpdatePeriod = 0;
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700360 AudioSystem::acquireAudioSessionId(mSessionId);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800361 mSequence = 1;
362 mObservedSequence = mSequence;
363 mInUnderrun = false;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100364 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800365
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800366 return NO_ERROR;
367}
368
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800369// -------------------------------------------------------------------------
370
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100371status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800372{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800373 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100374
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800375 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100376 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800377 }
378
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800379 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800380
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800381 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100382 if (previousState == STATE_PAUSED_STOPPING) {
383 mState = STATE_STOPPING;
384 } else {
385 mState = STATE_ACTIVE;
386 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800387 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
388 // reset current position as seen by client to 0
389 mProxy->setEpoch(mProxy->getEpoch() - mProxy->getPosition());
390 }
391 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
392 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->flags);
393
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800394 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800395 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100396 if (previousState == STATE_STOPPING) {
397 mProxy->interrupt();
398 } else {
399 t->resume();
400 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800401 } else {
402 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
403 get_sched_policy(0, &mPreviousSchedulingGroup);
404 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
405 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800406
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800407 status_t status = NO_ERROR;
408 if (!(flags & CBLK_INVALID)) {
409 status = mAudioTrack->start();
410 if (status == DEAD_OBJECT) {
411 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800412 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800413 }
414 if (flags & CBLK_INVALID) {
415 status = restoreTrack_l("start");
416 }
417
418 if (status != NO_ERROR) {
419 ALOGE("start() status %d", status);
420 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800421 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100422 if (previousState != STATE_STOPPING) {
423 t->pause();
424 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800425 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700426 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700427 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800428 }
429 }
430
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100431 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800432}
433
434void AudioTrack::stop()
435{
436 AutoMutex lock(mLock);
437 // FIXME pause then stop should not be a nop
438 if (mState != STATE_ACTIVE) {
439 return;
440 }
441
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100442 if (isOffloaded()) {
443 mState = STATE_STOPPING;
444 } else {
445 mState = STATE_STOPPED;
446 }
447
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800448 mProxy->interrupt();
449 mAudioTrack->stop();
450 // the playback head position will reset to 0, so if a marker is set, we need
451 // to activate it again
452 mMarkerReached = false;
453#if 0
454 // Force flush if a shared buffer is used otherwise audioflinger
455 // will not stop before end of buffer is reached.
456 // It may be needed to make sure that we stop playback, likely in case looping is on.
457 if (mSharedBuffer != 0) {
458 flush_l();
459 }
460#endif
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100461
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800462 sp<AudioTrackThread> t = mAudioTrackThread;
463 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100464 if (!isOffloaded()) {
465 t->pause();
466 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800467 } else {
468 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
469 set_sched_policy(0, mPreviousSchedulingGroup);
470 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800471}
472
473bool AudioTrack::stopped() const
474{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800475 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800476 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800477}
478
479void AudioTrack::flush()
480{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800481 if (mSharedBuffer != 0) {
482 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800483 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800484 AutoMutex lock(mLock);
485 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
486 return;
487 }
488 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800489}
490
Eric Laurent1703cdf2011-03-07 14:52:59 -0800491void AudioTrack::flush_l()
492{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800493 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700494
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700495 // clear playback marker and periodic update counter
496 mMarkerPosition = 0;
497 mMarkerReached = false;
498 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100499 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700500
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800501 mState = STATE_FLUSHED;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100502 if (isOffloaded()) {
503 mProxy->interrupt();
504 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800505 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800506 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800507}
508
509void AudioTrack::pause()
510{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800511 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100512 if (mState == STATE_ACTIVE) {
513 mState = STATE_PAUSED;
514 } else if (mState == STATE_STOPPING) {
515 mState = STATE_PAUSED_STOPPING;
516 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800517 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800518 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800519 mProxy->interrupt();
520 mAudioTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800521}
522
Eric Laurentbe916aa2010-06-01 23:49:17 -0700523status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800524{
Glenn Kastenf0c49502011-11-30 09:46:04 -0800525 if (left < 0.0f || left > 1.0f || right < 0.0f || right > 1.0f) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700526 return BAD_VALUE;
527 }
528
Eric Laurent1703cdf2011-03-07 14:52:59 -0800529 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800530 mVolume[LEFT] = left;
531 mVolume[RIGHT] = right;
532
Glenn Kastene3aa6592012-12-04 12:22:46 -0800533 mProxy->setVolumeLR((uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700534
535 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800536}
537
Glenn Kastenb1c09932012-02-27 16:21:04 -0800538status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800539{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800540 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700541}
542
Eric Laurent2beeb502010-07-16 07:43:46 -0700543status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700544{
Glenn Kasten05632a52012-01-03 14:22:33 -0800545 if (level < 0.0f || level > 1.0f) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700546 return BAD_VALUE;
547 }
548
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800549 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700550 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800551 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700552
553 return NO_ERROR;
554}
555
Glenn Kastena5224f32012-01-04 12:41:44 -0800556void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700557{
558 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800559 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700560 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800561}
562
Glenn Kasten3b16c762012-11-14 08:44:39 -0800563status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800564{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100565 if (mIsTimed || isOffloaded()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800566 return INVALID_OPERATION;
567 }
568
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800569 uint32_t afSamplingRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800570 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700571 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800572 }
573 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Glenn Kastend65d73c2012-06-22 17:21:07 -0700574 if (rate == 0 || rate > afSamplingRate*2 ) {
575 return BAD_VALUE;
576 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800577
Eric Laurent1703cdf2011-03-07 14:52:59 -0800578 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800579 mSampleRate = rate;
580 mProxy->setSampleRate(rate);
581
Eric Laurent57326622009-07-07 07:10:45 -0700582 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800583}
584
Glenn Kastena5224f32012-01-04 12:41:44 -0800585uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800586{
John Grossman4ff14ba2012-02-08 16:37:41 -0800587 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800588 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800589 }
590
Eric Laurent1703cdf2011-03-07 14:52:59 -0800591 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800592 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800593}
594
595status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
596{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100597 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800598 return INVALID_OPERATION;
599 }
600
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800601 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800602 ;
603 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
604 loopEnd - loopStart >= MIN_LOOP) {
605 ;
606 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800607 return BAD_VALUE;
608 }
609
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800610 AutoMutex lock(mLock);
611 // See setPosition() regarding setting parameters such as loop points or position while active
612 if (mState == STATE_ACTIVE) {
613 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700614 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800615 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800616 return NO_ERROR;
617}
618
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800619void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
620{
621 // FIXME If setting a loop also sets position to start of loop, then
622 // this is correct. Otherwise it should be removed.
623 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
624 mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0;
625 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
626}
627
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800628status_t AudioTrack::setMarkerPosition(uint32_t marker)
629{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700630 // The only purpose of setting marker position is to get a callback
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100631 if (mCbf == NULL || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700632 return INVALID_OPERATION;
633 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800634
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800635 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800636 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700637 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800638
639 return NO_ERROR;
640}
641
Glenn Kastena5224f32012-01-04 12:41:44 -0800642status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800643{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100644 if (isOffloaded()) {
645 return INVALID_OPERATION;
646 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700647 if (marker == NULL) {
648 return BAD_VALUE;
649 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800650
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800651 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800652 *marker = mMarkerPosition;
653
654 return NO_ERROR;
655}
656
657status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
658{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700659 // The only purpose of setting position update period is to get a callback
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100660 if (mCbf == NULL || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700661 return INVALID_OPERATION;
662 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800663
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800664 AutoMutex lock(mLock);
665 mNewPosition = mProxy->getPosition() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800666 mUpdatePeriod = updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800667 return NO_ERROR;
668}
669
Glenn Kastena5224f32012-01-04 12:41:44 -0800670status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800671{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100672 if (isOffloaded()) {
673 return INVALID_OPERATION;
674 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700675 if (updatePeriod == NULL) {
676 return BAD_VALUE;
677 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800678
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800679 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800680 *updatePeriod = mUpdatePeriod;
681
682 return NO_ERROR;
683}
684
685status_t AudioTrack::setPosition(uint32_t position)
686{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100687 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700688 return INVALID_OPERATION;
689 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800690 if (position > mFrameCount) {
691 return BAD_VALUE;
692 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800693
Eric Laurent1703cdf2011-03-07 14:52:59 -0800694 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800695 // Currently we require that the player is inactive before setting parameters such as position
696 // or loop points. Otherwise, there could be a race condition: the application could read the
697 // current position, compute a new position or loop parameters, and then set that position or
698 // loop parameters but it would do the "wrong" thing since the position has continued to advance
699 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
700 // to specify how it wants to handle such scenarios.
701 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700702 return INVALID_OPERATION;
703 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800704 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
705 mLoopPeriod = 0;
706 // FIXME Check whether loops and setting position are incompatible in old code.
707 // If we use setLoop for both purposes we lose the capability to set the position while looping.
708 mStaticProxy->setLoop(position, mFrameCount, 0);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700709
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800710 return NO_ERROR;
711}
712
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800713status_t AudioTrack::getPosition(uint32_t *position) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800714{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700715 if (position == NULL) {
716 return BAD_VALUE;
717 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800718
Eric Laurent1703cdf2011-03-07 14:52:59 -0800719 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100720 if (isOffloaded()) {
721 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800722
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100723 if (mOutput != 0) {
724 uint32_t halFrames;
725 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
726 }
727 *position = dspFrames;
728 } else {
729 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
730 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ? 0 :
731 mProxy->getPosition();
732 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800733 return NO_ERROR;
734}
735
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800736status_t AudioTrack::getBufferPosition(size_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800737{
738 if (mSharedBuffer == 0 || mIsTimed) {
739 return INVALID_OPERATION;
740 }
741 if (position == NULL) {
742 return BAD_VALUE;
743 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800744
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800745 AutoMutex lock(mLock);
746 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800747 return NO_ERROR;
748}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800749
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800750status_t AudioTrack::reload()
751{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100752 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800753 return INVALID_OPERATION;
754 }
755
Eric Laurent1703cdf2011-03-07 14:52:59 -0800756 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800757 // See setPosition() regarding setting parameters such as loop points or position while active
758 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700759 return INVALID_OPERATION;
760 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800761 mNewPosition = mUpdatePeriod;
762 mLoopPeriod = 0;
763 // FIXME The new code cannot reload while keeping a loop specified.
764 // Need to check how the old code handled this, and whether it's a significant change.
765 mStaticProxy->setLoop(0, mFrameCount, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800766 return NO_ERROR;
767}
768
Eric Laurentc2f1f072009-07-17 12:17:14 -0700769audio_io_handle_t AudioTrack::getOutput()
770{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800771 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100772 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800773}
774
775// must be called with mLock held
776audio_io_handle_t AudioTrack::getOutput_l()
777{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100778 if (mOutput) {
779 return mOutput;
780 } else {
781 return AudioSystem::getOutput(mStreamType,
782 mSampleRate, mFormat, mChannelMask, mFlags);
783 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700784}
785
Eric Laurentbe916aa2010-06-01 23:49:17 -0700786status_t AudioTrack::attachAuxEffect(int effectId)
787{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800788 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700789 status_t status = mAudioTrack->attachAuxEffect(effectId);
790 if (status == NO_ERROR) {
791 mAuxEffectId = effectId;
792 }
793 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700794}
795
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800796// -------------------------------------------------------------------------
797
Eric Laurent1703cdf2011-03-07 14:52:59 -0800798// must be called with mLock held
799status_t AudioTrack::createTrack_l(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800800 audio_stream_type_t streamType,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800801 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800802 audio_format_t format,
Glenn Kastene33054e2012-11-14 12:54:39 -0800803 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700804 audio_output_flags_t flags,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800805 const sp<IMemory>& sharedBuffer,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800806 audio_io_handle_t output,
807 size_t epoch)
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800808{
809 status_t status;
810 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
811 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700812 ALOGE("Could not get audioflinger");
813 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800814 }
815
Eric Laurentd1b449a2010-05-14 03:26:45 -0700816 uint32_t afLatency;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800817 if ((status = AudioSystem::getLatency(output, streamType, &afLatency)) != NO_ERROR) {
818 ALOGE("getLatency(%d) failed status %d", output, status);
Eric Laurentd1b449a2010-05-14 03:26:45 -0700819 return NO_INIT;
820 }
821
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700822 // Client decides whether the track is TIMED (see below), but can only express a preference
823 // for FAST. Server will perform additional tests.
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700824 if ((flags & AUDIO_OUTPUT_FLAG_FAST) && !(
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700825 // either of these use cases:
826 // use case 1: shared buffer
827 (sharedBuffer != 0) ||
828 // use case 2: callback handler
829 (mCbf != NULL))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800830 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -0700831 // once denied, do not request again if IAudioTrack is re-created
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700832 flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten093000f2012-05-03 09:35:36 -0700833 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700834 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700835 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700836
Eric Laurentd1b449a2010-05-14 03:26:45 -0700837 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700838
Dima Zavinfce7a472011-04-19 22:30:36 -0700839 if (!audio_is_linear_pcm(format)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700840
Eric Laurentd1b449a2010-05-14 03:26:45 -0700841 if (sharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700842 // Same comment as below about ignoring frameCount parameter for set()
Eric Laurentd1b449a2010-05-14 03:26:45 -0700843 frameCount = sharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -0700844 } else if (frameCount == 0) {
Glenn Kastene33054e2012-11-14 12:54:39 -0800845 size_t afFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800846 status = AudioSystem::getFrameCount(output, streamType, &afFrameCount);
847 if (status != NO_ERROR) {
848 ALOGE("getFrameCount(output=%d, streamType=%d) status %d", output, streamType,
849 status);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700850 return NO_INIT;
851 }
852 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700853 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100854 if (mNotificationFramesAct != frameCount) {
855 mNotificationFramesAct = frameCount;
856 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700857 } else if (sharedBuffer != 0) {
858
Glenn Kastena42ff002012-11-14 12:47:55 -0800859 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -0700860 // 8-bit data in shared memory is not currently supported by AudioFlinger
861 size_t alignment = /* format == AUDIO_FORMAT_PCM_8_BIT ? 1 : */ 2;
Glenn Kastena42ff002012-11-14 12:47:55 -0800862 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700863 // More than 2 channels does not require stronger alignment than stereo
864 alignment <<= 1;
865 }
Glenn Kastena42ff002012-11-14 12:47:55 -0800866 if (((size_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
867 ALOGE("Invalid buffer alignment: address %p, channel count %u",
868 sharedBuffer->pointer(), mChannelCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700869 return BAD_VALUE;
870 }
871
872 // When initializing a shared buffer AudioTrack via constructors,
873 // there's no frameCount parameter.
874 // But when initializing a shared buffer AudioTrack via set(),
875 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kastena42ff002012-11-14 12:47:55 -0800876 frameCount = sharedBuffer->size()/mChannelCount/sizeof(int16_t);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700877
878 } else if (!(flags & AUDIO_OUTPUT_FLAG_FAST)) {
879
880 // FIXME move these calculations and associated checks to server
Glenn Kasten3b16c762012-11-14 08:44:39 -0800881 uint32_t afSampleRate;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800882 status = AudioSystem::getSamplingRate(output, streamType, &afSampleRate);
883 if (status != NO_ERROR) {
884 ALOGE("getSamplingRate(output=%d, streamType=%d) status %d", output, streamType,
885 status);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700886 return NO_INIT;
887 }
Glenn Kastene33054e2012-11-14 12:54:39 -0800888 size_t afFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800889 status = AudioSystem::getFrameCount(output, streamType, &afFrameCount);
890 if (status != NO_ERROR) {
891 ALOGE("getFrameCount(output=%d, streamType=%d) status %d", output, streamType, status);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700892 return NO_INIT;
893 }
894
Eric Laurentd1b449a2010-05-14 03:26:45 -0700895 // Ensure that buffer depth covers at least audio hardware latency
896 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Glenn Kastenbb6f0a02013-06-03 15:00:29 -0700897 ALOGV("afFrameCount=%d, minBufCount=%d, afSampleRate=%u, afLatency=%d",
898 afFrameCount, minBufCount, afSampleRate, afLatency);
899 if (minBufCount <= 2) {
900 minBufCount = sampleRate == afSampleRate ? 2 : 3;
Glenn Kasten7c027242012-12-26 14:43:16 -0800901 }
Eric Laurentd1b449a2010-05-14 03:26:45 -0700902
Glenn Kastene33054e2012-11-14 12:54:39 -0800903 size_t minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
904 ALOGV("minFrameCount: %u, afFrameCount=%d, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -0800905 ", afLatency=%d",
906 minFrameCount, afFrameCount, minBufCount, sampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700907
908 if (frameCount == 0) {
909 frameCount = minFrameCount;
910 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700911 // Make sure that application is notified with sufficient margin
912 // before underrun
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800913 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/2) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700914 mNotificationFramesAct = frameCount/2;
915 }
916 if (frameCount < minFrameCount) {
917 // not ALOGW because it happens all the time when playing key clicks over A2DP
918 ALOGV("Minimum buffer size corrected from %d to %d",
919 frameCount, minFrameCount);
920 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800921 }
Eric Laurentd1b449a2010-05-14 03:26:45 -0700922
Glenn Kastene0fa4672012-04-24 14:35:14 -0700923 } else {
924 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -0700925 }
926
Glenn Kastena075db42012-03-06 11:22:44 -0800927 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
928 if (mIsTimed) {
929 trackFlags |= IAudioFlinger::TRACK_TIMED;
930 }
Glenn Kasten3acbd052012-02-28 10:39:56 -0800931
932 pid_t tid = -1;
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700933 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700934 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800935 if (mAudioTrackThread != 0) {
936 tid = mAudioTrackThread->getTid();
937 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700938 }
939
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100940 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
941 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
942 }
943
Glenn Kasten8d6cc842012-02-03 11:06:53 -0800944 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800945 sampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -0700946 // AudioFlinger only sees 16-bit PCM
947 format == AUDIO_FORMAT_PCM_8_BIT ?
948 AUDIO_FORMAT_PCM_16_BIT : format,
Glenn Kastena42ff002012-11-14 12:47:55 -0800949 mChannelMask,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800950 frameCount,
Glenn Kastene0b07172012-11-06 15:03:34 -0800951 &trackFlags,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800952 sharedBuffer,
953 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800954 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700955 &mSessionId,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800956 &status);
957
958 if (track == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000959 ALOGE("AudioFlinger could not create track, status: %d", status);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800960 return status;
961 }
Glenn Kastend2c38fc2012-11-01 14:58:02 -0700962 sp<IMemory> iMem = track->getCblk();
963 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000964 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800965 return NO_INIT;
966 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800967 if (mAudioTrack != 0) {
968 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
969 mDeathNotifier.clear();
970 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800971 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -0700972 mCblkMemory = iMem;
973 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMem->pointer());
974 mCblk = cblk;
Glenn Kastenb6037442012-11-14 13:42:25 -0800975 size_t temp = cblk->frameCount_;
976 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
977 // In current design, AudioTrack client checks and ensures frame count validity before
978 // passing it to AudioFlinger so AudioFlinger should not return a different value except
979 // for fast track as it uses a special method of assigning frame count.
980 ALOGW("Requested frameCount %u but received frameCount %u", frameCount, temp);
981 }
982 frameCount = temp;
Glenn Kastena07f17c2013-04-23 12:39:37 -0700983 mAwaitBoost = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800984 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -0800985 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Glenn Kastenb6037442012-11-14 13:42:25 -0800986 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %u", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -0700987 mAwaitBoost = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800988 if (sharedBuffer == 0) {
989 // double-buffering is not required for fast tracks, due to tighter scheduling
990 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount) {
991 mNotificationFramesAct = frameCount;
992 }
993 }
Glenn Kasten3acbd052012-02-28 10:39:56 -0800994 } else {
Glenn Kastenb6037442012-11-14 13:42:25 -0800995 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %u", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -0700996 // once denied, do not request again if IAudioTrack is re-created
997 flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST);
998 mFlags = flags;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800999 if (sharedBuffer == 0) {
1000 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/2) {
1001 mNotificationFramesAct = frameCount/2;
1002 }
1003 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001004 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001005 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001006 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
1007 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1008 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1009 } else {
1010 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
1011 flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1012 mFlags = flags;
1013 return NO_INIT;
1014 }
1015 }
1016
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001017 mRefreshRemaining = true;
1018
1019 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1020 // is the value of pointer() for the shared buffer, otherwise buffers points
1021 // immediately after the control block. This address is for the mapping within client
1022 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1023 void* buffers;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001024 if (sharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001025 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001026 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001027 buffers = sharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001028 }
1029
Eric Laurent2beeb502010-07-16 07:43:46 -07001030 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001031 // FIXME don't believe this lie
Glenn Kastenb6037442012-11-14 13:42:25 -08001032 mLatency = afLatency + (1000*frameCount) / sampleRate;
1033 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001034 // If IAudioTrack is re-created, don't let the requested frameCount
1035 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001036 if (frameCount > mReqFrameCount) {
1037 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001038 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001039
1040 // update proxy
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001041 if (sharedBuffer == 0) {
1042 mStaticProxy.clear();
1043 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1044 } else {
1045 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1046 mProxy = mStaticProxy;
1047 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001048 mProxy->setVolumeLR((uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) |
1049 uint16_t(mVolume[LEFT] * 0x1000));
1050 mProxy->setSendLevel(mSendLevel);
1051 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001052 mProxy->setEpoch(epoch);
1053 mProxy->setMinimum(mNotificationFramesAct);
1054
1055 mDeathNotifier = new DeathNotifier(this);
1056 mAudioTrack->asBinder()->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001057
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001058 return NO_ERROR;
1059}
1060
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001061status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1062{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001063 if (audioBuffer == NULL) {
1064 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001065 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001066 if (mTransfer != TRANSFER_OBTAIN) {
1067 audioBuffer->frameCount = 0;
1068 audioBuffer->size = 0;
1069 audioBuffer->raw = NULL;
1070 return INVALID_OPERATION;
1071 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001072
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001073 const struct timespec *requested;
1074 if (waitCount == -1) {
1075 requested = &ClientProxy::kForever;
1076 } else if (waitCount == 0) {
1077 requested = &ClientProxy::kNonBlocking;
1078 } else if (waitCount > 0) {
1079 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
1080 struct timespec timeout;
1081 timeout.tv_sec = ms / 1000;
1082 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1083 requested = &timeout;
1084 } else {
1085 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1086 requested = NULL;
1087 }
1088 return obtainBuffer(audioBuffer, requested);
1089}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001090
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001091status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1092 struct timespec *elapsed, size_t *nonContig)
1093{
1094 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1095 uint32_t oldSequence = 0;
1096 uint32_t newSequence;
1097
1098 Proxy::Buffer buffer;
1099 status_t status = NO_ERROR;
1100
1101 static const int32_t kMaxTries = 5;
1102 int32_t tryCounter = kMaxTries;
1103
1104 do {
1105 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1106 // keep them from going away if another thread re-creates the track during obtainBuffer()
1107 sp<AudioTrackClientProxy> proxy;
1108 sp<IMemory> iMem;
1109
1110 { // start of lock scope
1111 AutoMutex lock(mLock);
1112
1113 newSequence = mSequence;
1114 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1115 if (status == DEAD_OBJECT) {
1116 // re-create track, unless someone else has already done so
1117 if (newSequence == oldSequence) {
1118 status = restoreTrack_l("obtainBuffer");
1119 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001120 buffer.mFrameCount = 0;
1121 buffer.mRaw = NULL;
1122 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001123 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001124 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001125 }
1126 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001127 oldSequence = newSequence;
1128
1129 // Keep the extra references
1130 proxy = mProxy;
1131 iMem = mCblkMemory;
1132
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001133 if (mState == STATE_STOPPING) {
1134 status = -EINTR;
1135 buffer.mFrameCount = 0;
1136 buffer.mRaw = NULL;
1137 buffer.mNonContig = 0;
1138 break;
1139 }
1140
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001141 // Non-blocking if track is stopped or paused
1142 if (mState != STATE_ACTIVE) {
1143 requested = &ClientProxy::kNonBlocking;
1144 }
1145
1146 } // end of lock scope
1147
1148 buffer.mFrameCount = audioBuffer->frameCount;
1149 // FIXME starts the requested timeout and elapsed over from scratch
1150 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1151
1152 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1153
1154 audioBuffer->frameCount = buffer.mFrameCount;
1155 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1156 audioBuffer->raw = buffer.mRaw;
1157 if (nonContig != NULL) {
1158 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001159 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001160 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001161}
1162
1163void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1164{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001165 if (mTransfer == TRANSFER_SHARED) {
1166 return;
1167 }
1168
1169 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1170 if (stepCount == 0) {
1171 return;
1172 }
1173
1174 Proxy::Buffer buffer;
1175 buffer.mFrameCount = stepCount;
1176 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001177
Eric Laurent1703cdf2011-03-07 14:52:59 -08001178 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001179 mInUnderrun = false;
1180 mProxy->releaseBuffer(&buffer);
1181
1182 // restart track if it was disabled by audioflinger due to previous underrun
1183 if (mState == STATE_ACTIVE) {
1184 audio_track_cblk_t* cblk = mCblk;
1185 if (android_atomic_and(~CBLK_DISABLED, &cblk->flags) & CBLK_DISABLED) {
1186 ALOGW("releaseBuffer() track %p name=%#x disabled due to previous underrun, restarting",
1187 this, cblk->mName);
1188 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001189 mAudioTrack->start();
1190 }
1191 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001192}
1193
1194// -------------------------------------------------------------------------
1195
1196ssize_t AudioTrack::write(const void* buffer, size_t userSize)
1197{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001198 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001199 return INVALID_OPERATION;
1200 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001201
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001202 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001203 // Sanity-check: user is most-likely passing an error code, and it would
1204 // make the return value ambiguous (actualSize vs error).
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001205 ALOGE("AudioTrack::write(buffer=%p, size=%u (%d)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001206 return BAD_VALUE;
1207 }
1208
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001209 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001210 Buffer audioBuffer;
1211
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001212 while (userSize >= mFrameSize) {
1213 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001214
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001215 status_t err = obtainBuffer(&audioBuffer, &ClientProxy::kForever);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001216 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001217 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001218 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001219 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001220 return ssize_t(err);
1221 }
1222
1223 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001224 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001225 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001226 toWrite = audioBuffer.size >> 1;
1227 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001228 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001229 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001230 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001231 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001232 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001233 userSize -= toWrite;
1234 written += toWrite;
1235
1236 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001237 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001238
1239 return written;
1240}
1241
1242// -------------------------------------------------------------------------
1243
John Grossman4ff14ba2012-02-08 16:37:41 -08001244TimedAudioTrack::TimedAudioTrack() {
1245 mIsTimed = true;
1246}
1247
1248status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1249{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001250 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001251 status_t result = UNKNOWN_ERROR;
1252
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001253#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001254 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1255 // while we are accessing the cblk
1256 sp<IAudioTrack> audioTrack = mAudioTrack;
1257 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001258#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001259
John Grossman4ff14ba2012-02-08 16:37:41 -08001260 // If the track is not invalid already, try to allocate a buffer. alloc
1261 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001262 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001263 audio_track_cblk_t* cblk = mCblk;
1264 if (!(cblk->flags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001265 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1266 if (result == DEAD_OBJECT) {
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001267 android_atomic_or(CBLK_INVALID, &cblk->flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001268 }
1269 }
1270
1271 // If the track is invalid at this point, attempt to restore it. and try the
1272 // allocation one more time.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001273 if (cblk->flags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001274 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001275
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001276 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001277 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001278 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001279 }
1280
1281 return result;
1282}
1283
1284status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1285 int64_t pts)
1286{
Eric Laurentdf839842012-05-31 14:27:14 -07001287 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1288 {
1289 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001290 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001291 // restart track if it was disabled by audioflinger due to previous underrun
1292 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001293 (mState == STATE_ACTIVE) && (cblk->flags & CBLK_DISABLED)) {
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001294 android_atomic_and(~CBLK_DISABLED, &cblk->flags);
Eric Laurentdf839842012-05-31 14:27:14 -07001295 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001296 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001297 mAudioTrack->start();
1298 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001299 }
Eric Laurentdf839842012-05-31 14:27:14 -07001300 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001301}
1302
1303status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1304 TargetTimeline target)
1305{
1306 return mAudioTrack->setMediaTimeTransform(xform, target);
1307}
1308
1309// -------------------------------------------------------------------------
1310
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001311nsecs_t AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001312{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001313 // Currently the AudioTrack thread is not created if there are no callbacks.
1314 // Would it ever make sense to run the thread, even without callbacks?
1315 // If so, then replace this by checks at each use for mCbf != NULL.
1316 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1317
Eric Laurent1703cdf2011-03-07 14:52:59 -08001318 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001319 if (mAwaitBoost) {
1320 mAwaitBoost = false;
1321 mLock.unlock();
1322 static const int32_t kMaxTries = 5;
1323 int32_t tryCounter = kMaxTries;
1324 uint32_t pollUs = 10000;
1325 do {
1326 int policy = sched_getscheduler(0);
1327 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1328 break;
1329 }
1330 usleep(pollUs);
1331 pollUs <<= 1;
1332 } while (tryCounter-- > 0);
1333 if (tryCounter < 0) {
1334 ALOGE("did not receive expected priority boost on time");
1335 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001336 // Run again immediately
1337 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001338 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001339
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001340 // Can only reference mCblk while locked
1341 int32_t flags = android_atomic_and(
1342 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->flags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001343
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001344 // Check for track invalidation
1345 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001346 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1347 // AudioSystem cache. We should not exit here but after calling the callback so
1348 // that the upper layers can recreate the track
1349 if (!isOffloaded() || (mSequence == mObservedSequence)) {
1350 status_t status = restoreTrack_l("processAudioBuffer");
1351 mLock.unlock();
1352 // Run again immediately, but with a new IAudioTrack
1353 return 0;
1354 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001355 }
1356
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001357 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001358 bool active = mState == STATE_ACTIVE;
1359
1360 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1361 bool newUnderrun = false;
1362 if (flags & CBLK_UNDERRUN) {
1363#if 0
1364 // Currently in shared buffer mode, when the server reaches the end of buffer,
1365 // the track stays active in continuous underrun state. It's up to the application
1366 // to pause or stop the track, or set the position to a new offset within buffer.
1367 // This was some experimental code to auto-pause on underrun. Keeping it here
1368 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1369 if (mTransfer == TRANSFER_SHARED) {
1370 mState = STATE_PAUSED;
1371 active = false;
1372 }
1373#endif
1374 if (!mInUnderrun) {
1375 mInUnderrun = true;
1376 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001377 }
1378 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001379
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001380 // Get current position of server
1381 size_t position = mProxy->getPosition();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001382
1383 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001384 bool markerReached = false;
1385 size_t markerPosition = mMarkerPosition;
1386 // FIXME fails for wraparound, need 64 bits
1387 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1388 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001389 }
1390
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001391 // Determine number of new position callback(s) that will be needed, while locked
1392 size_t newPosCount = 0;
1393 size_t newPosition = mNewPosition;
1394 size_t updatePeriod = mUpdatePeriod;
1395 // FIXME fails for wraparound, need 64 bits
1396 if (updatePeriod > 0 && position >= newPosition) {
1397 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1398 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001399 }
1400
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001401 // Cache other fields that will be needed soon
1402 uint32_t loopPeriod = mLoopPeriod;
1403 uint32_t sampleRate = mSampleRate;
1404 size_t notificationFrames = mNotificationFramesAct;
1405 if (mRefreshRemaining) {
1406 mRefreshRemaining = false;
1407 mRemainingFrames = notificationFrames;
1408 mRetryOnPartialBuffer = false;
1409 }
1410 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001411 uint32_t sequence = mSequence;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001412
1413 // These fields don't need to be cached, because they are assigned only by set():
1414 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1415 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1416
1417 mLock.unlock();
1418
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001419 if (waitStreamEnd) {
1420 AutoMutex lock(mLock);
1421
1422 sp<AudioTrackClientProxy> proxy = mProxy;
1423 sp<IMemory> iMem = mCblkMemory;
1424
1425 struct timespec timeout;
1426 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1427 timeout.tv_nsec = 0;
1428
1429 mLock.unlock();
1430 status_t status = mProxy->waitStreamEndDone(&timeout);
1431 mLock.lock();
1432 switch (status) {
1433 case NO_ERROR:
1434 case DEAD_OBJECT:
1435 case TIMED_OUT:
1436 mLock.unlock();
1437 mCbf(EVENT_STREAM_END, mUserData, NULL);
1438 mLock.lock();
1439 if (mState == STATE_STOPPING) {
1440 mState = STATE_STOPPED;
1441 if (status != DEAD_OBJECT) {
1442 return NS_INACTIVE;
1443 }
1444 }
1445 return 0;
1446 default:
1447 return 0;
1448 }
1449 }
1450
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001451 // perform callbacks while unlocked
1452 if (newUnderrun) {
1453 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1454 }
1455 // FIXME we will miss loops if loop cycle was signaled several times since last call
1456 // to processAudioBuffer()
1457 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1458 mCbf(EVENT_LOOP_END, mUserData, NULL);
1459 }
1460 if (flags & CBLK_BUFFER_END) {
1461 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1462 }
1463 if (markerReached) {
1464 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1465 }
1466 while (newPosCount > 0) {
1467 size_t temp = newPosition;
1468 mCbf(EVENT_NEW_POS, mUserData, &temp);
1469 newPosition += updatePeriod;
1470 newPosCount--;
1471 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001472
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001473 if (mObservedSequence != sequence) {
1474 mObservedSequence = sequence;
1475 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001476 // for offloaded tracks, just wait for the upper layers to recreate the track
1477 if (isOffloaded()) {
1478 return NS_INACTIVE;
1479 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001480 }
1481
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001482 // if inactive, then don't run me again until re-started
1483 if (!active) {
1484 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001485 }
1486
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001487 // Compute the estimated time until the next timed event (position, markers, loops)
1488 // FIXME only for non-compressed audio
1489 uint32_t minFrames = ~0;
1490 if (!markerReached && position < markerPosition) {
1491 minFrames = markerPosition - position;
1492 }
1493 if (loopPeriod > 0 && loopPeriod < minFrames) {
1494 minFrames = loopPeriod;
1495 }
1496 if (updatePeriod > 0 && updatePeriod < minFrames) {
1497 minFrames = updatePeriod;
1498 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001499
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001500 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1501 static const uint32_t kPoll = 0;
1502 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1503 minFrames = kPoll * notificationFrames;
1504 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001505
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001506 // Convert frame units to time units
1507 nsecs_t ns = NS_WHENEVER;
1508 if (minFrames != (uint32_t) ~0) {
1509 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1510 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1511 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1512 }
1513
1514 // If not supplying data by EVENT_MORE_DATA, then we're done
1515 if (mTransfer != TRANSFER_CALLBACK) {
1516 return ns;
1517 }
1518
1519 struct timespec timeout;
1520 const struct timespec *requested = &ClientProxy::kForever;
1521 if (ns != NS_WHENEVER) {
1522 timeout.tv_sec = ns / 1000000000LL;
1523 timeout.tv_nsec = ns % 1000000000LL;
1524 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1525 requested = &timeout;
1526 }
1527
1528 while (mRemainingFrames > 0) {
1529
1530 Buffer audioBuffer;
1531 audioBuffer.frameCount = mRemainingFrames;
1532 size_t nonContig;
1533 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1534 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1535 "obtainBuffer() err=%d frameCount=%u", err, audioBuffer.frameCount);
1536 requested = &ClientProxy::kNonBlocking;
1537 size_t avail = audioBuffer.frameCount + nonContig;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001538 ALOGV("obtainBuffer(%u) returned %u = %u + %u err %d",
1539 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001540 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001541 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1542 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001543 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001544 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001545 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1546 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001547 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001548
1549 if (mRetryOnPartialBuffer) {
1550 mRetryOnPartialBuffer = false;
1551 if (avail < mRemainingFrames) {
1552 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1553 if (ns < 0 || myns < ns) {
1554 ns = myns;
1555 }
1556 return ns;
1557 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001558 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001559
1560 // Divide buffer size by 2 to take into account the expansion
1561 // due to 8 to 16 bit conversion: the callback must fill only half
1562 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001563 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001564 audioBuffer.size >>= 1;
1565 }
1566
1567 size_t reqSize = audioBuffer.size;
1568 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001569 size_t writtenSize = audioBuffer.size;
1570 size_t writtenFrames = writtenSize / mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001571
1572 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001573 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
1574 ALOGE("EVENT_MORE_DATA requested %u bytes but callback returned %d bytes",
1575 reqSize, (int) writtenSize);
1576 return NS_NEVER;
1577 }
1578
1579 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001580 // The callback is done filling buffers
1581 // Keep this thread going to handle timed events and
1582 // still try to get more data in intervals of WAIT_PERIOD_MS
1583 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001584 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001585 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001586
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001587 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001588 // 8 to 16 bit conversion, note that source and destination are the same address
1589 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001590 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001591 }
1592
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001593 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1594 audioBuffer.frameCount = releasedFrames;
1595 mRemainingFrames -= releasedFrames;
1596 if (misalignment >= releasedFrames) {
1597 misalignment -= releasedFrames;
1598 } else {
1599 misalignment = 0;
1600 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001601
1602 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001603
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001604 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1605 // if callback doesn't like to accept the full chunk
1606 if (writtenSize < reqSize) {
1607 continue;
1608 }
1609
1610 // There could be enough non-contiguous frames available to satisfy the remaining request
1611 if (mRemainingFrames <= nonContig) {
1612 continue;
1613 }
1614
1615#if 0
1616 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1617 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1618 // that total to a sum == notificationFrames.
1619 if (0 < misalignment && misalignment <= mRemainingFrames) {
1620 mRemainingFrames = misalignment;
1621 return (mRemainingFrames * 1100000000LL) / sampleRate;
1622 }
1623#endif
1624
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001625 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001626 mRemainingFrames = notificationFrames;
1627 mRetryOnPartialBuffer = true;
1628
1629 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1630 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001631}
1632
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001633status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001634{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001635 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
1636 isOffloaded() ? "Offloaded" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001637 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001638 status_t result;
1639
Glenn Kastena47f3162012-11-07 10:13:08 -08001640 // refresh the audio configuration cache in this process to make sure we get new
1641 // output parameters in getOutput_l() and createTrack_l()
1642 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001643
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001644 if (isOffloaded()) {
1645 return DEAD_OBJECT;
1646 }
1647
1648 // force new output query from audio policy manager;
1649 mOutput = 0;
1650 audio_io_handle_t output = getOutput_l();
1651
Glenn Kastena47f3162012-11-07 10:13:08 -08001652 // if the new IAudioTrack is created, createTrack_l() will modify the
1653 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1654 // It will also delete the strong references on previous IAudioTrack and IMemory
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001655 size_t position = mProxy->getPosition();
1656 mNewPosition = position + mUpdatePeriod;
1657 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
Glenn Kastena47f3162012-11-07 10:13:08 -08001658 result = createTrack_l(mStreamType,
Glenn Kastene3aa6592012-12-04 12:22:46 -08001659 mSampleRate,
Glenn Kastena47f3162012-11-07 10:13:08 -08001660 mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001661 mReqFrameCount, // so that frame count never goes down
Glenn Kastena47f3162012-11-07 10:13:08 -08001662 mFlags,
1663 mSharedBuffer,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001664 output,
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001665 position /*epoch*/);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001666
Glenn Kastena47f3162012-11-07 10:13:08 -08001667 if (result == NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001668 // continue playback from last known position, but
1669 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1670 if (mStaticProxy != NULL) {
1671 mLoopPeriod = 0;
1672 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1673 }
1674 // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1675 // track destruction have been played? This is critical for SoundPool implementation
1676 // This must be broken, and needs to be tested/debugged.
1677#if 0
Glenn Kastena47f3162012-11-07 10:13:08 -08001678 // restore write index and set other indexes to reflect empty buffer status
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001679 if (!strcmp(from, "start")) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001680 // Make sure that a client relying on callback events indicating underrun or
1681 // the actual amount of audio frames played (e.g SoundPool) receives them.
1682 if (mSharedBuffer == 0) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001683 // restart playback even if buffer is not completely filled.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001684 android_atomic_or(CBLK_FORCEREADY, &mCblk->flags);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001685 }
1686 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001687#endif
1688 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001689 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001690 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001691 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001692 if (result != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001693 //Use of direct and offloaded output streams is ref counted by audio policy manager.
1694 // As getOutput was called above and resulted in an output stream to be opened,
1695 // we need to release it.
1696 AudioSystem::releaseOutput(output);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001697 ALOGW("restoreTrack_l() failed status %d", result);
1698 mState = STATE_STOPPED;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001699 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001700
1701 return result;
1702}
1703
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001704status_t AudioTrack::setParameters(const String8& keyValuePairs)
1705{
1706 AutoMutex lock(mLock);
1707 if (mAudioTrack != 0) {
1708 return mAudioTrack->setParameters(keyValuePairs);
1709 } else {
1710 return NO_INIT;
1711 }
1712}
1713
1714String8 AudioTrack::getParameters(const String8& keys)
1715{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001716 if (mOutput) {
1717 return AudioSystem::getParameters(mOutput, keys);
1718 } else {
1719 return String8::empty();
1720 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001721}
1722
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001723status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1724{
1725
1726 const size_t SIZE = 256;
1727 char buffer[SIZE];
1728 String8 result;
1729
1730 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001731 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
1732 mVolume[0], mVolume[1]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001733 result.append(buffer);
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001734 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001735 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001736 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001737 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001738 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001739 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001740 result.append(buffer);
1741 ::write(fd, result.string(), result.size());
1742 return NO_ERROR;
1743}
1744
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001745uint32_t AudioTrack::getUnderrunFrames() const
1746{
1747 AutoMutex lock(mLock);
1748 return mProxy->getUnderrunFrames();
1749}
1750
1751// =========================================================================
1752
1753void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who)
1754{
1755 sp<AudioTrack> audioTrack = mAudioTrack.promote();
1756 if (audioTrack != 0) {
1757 AutoMutex lock(audioTrack->mLock);
1758 audioTrack->mProxy->binderDied();
1759 }
1760}
1761
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001762// =========================================================================
1763
1764AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001765 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mResumeLatch(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08001766{
1767}
1768
1769AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001770{
1771}
1772
1773bool AudioTrack::AudioTrackThread::threadLoop()
1774{
Glenn Kasten3acbd052012-02-28 10:39:56 -08001775 {
1776 AutoMutex _l(mMyLock);
1777 if (mPaused) {
1778 mMyCond.wait(mMyLock);
1779 // caller will check for exitPending()
1780 return true;
1781 }
1782 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001783 nsecs_t ns = mReceiver.processAudioBuffer(this);
1784 switch (ns) {
1785 case 0:
1786 return true;
1787 case NS_WHENEVER:
1788 sleep(1);
1789 return true;
1790 case NS_INACTIVE:
1791 pauseConditional();
1792 return true;
1793 case NS_NEVER:
1794 return false;
1795 default:
1796 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns);
1797 struct timespec req;
1798 req.tv_sec = ns / 1000000000LL;
1799 req.tv_nsec = ns % 1000000000LL;
1800 nanosleep(&req, NULL /*rem*/);
1801 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07001802 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001803}
1804
Glenn Kasten3acbd052012-02-28 10:39:56 -08001805void AudioTrack::AudioTrackThread::requestExit()
1806{
1807 // must be in this order to avoid a race condition
1808 Thread::requestExit();
Glenn Kastenf4022f92012-05-02 10:34:59 -07001809 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08001810}
1811
1812void AudioTrack::AudioTrackThread::pause()
1813{
1814 AutoMutex _l(mMyLock);
1815 mPaused = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001816 mResumeLatch = false;
1817}
1818
1819void AudioTrack::AudioTrackThread::pauseConditional()
1820{
1821 AutoMutex _l(mMyLock);
1822 if (mResumeLatch) {
1823 mResumeLatch = false;
1824 } else {
1825 mPaused = true;
1826 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001827}
1828
1829void AudioTrack::AudioTrackThread::resume()
1830{
1831 AutoMutex _l(mMyLock);
1832 if (mPaused) {
1833 mPaused = false;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001834 mResumeLatch = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001835 mMyCond.signal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001836 } else {
1837 mResumeLatch = true;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001838 }
1839}
1840
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001841}; // namespace android