blob: 78ae37e4afd585b9b3da2eca3f95bf526606985c [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());
389 }
390 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700391 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800392
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800393 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800394 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100395 if (previousState == STATE_STOPPING) {
396 mProxy->interrupt();
397 } else {
398 t->resume();
399 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800400 } else {
401 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
402 get_sched_policy(0, &mPreviousSchedulingGroup);
403 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
404 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800405
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800406 status_t status = NO_ERROR;
407 if (!(flags & CBLK_INVALID)) {
408 status = mAudioTrack->start();
409 if (status == DEAD_OBJECT) {
410 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800411 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800412 }
413 if (flags & CBLK_INVALID) {
414 status = restoreTrack_l("start");
415 }
416
417 if (status != NO_ERROR) {
418 ALOGE("start() status %d", status);
419 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800420 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100421 if (previousState != STATE_STOPPING) {
422 t->pause();
423 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800424 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700425 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700426 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800427 }
428 }
429
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100430 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800431}
432
433void AudioTrack::stop()
434{
435 AutoMutex lock(mLock);
436 // FIXME pause then stop should not be a nop
437 if (mState != STATE_ACTIVE) {
438 return;
439 }
440
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100441 if (isOffloaded()) {
442 mState = STATE_STOPPING;
443 } else {
444 mState = STATE_STOPPED;
445 }
446
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800447 mProxy->interrupt();
448 mAudioTrack->stop();
449 // the playback head position will reset to 0, so if a marker is set, we need
450 // to activate it again
451 mMarkerReached = false;
452#if 0
453 // Force flush if a shared buffer is used otherwise audioflinger
454 // will not stop before end of buffer is reached.
455 // It may be needed to make sure that we stop playback, likely in case looping is on.
456 if (mSharedBuffer != 0) {
457 flush_l();
458 }
459#endif
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100460
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800461 sp<AudioTrackThread> t = mAudioTrackThread;
462 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100463 if (!isOffloaded()) {
464 t->pause();
465 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800466 } else {
467 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
468 set_sched_policy(0, mPreviousSchedulingGroup);
469 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800470}
471
472bool AudioTrack::stopped() const
473{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800474 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800475 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800476}
477
478void AudioTrack::flush()
479{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800480 if (mSharedBuffer != 0) {
481 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800482 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800483 AutoMutex lock(mLock);
484 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
485 return;
486 }
487 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800488}
489
Eric Laurent1703cdf2011-03-07 14:52:59 -0800490void AudioTrack::flush_l()
491{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800492 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700493
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700494 // clear playback marker and periodic update counter
495 mMarkerPosition = 0;
496 mMarkerReached = false;
497 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100498 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700499
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800500 mState = STATE_FLUSHED;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100501 if (isOffloaded()) {
502 mProxy->interrupt();
503 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800504 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800505 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800506}
507
508void AudioTrack::pause()
509{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800510 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100511 if (mState == STATE_ACTIVE) {
512 mState = STATE_PAUSED;
513 } else if (mState == STATE_STOPPING) {
514 mState = STATE_PAUSED_STOPPING;
515 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800516 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800517 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800518 mProxy->interrupt();
519 mAudioTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800520}
521
Eric Laurentbe916aa2010-06-01 23:49:17 -0700522status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800523{
Glenn Kastenf0c49502011-11-30 09:46:04 -0800524 if (left < 0.0f || left > 1.0f || right < 0.0f || right > 1.0f) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700525 return BAD_VALUE;
526 }
527
Eric Laurent1703cdf2011-03-07 14:52:59 -0800528 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800529 mVolume[LEFT] = left;
530 mVolume[RIGHT] = right;
531
Glenn Kastene3aa6592012-12-04 12:22:46 -0800532 mProxy->setVolumeLR((uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700533
534 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800535}
536
Glenn Kastenb1c09932012-02-27 16:21:04 -0800537status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800538{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800539 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700540}
541
Eric Laurent2beeb502010-07-16 07:43:46 -0700542status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700543{
Glenn Kasten05632a52012-01-03 14:22:33 -0800544 if (level < 0.0f || level > 1.0f) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700545 return BAD_VALUE;
546 }
547
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800548 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700549 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800550 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700551
552 return NO_ERROR;
553}
554
Glenn Kastena5224f32012-01-04 12:41:44 -0800555void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700556{
557 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800558 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700559 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800560}
561
Glenn Kasten3b16c762012-11-14 08:44:39 -0800562status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800563{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100564 if (mIsTimed || isOffloaded()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800565 return INVALID_OPERATION;
566 }
567
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800568 uint32_t afSamplingRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800569 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700570 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800571 }
572 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Glenn Kastend65d73c2012-06-22 17:21:07 -0700573 if (rate == 0 || rate > afSamplingRate*2 ) {
574 return BAD_VALUE;
575 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800576
Eric Laurent1703cdf2011-03-07 14:52:59 -0800577 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800578 mSampleRate = rate;
579 mProxy->setSampleRate(rate);
580
Eric Laurent57326622009-07-07 07:10:45 -0700581 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800582}
583
Glenn Kastena5224f32012-01-04 12:41:44 -0800584uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800585{
John Grossman4ff14ba2012-02-08 16:37:41 -0800586 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800587 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800588 }
589
Eric Laurent1703cdf2011-03-07 14:52:59 -0800590 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800591 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800592}
593
594status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
595{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100596 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800597 return INVALID_OPERATION;
598 }
599
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800600 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800601 ;
602 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
603 loopEnd - loopStart >= MIN_LOOP) {
604 ;
605 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800606 return BAD_VALUE;
607 }
608
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800609 AutoMutex lock(mLock);
610 // See setPosition() regarding setting parameters such as loop points or position while active
611 if (mState == STATE_ACTIVE) {
612 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700613 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800614 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800615 return NO_ERROR;
616}
617
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800618void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
619{
620 // FIXME If setting a loop also sets position to start of loop, then
621 // this is correct. Otherwise it should be removed.
622 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
623 mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0;
624 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
625}
626
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800627status_t AudioTrack::setMarkerPosition(uint32_t marker)
628{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700629 // The only purpose of setting marker position is to get a callback
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100630 if (mCbf == NULL || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700631 return INVALID_OPERATION;
632 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800633
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800634 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800635 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700636 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800637
638 return NO_ERROR;
639}
640
Glenn Kastena5224f32012-01-04 12:41:44 -0800641status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800642{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100643 if (isOffloaded()) {
644 return INVALID_OPERATION;
645 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700646 if (marker == NULL) {
647 return BAD_VALUE;
648 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800649
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800650 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800651 *marker = mMarkerPosition;
652
653 return NO_ERROR;
654}
655
656status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
657{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700658 // The only purpose of setting position update period is to get a callback
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100659 if (mCbf == NULL || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700660 return INVALID_OPERATION;
661 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800662
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800663 AutoMutex lock(mLock);
664 mNewPosition = mProxy->getPosition() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800665 mUpdatePeriod = updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800666 return NO_ERROR;
667}
668
Glenn Kastena5224f32012-01-04 12:41:44 -0800669status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800670{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100671 if (isOffloaded()) {
672 return INVALID_OPERATION;
673 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700674 if (updatePeriod == NULL) {
675 return BAD_VALUE;
676 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800677
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800678 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800679 *updatePeriod = mUpdatePeriod;
680
681 return NO_ERROR;
682}
683
684status_t AudioTrack::setPosition(uint32_t position)
685{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100686 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700687 return INVALID_OPERATION;
688 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800689 if (position > mFrameCount) {
690 return BAD_VALUE;
691 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800692
Eric Laurent1703cdf2011-03-07 14:52:59 -0800693 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800694 // Currently we require that the player is inactive before setting parameters such as position
695 // or loop points. Otherwise, there could be a race condition: the application could read the
696 // current position, compute a new position or loop parameters, and then set that position or
697 // loop parameters but it would do the "wrong" thing since the position has continued to advance
698 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
699 // to specify how it wants to handle such scenarios.
700 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700701 return INVALID_OPERATION;
702 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800703 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
704 mLoopPeriod = 0;
705 // FIXME Check whether loops and setting position are incompatible in old code.
706 // If we use setLoop for both purposes we lose the capability to set the position while looping.
707 mStaticProxy->setLoop(position, mFrameCount, 0);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700708
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800709 return NO_ERROR;
710}
711
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800712status_t AudioTrack::getPosition(uint32_t *position) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800713{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700714 if (position == NULL) {
715 return BAD_VALUE;
716 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800717
Eric Laurent1703cdf2011-03-07 14:52:59 -0800718 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100719 if (isOffloaded()) {
720 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800721
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100722 if (mOutput != 0) {
723 uint32_t halFrames;
724 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
725 }
726 *position = dspFrames;
727 } else {
728 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
729 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ? 0 :
730 mProxy->getPosition();
731 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800732 return NO_ERROR;
733}
734
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800735status_t AudioTrack::getBufferPosition(size_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800736{
737 if (mSharedBuffer == 0 || mIsTimed) {
738 return INVALID_OPERATION;
739 }
740 if (position == NULL) {
741 return BAD_VALUE;
742 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800743
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800744 AutoMutex lock(mLock);
745 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800746 return NO_ERROR;
747}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800748
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800749status_t AudioTrack::reload()
750{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100751 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800752 return INVALID_OPERATION;
753 }
754
Eric Laurent1703cdf2011-03-07 14:52:59 -0800755 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800756 // See setPosition() regarding setting parameters such as loop points or position while active
757 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700758 return INVALID_OPERATION;
759 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800760 mNewPosition = mUpdatePeriod;
761 mLoopPeriod = 0;
762 // FIXME The new code cannot reload while keeping a loop specified.
763 // Need to check how the old code handled this, and whether it's a significant change.
764 mStaticProxy->setLoop(0, mFrameCount, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800765 return NO_ERROR;
766}
767
Eric Laurentc2f1f072009-07-17 12:17:14 -0700768audio_io_handle_t AudioTrack::getOutput()
769{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800770 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100771 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800772}
773
774// must be called with mLock held
775audio_io_handle_t AudioTrack::getOutput_l()
776{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100777 if (mOutput) {
778 return mOutput;
779 } else {
780 return AudioSystem::getOutput(mStreamType,
781 mSampleRate, mFormat, mChannelMask, mFlags);
782 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700783}
784
Eric Laurentbe916aa2010-06-01 23:49:17 -0700785status_t AudioTrack::attachAuxEffect(int effectId)
786{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800787 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700788 status_t status = mAudioTrack->attachAuxEffect(effectId);
789 if (status == NO_ERROR) {
790 mAuxEffectId = effectId;
791 }
792 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700793}
794
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800795// -------------------------------------------------------------------------
796
Eric Laurent1703cdf2011-03-07 14:52:59 -0800797// must be called with mLock held
798status_t AudioTrack::createTrack_l(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800799 audio_stream_type_t streamType,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800800 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800801 audio_format_t format,
Glenn Kastene33054e2012-11-14 12:54:39 -0800802 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700803 audio_output_flags_t flags,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800804 const sp<IMemory>& sharedBuffer,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800805 audio_io_handle_t output,
806 size_t epoch)
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800807{
808 status_t status;
809 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
810 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700811 ALOGE("Could not get audioflinger");
812 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800813 }
814
Eric Laurentd1b449a2010-05-14 03:26:45 -0700815 uint32_t afLatency;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800816 if ((status = AudioSystem::getLatency(output, streamType, &afLatency)) != NO_ERROR) {
817 ALOGE("getLatency(%d) failed status %d", output, status);
Eric Laurentd1b449a2010-05-14 03:26:45 -0700818 return NO_INIT;
819 }
820
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700821 // Client decides whether the track is TIMED (see below), but can only express a preference
822 // for FAST. Server will perform additional tests.
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700823 if ((flags & AUDIO_OUTPUT_FLAG_FAST) && !(
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700824 // either of these use cases:
825 // use case 1: shared buffer
826 (sharedBuffer != 0) ||
827 // use case 2: callback handler
828 (mCbf != NULL))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800829 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -0700830 // once denied, do not request again if IAudioTrack is re-created
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700831 flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten093000f2012-05-03 09:35:36 -0700832 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700833 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700834 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700835
Eric Laurentd1b449a2010-05-14 03:26:45 -0700836 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700837
Dima Zavinfce7a472011-04-19 22:30:36 -0700838 if (!audio_is_linear_pcm(format)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700839
Eric Laurentd1b449a2010-05-14 03:26:45 -0700840 if (sharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700841 // Same comment as below about ignoring frameCount parameter for set()
Eric Laurentd1b449a2010-05-14 03:26:45 -0700842 frameCount = sharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -0700843 } else if (frameCount == 0) {
Glenn Kastene33054e2012-11-14 12:54:39 -0800844 size_t afFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800845 status = AudioSystem::getFrameCount(output, streamType, &afFrameCount);
846 if (status != NO_ERROR) {
847 ALOGE("getFrameCount(output=%d, streamType=%d) status %d", output, streamType,
848 status);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700849 return NO_INIT;
850 }
851 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700852 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100853 if (mNotificationFramesAct != frameCount) {
854 mNotificationFramesAct = frameCount;
855 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700856 } else if (sharedBuffer != 0) {
857
Glenn Kastena42ff002012-11-14 12:47:55 -0800858 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -0700859 // 8-bit data in shared memory is not currently supported by AudioFlinger
860 size_t alignment = /* format == AUDIO_FORMAT_PCM_8_BIT ? 1 : */ 2;
Glenn Kastena42ff002012-11-14 12:47:55 -0800861 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700862 // More than 2 channels does not require stronger alignment than stereo
863 alignment <<= 1;
864 }
Glenn Kastena42ff002012-11-14 12:47:55 -0800865 if (((size_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
866 ALOGE("Invalid buffer alignment: address %p, channel count %u",
867 sharedBuffer->pointer(), mChannelCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700868 return BAD_VALUE;
869 }
870
871 // When initializing a shared buffer AudioTrack via constructors,
872 // there's no frameCount parameter.
873 // But when initializing a shared buffer AudioTrack via set(),
874 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kastena42ff002012-11-14 12:47:55 -0800875 frameCount = sharedBuffer->size()/mChannelCount/sizeof(int16_t);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700876
877 } else if (!(flags & AUDIO_OUTPUT_FLAG_FAST)) {
878
879 // FIXME move these calculations and associated checks to server
Glenn Kasten3b16c762012-11-14 08:44:39 -0800880 uint32_t afSampleRate;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800881 status = AudioSystem::getSamplingRate(output, streamType, &afSampleRate);
882 if (status != NO_ERROR) {
883 ALOGE("getSamplingRate(output=%d, streamType=%d) status %d", output, streamType,
884 status);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700885 return NO_INIT;
886 }
Glenn Kastene33054e2012-11-14 12:54:39 -0800887 size_t afFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800888 status = AudioSystem::getFrameCount(output, streamType, &afFrameCount);
889 if (status != NO_ERROR) {
890 ALOGE("getFrameCount(output=%d, streamType=%d) status %d", output, streamType, status);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700891 return NO_INIT;
892 }
893
Eric Laurentd1b449a2010-05-14 03:26:45 -0700894 // Ensure that buffer depth covers at least audio hardware latency
895 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Glenn Kastenbb6f0a02013-06-03 15:00:29 -0700896 ALOGV("afFrameCount=%d, minBufCount=%d, afSampleRate=%u, afLatency=%d",
897 afFrameCount, minBufCount, afSampleRate, afLatency);
898 if (minBufCount <= 2) {
899 minBufCount = sampleRate == afSampleRate ? 2 : 3;
Glenn Kasten7c027242012-12-26 14:43:16 -0800900 }
Eric Laurentd1b449a2010-05-14 03:26:45 -0700901
Glenn Kastene33054e2012-11-14 12:54:39 -0800902 size_t minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
903 ALOGV("minFrameCount: %u, afFrameCount=%d, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -0800904 ", afLatency=%d",
905 minFrameCount, afFrameCount, minBufCount, sampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700906
907 if (frameCount == 0) {
908 frameCount = minFrameCount;
909 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700910 // Make sure that application is notified with sufficient margin
911 // before underrun
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800912 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/2) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700913 mNotificationFramesAct = frameCount/2;
914 }
915 if (frameCount < minFrameCount) {
916 // not ALOGW because it happens all the time when playing key clicks over A2DP
917 ALOGV("Minimum buffer size corrected from %d to %d",
918 frameCount, minFrameCount);
919 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800920 }
Eric Laurentd1b449a2010-05-14 03:26:45 -0700921
Glenn Kastene0fa4672012-04-24 14:35:14 -0700922 } else {
923 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -0700924 }
925
Glenn Kastena075db42012-03-06 11:22:44 -0800926 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
927 if (mIsTimed) {
928 trackFlags |= IAudioFlinger::TRACK_TIMED;
929 }
Glenn Kasten3acbd052012-02-28 10:39:56 -0800930
931 pid_t tid = -1;
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700932 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700933 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800934 if (mAudioTrackThread != 0) {
935 tid = mAudioTrackThread->getTid();
936 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700937 }
938
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100939 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
940 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
941 }
942
Glenn Kasten8d6cc842012-02-03 11:06:53 -0800943 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800944 sampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -0700945 // AudioFlinger only sees 16-bit PCM
946 format == AUDIO_FORMAT_PCM_8_BIT ?
947 AUDIO_FORMAT_PCM_16_BIT : format,
Glenn Kastena42ff002012-11-14 12:47:55 -0800948 mChannelMask,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800949 frameCount,
Glenn Kastene0b07172012-11-06 15:03:34 -0800950 &trackFlags,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800951 sharedBuffer,
952 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800953 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700954 &mSessionId,
Glenn Kastend054c322013-07-12 12:59:20 -0700955 mName,
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 Kasten53cec222013-08-29 09:01:02 -0700967 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800968 if (mAudioTrack != 0) {
969 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
970 mDeathNotifier.clear();
971 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800972 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -0700973 mCblkMemory = iMem;
974 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMem->pointer());
975 mCblk = cblk;
Glenn Kastenb6037442012-11-14 13:42:25 -0800976 size_t temp = cblk->frameCount_;
977 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
978 // In current design, AudioTrack client checks and ensures frame count validity before
979 // passing it to AudioFlinger so AudioFlinger should not return a different value except
980 // for fast track as it uses a special method of assigning frame count.
981 ALOGW("Requested frameCount %u but received frameCount %u", frameCount, temp);
982 }
983 frameCount = temp;
Glenn Kastena07f17c2013-04-23 12:39:37 -0700984 mAwaitBoost = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800985 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -0800986 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Glenn Kastenb6037442012-11-14 13:42:25 -0800987 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %u", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -0700988 mAwaitBoost = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800989 if (sharedBuffer == 0) {
990 // double-buffering is not required for fast tracks, due to tighter scheduling
991 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount) {
992 mNotificationFramesAct = frameCount;
993 }
994 }
Glenn Kasten3acbd052012-02-28 10:39:56 -0800995 } else {
Glenn Kastenb6037442012-11-14 13:42:25 -0800996 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %u", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -0700997 // once denied, do not request again if IAudioTrack is re-created
998 flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST);
999 mFlags = flags;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001000 if (sharedBuffer == 0) {
1001 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/2) {
1002 mNotificationFramesAct = frameCount/2;
1003 }
1004 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001005 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001006 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001007 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
1008 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1009 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1010 } else {
1011 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
1012 flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1013 mFlags = flags;
1014 return NO_INIT;
1015 }
1016 }
1017
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001018 mRefreshRemaining = true;
1019
1020 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1021 // is the value of pointer() for the shared buffer, otherwise buffers points
1022 // immediately after the control block. This address is for the mapping within client
1023 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1024 void* buffers;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001025 if (sharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001026 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001027 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001028 buffers = sharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001029 }
1030
Eric Laurent2beeb502010-07-16 07:43:46 -07001031 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001032 // FIXME don't believe this lie
Glenn Kastenb6037442012-11-14 13:42:25 -08001033 mLatency = afLatency + (1000*frameCount) / sampleRate;
1034 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001035 // If IAudioTrack is re-created, don't let the requested frameCount
1036 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001037 if (frameCount > mReqFrameCount) {
1038 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001039 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001040
1041 // update proxy
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001042 if (sharedBuffer == 0) {
1043 mStaticProxy.clear();
1044 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1045 } else {
1046 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1047 mProxy = mStaticProxy;
1048 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001049 mProxy->setVolumeLR((uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) |
1050 uint16_t(mVolume[LEFT] * 0x1000));
1051 mProxy->setSendLevel(mSendLevel);
1052 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001053 mProxy->setEpoch(epoch);
1054 mProxy->setMinimum(mNotificationFramesAct);
1055
1056 mDeathNotifier = new DeathNotifier(this);
1057 mAudioTrack->asBinder()->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001058
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001059 return NO_ERROR;
1060}
1061
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001062status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1063{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001064 if (audioBuffer == NULL) {
1065 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001066 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001067 if (mTransfer != TRANSFER_OBTAIN) {
1068 audioBuffer->frameCount = 0;
1069 audioBuffer->size = 0;
1070 audioBuffer->raw = NULL;
1071 return INVALID_OPERATION;
1072 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001073
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001074 const struct timespec *requested;
1075 if (waitCount == -1) {
1076 requested = &ClientProxy::kForever;
1077 } else if (waitCount == 0) {
1078 requested = &ClientProxy::kNonBlocking;
1079 } else if (waitCount > 0) {
1080 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
1081 struct timespec timeout;
1082 timeout.tv_sec = ms / 1000;
1083 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1084 requested = &timeout;
1085 } else {
1086 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1087 requested = NULL;
1088 }
1089 return obtainBuffer(audioBuffer, requested);
1090}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001091
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001092status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1093 struct timespec *elapsed, size_t *nonContig)
1094{
1095 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1096 uint32_t oldSequence = 0;
1097 uint32_t newSequence;
1098
1099 Proxy::Buffer buffer;
1100 status_t status = NO_ERROR;
1101
1102 static const int32_t kMaxTries = 5;
1103 int32_t tryCounter = kMaxTries;
1104
1105 do {
1106 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1107 // keep them from going away if another thread re-creates the track during obtainBuffer()
1108 sp<AudioTrackClientProxy> proxy;
1109 sp<IMemory> iMem;
1110
1111 { // start of lock scope
1112 AutoMutex lock(mLock);
1113
1114 newSequence = mSequence;
1115 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1116 if (status == DEAD_OBJECT) {
1117 // re-create track, unless someone else has already done so
1118 if (newSequence == oldSequence) {
1119 status = restoreTrack_l("obtainBuffer");
1120 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001121 buffer.mFrameCount = 0;
1122 buffer.mRaw = NULL;
1123 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001124 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001125 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001126 }
1127 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001128 oldSequence = newSequence;
1129
1130 // Keep the extra references
1131 proxy = mProxy;
1132 iMem = mCblkMemory;
1133
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001134 if (mState == STATE_STOPPING) {
1135 status = -EINTR;
1136 buffer.mFrameCount = 0;
1137 buffer.mRaw = NULL;
1138 buffer.mNonContig = 0;
1139 break;
1140 }
1141
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001142 // Non-blocking if track is stopped or paused
1143 if (mState != STATE_ACTIVE) {
1144 requested = &ClientProxy::kNonBlocking;
1145 }
1146
1147 } // end of lock scope
1148
1149 buffer.mFrameCount = audioBuffer->frameCount;
1150 // FIXME starts the requested timeout and elapsed over from scratch
1151 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1152
1153 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1154
1155 audioBuffer->frameCount = buffer.mFrameCount;
1156 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1157 audioBuffer->raw = buffer.mRaw;
1158 if (nonContig != NULL) {
1159 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001160 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001161 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001162}
1163
1164void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1165{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001166 if (mTransfer == TRANSFER_SHARED) {
1167 return;
1168 }
1169
1170 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1171 if (stepCount == 0) {
1172 return;
1173 }
1174
1175 Proxy::Buffer buffer;
1176 buffer.mFrameCount = stepCount;
1177 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001178
Eric Laurent1703cdf2011-03-07 14:52:59 -08001179 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001180 mInUnderrun = false;
1181 mProxy->releaseBuffer(&buffer);
1182
1183 // restart track if it was disabled by audioflinger due to previous underrun
1184 if (mState == STATE_ACTIVE) {
1185 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001186 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastend054c322013-07-12 12:59:20 -07001187 ALOGW("releaseBuffer() track %p name=%s disabled due to previous underrun, restarting",
1188 this, mName.string());
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001189 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001190 mAudioTrack->start();
1191 }
1192 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001193}
1194
1195// -------------------------------------------------------------------------
1196
1197ssize_t AudioTrack::write(const void* buffer, size_t userSize)
1198{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001199 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001200 return INVALID_OPERATION;
1201 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001202
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001203 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001204 // Sanity-check: user is most-likely passing an error code, and it would
1205 // make the return value ambiguous (actualSize vs error).
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001206 ALOGE("AudioTrack::write(buffer=%p, size=%u (%d)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001207 return BAD_VALUE;
1208 }
1209
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001210 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001211 Buffer audioBuffer;
1212
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001213 while (userSize >= mFrameSize) {
1214 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001215
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001216 status_t err = obtainBuffer(&audioBuffer, &ClientProxy::kForever);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001217 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001218 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001219 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001220 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001221 return ssize_t(err);
1222 }
1223
1224 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001225 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001226 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001227 toWrite = audioBuffer.size >> 1;
1228 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001229 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001230 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001231 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001232 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001233 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001234 userSize -= toWrite;
1235 written += toWrite;
1236
1237 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001238 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001239
1240 return written;
1241}
1242
1243// -------------------------------------------------------------------------
1244
John Grossman4ff14ba2012-02-08 16:37:41 -08001245TimedAudioTrack::TimedAudioTrack() {
1246 mIsTimed = true;
1247}
1248
1249status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1250{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001251 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001252 status_t result = UNKNOWN_ERROR;
1253
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001254#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001255 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1256 // while we are accessing the cblk
1257 sp<IAudioTrack> audioTrack = mAudioTrack;
1258 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001259#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001260
John Grossman4ff14ba2012-02-08 16:37:41 -08001261 // If the track is not invalid already, try to allocate a buffer. alloc
1262 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001263 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001264 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001265 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001266 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1267 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001268 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001269 }
1270 }
1271
1272 // If the track is invalid at this point, attempt to restore it. and try the
1273 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001274 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001275 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001276
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001277 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001278 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001279 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001280 }
1281
1282 return result;
1283}
1284
1285status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1286 int64_t pts)
1287{
Eric Laurentdf839842012-05-31 14:27:14 -07001288 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1289 {
1290 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001291 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001292 // restart track if it was disabled by audioflinger due to previous underrun
1293 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001294 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1295 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001296 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001297 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001298 mAudioTrack->start();
1299 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001300 }
Eric Laurentdf839842012-05-31 14:27:14 -07001301 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001302}
1303
1304status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1305 TargetTimeline target)
1306{
1307 return mAudioTrack->setMediaTimeTransform(xform, target);
1308}
1309
1310// -------------------------------------------------------------------------
1311
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001312nsecs_t AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001313{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001314 // Currently the AudioTrack thread is not created if there are no callbacks.
1315 // Would it ever make sense to run the thread, even without callbacks?
1316 // If so, then replace this by checks at each use for mCbf != NULL.
1317 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1318
Eric Laurent1703cdf2011-03-07 14:52:59 -08001319 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001320 if (mAwaitBoost) {
1321 mAwaitBoost = false;
1322 mLock.unlock();
1323 static const int32_t kMaxTries = 5;
1324 int32_t tryCounter = kMaxTries;
1325 uint32_t pollUs = 10000;
1326 do {
1327 int policy = sched_getscheduler(0);
1328 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1329 break;
1330 }
1331 usleep(pollUs);
1332 pollUs <<= 1;
1333 } while (tryCounter-- > 0);
1334 if (tryCounter < 0) {
1335 ALOGE("did not receive expected priority boost on time");
1336 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001337 // Run again immediately
1338 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001339 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001340
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001341 // Can only reference mCblk while locked
1342 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001343 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001344
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001345 // Check for track invalidation
1346 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001347 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1348 // AudioSystem cache. We should not exit here but after calling the callback so
1349 // that the upper layers can recreate the track
1350 if (!isOffloaded() || (mSequence == mObservedSequence)) {
1351 status_t status = restoreTrack_l("processAudioBuffer");
1352 mLock.unlock();
1353 // Run again immediately, but with a new IAudioTrack
1354 return 0;
1355 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001356 }
1357
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001358 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001359 bool active = mState == STATE_ACTIVE;
1360
1361 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1362 bool newUnderrun = false;
1363 if (flags & CBLK_UNDERRUN) {
1364#if 0
1365 // Currently in shared buffer mode, when the server reaches the end of buffer,
1366 // the track stays active in continuous underrun state. It's up to the application
1367 // to pause or stop the track, or set the position to a new offset within buffer.
1368 // This was some experimental code to auto-pause on underrun. Keeping it here
1369 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1370 if (mTransfer == TRANSFER_SHARED) {
1371 mState = STATE_PAUSED;
1372 active = false;
1373 }
1374#endif
1375 if (!mInUnderrun) {
1376 mInUnderrun = true;
1377 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001378 }
1379 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001380
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001381 // Get current position of server
1382 size_t position = mProxy->getPosition();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001383
1384 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001385 bool markerReached = false;
1386 size_t markerPosition = mMarkerPosition;
1387 // FIXME fails for wraparound, need 64 bits
1388 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1389 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001390 }
1391
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001392 // Determine number of new position callback(s) that will be needed, while locked
1393 size_t newPosCount = 0;
1394 size_t newPosition = mNewPosition;
1395 size_t updatePeriod = mUpdatePeriod;
1396 // FIXME fails for wraparound, need 64 bits
1397 if (updatePeriod > 0 && position >= newPosition) {
1398 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1399 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001400 }
1401
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001402 // Cache other fields that will be needed soon
1403 uint32_t loopPeriod = mLoopPeriod;
1404 uint32_t sampleRate = mSampleRate;
1405 size_t notificationFrames = mNotificationFramesAct;
1406 if (mRefreshRemaining) {
1407 mRefreshRemaining = false;
1408 mRemainingFrames = notificationFrames;
1409 mRetryOnPartialBuffer = false;
1410 }
1411 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001412 uint32_t sequence = mSequence;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001413
1414 // These fields don't need to be cached, because they are assigned only by set():
1415 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1416 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1417
1418 mLock.unlock();
1419
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001420 if (waitStreamEnd) {
1421 AutoMutex lock(mLock);
1422
1423 sp<AudioTrackClientProxy> proxy = mProxy;
1424 sp<IMemory> iMem = mCblkMemory;
1425
1426 struct timespec timeout;
1427 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1428 timeout.tv_nsec = 0;
1429
1430 mLock.unlock();
1431 status_t status = mProxy->waitStreamEndDone(&timeout);
1432 mLock.lock();
1433 switch (status) {
1434 case NO_ERROR:
1435 case DEAD_OBJECT:
1436 case TIMED_OUT:
1437 mLock.unlock();
1438 mCbf(EVENT_STREAM_END, mUserData, NULL);
1439 mLock.lock();
1440 if (mState == STATE_STOPPING) {
1441 mState = STATE_STOPPED;
1442 if (status != DEAD_OBJECT) {
1443 return NS_INACTIVE;
1444 }
1445 }
1446 return 0;
1447 default:
1448 return 0;
1449 }
1450 }
1451
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001452 // perform callbacks while unlocked
1453 if (newUnderrun) {
1454 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1455 }
1456 // FIXME we will miss loops if loop cycle was signaled several times since last call
1457 // to processAudioBuffer()
1458 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1459 mCbf(EVENT_LOOP_END, mUserData, NULL);
1460 }
1461 if (flags & CBLK_BUFFER_END) {
1462 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1463 }
1464 if (markerReached) {
1465 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1466 }
1467 while (newPosCount > 0) {
1468 size_t temp = newPosition;
1469 mCbf(EVENT_NEW_POS, mUserData, &temp);
1470 newPosition += updatePeriod;
1471 newPosCount--;
1472 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001473
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001474 if (mObservedSequence != sequence) {
1475 mObservedSequence = sequence;
1476 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001477 // for offloaded tracks, just wait for the upper layers to recreate the track
1478 if (isOffloaded()) {
1479 return NS_INACTIVE;
1480 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001481 }
1482
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001483 // if inactive, then don't run me again until re-started
1484 if (!active) {
1485 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001486 }
1487
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001488 // Compute the estimated time until the next timed event (position, markers, loops)
1489 // FIXME only for non-compressed audio
1490 uint32_t minFrames = ~0;
1491 if (!markerReached && position < markerPosition) {
1492 minFrames = markerPosition - position;
1493 }
1494 if (loopPeriod > 0 && loopPeriod < minFrames) {
1495 minFrames = loopPeriod;
1496 }
1497 if (updatePeriod > 0 && updatePeriod < minFrames) {
1498 minFrames = updatePeriod;
1499 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001500
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001501 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1502 static const uint32_t kPoll = 0;
1503 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1504 minFrames = kPoll * notificationFrames;
1505 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001506
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001507 // Convert frame units to time units
1508 nsecs_t ns = NS_WHENEVER;
1509 if (minFrames != (uint32_t) ~0) {
1510 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1511 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1512 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1513 }
1514
1515 // If not supplying data by EVENT_MORE_DATA, then we're done
1516 if (mTransfer != TRANSFER_CALLBACK) {
1517 return ns;
1518 }
1519
1520 struct timespec timeout;
1521 const struct timespec *requested = &ClientProxy::kForever;
1522 if (ns != NS_WHENEVER) {
1523 timeout.tv_sec = ns / 1000000000LL;
1524 timeout.tv_nsec = ns % 1000000000LL;
1525 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1526 requested = &timeout;
1527 }
1528
1529 while (mRemainingFrames > 0) {
1530
1531 Buffer audioBuffer;
1532 audioBuffer.frameCount = mRemainingFrames;
1533 size_t nonContig;
1534 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1535 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1536 "obtainBuffer() err=%d frameCount=%u", err, audioBuffer.frameCount);
1537 requested = &ClientProxy::kNonBlocking;
1538 size_t avail = audioBuffer.frameCount + nonContig;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001539 ALOGV("obtainBuffer(%u) returned %u = %u + %u err %d",
1540 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001541 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001542 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1543 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001544 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001545 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001546 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1547 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001548 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001549
1550 if (mRetryOnPartialBuffer) {
1551 mRetryOnPartialBuffer = false;
1552 if (avail < mRemainingFrames) {
1553 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1554 if (ns < 0 || myns < ns) {
1555 ns = myns;
1556 }
1557 return ns;
1558 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001559 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001560
1561 // Divide buffer size by 2 to take into account the expansion
1562 // due to 8 to 16 bit conversion: the callback must fill only half
1563 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001564 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001565 audioBuffer.size >>= 1;
1566 }
1567
1568 size_t reqSize = audioBuffer.size;
1569 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001570 size_t writtenSize = audioBuffer.size;
1571 size_t writtenFrames = writtenSize / mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001572
1573 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001574 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
1575 ALOGE("EVENT_MORE_DATA requested %u bytes but callback returned %d bytes",
1576 reqSize, (int) writtenSize);
1577 return NS_NEVER;
1578 }
1579
1580 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001581 // The callback is done filling buffers
1582 // Keep this thread going to handle timed events and
1583 // still try to get more data in intervals of WAIT_PERIOD_MS
1584 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001585 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001586 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001587
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001588 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001589 // 8 to 16 bit conversion, note that source and destination are the same address
1590 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001591 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001592 }
1593
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001594 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1595 audioBuffer.frameCount = releasedFrames;
1596 mRemainingFrames -= releasedFrames;
1597 if (misalignment >= releasedFrames) {
1598 misalignment -= releasedFrames;
1599 } else {
1600 misalignment = 0;
1601 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001602
1603 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001604
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001605 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1606 // if callback doesn't like to accept the full chunk
1607 if (writtenSize < reqSize) {
1608 continue;
1609 }
1610
1611 // There could be enough non-contiguous frames available to satisfy the remaining request
1612 if (mRemainingFrames <= nonContig) {
1613 continue;
1614 }
1615
1616#if 0
1617 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1618 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1619 // that total to a sum == notificationFrames.
1620 if (0 < misalignment && misalignment <= mRemainingFrames) {
1621 mRemainingFrames = misalignment;
1622 return (mRemainingFrames * 1100000000LL) / sampleRate;
1623 }
1624#endif
1625
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001626 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001627 mRemainingFrames = notificationFrames;
1628 mRetryOnPartialBuffer = true;
1629
1630 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1631 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001632}
1633
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001634status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001635{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001636 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
1637 isOffloaded() ? "Offloaded" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001638 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001639 status_t result;
1640
Glenn Kastena47f3162012-11-07 10:13:08 -08001641 // refresh the audio configuration cache in this process to make sure we get new
1642 // output parameters in getOutput_l() and createTrack_l()
1643 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001644
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001645 if (isOffloaded()) {
1646 return DEAD_OBJECT;
1647 }
1648
1649 // force new output query from audio policy manager;
1650 mOutput = 0;
1651 audio_io_handle_t output = getOutput_l();
1652
Glenn Kastena47f3162012-11-07 10:13:08 -08001653 // if the new IAudioTrack is created, createTrack_l() will modify the
1654 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1655 // It will also delete the strong references on previous IAudioTrack and IMemory
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001656 size_t position = mProxy->getPosition();
1657 mNewPosition = position + mUpdatePeriod;
1658 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
Glenn Kastena47f3162012-11-07 10:13:08 -08001659 result = createTrack_l(mStreamType,
Glenn Kastene3aa6592012-12-04 12:22:46 -08001660 mSampleRate,
Glenn Kastena47f3162012-11-07 10:13:08 -08001661 mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001662 mReqFrameCount, // so that frame count never goes down
Glenn Kastena47f3162012-11-07 10:13:08 -08001663 mFlags,
1664 mSharedBuffer,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001665 output,
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001666 position /*epoch*/);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001667
Glenn Kastena47f3162012-11-07 10:13:08 -08001668 if (result == NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001669 // continue playback from last known position, but
1670 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1671 if (mStaticProxy != NULL) {
1672 mLoopPeriod = 0;
1673 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1674 }
1675 // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1676 // track destruction have been played? This is critical for SoundPool implementation
1677 // This must be broken, and needs to be tested/debugged.
1678#if 0
Glenn Kastena47f3162012-11-07 10:13:08 -08001679 // restore write index and set other indexes to reflect empty buffer status
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001680 if (!strcmp(from, "start")) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001681 // Make sure that a client relying on callback events indicating underrun or
1682 // the actual amount of audio frames played (e.g SoundPool) receives them.
1683 if (mSharedBuffer == 0) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001684 // restart playback even if buffer is not completely filled.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001685 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001686 }
1687 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001688#endif
1689 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001690 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001691 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001692 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001693 if (result != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001694 //Use of direct and offloaded output streams is ref counted by audio policy manager.
1695 // As getOutput was called above and resulted in an output stream to be opened,
1696 // we need to release it.
1697 AudioSystem::releaseOutput(output);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001698 ALOGW("restoreTrack_l() failed status %d", result);
1699 mState = STATE_STOPPED;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001700 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001701
1702 return result;
1703}
1704
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001705status_t AudioTrack::setParameters(const String8& keyValuePairs)
1706{
1707 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001708 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001709}
1710
Glenn Kastence703742013-07-19 16:33:58 -07001711status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1712{
Glenn Kasten53cec222013-08-29 09:01:02 -07001713 AutoMutex lock(mLock);
1714 return mAudioTrack->getTimestamp(timestamp);
Glenn Kastence703742013-07-19 16:33:58 -07001715}
1716
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001717String8 AudioTrack::getParameters(const String8& keys)
1718{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001719 if (mOutput) {
1720 return AudioSystem::getParameters(mOutput, keys);
1721 } else {
1722 return String8::empty();
1723 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001724}
1725
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001726status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1727{
1728
1729 const size_t SIZE = 256;
1730 char buffer[SIZE];
1731 String8 result;
1732
1733 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001734 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
1735 mVolume[0], mVolume[1]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001736 result.append(buffer);
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001737 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001738 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001739 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001740 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001741 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001742 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001743 result.append(buffer);
1744 ::write(fd, result.string(), result.size());
1745 return NO_ERROR;
1746}
1747
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001748uint32_t AudioTrack::getUnderrunFrames() const
1749{
1750 AutoMutex lock(mLock);
1751 return mProxy->getUnderrunFrames();
1752}
1753
1754// =========================================================================
1755
1756void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who)
1757{
1758 sp<AudioTrack> audioTrack = mAudioTrack.promote();
1759 if (audioTrack != 0) {
1760 AutoMutex lock(audioTrack->mLock);
1761 audioTrack->mProxy->binderDied();
1762 }
1763}
1764
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001765// =========================================================================
1766
1767AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001768 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mResumeLatch(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08001769{
1770}
1771
1772AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001773{
1774}
1775
1776bool AudioTrack::AudioTrackThread::threadLoop()
1777{
Glenn Kasten3acbd052012-02-28 10:39:56 -08001778 {
1779 AutoMutex _l(mMyLock);
1780 if (mPaused) {
1781 mMyCond.wait(mMyLock);
1782 // caller will check for exitPending()
1783 return true;
1784 }
1785 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001786 nsecs_t ns = mReceiver.processAudioBuffer(this);
1787 switch (ns) {
1788 case 0:
1789 return true;
1790 case NS_WHENEVER:
1791 sleep(1);
1792 return true;
1793 case NS_INACTIVE:
1794 pauseConditional();
1795 return true;
1796 case NS_NEVER:
1797 return false;
1798 default:
1799 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns);
1800 struct timespec req;
1801 req.tv_sec = ns / 1000000000LL;
1802 req.tv_nsec = ns % 1000000000LL;
1803 nanosleep(&req, NULL /*rem*/);
1804 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07001805 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001806}
1807
Glenn Kasten3acbd052012-02-28 10:39:56 -08001808void AudioTrack::AudioTrackThread::requestExit()
1809{
1810 // must be in this order to avoid a race condition
1811 Thread::requestExit();
Glenn Kastenf4022f92012-05-02 10:34:59 -07001812 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08001813}
1814
1815void AudioTrack::AudioTrackThread::pause()
1816{
1817 AutoMutex _l(mMyLock);
1818 mPaused = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001819 mResumeLatch = false;
1820}
1821
1822void AudioTrack::AudioTrackThread::pauseConditional()
1823{
1824 AutoMutex _l(mMyLock);
1825 if (mResumeLatch) {
1826 mResumeLatch = false;
1827 } else {
1828 mPaused = true;
1829 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001830}
1831
1832void AudioTrack::AudioTrackThread::resume()
1833{
1834 AutoMutex _l(mMyLock);
1835 if (mPaused) {
1836 mPaused = false;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001837 mResumeLatch = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001838 mMyCond.signal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001839 } else {
1840 mResumeLatch = true;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001841 }
1842}
1843
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001844}; // namespace android