blob: a50ed1f4b9a2cff2e92a0ab65f294926a46571e4 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19//#define LOG_NDEBUG 0
20#define LOG_TAG "AudioTrack"
21
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080022#include <sys/resource.h>
Glenn Kasten9f80dd22012-12-18 15:57:32 -080023#include <audio_utils/primitives.h>
24#include <binder/IPCThreadState.h>
25#include <media/AudioTrack.h>
26#include <utils/Log.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080027#include <private/media/AudioTrackShared.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070028#include <media/IAudioFlinger.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080029
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010030#define WAIT_PERIOD_MS 10
31#define WAIT_STREAM_END_TIMEOUT_SEC 120
32
Glenn Kasten511754b2012-01-11 09:52:19 -080033
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080034namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080035// ---------------------------------------------------------------------------
36
37// static
38status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080039 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080040 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080041 uint32_t sampleRate)
42{
Glenn Kastend65d73c2012-06-22 17:21:07 -070043 if (frameCount == NULL) {
44 return BAD_VALUE;
45 }
Glenn Kasten04cd0182012-06-25 11:49:27 -070046
47 // default to 0 in case of error
48 *frameCount = 0;
49
Glenn Kastene0fa4672012-04-24 14:35:14 -070050 // FIXME merge with similar code in createTrack_l(), except we're missing
51 // some information here that is available in createTrack_l():
52 // audio_io_handle_t output
53 // audio_format_t format
54 // audio_channel_mask_t channelMask
55 // audio_output_flags_t flags
Glenn Kasten3b16c762012-11-14 08:44:39 -080056 uint32_t afSampleRate;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080057 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
58 return NO_INIT;
59 }
Glenn Kastene33054e2012-11-14 12:54:39 -080060 size_t afFrameCount;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080061 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
62 return NO_INIT;
63 }
64 uint32_t afLatency;
65 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
66 return NO_INIT;
67 }
68
69 // Ensure that buffer depth covers at least audio hardware latency
70 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080071 if (minBufCount < 2) {
72 minBufCount = 2;
73 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +080074
75 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
Glenn Kastene53b9ea2012-03-12 16:29:55 -070076 afFrameCount * minBufCount * sampleRate / afSampleRate;
Glenn Kasten3acbd052012-02-28 10:39:56 -080077 ALOGV("getMinFrameCount=%d: afFrameCount=%d, minBufCount=%d, afSampleRate=%d, afLatency=%d",
78 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +080079 return NO_ERROR;
80}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080081
82// ---------------------------------------------------------------------------
83
84AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -070085 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -080086 mIsTimed(false),
87 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Glenn Kasten9f80dd22012-12-18 15:57:32 -080088 mPreviousSchedulingGroup(SP_DEFAULT)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080089{
90}
91
92AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -080093 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080094 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -080095 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -070096 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080097 int frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -070098 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080099 callback_t cbf,
100 void* user,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700101 int notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800102 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000103 transfer_type transferType,
104 const audio_offload_info_t *offloadInfo)
Glenn Kasten87913512011-06-22 16:15:25 -0700105 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800106 mIsTimed(false),
107 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800108 mPreviousSchedulingGroup(SP_DEFAULT)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800109{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700110 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700111 frameCount, flags, cbf, user, notificationFrames,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000112 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800113}
114
Andreas Huberc8139852012-01-18 10:51:55 -0800115AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800116 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800117 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800118 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700119 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800120 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700121 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800122 callback_t cbf,
123 void* user,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700124 int notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800125 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000126 transfer_type transferType,
127 const audio_offload_info_t *offloadInfo)
Glenn Kasten87913512011-06-22 16:15:25 -0700128 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800129 mIsTimed(false),
130 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800131 mPreviousSchedulingGroup(SP_DEFAULT)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800132{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700133 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800134 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000135 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800136}
137
138AudioTrack::~AudioTrack()
139{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800140 if (mStatus == NO_ERROR) {
141 // Make sure that callback function exits in the case where
142 // it is looping on buffer full condition in obtainBuffer().
143 // Otherwise the callback thread will never exit.
144 stop();
145 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100146 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800147 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800148 mAudioTrackThread->requestExitAndWait();
149 mAudioTrackThread.clear();
150 }
Glenn Kasten53cec222013-08-29 09:01:02 -0700151 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
152 mAudioTrack.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800153 IPCThreadState::self()->flushCommands();
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700154 AudioSystem::releaseAudioSessionId(mSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800155 }
156}
157
158status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800159 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800160 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800161 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700162 audio_channel_mask_t channelMask,
Glenn Kastene33054e2012-11-14 12:54:39 -0800163 int frameCountInt,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700164 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800165 callback_t cbf,
166 void* user,
167 int notificationFrames,
168 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700169 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800170 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000171 transfer_type transferType,
172 const audio_offload_info_t *offloadInfo)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800173{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800174 switch (transferType) {
175 case TRANSFER_DEFAULT:
176 if (sharedBuffer != 0) {
177 transferType = TRANSFER_SHARED;
178 } else if (cbf == NULL || threadCanCallJava) {
179 transferType = TRANSFER_SYNC;
180 } else {
181 transferType = TRANSFER_CALLBACK;
182 }
183 break;
184 case TRANSFER_CALLBACK:
185 if (cbf == NULL || sharedBuffer != 0) {
186 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
187 return BAD_VALUE;
188 }
189 break;
190 case TRANSFER_OBTAIN:
191 case TRANSFER_SYNC:
192 if (sharedBuffer != 0) {
193 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
194 return BAD_VALUE;
195 }
196 break;
197 case TRANSFER_SHARED:
198 if (sharedBuffer == 0) {
199 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
200 return BAD_VALUE;
201 }
202 break;
203 default:
204 ALOGE("Invalid transfer type %d", transferType);
205 return BAD_VALUE;
206 }
207 mTransfer = transferType;
208
Glenn Kastene33054e2012-11-14 12:54:39 -0800209 // FIXME "int" here is legacy and will be replaced by size_t later
210 if (frameCountInt < 0) {
211 ALOGE("Invalid frame count %d", frameCountInt);
212 return BAD_VALUE;
213 }
214 size_t frameCount = frameCountInt;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800215
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700216 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
217 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800218
Glenn Kastene33054e2012-11-14 12:54:39 -0800219 ALOGV("set() streamType %d frameCount %u flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700220
Eric Laurent1703cdf2011-03-07 14:52:59 -0800221 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800222
Glenn Kasten53cec222013-08-29 09:01:02 -0700223 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700224 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000225 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800226 return INVALID_OPERATION;
227 }
228
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100229 mOutput = 0;
230
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800231 // handle default values first.
Dima Zavinfce7a472011-04-19 22:30:36 -0700232 if (streamType == AUDIO_STREAM_DEFAULT) {
233 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800234 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700235
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800236 if (sampleRate == 0) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800237 uint32_t afSampleRate;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700238 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
239 return NO_INIT;
240 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800241 sampleRate = afSampleRate;
242 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800243 mSampleRate = sampleRate;
Glenn Kastenea7939a2012-03-14 12:56:26 -0700244
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800245 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800246 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700247 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800248 }
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700249 if (channelMask == 0) {
250 channelMask = AUDIO_CHANNEL_OUT_STEREO;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800251 }
252
253 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700254 if (!audio_is_valid_format(format)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800255 ALOGE("Invalid format %d", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800256 return BAD_VALUE;
257 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700258
Glenn Kastene0fa4672012-04-24 14:35:14 -0700259 // AudioFlinger does not currently support 8-bit data in shared memory
260 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
261 ALOGE("8-bit data in shared memory is not supported");
262 return BAD_VALUE;
263 }
264
Eric Laurentc2f1f072009-07-17 12:17:14 -0700265 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100266 // or offload was requested
267 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
268 || !audio_is_linear_pcm(format)) {
269 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
270 ? "Offload request, forcing to Direct Output"
271 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700272 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800273 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700274 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700275 }
Eric Laurent1948eb32012-04-13 16:50:19 -0700276 // only allow deep buffering for music stream type
277 if (streamType != AUDIO_STREAM_MUSIC) {
278 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
279 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700280
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700281 if (!audio_is_output_channel(channelMask)) {
Glenn Kasten28b76b32012-07-03 17:24:41 -0700282 ALOGE("Invalid channel mask %#x", channelMask);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700283 return BAD_VALUE;
284 }
Glenn Kastena42ff002012-11-14 12:47:55 -0800285 mChannelMask = channelMask;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700286 uint32_t channelCount = popcount(channelMask);
Glenn Kastena42ff002012-11-14 12:47:55 -0800287 mChannelCount = channelCount;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700288
Glenn Kastene3aa6592012-12-04 12:22:46 -0800289 if (audio_is_linear_pcm(format)) {
290 mFrameSize = channelCount * audio_bytes_per_sample(format);
291 mFrameSizeAF = channelCount * sizeof(int16_t);
292 } else {
293 mFrameSize = sizeof(uint8_t);
294 mFrameSizeAF = sizeof(uint8_t);
295 }
296
Dima Zavinfce7a472011-04-19 22:30:36 -0700297 audio_io_handle_t output = AudioSystem::getOutput(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800298 streamType,
Glenn Kastene1c39622012-01-04 09:36:37 -0800299 sampleRate, format, channelMask,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000300 flags,
301 offloadInfo);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700302
303 if (output == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000304 ALOGE("Could not get audio output for stream type %d", streamType);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800305 return BAD_VALUE;
306 }
307
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800308 mVolume[LEFT] = 1.0f;
309 mVolume[RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800310 mSendLevel = 0.0f;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700311 mFrameCount = frameCount;
Glenn Kastenb6037442012-11-14 13:42:25 -0800312 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700313 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800314 mNotificationFramesAct = 0;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700315 mSessionId = sessionId;
Eric Laurent2beeb502010-07-16 07:43:46 -0700316 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700317 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700318 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700319
Glenn Kastena997e7a2012-08-07 09:44:19 -0700320 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700321 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700322 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
323 }
324
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800325 // create the IAudioTrack
Eric Laurent1703cdf2011-03-07 14:52:59 -0800326 status_t status = createTrack_l(streamType,
327 sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800328 format,
Eric Laurent1703cdf2011-03-07 14:52:59 -0800329 frameCount,
330 flags,
331 sharedBuffer,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800332 output,
333 0 /*epoch*/);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800334
Glenn Kastena997e7a2012-08-07 09:44:19 -0700335 if (status != NO_ERROR) {
336 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100337 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
338 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700339 mAudioTrackThread.clear();
340 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100341 //Use of direct and offloaded output streams is ref counted by audio policy manager.
342 // As getOutput was called above and resulted in an output stream to be opened,
343 // we need to release it.
344 AudioSystem::releaseOutput(output);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700345 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700346 }
347
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800348 mStatus = NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800349 mStreamType = streamType;
Glenn Kastene1c39622012-01-04 09:36:37 -0800350 mFormat = format;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800351 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800352 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800353 mUserData = user;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800354 mLoopPeriod = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800355 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700356 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800357 mNewPosition = 0;
358 mUpdatePeriod = 0;
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700359 AudioSystem::acquireAudioSessionId(mSessionId);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800360 mSequence = 1;
361 mObservedSequence = mSequence;
362 mInUnderrun = false;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100363 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800364
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800365 return NO_ERROR;
366}
367
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800368// -------------------------------------------------------------------------
369
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100370status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800371{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800372 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100373
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800374 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100375 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800376 }
377
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800378 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800379
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800380 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100381 if (previousState == STATE_PAUSED_STOPPING) {
382 mState = STATE_STOPPING;
383 } else {
384 mState = STATE_ACTIVE;
385 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800386 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
387 // reset current position as seen by client to 0
388 mProxy->setEpoch(mProxy->getEpoch() - mProxy->getPosition());
Eric Laurentec9a0322013-08-28 10:23:01 -0700389 // force refresh of remaining frames by processAudioBuffer() as last
390 // write before stop could be partial.
391 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800392 }
393 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700394 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800395
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800396 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800397 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100398 if (previousState == STATE_STOPPING) {
399 mProxy->interrupt();
400 } else {
401 t->resume();
402 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800403 } else {
404 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
405 get_sched_policy(0, &mPreviousSchedulingGroup);
406 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
407 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800408
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800409 status_t status = NO_ERROR;
410 if (!(flags & CBLK_INVALID)) {
411 status = mAudioTrack->start();
412 if (status == DEAD_OBJECT) {
413 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800414 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800415 }
416 if (flags & CBLK_INVALID) {
417 status = restoreTrack_l("start");
418 }
419
420 if (status != NO_ERROR) {
421 ALOGE("start() status %d", status);
422 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800423 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100424 if (previousState != STATE_STOPPING) {
425 t->pause();
426 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800427 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700428 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700429 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800430 }
431 }
432
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100433 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800434}
435
436void AudioTrack::stop()
437{
438 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700439 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800440 return;
441 }
442
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100443 if (isOffloaded()) {
444 mState = STATE_STOPPING;
445 } else {
446 mState = STATE_STOPPED;
447 }
448
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800449 mProxy->interrupt();
450 mAudioTrack->stop();
451 // the playback head position will reset to 0, so if a marker is set, we need
452 // to activate it again
453 mMarkerReached = false;
454#if 0
455 // Force flush if a shared buffer is used otherwise audioflinger
456 // will not stop before end of buffer is reached.
457 // It may be needed to make sure that we stop playback, likely in case looping is on.
458 if (mSharedBuffer != 0) {
459 flush_l();
460 }
461#endif
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100462
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800463 sp<AudioTrackThread> t = mAudioTrackThread;
464 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100465 if (!isOffloaded()) {
466 t->pause();
467 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800468 } else {
469 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
470 set_sched_policy(0, mPreviousSchedulingGroup);
471 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800472}
473
474bool AudioTrack::stopped() const
475{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800476 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800477 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800478}
479
480void AudioTrack::flush()
481{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800482 if (mSharedBuffer != 0) {
483 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800484 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800485 AutoMutex lock(mLock);
486 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
487 return;
488 }
489 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800490}
491
Eric Laurent1703cdf2011-03-07 14:52:59 -0800492void AudioTrack::flush_l()
493{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800494 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700495
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700496 // clear playback marker and periodic update counter
497 mMarkerPosition = 0;
498 mMarkerReached = false;
499 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100500 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700501
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800502 mState = STATE_FLUSHED;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100503 if (isOffloaded()) {
504 mProxy->interrupt();
505 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800506 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800507 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800508}
509
510void AudioTrack::pause()
511{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800512 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100513 if (mState == STATE_ACTIVE) {
514 mState = STATE_PAUSED;
515 } else if (mState == STATE_STOPPING) {
516 mState = STATE_PAUSED_STOPPING;
517 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800518 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800519 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800520 mProxy->interrupt();
521 mAudioTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800522}
523
Eric Laurentbe916aa2010-06-01 23:49:17 -0700524status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800525{
Glenn Kastenf0c49502011-11-30 09:46:04 -0800526 if (left < 0.0f || left > 1.0f || right < 0.0f || right > 1.0f) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700527 return BAD_VALUE;
528 }
529
Eric Laurent1703cdf2011-03-07 14:52:59 -0800530 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800531 mVolume[LEFT] = left;
532 mVolume[RIGHT] = right;
533
Glenn Kastene3aa6592012-12-04 12:22:46 -0800534 mProxy->setVolumeLR((uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700535
Eric Laurent59fe0102013-09-27 18:48:26 -0700536 if (isOffloaded()) {
537 mAudioTrack->signal();
538 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700539 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800540}
541
Glenn Kastenb1c09932012-02-27 16:21:04 -0800542status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800543{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800544 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700545}
546
Eric Laurent2beeb502010-07-16 07:43:46 -0700547status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700548{
Glenn Kasten05632a52012-01-03 14:22:33 -0800549 if (level < 0.0f || level > 1.0f) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700550 return BAD_VALUE;
551 }
552
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800553 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700554 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800555 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700556
557 return NO_ERROR;
558}
559
Glenn Kastena5224f32012-01-04 12:41:44 -0800560void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700561{
562 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800563 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700564 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800565}
566
Glenn Kasten3b16c762012-11-14 08:44:39 -0800567status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800568{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100569 if (mIsTimed || isOffloaded()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800570 return INVALID_OPERATION;
571 }
572
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800573 uint32_t afSamplingRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800574 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700575 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800576 }
577 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Glenn Kastend65d73c2012-06-22 17:21:07 -0700578 if (rate == 0 || rate > afSamplingRate*2 ) {
579 return BAD_VALUE;
580 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800581
Eric Laurent1703cdf2011-03-07 14:52:59 -0800582 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800583 mSampleRate = rate;
584 mProxy->setSampleRate(rate);
585
Eric Laurent57326622009-07-07 07:10:45 -0700586 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800587}
588
Glenn Kastena5224f32012-01-04 12:41:44 -0800589uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800590{
John Grossman4ff14ba2012-02-08 16:37:41 -0800591 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800592 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800593 }
594
Eric Laurent1703cdf2011-03-07 14:52:59 -0800595 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800596 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800597}
598
599status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
600{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100601 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800602 return INVALID_OPERATION;
603 }
604
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800605 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800606 ;
607 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
608 loopEnd - loopStart >= MIN_LOOP) {
609 ;
610 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800611 return BAD_VALUE;
612 }
613
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800614 AutoMutex lock(mLock);
615 // See setPosition() regarding setting parameters such as loop points or position while active
616 if (mState == STATE_ACTIVE) {
617 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700618 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800619 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800620 return NO_ERROR;
621}
622
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800623void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
624{
625 // FIXME If setting a loop also sets position to start of loop, then
626 // this is correct. Otherwise it should be removed.
627 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
628 mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0;
629 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
630}
631
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800632status_t AudioTrack::setMarkerPosition(uint32_t marker)
633{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700634 // The only purpose of setting marker position is to get a callback
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100635 if (mCbf == NULL || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700636 return INVALID_OPERATION;
637 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800638
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800639 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800640 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700641 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800642
643 return NO_ERROR;
644}
645
Glenn Kastena5224f32012-01-04 12:41:44 -0800646status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800647{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100648 if (isOffloaded()) {
649 return INVALID_OPERATION;
650 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700651 if (marker == NULL) {
652 return BAD_VALUE;
653 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800654
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800655 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800656 *marker = mMarkerPosition;
657
658 return NO_ERROR;
659}
660
661status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
662{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700663 // The only purpose of setting position update period is to get a callback
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100664 if (mCbf == NULL || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700665 return INVALID_OPERATION;
666 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800667
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800668 AutoMutex lock(mLock);
669 mNewPosition = mProxy->getPosition() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800670 mUpdatePeriod = updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800671 return NO_ERROR;
672}
673
Glenn Kastena5224f32012-01-04 12:41:44 -0800674status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800675{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100676 if (isOffloaded()) {
677 return INVALID_OPERATION;
678 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700679 if (updatePeriod == NULL) {
680 return BAD_VALUE;
681 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800682
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800683 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800684 *updatePeriod = mUpdatePeriod;
685
686 return NO_ERROR;
687}
688
689status_t AudioTrack::setPosition(uint32_t position)
690{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100691 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700692 return INVALID_OPERATION;
693 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800694 if (position > mFrameCount) {
695 return BAD_VALUE;
696 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800697
Eric Laurent1703cdf2011-03-07 14:52:59 -0800698 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800699 // Currently we require that the player is inactive before setting parameters such as position
700 // or loop points. Otherwise, there could be a race condition: the application could read the
701 // current position, compute a new position or loop parameters, and then set that position or
702 // loop parameters but it would do the "wrong" thing since the position has continued to advance
703 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
704 // to specify how it wants to handle such scenarios.
705 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700706 return INVALID_OPERATION;
707 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800708 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
709 mLoopPeriod = 0;
710 // FIXME Check whether loops and setting position are incompatible in old code.
711 // If we use setLoop for both purposes we lose the capability to set the position while looping.
712 mStaticProxy->setLoop(position, mFrameCount, 0);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700713
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800714 return NO_ERROR;
715}
716
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800717status_t AudioTrack::getPosition(uint32_t *position) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800718{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700719 if (position == NULL) {
720 return BAD_VALUE;
721 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800722
Eric Laurent1703cdf2011-03-07 14:52:59 -0800723 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100724 if (isOffloaded()) {
725 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800726
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100727 if (mOutput != 0) {
728 uint32_t halFrames;
729 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
730 }
731 *position = dspFrames;
732 } else {
733 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
734 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ? 0 :
735 mProxy->getPosition();
736 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800737 return NO_ERROR;
738}
739
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800740status_t AudioTrack::getBufferPosition(size_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800741{
742 if (mSharedBuffer == 0 || mIsTimed) {
743 return INVALID_OPERATION;
744 }
745 if (position == NULL) {
746 return BAD_VALUE;
747 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800748
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800749 AutoMutex lock(mLock);
750 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800751 return NO_ERROR;
752}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800753
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800754status_t AudioTrack::reload()
755{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100756 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800757 return INVALID_OPERATION;
758 }
759
Eric Laurent1703cdf2011-03-07 14:52:59 -0800760 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800761 // See setPosition() regarding setting parameters such as loop points or position while active
762 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700763 return INVALID_OPERATION;
764 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800765 mNewPosition = mUpdatePeriod;
766 mLoopPeriod = 0;
767 // FIXME The new code cannot reload while keeping a loop specified.
768 // Need to check how the old code handled this, and whether it's a significant change.
769 mStaticProxy->setLoop(0, mFrameCount, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800770 return NO_ERROR;
771}
772
Eric Laurentc2f1f072009-07-17 12:17:14 -0700773audio_io_handle_t AudioTrack::getOutput()
774{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800775 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100776 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800777}
778
779// must be called with mLock held
780audio_io_handle_t AudioTrack::getOutput_l()
781{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100782 if (mOutput) {
783 return mOutput;
784 } else {
785 return AudioSystem::getOutput(mStreamType,
786 mSampleRate, mFormat, mChannelMask, mFlags);
787 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700788}
789
Eric Laurentbe916aa2010-06-01 23:49:17 -0700790status_t AudioTrack::attachAuxEffect(int effectId)
791{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800792 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700793 status_t status = mAudioTrack->attachAuxEffect(effectId);
794 if (status == NO_ERROR) {
795 mAuxEffectId = effectId;
796 }
797 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700798}
799
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800800// -------------------------------------------------------------------------
801
Eric Laurent1703cdf2011-03-07 14:52:59 -0800802// must be called with mLock held
803status_t AudioTrack::createTrack_l(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800804 audio_stream_type_t streamType,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800805 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800806 audio_format_t format,
Glenn Kastene33054e2012-11-14 12:54:39 -0800807 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700808 audio_output_flags_t flags,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800809 const sp<IMemory>& sharedBuffer,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800810 audio_io_handle_t output,
811 size_t epoch)
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800812{
813 status_t status;
814 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
815 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700816 ALOGE("Could not get audioflinger");
817 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800818 }
819
Glenn Kastence8828a2013-09-16 18:07:38 -0700820 // Not all of these values are needed under all conditions, but it is easier to get them all
821
Eric Laurentd1b449a2010-05-14 03:26:45 -0700822 uint32_t afLatency;
Glenn Kastence8828a2013-09-16 18:07:38 -0700823 status = AudioSystem::getLatency(output, streamType, &afLatency);
824 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800825 ALOGE("getLatency(%d) failed status %d", output, status);
Eric Laurentd1b449a2010-05-14 03:26:45 -0700826 return NO_INIT;
827 }
828
Glenn Kastence8828a2013-09-16 18:07:38 -0700829 size_t afFrameCount;
830 status = AudioSystem::getFrameCount(output, streamType, &afFrameCount);
831 if (status != NO_ERROR) {
832 ALOGE("getFrameCount(output=%d, streamType=%d) status %d", output, streamType, status);
833 return NO_INIT;
834 }
835
836 uint32_t afSampleRate;
837 status = AudioSystem::getSamplingRate(output, streamType, &afSampleRate);
838 if (status != NO_ERROR) {
839 ALOGE("getSamplingRate(output=%d, streamType=%d) status %d", output, streamType, status);
840 return NO_INIT;
841 }
842
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700843 // Client decides whether the track is TIMED (see below), but can only express a preference
844 // for FAST. Server will perform additional tests.
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700845 if ((flags & AUDIO_OUTPUT_FLAG_FAST) && !(
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700846 // either of these use cases:
847 // use case 1: shared buffer
848 (sharedBuffer != 0) ||
849 // use case 2: callback handler
850 (mCbf != NULL))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800851 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -0700852 // once denied, do not request again if IAudioTrack is re-created
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700853 flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten093000f2012-05-03 09:35:36 -0700854 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700855 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700856 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700857
Glenn Kastence8828a2013-09-16 18:07:38 -0700858 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
859 // n = 1 fast track; nBuffering is ignored
860 // n = 2 normal track, no sample rate conversion
861 // n = 3 normal track, with sample rate conversion
862 // (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering)
863 // n > 3 very high latency or very small notification interval; nBuffering is ignored
864 const uint32_t nBuffering = (sampleRate == afSampleRate) ? 2 : 3;
865
Eric Laurentd1b449a2010-05-14 03:26:45 -0700866 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700867
Dima Zavinfce7a472011-04-19 22:30:36 -0700868 if (!audio_is_linear_pcm(format)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700869
Eric Laurentd1b449a2010-05-14 03:26:45 -0700870 if (sharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700871 // Same comment as below about ignoring frameCount parameter for set()
Eric Laurentd1b449a2010-05-14 03:26:45 -0700872 frameCount = sharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -0700873 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700874 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700875 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100876 if (mNotificationFramesAct != frameCount) {
877 mNotificationFramesAct = frameCount;
878 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700879 } else if (sharedBuffer != 0) {
880
Glenn Kastena42ff002012-11-14 12:47:55 -0800881 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -0700882 // 8-bit data in shared memory is not currently supported by AudioFlinger
883 size_t alignment = /* format == AUDIO_FORMAT_PCM_8_BIT ? 1 : */ 2;
Glenn Kastena42ff002012-11-14 12:47:55 -0800884 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700885 // More than 2 channels does not require stronger alignment than stereo
886 alignment <<= 1;
887 }
Glenn Kastena42ff002012-11-14 12:47:55 -0800888 if (((size_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
889 ALOGE("Invalid buffer alignment: address %p, channel count %u",
890 sharedBuffer->pointer(), mChannelCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700891 return BAD_VALUE;
892 }
893
894 // When initializing a shared buffer AudioTrack via constructors,
895 // there's no frameCount parameter.
896 // But when initializing a shared buffer AudioTrack via set(),
897 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kastena42ff002012-11-14 12:47:55 -0800898 frameCount = sharedBuffer->size()/mChannelCount/sizeof(int16_t);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700899
900 } else if (!(flags & AUDIO_OUTPUT_FLAG_FAST)) {
901
902 // FIXME move these calculations and associated checks to server
Glenn Kastene0fa4672012-04-24 14:35:14 -0700903
Eric Laurentd1b449a2010-05-14 03:26:45 -0700904 // Ensure that buffer depth covers at least audio hardware latency
905 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Glenn Kastenbb6f0a02013-06-03 15:00:29 -0700906 ALOGV("afFrameCount=%d, minBufCount=%d, afSampleRate=%u, afLatency=%d",
907 afFrameCount, minBufCount, afSampleRate, afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700908 if (minBufCount <= nBuffering) {
909 minBufCount = nBuffering;
Glenn Kasten7c027242012-12-26 14:43:16 -0800910 }
Eric Laurentd1b449a2010-05-14 03:26:45 -0700911
Glenn Kastene33054e2012-11-14 12:54:39 -0800912 size_t minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
913 ALOGV("minFrameCount: %u, afFrameCount=%d, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -0800914 ", afLatency=%d",
915 minFrameCount, afFrameCount, minBufCount, sampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700916
917 if (frameCount == 0) {
918 frameCount = minFrameCount;
Glenn Kastence8828a2013-09-16 18:07:38 -0700919 } else if (frameCount < minFrameCount) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700920 // not ALOGW because it happens all the time when playing key clicks over A2DP
921 ALOGV("Minimum buffer size corrected from %d to %d",
922 frameCount, minFrameCount);
923 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800924 }
Glenn Kastence8828a2013-09-16 18:07:38 -0700925 // Make sure that application is notified with sufficient margin before underrun
926 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
927 mNotificationFramesAct = frameCount/nBuffering;
928 }
Eric Laurentd1b449a2010-05-14 03:26:45 -0700929
Glenn Kastene0fa4672012-04-24 14:35:14 -0700930 } else {
931 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -0700932 }
933
Glenn Kastena075db42012-03-06 11:22:44 -0800934 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
935 if (mIsTimed) {
936 trackFlags |= IAudioFlinger::TRACK_TIMED;
937 }
Glenn Kasten3acbd052012-02-28 10:39:56 -0800938
939 pid_t tid = -1;
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700940 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700941 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800942 if (mAudioTrackThread != 0) {
943 tid = mAudioTrackThread->getTid();
944 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700945 }
946
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100947 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
948 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
949 }
950
Glenn Kasten8d6cc842012-02-03 11:06:53 -0800951 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800952 sampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -0700953 // AudioFlinger only sees 16-bit PCM
954 format == AUDIO_FORMAT_PCM_8_BIT ?
955 AUDIO_FORMAT_PCM_16_BIT : format,
Glenn Kastena42ff002012-11-14 12:47:55 -0800956 mChannelMask,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800957 frameCount,
Glenn Kastene0b07172012-11-06 15:03:34 -0800958 &trackFlags,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800959 sharedBuffer,
960 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800961 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700962 &mSessionId,
Glenn Kastend054c322013-07-12 12:59:20 -0700963 mName,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800964 &status);
965
966 if (track == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000967 ALOGE("AudioFlinger could not create track, status: %d", status);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800968 return status;
969 }
Glenn Kastend2c38fc2012-11-01 14:58:02 -0700970 sp<IMemory> iMem = track->getCblk();
971 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000972 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800973 return NO_INIT;
974 }
Glenn Kasten53cec222013-08-29 09:01:02 -0700975 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800976 if (mAudioTrack != 0) {
977 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
978 mDeathNotifier.clear();
979 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800980 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -0700981 mCblkMemory = iMem;
982 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMem->pointer());
983 mCblk = cblk;
Glenn Kastenb6037442012-11-14 13:42:25 -0800984 size_t temp = cblk->frameCount_;
985 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
986 // In current design, AudioTrack client checks and ensures frame count validity before
987 // passing it to AudioFlinger so AudioFlinger should not return a different value except
988 // for fast track as it uses a special method of assigning frame count.
989 ALOGW("Requested frameCount %u but received frameCount %u", frameCount, temp);
990 }
991 frameCount = temp;
Glenn Kastena07f17c2013-04-23 12:39:37 -0700992 mAwaitBoost = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800993 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -0800994 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Glenn Kastenb6037442012-11-14 13:42:25 -0800995 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %u", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -0700996 mAwaitBoost = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800997 if (sharedBuffer == 0) {
998 // double-buffering is not required for fast tracks, due to tighter scheduling
999 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount) {
1000 mNotificationFramesAct = frameCount;
1001 }
1002 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001003 } else {
Glenn Kastenb6037442012-11-14 13:42:25 -08001004 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %u", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001005 // once denied, do not request again if IAudioTrack is re-created
1006 flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST);
1007 mFlags = flags;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001008 if (sharedBuffer == 0) {
Glenn Kastence8828a2013-09-16 18:07:38 -07001009 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1010 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001011 }
1012 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001013 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001014 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001015 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
1016 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1017 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1018 } else {
1019 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
1020 flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1021 mFlags = flags;
1022 return NO_INIT;
1023 }
1024 }
1025
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001026 mRefreshRemaining = true;
1027
1028 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1029 // is the value of pointer() for the shared buffer, otherwise buffers points
1030 // immediately after the control block. This address is for the mapping within client
1031 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1032 void* buffers;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001033 if (sharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001034 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001035 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001036 buffers = sharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001037 }
1038
Eric Laurent2beeb502010-07-16 07:43:46 -07001039 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001040 // FIXME don't believe this lie
Glenn Kastenb6037442012-11-14 13:42:25 -08001041 mLatency = afLatency + (1000*frameCount) / sampleRate;
1042 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001043 // If IAudioTrack is re-created, don't let the requested frameCount
1044 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001045 if (frameCount > mReqFrameCount) {
1046 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001047 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001048
1049 // update proxy
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001050 if (sharedBuffer == 0) {
1051 mStaticProxy.clear();
1052 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1053 } else {
1054 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1055 mProxy = mStaticProxy;
1056 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001057 mProxy->setVolumeLR((uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) |
1058 uint16_t(mVolume[LEFT] * 0x1000));
1059 mProxy->setSendLevel(mSendLevel);
1060 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001061 mProxy->setEpoch(epoch);
1062 mProxy->setMinimum(mNotificationFramesAct);
1063
1064 mDeathNotifier = new DeathNotifier(this);
1065 mAudioTrack->asBinder()->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001066
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001067 return NO_ERROR;
1068}
1069
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001070status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1071{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001072 if (audioBuffer == NULL) {
1073 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001074 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001075 if (mTransfer != TRANSFER_OBTAIN) {
1076 audioBuffer->frameCount = 0;
1077 audioBuffer->size = 0;
1078 audioBuffer->raw = NULL;
1079 return INVALID_OPERATION;
1080 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001081
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001082 const struct timespec *requested;
1083 if (waitCount == -1) {
1084 requested = &ClientProxy::kForever;
1085 } else if (waitCount == 0) {
1086 requested = &ClientProxy::kNonBlocking;
1087 } else if (waitCount > 0) {
1088 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
1089 struct timespec timeout;
1090 timeout.tv_sec = ms / 1000;
1091 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1092 requested = &timeout;
1093 } else {
1094 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1095 requested = NULL;
1096 }
1097 return obtainBuffer(audioBuffer, requested);
1098}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001099
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001100status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1101 struct timespec *elapsed, size_t *nonContig)
1102{
1103 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1104 uint32_t oldSequence = 0;
1105 uint32_t newSequence;
1106
1107 Proxy::Buffer buffer;
1108 status_t status = NO_ERROR;
1109
1110 static const int32_t kMaxTries = 5;
1111 int32_t tryCounter = kMaxTries;
1112
1113 do {
1114 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1115 // keep them from going away if another thread re-creates the track during obtainBuffer()
1116 sp<AudioTrackClientProxy> proxy;
1117 sp<IMemory> iMem;
1118
1119 { // start of lock scope
1120 AutoMutex lock(mLock);
1121
1122 newSequence = mSequence;
1123 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1124 if (status == DEAD_OBJECT) {
1125 // re-create track, unless someone else has already done so
1126 if (newSequence == oldSequence) {
1127 status = restoreTrack_l("obtainBuffer");
1128 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001129 buffer.mFrameCount = 0;
1130 buffer.mRaw = NULL;
1131 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001132 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001133 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001134 }
1135 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001136 oldSequence = newSequence;
1137
1138 // Keep the extra references
1139 proxy = mProxy;
1140 iMem = mCblkMemory;
1141
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001142 if (mState == STATE_STOPPING) {
1143 status = -EINTR;
1144 buffer.mFrameCount = 0;
1145 buffer.mRaw = NULL;
1146 buffer.mNonContig = 0;
1147 break;
1148 }
1149
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001150 // Non-blocking if track is stopped or paused
1151 if (mState != STATE_ACTIVE) {
1152 requested = &ClientProxy::kNonBlocking;
1153 }
1154
1155 } // end of lock scope
1156
1157 buffer.mFrameCount = audioBuffer->frameCount;
1158 // FIXME starts the requested timeout and elapsed over from scratch
1159 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1160
1161 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1162
1163 audioBuffer->frameCount = buffer.mFrameCount;
1164 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1165 audioBuffer->raw = buffer.mRaw;
1166 if (nonContig != NULL) {
1167 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001168 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001169 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001170}
1171
1172void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1173{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001174 if (mTransfer == TRANSFER_SHARED) {
1175 return;
1176 }
1177
1178 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1179 if (stepCount == 0) {
1180 return;
1181 }
1182
1183 Proxy::Buffer buffer;
1184 buffer.mFrameCount = stepCount;
1185 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001186
Eric Laurent1703cdf2011-03-07 14:52:59 -08001187 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001188 mInUnderrun = false;
1189 mProxy->releaseBuffer(&buffer);
1190
1191 // restart track if it was disabled by audioflinger due to previous underrun
1192 if (mState == STATE_ACTIVE) {
1193 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001194 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastend054c322013-07-12 12:59:20 -07001195 ALOGW("releaseBuffer() track %p name=%s disabled due to previous underrun, restarting",
1196 this, mName.string());
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001197 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001198 mAudioTrack->start();
1199 }
1200 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001201}
1202
1203// -------------------------------------------------------------------------
1204
1205ssize_t AudioTrack::write(const void* buffer, size_t userSize)
1206{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001207 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001208 return INVALID_OPERATION;
1209 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001210
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001211 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001212 // Sanity-check: user is most-likely passing an error code, and it would
1213 // make the return value ambiguous (actualSize vs error).
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001214 ALOGE("AudioTrack::write(buffer=%p, size=%u (%d)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001215 return BAD_VALUE;
1216 }
1217
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001218 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001219 Buffer audioBuffer;
1220
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001221 while (userSize >= mFrameSize) {
1222 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001223
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001224 status_t err = obtainBuffer(&audioBuffer, &ClientProxy::kForever);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001225 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001226 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001227 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001228 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001229 return ssize_t(err);
1230 }
1231
1232 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001233 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001234 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001235 toWrite = audioBuffer.size >> 1;
1236 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001237 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001238 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001239 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001240 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001241 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001242 userSize -= toWrite;
1243 written += toWrite;
1244
1245 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001246 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001247
1248 return written;
1249}
1250
1251// -------------------------------------------------------------------------
1252
John Grossman4ff14ba2012-02-08 16:37:41 -08001253TimedAudioTrack::TimedAudioTrack() {
1254 mIsTimed = true;
1255}
1256
1257status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1258{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001259 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001260 status_t result = UNKNOWN_ERROR;
1261
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001262#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001263 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1264 // while we are accessing the cblk
1265 sp<IAudioTrack> audioTrack = mAudioTrack;
1266 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001267#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001268
John Grossman4ff14ba2012-02-08 16:37:41 -08001269 // If the track is not invalid already, try to allocate a buffer. alloc
1270 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001271 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001272 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001273 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001274 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1275 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001276 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001277 }
1278 }
1279
1280 // If the track is invalid at this point, attempt to restore it. and try the
1281 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001282 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001283 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001284
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001285 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001286 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001287 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001288 }
1289
1290 return result;
1291}
1292
1293status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1294 int64_t pts)
1295{
Eric Laurentdf839842012-05-31 14:27:14 -07001296 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1297 {
1298 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001299 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001300 // restart track if it was disabled by audioflinger due to previous underrun
1301 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001302 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1303 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001304 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001305 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001306 mAudioTrack->start();
1307 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001308 }
Eric Laurentdf839842012-05-31 14:27:14 -07001309 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001310}
1311
1312status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1313 TargetTimeline target)
1314{
1315 return mAudioTrack->setMediaTimeTransform(xform, target);
1316}
1317
1318// -------------------------------------------------------------------------
1319
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001320nsecs_t AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001321{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001322 // Currently the AudioTrack thread is not created if there are no callbacks.
1323 // Would it ever make sense to run the thread, even without callbacks?
1324 // If so, then replace this by checks at each use for mCbf != NULL.
1325 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1326
Eric Laurent1703cdf2011-03-07 14:52:59 -08001327 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001328 if (mAwaitBoost) {
1329 mAwaitBoost = false;
1330 mLock.unlock();
1331 static const int32_t kMaxTries = 5;
1332 int32_t tryCounter = kMaxTries;
1333 uint32_t pollUs = 10000;
1334 do {
1335 int policy = sched_getscheduler(0);
1336 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1337 break;
1338 }
1339 usleep(pollUs);
1340 pollUs <<= 1;
1341 } while (tryCounter-- > 0);
1342 if (tryCounter < 0) {
1343 ALOGE("did not receive expected priority boost on time");
1344 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001345 // Run again immediately
1346 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001347 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001348
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001349 // Can only reference mCblk while locked
1350 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001351 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001352
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001353 // Check for track invalidation
1354 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001355 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1356 // AudioSystem cache. We should not exit here but after calling the callback so
1357 // that the upper layers can recreate the track
1358 if (!isOffloaded() || (mSequence == mObservedSequence)) {
1359 status_t status = restoreTrack_l("processAudioBuffer");
1360 mLock.unlock();
1361 // Run again immediately, but with a new IAudioTrack
1362 return 0;
1363 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001364 }
1365
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001366 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001367 bool active = mState == STATE_ACTIVE;
1368
1369 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1370 bool newUnderrun = false;
1371 if (flags & CBLK_UNDERRUN) {
1372#if 0
1373 // Currently in shared buffer mode, when the server reaches the end of buffer,
1374 // the track stays active in continuous underrun state. It's up to the application
1375 // to pause or stop the track, or set the position to a new offset within buffer.
1376 // This was some experimental code to auto-pause on underrun. Keeping it here
1377 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1378 if (mTransfer == TRANSFER_SHARED) {
1379 mState = STATE_PAUSED;
1380 active = false;
1381 }
1382#endif
1383 if (!mInUnderrun) {
1384 mInUnderrun = true;
1385 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001386 }
1387 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001388
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001389 // Get current position of server
1390 size_t position = mProxy->getPosition();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001391
1392 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001393 bool markerReached = false;
1394 size_t markerPosition = mMarkerPosition;
1395 // FIXME fails for wraparound, need 64 bits
1396 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1397 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001398 }
1399
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001400 // Determine number of new position callback(s) that will be needed, while locked
1401 size_t newPosCount = 0;
1402 size_t newPosition = mNewPosition;
1403 size_t updatePeriod = mUpdatePeriod;
1404 // FIXME fails for wraparound, need 64 bits
1405 if (updatePeriod > 0 && position >= newPosition) {
1406 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1407 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001408 }
1409
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001410 // Cache other fields that will be needed soon
1411 uint32_t loopPeriod = mLoopPeriod;
1412 uint32_t sampleRate = mSampleRate;
1413 size_t notificationFrames = mNotificationFramesAct;
1414 if (mRefreshRemaining) {
1415 mRefreshRemaining = false;
1416 mRemainingFrames = notificationFrames;
1417 mRetryOnPartialBuffer = false;
1418 }
1419 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001420 uint32_t sequence = mSequence;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001421
1422 // These fields don't need to be cached, because they are assigned only by set():
1423 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1424 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1425
1426 mLock.unlock();
1427
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001428 if (waitStreamEnd) {
1429 AutoMutex lock(mLock);
1430
1431 sp<AudioTrackClientProxy> proxy = mProxy;
1432 sp<IMemory> iMem = mCblkMemory;
1433
1434 struct timespec timeout;
1435 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1436 timeout.tv_nsec = 0;
1437
1438 mLock.unlock();
1439 status_t status = mProxy->waitStreamEndDone(&timeout);
1440 mLock.lock();
1441 switch (status) {
1442 case NO_ERROR:
1443 case DEAD_OBJECT:
1444 case TIMED_OUT:
1445 mLock.unlock();
1446 mCbf(EVENT_STREAM_END, mUserData, NULL);
1447 mLock.lock();
1448 if (mState == STATE_STOPPING) {
1449 mState = STATE_STOPPED;
1450 if (status != DEAD_OBJECT) {
1451 return NS_INACTIVE;
1452 }
1453 }
1454 return 0;
1455 default:
1456 return 0;
1457 }
1458 }
1459
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001460 // perform callbacks while unlocked
1461 if (newUnderrun) {
1462 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1463 }
1464 // FIXME we will miss loops if loop cycle was signaled several times since last call
1465 // to processAudioBuffer()
1466 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1467 mCbf(EVENT_LOOP_END, mUserData, NULL);
1468 }
1469 if (flags & CBLK_BUFFER_END) {
1470 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1471 }
1472 if (markerReached) {
1473 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1474 }
1475 while (newPosCount > 0) {
1476 size_t temp = newPosition;
1477 mCbf(EVENT_NEW_POS, mUserData, &temp);
1478 newPosition += updatePeriod;
1479 newPosCount--;
1480 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001481
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001482 if (mObservedSequence != sequence) {
1483 mObservedSequence = sequence;
1484 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001485 // for offloaded tracks, just wait for the upper layers to recreate the track
1486 if (isOffloaded()) {
1487 return NS_INACTIVE;
1488 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001489 }
1490
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001491 // if inactive, then don't run me again until re-started
1492 if (!active) {
1493 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001494 }
1495
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001496 // Compute the estimated time until the next timed event (position, markers, loops)
1497 // FIXME only for non-compressed audio
1498 uint32_t minFrames = ~0;
1499 if (!markerReached && position < markerPosition) {
1500 minFrames = markerPosition - position;
1501 }
1502 if (loopPeriod > 0 && loopPeriod < minFrames) {
1503 minFrames = loopPeriod;
1504 }
1505 if (updatePeriod > 0 && updatePeriod < minFrames) {
1506 minFrames = updatePeriod;
1507 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001508
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001509 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1510 static const uint32_t kPoll = 0;
1511 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1512 minFrames = kPoll * notificationFrames;
1513 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001514
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001515 // Convert frame units to time units
1516 nsecs_t ns = NS_WHENEVER;
1517 if (minFrames != (uint32_t) ~0) {
1518 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1519 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1520 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1521 }
1522
1523 // If not supplying data by EVENT_MORE_DATA, then we're done
1524 if (mTransfer != TRANSFER_CALLBACK) {
1525 return ns;
1526 }
1527
1528 struct timespec timeout;
1529 const struct timespec *requested = &ClientProxy::kForever;
1530 if (ns != NS_WHENEVER) {
1531 timeout.tv_sec = ns / 1000000000LL;
1532 timeout.tv_nsec = ns % 1000000000LL;
1533 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1534 requested = &timeout;
1535 }
1536
1537 while (mRemainingFrames > 0) {
1538
1539 Buffer audioBuffer;
1540 audioBuffer.frameCount = mRemainingFrames;
1541 size_t nonContig;
1542 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1543 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1544 "obtainBuffer() err=%d frameCount=%u", err, audioBuffer.frameCount);
1545 requested = &ClientProxy::kNonBlocking;
1546 size_t avail = audioBuffer.frameCount + nonContig;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001547 ALOGV("obtainBuffer(%u) returned %u = %u + %u err %d",
1548 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001549 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001550 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1551 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001552 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001553 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001554 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1555 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001556 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001557
Eric Laurent42a6f422013-08-29 14:35:05 -07001558 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001559 mRetryOnPartialBuffer = false;
1560 if (avail < mRemainingFrames) {
1561 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1562 if (ns < 0 || myns < ns) {
1563 ns = myns;
1564 }
1565 return ns;
1566 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001567 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001568
1569 // Divide buffer size by 2 to take into account the expansion
1570 // due to 8 to 16 bit conversion: the callback must fill only half
1571 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001572 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001573 audioBuffer.size >>= 1;
1574 }
1575
1576 size_t reqSize = audioBuffer.size;
1577 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001578 size_t writtenSize = audioBuffer.size;
1579 size_t writtenFrames = writtenSize / mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001580
1581 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001582 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
1583 ALOGE("EVENT_MORE_DATA requested %u bytes but callback returned %d bytes",
1584 reqSize, (int) writtenSize);
1585 return NS_NEVER;
1586 }
1587
1588 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001589 // The callback is done filling buffers
1590 // Keep this thread going to handle timed events and
1591 // still try to get more data in intervals of WAIT_PERIOD_MS
1592 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001593 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001594 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001595
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001596 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001597 // 8 to 16 bit conversion, note that source and destination are the same address
1598 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001599 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001600 }
1601
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001602 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1603 audioBuffer.frameCount = releasedFrames;
1604 mRemainingFrames -= releasedFrames;
1605 if (misalignment >= releasedFrames) {
1606 misalignment -= releasedFrames;
1607 } else {
1608 misalignment = 0;
1609 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001610
1611 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001612
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001613 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1614 // if callback doesn't like to accept the full chunk
1615 if (writtenSize < reqSize) {
1616 continue;
1617 }
1618
1619 // There could be enough non-contiguous frames available to satisfy the remaining request
1620 if (mRemainingFrames <= nonContig) {
1621 continue;
1622 }
1623
1624#if 0
1625 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1626 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1627 // that total to a sum == notificationFrames.
1628 if (0 < misalignment && misalignment <= mRemainingFrames) {
1629 mRemainingFrames = misalignment;
1630 return (mRemainingFrames * 1100000000LL) / sampleRate;
1631 }
1632#endif
1633
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001634 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001635 mRemainingFrames = notificationFrames;
1636 mRetryOnPartialBuffer = true;
1637
1638 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1639 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001640}
1641
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001642status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001643{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001644 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
1645 isOffloaded() ? "Offloaded" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001646 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001647 status_t result;
1648
Glenn Kastena47f3162012-11-07 10:13:08 -08001649 // refresh the audio configuration cache in this process to make sure we get new
1650 // output parameters in getOutput_l() and createTrack_l()
1651 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001652
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001653 if (isOffloaded()) {
1654 return DEAD_OBJECT;
1655 }
1656
1657 // force new output query from audio policy manager;
1658 mOutput = 0;
1659 audio_io_handle_t output = getOutput_l();
1660
Glenn Kastena47f3162012-11-07 10:13:08 -08001661 // if the new IAudioTrack is created, createTrack_l() will modify the
1662 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1663 // It will also delete the strong references on previous IAudioTrack and IMemory
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001664
1665 // take the frames that will be lost by track recreation into account in saved position
1666 size_t position = mProxy->getPosition() + mProxy->getFramesFilled();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001667 mNewPosition = position + mUpdatePeriod;
1668 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
Glenn Kastena47f3162012-11-07 10:13:08 -08001669 result = createTrack_l(mStreamType,
Glenn Kastene3aa6592012-12-04 12:22:46 -08001670 mSampleRate,
Glenn Kastena47f3162012-11-07 10:13:08 -08001671 mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001672 mReqFrameCount, // so that frame count never goes down
Glenn Kastena47f3162012-11-07 10:13:08 -08001673 mFlags,
1674 mSharedBuffer,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001675 output,
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001676 position /*epoch*/);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001677
Glenn Kastena47f3162012-11-07 10:13:08 -08001678 if (result == NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001679 // continue playback from last known position, but
1680 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1681 if (mStaticProxy != NULL) {
1682 mLoopPeriod = 0;
1683 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1684 }
1685 // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1686 // track destruction have been played? This is critical for SoundPool implementation
1687 // This must be broken, and needs to be tested/debugged.
1688#if 0
Glenn Kastena47f3162012-11-07 10:13:08 -08001689 // restore write index and set other indexes to reflect empty buffer status
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001690 if (!strcmp(from, "start")) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001691 // Make sure that a client relying on callback events indicating underrun or
1692 // the actual amount of audio frames played (e.g SoundPool) receives them.
1693 if (mSharedBuffer == 0) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001694 // restart playback even if buffer is not completely filled.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001695 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001696 }
1697 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001698#endif
1699 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001700 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001701 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001702 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001703 if (result != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001704 //Use of direct and offloaded output streams is ref counted by audio policy manager.
1705 // As getOutput was called above and resulted in an output stream to be opened,
1706 // we need to release it.
1707 AudioSystem::releaseOutput(output);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001708 ALOGW("restoreTrack_l() failed status %d", result);
1709 mState = STATE_STOPPED;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001710 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001711
1712 return result;
1713}
1714
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001715status_t AudioTrack::setParameters(const String8& keyValuePairs)
1716{
1717 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001718 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001719}
1720
Glenn Kastence703742013-07-19 16:33:58 -07001721status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1722{
Glenn Kasten53cec222013-08-29 09:01:02 -07001723 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001724 // FIXME not implemented for fast tracks; should use proxy and SSQ
1725 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1726 return INVALID_OPERATION;
1727 }
1728 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
1729 return INVALID_OPERATION;
1730 }
1731 status_t status = mAudioTrack->getTimestamp(timestamp);
1732 if (status == NO_ERROR) {
1733 timestamp.mPosition += mProxy->getEpoch();
1734 }
1735 return status;
Glenn Kastence703742013-07-19 16:33:58 -07001736}
1737
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001738String8 AudioTrack::getParameters(const String8& keys)
1739{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001740 if (mOutput) {
1741 return AudioSystem::getParameters(mOutput, keys);
1742 } else {
1743 return String8::empty();
1744 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001745}
1746
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001747status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1748{
1749
1750 const size_t SIZE = 256;
1751 char buffer[SIZE];
1752 String8 result;
1753
1754 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001755 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
1756 mVolume[0], mVolume[1]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001757 result.append(buffer);
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001758 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001759 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001760 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001761 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001762 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001763 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001764 result.append(buffer);
1765 ::write(fd, result.string(), result.size());
1766 return NO_ERROR;
1767}
1768
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001769uint32_t AudioTrack::getUnderrunFrames() const
1770{
1771 AutoMutex lock(mLock);
1772 return mProxy->getUnderrunFrames();
1773}
1774
1775// =========================================================================
1776
1777void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who)
1778{
1779 sp<AudioTrack> audioTrack = mAudioTrack.promote();
1780 if (audioTrack != 0) {
1781 AutoMutex lock(audioTrack->mLock);
1782 audioTrack->mProxy->binderDied();
1783 }
1784}
1785
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001786// =========================================================================
1787
1788AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07001789 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
1790 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08001791{
1792}
1793
1794AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001795{
1796}
1797
1798bool AudioTrack::AudioTrackThread::threadLoop()
1799{
Glenn Kasten3acbd052012-02-28 10:39:56 -08001800 {
1801 AutoMutex _l(mMyLock);
1802 if (mPaused) {
1803 mMyCond.wait(mMyLock);
1804 // caller will check for exitPending()
1805 return true;
1806 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07001807 if (mIgnoreNextPausedInt) {
1808 mIgnoreNextPausedInt = false;
1809 mPausedInt = false;
1810 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001811 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001812 if (mPausedNs > 0) {
1813 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
1814 } else {
1815 mMyCond.wait(mMyLock);
1816 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07001817 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001818 return true;
1819 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001820 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001821 nsecs_t ns = mReceiver.processAudioBuffer(this);
1822 switch (ns) {
1823 case 0:
1824 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001825 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001826 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001827 return true;
1828 case NS_NEVER:
1829 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001830 case NS_WHENEVER:
1831 // FIXME increase poll interval, or make event-driven
1832 ns = 1000000000LL;
1833 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001834 default:
1835 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001836 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001837 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07001838 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001839}
1840
Glenn Kasten3acbd052012-02-28 10:39:56 -08001841void AudioTrack::AudioTrackThread::requestExit()
1842{
1843 // must be in this order to avoid a race condition
1844 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07001845 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08001846}
1847
1848void AudioTrack::AudioTrackThread::pause()
1849{
1850 AutoMutex _l(mMyLock);
1851 mPaused = true;
1852}
1853
1854void AudioTrack::AudioTrackThread::resume()
1855{
1856 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07001857 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07001858 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08001859 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07001860 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001861 mMyCond.signal();
1862 }
1863}
1864
Glenn Kasten5a6cd222013-09-20 09:20:45 -07001865void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
1866{
1867 AutoMutex _l(mMyLock);
1868 mPausedInt = true;
1869 mPausedNs = ns;
1870}
1871
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001872}; // namespace android