blob: 3f4cbc2ff71f7b671788644e37d4d085b0ac195f [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
Glenn Kasten9f80dd22012-12-18 15:57:32 -080030#define WAIT_PERIOD_MS 10
Glenn Kasten511754b2012-01-11 09:52:19 -080031
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080032namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080033// ---------------------------------------------------------------------------
34
35// static
36status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080037 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080038 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080039 uint32_t sampleRate)
40{
Glenn Kastend65d73c2012-06-22 17:21:07 -070041 if (frameCount == NULL) {
42 return BAD_VALUE;
43 }
Glenn Kasten04cd0182012-06-25 11:49:27 -070044
45 // default to 0 in case of error
46 *frameCount = 0;
47
Glenn Kastene0fa4672012-04-24 14:35:14 -070048 // FIXME merge with similar code in createTrack_l(), except we're missing
49 // some information here that is available in createTrack_l():
50 // audio_io_handle_t output
51 // audio_format_t format
52 // audio_channel_mask_t channelMask
53 // audio_output_flags_t flags
Glenn Kasten3b16c762012-11-14 08:44:39 -080054 uint32_t afSampleRate;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080055 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
56 return NO_INIT;
57 }
Glenn Kastene33054e2012-11-14 12:54:39 -080058 size_t afFrameCount;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080059 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
60 return NO_INIT;
61 }
62 uint32_t afLatency;
63 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
64 return NO_INIT;
65 }
66
67 // Ensure that buffer depth covers at least audio hardware latency
68 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080069 if (minBufCount < 2) {
70 minBufCount = 2;
71 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +080072
73 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
Glenn Kastene53b9ea2012-03-12 16:29:55 -070074 afFrameCount * minBufCount * sampleRate / afSampleRate;
Glenn Kasten3acbd052012-02-28 10:39:56 -080075 ALOGV("getMinFrameCount=%d: afFrameCount=%d, minBufCount=%d, afSampleRate=%d, afLatency=%d",
76 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +080077 return NO_ERROR;
78}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080079
80// ---------------------------------------------------------------------------
81
82AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -070083 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -080084 mIsTimed(false),
85 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Glenn Kasten9f80dd22012-12-18 15:57:32 -080086 mPreviousSchedulingGroup(SP_DEFAULT)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080087{
88}
89
90AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -080091 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080092 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -080093 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -070094 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080095 int frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -070096 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080097 callback_t cbf,
98 void* user,
Eric Laurentbe916aa2010-06-01 23:49:17 -070099 int notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800100 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000101 transfer_type transferType,
102 const audio_offload_info_t *offloadInfo)
Glenn Kasten87913512011-06-22 16:15:25 -0700103 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800104 mIsTimed(false),
105 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800106 mPreviousSchedulingGroup(SP_DEFAULT)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800107{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700108 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700109 frameCount, flags, cbf, user, notificationFrames,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000110 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800111}
112
Andreas Huberc8139852012-01-18 10:51:55 -0800113AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800114 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800115 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800116 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700117 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800118 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700119 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800120 callback_t cbf,
121 void* user,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700122 int notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800123 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000124 transfer_type transferType,
125 const audio_offload_info_t *offloadInfo)
Glenn Kasten87913512011-06-22 16:15:25 -0700126 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800127 mIsTimed(false),
128 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800129 mPreviousSchedulingGroup(SP_DEFAULT)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800130{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700131 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800132 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000133 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800134}
135
136AudioTrack::~AudioTrack()
137{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800138 if (mStatus == NO_ERROR) {
139 // Make sure that callback function exits in the case where
140 // it is looping on buffer full condition in obtainBuffer().
141 // Otherwise the callback thread will never exit.
142 stop();
143 if (mAudioTrackThread != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800144 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800145 mAudioTrackThread->requestExitAndWait();
146 mAudioTrackThread.clear();
147 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800148 if (mAudioTrack != 0) {
149 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
150 mAudioTrack.clear();
151 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800152 IPCThreadState::self()->flushCommands();
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700153 AudioSystem::releaseAudioSessionId(mSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800154 }
155}
156
157status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800158 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800159 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800160 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700161 audio_channel_mask_t channelMask,
Glenn Kastene33054e2012-11-14 12:54:39 -0800162 int frameCountInt,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700163 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800164 callback_t cbf,
165 void* user,
166 int notificationFrames,
167 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700168 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800169 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000170 transfer_type transferType,
171 const audio_offload_info_t *offloadInfo)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800172{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800173 switch (transferType) {
174 case TRANSFER_DEFAULT:
175 if (sharedBuffer != 0) {
176 transferType = TRANSFER_SHARED;
177 } else if (cbf == NULL || threadCanCallJava) {
178 transferType = TRANSFER_SYNC;
179 } else {
180 transferType = TRANSFER_CALLBACK;
181 }
182 break;
183 case TRANSFER_CALLBACK:
184 if (cbf == NULL || sharedBuffer != 0) {
185 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
186 return BAD_VALUE;
187 }
188 break;
189 case TRANSFER_OBTAIN:
190 case TRANSFER_SYNC:
191 if (sharedBuffer != 0) {
192 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
193 return BAD_VALUE;
194 }
195 break;
196 case TRANSFER_SHARED:
197 if (sharedBuffer == 0) {
198 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
199 return BAD_VALUE;
200 }
201 break;
202 default:
203 ALOGE("Invalid transfer type %d", transferType);
204 return BAD_VALUE;
205 }
206 mTransfer = transferType;
207
Glenn Kastene33054e2012-11-14 12:54:39 -0800208 // FIXME "int" here is legacy and will be replaced by size_t later
209 if (frameCountInt < 0) {
210 ALOGE("Invalid frame count %d", frameCountInt);
211 return BAD_VALUE;
212 }
213 size_t frameCount = frameCountInt;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800214
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700215 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
216 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800217
Glenn Kastene33054e2012-11-14 12:54:39 -0800218 ALOGV("set() streamType %d frameCount %u flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700219
Eric Laurent1703cdf2011-03-07 14:52:59 -0800220 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800221
Eric Laurent1dd70b92009-04-21 07:56:33 -0700222 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000223 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800224 return INVALID_OPERATION;
225 }
226
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800227 // handle default values first.
Dima Zavinfce7a472011-04-19 22:30:36 -0700228 if (streamType == AUDIO_STREAM_DEFAULT) {
229 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800230 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700231
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800232 if (sampleRate == 0) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800233 uint32_t afSampleRate;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700234 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
235 return NO_INIT;
236 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800237 sampleRate = afSampleRate;
238 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800239 mSampleRate = sampleRate;
Glenn Kastenea7939a2012-03-14 12:56:26 -0700240
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800241 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800242 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700243 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800244 }
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700245 if (channelMask == 0) {
246 channelMask = AUDIO_CHANNEL_OUT_STEREO;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800247 }
248
249 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700250 if (!audio_is_valid_format(format)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800251 ALOGE("Invalid format %d", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800252 return BAD_VALUE;
253 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700254
Glenn Kastene0fa4672012-04-24 14:35:14 -0700255 // AudioFlinger does not currently support 8-bit data in shared memory
256 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
257 ALOGE("8-bit data in shared memory is not supported");
258 return BAD_VALUE;
259 }
260
Eric Laurentc2f1f072009-07-17 12:17:14 -0700261 // force direct flag if format is not linear PCM
Dima Zavinfce7a472011-04-19 22:30:36 -0700262 if (!audio_is_linear_pcm(format)) {
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700263 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800264 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700265 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700266 }
Eric Laurent1948eb32012-04-13 16:50:19 -0700267 // only allow deep buffering for music stream type
268 if (streamType != AUDIO_STREAM_MUSIC) {
269 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
270 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700271
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700272 if (!audio_is_output_channel(channelMask)) {
Glenn Kasten28b76b32012-07-03 17:24:41 -0700273 ALOGE("Invalid channel mask %#x", channelMask);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700274 return BAD_VALUE;
275 }
Glenn Kastena42ff002012-11-14 12:47:55 -0800276 mChannelMask = channelMask;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700277 uint32_t channelCount = popcount(channelMask);
Glenn Kastena42ff002012-11-14 12:47:55 -0800278 mChannelCount = channelCount;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700279
Glenn Kastene3aa6592012-12-04 12:22:46 -0800280 if (audio_is_linear_pcm(format)) {
281 mFrameSize = channelCount * audio_bytes_per_sample(format);
282 mFrameSizeAF = channelCount * sizeof(int16_t);
283 } else {
284 mFrameSize = sizeof(uint8_t);
285 mFrameSizeAF = sizeof(uint8_t);
286 }
287
Dima Zavinfce7a472011-04-19 22:30:36 -0700288 audio_io_handle_t output = AudioSystem::getOutput(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800289 streamType,
Glenn Kastene1c39622012-01-04 09:36:37 -0800290 sampleRate, format, channelMask,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000291 flags,
292 offloadInfo);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700293
294 if (output == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000295 ALOGE("Could not get audio output for stream type %d", streamType);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800296 return BAD_VALUE;
297 }
298
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800299 mVolume[LEFT] = 1.0f;
300 mVolume[RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800301 mSendLevel = 0.0f;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700302 mFrameCount = frameCount;
Glenn Kastenb6037442012-11-14 13:42:25 -0800303 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700304 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800305 mNotificationFramesAct = 0;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700306 mSessionId = sessionId;
Eric Laurent2beeb502010-07-16 07:43:46 -0700307 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700308 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700309 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700310
Glenn Kastena997e7a2012-08-07 09:44:19 -0700311 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700312 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700313 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
314 }
315
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800316 // create the IAudioTrack
Eric Laurent1703cdf2011-03-07 14:52:59 -0800317 status_t status = createTrack_l(streamType,
318 sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800319 format,
Eric Laurent1703cdf2011-03-07 14:52:59 -0800320 frameCount,
321 flags,
322 sharedBuffer,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800323 output,
324 0 /*epoch*/);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800325
Glenn Kastena997e7a2012-08-07 09:44:19 -0700326 if (status != NO_ERROR) {
327 if (mAudioTrackThread != 0) {
328 mAudioTrackThread->requestExit();
329 mAudioTrackThread.clear();
330 }
331 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700332 }
333
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800334 mStatus = NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800335 mStreamType = streamType;
Glenn Kastene1c39622012-01-04 09:36:37 -0800336 mFormat = format;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800337 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800338 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800339 mUserData = user;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800340 mLoopPeriod = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800341 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700342 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800343 mNewPosition = 0;
344 mUpdatePeriod = 0;
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700345 AudioSystem::acquireAudioSessionId(mSessionId);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800346 mSequence = 1;
347 mObservedSequence = mSequence;
348 mInUnderrun = false;
349
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800350 return NO_ERROR;
351}
352
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800353// -------------------------------------------------------------------------
354
355void AudioTrack::start()
356{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800357 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800358 if (mState == STATE_ACTIVE) {
359 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800360 }
361
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800362 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800363
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800364 State previousState = mState;
365 mState = STATE_ACTIVE;
366 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
367 // reset current position as seen by client to 0
368 mProxy->setEpoch(mProxy->getEpoch() - mProxy->getPosition());
369 }
370 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
371 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->flags);
372
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800373 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800374 if (t != 0) {
375 t->resume();
376 } else {
377 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
378 get_sched_policy(0, &mPreviousSchedulingGroup);
379 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
380 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800381
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800382 status_t status = NO_ERROR;
383 if (!(flags & CBLK_INVALID)) {
384 status = mAudioTrack->start();
385 if (status == DEAD_OBJECT) {
386 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800387 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800388 }
389 if (flags & CBLK_INVALID) {
390 status = restoreTrack_l("start");
391 }
392
393 if (status != NO_ERROR) {
394 ALOGE("start() status %d", status);
395 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800396 if (t != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800397 t->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800398 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700399 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700400 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800401 }
402 }
403
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800404 // FIXME discarding status
405}
406
407void AudioTrack::stop()
408{
409 AutoMutex lock(mLock);
410 // FIXME pause then stop should not be a nop
411 if (mState != STATE_ACTIVE) {
412 return;
413 }
414
415 mState = STATE_STOPPED;
416 mProxy->interrupt();
417 mAudioTrack->stop();
418 // the playback head position will reset to 0, so if a marker is set, we need
419 // to activate it again
420 mMarkerReached = false;
421#if 0
422 // Force flush if a shared buffer is used otherwise audioflinger
423 // will not stop before end of buffer is reached.
424 // It may be needed to make sure that we stop playback, likely in case looping is on.
425 if (mSharedBuffer != 0) {
426 flush_l();
427 }
428#endif
429 sp<AudioTrackThread> t = mAudioTrackThread;
430 if (t != 0) {
431 t->pause();
432 } else {
433 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
434 set_sched_policy(0, mPreviousSchedulingGroup);
435 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800436}
437
438bool AudioTrack::stopped() const
439{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800440 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800441 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800442}
443
444void AudioTrack::flush()
445{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800446 if (mSharedBuffer != 0) {
447 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800448 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800449 AutoMutex lock(mLock);
450 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
451 return;
452 }
453 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800454}
455
Eric Laurent1703cdf2011-03-07 14:52:59 -0800456void AudioTrack::flush_l()
457{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800458 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700459
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700460 // clear playback marker and periodic update counter
461 mMarkerPosition = 0;
462 mMarkerReached = false;
463 mUpdatePeriod = 0;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700464
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800465 mState = STATE_FLUSHED;
466 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800467 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800468}
469
470void AudioTrack::pause()
471{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800472 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800473 if (mState != STATE_ACTIVE) {
474 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800475 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800476 mState = STATE_PAUSED;
477 mProxy->interrupt();
478 mAudioTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800479}
480
Eric Laurentbe916aa2010-06-01 23:49:17 -0700481status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800482{
Glenn Kastenf0c49502011-11-30 09:46:04 -0800483 if (left < 0.0f || left > 1.0f || right < 0.0f || right > 1.0f) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700484 return BAD_VALUE;
485 }
486
Eric Laurent1703cdf2011-03-07 14:52:59 -0800487 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800488 mVolume[LEFT] = left;
489 mVolume[RIGHT] = right;
490
Glenn Kastene3aa6592012-12-04 12:22:46 -0800491 mProxy->setVolumeLR((uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700492
493 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800494}
495
Glenn Kastenb1c09932012-02-27 16:21:04 -0800496status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800497{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800498 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700499}
500
Eric Laurent2beeb502010-07-16 07:43:46 -0700501status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700502{
Glenn Kasten05632a52012-01-03 14:22:33 -0800503 if (level < 0.0f || level > 1.0f) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700504 return BAD_VALUE;
505 }
506
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800507 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700508 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800509 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700510
511 return NO_ERROR;
512}
513
Glenn Kastena5224f32012-01-04 12:41:44 -0800514void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700515{
516 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800517 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700518 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800519}
520
Glenn Kasten3b16c762012-11-14 08:44:39 -0800521status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800522{
John Grossman4ff14ba2012-02-08 16:37:41 -0800523 if (mIsTimed) {
524 return INVALID_OPERATION;
525 }
526
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800527 uint32_t afSamplingRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800528 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700529 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800530 }
531 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Glenn Kastend65d73c2012-06-22 17:21:07 -0700532 if (rate == 0 || rate > afSamplingRate*2 ) {
533 return BAD_VALUE;
534 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800535
Eric Laurent1703cdf2011-03-07 14:52:59 -0800536 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800537 mSampleRate = rate;
538 mProxy->setSampleRate(rate);
539
Eric Laurent57326622009-07-07 07:10:45 -0700540 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800541}
542
Glenn Kastena5224f32012-01-04 12:41:44 -0800543uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800544{
John Grossman4ff14ba2012-02-08 16:37:41 -0800545 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800546 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800547 }
548
Eric Laurent1703cdf2011-03-07 14:52:59 -0800549 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800550 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800551}
552
553status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
554{
Glenn Kasten083d1c12012-11-30 15:00:36 -0800555 if (mSharedBuffer == 0 || mIsTimed) {
556 return INVALID_OPERATION;
557 }
558
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800559 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800560 ;
561 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
562 loopEnd - loopStart >= MIN_LOOP) {
563 ;
564 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800565 return BAD_VALUE;
566 }
567
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800568 AutoMutex lock(mLock);
569 // See setPosition() regarding setting parameters such as loop points or position while active
570 if (mState == STATE_ACTIVE) {
571 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700572 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800573 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800574 return NO_ERROR;
575}
576
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800577void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
578{
579 // FIXME If setting a loop also sets position to start of loop, then
580 // this is correct. Otherwise it should be removed.
581 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
582 mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0;
583 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
584}
585
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800586status_t AudioTrack::setMarkerPosition(uint32_t marker)
587{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700588 // The only purpose of setting marker position is to get a callback
Glenn Kastend65d73c2012-06-22 17:21:07 -0700589 if (mCbf == NULL) {
590 return INVALID_OPERATION;
591 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800592
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800593 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800594 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700595 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800596
597 return NO_ERROR;
598}
599
Glenn Kastena5224f32012-01-04 12:41:44 -0800600status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800601{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700602 if (marker == NULL) {
603 return BAD_VALUE;
604 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800605
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800606 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800607 *marker = mMarkerPosition;
608
609 return NO_ERROR;
610}
611
612status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
613{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700614 // The only purpose of setting position update period is to get a callback
Glenn Kastend65d73c2012-06-22 17:21:07 -0700615 if (mCbf == NULL) {
616 return INVALID_OPERATION;
617 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800618
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800619 AutoMutex lock(mLock);
620 mNewPosition = mProxy->getPosition() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800621 mUpdatePeriod = updatePeriod;
622
623 return NO_ERROR;
624}
625
Glenn Kastena5224f32012-01-04 12:41:44 -0800626status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800627{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700628 if (updatePeriod == NULL) {
629 return BAD_VALUE;
630 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800631
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800632 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800633 *updatePeriod = mUpdatePeriod;
634
635 return NO_ERROR;
636}
637
638status_t AudioTrack::setPosition(uint32_t position)
639{
Glenn Kasten083d1c12012-11-30 15:00:36 -0800640 if (mSharedBuffer == 0 || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700641 return INVALID_OPERATION;
642 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800643 if (position > mFrameCount) {
644 return BAD_VALUE;
645 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800646
Eric Laurent1703cdf2011-03-07 14:52:59 -0800647 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800648 // Currently we require that the player is inactive before setting parameters such as position
649 // or loop points. Otherwise, there could be a race condition: the application could read the
650 // current position, compute a new position or loop parameters, and then set that position or
651 // loop parameters but it would do the "wrong" thing since the position has continued to advance
652 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
653 // to specify how it wants to handle such scenarios.
654 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700655 return INVALID_OPERATION;
656 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800657 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
658 mLoopPeriod = 0;
659 // FIXME Check whether loops and setting position are incompatible in old code.
660 // If we use setLoop for both purposes we lose the capability to set the position while looping.
661 mStaticProxy->setLoop(position, mFrameCount, 0);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700662
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800663 return NO_ERROR;
664}
665
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800666status_t AudioTrack::getPosition(uint32_t *position) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800667{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700668 if (position == NULL) {
669 return BAD_VALUE;
670 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800671
Eric Laurent1703cdf2011-03-07 14:52:59 -0800672 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800673 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
674 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ? 0 :
675 mProxy->getPosition();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800676
677 return NO_ERROR;
678}
679
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800680status_t AudioTrack::getBufferPosition(size_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800681{
682 if (mSharedBuffer == 0 || mIsTimed) {
683 return INVALID_OPERATION;
684 }
685 if (position == NULL) {
686 return BAD_VALUE;
687 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800688
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800689 AutoMutex lock(mLock);
690 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800691 return NO_ERROR;
692}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800693
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800694status_t AudioTrack::reload()
695{
Glenn Kasten083d1c12012-11-30 15:00:36 -0800696 if (mSharedBuffer == 0 || mIsTimed) {
697 return INVALID_OPERATION;
698 }
699
Eric Laurent1703cdf2011-03-07 14:52:59 -0800700 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800701 // See setPosition() regarding setting parameters such as loop points or position while active
702 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700703 return INVALID_OPERATION;
704 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800705 mNewPosition = mUpdatePeriod;
706 mLoopPeriod = 0;
707 // FIXME The new code cannot reload while keeping a loop specified.
708 // Need to check how the old code handled this, and whether it's a significant change.
709 mStaticProxy->setLoop(0, mFrameCount, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800710 return NO_ERROR;
711}
712
Eric Laurentc2f1f072009-07-17 12:17:14 -0700713audio_io_handle_t AudioTrack::getOutput()
714{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800715 AutoMutex lock(mLock);
716 return getOutput_l();
717}
718
719// must be called with mLock held
720audio_io_handle_t AudioTrack::getOutput_l()
721{
Glenn Kastenfff6d712012-01-12 16:38:12 -0800722 return AudioSystem::getOutput(mStreamType,
Glenn Kastene3aa6592012-12-04 12:22:46 -0800723 mSampleRate, mFormat, mChannelMask, mFlags);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700724}
725
Eric Laurentbe916aa2010-06-01 23:49:17 -0700726status_t AudioTrack::attachAuxEffect(int effectId)
727{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800728 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700729 status_t status = mAudioTrack->attachAuxEffect(effectId);
730 if (status == NO_ERROR) {
731 mAuxEffectId = effectId;
732 }
733 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700734}
735
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800736// -------------------------------------------------------------------------
737
Eric Laurent1703cdf2011-03-07 14:52:59 -0800738// must be called with mLock held
739status_t AudioTrack::createTrack_l(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800740 audio_stream_type_t streamType,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800741 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800742 audio_format_t format,
Glenn Kastene33054e2012-11-14 12:54:39 -0800743 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700744 audio_output_flags_t flags,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800745 const sp<IMemory>& sharedBuffer,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800746 audio_io_handle_t output,
747 size_t epoch)
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800748{
749 status_t status;
750 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
751 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700752 ALOGE("Could not get audioflinger");
753 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800754 }
755
Eric Laurentd1b449a2010-05-14 03:26:45 -0700756 uint32_t afLatency;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800757 if ((status = AudioSystem::getLatency(output, streamType, &afLatency)) != NO_ERROR) {
758 ALOGE("getLatency(%d) failed status %d", output, status);
Eric Laurentd1b449a2010-05-14 03:26:45 -0700759 return NO_INIT;
760 }
761
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700762 // Client decides whether the track is TIMED (see below), but can only express a preference
763 // for FAST. Server will perform additional tests.
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700764 if ((flags & AUDIO_OUTPUT_FLAG_FAST) && !(
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700765 // either of these use cases:
766 // use case 1: shared buffer
767 (sharedBuffer != 0) ||
768 // use case 2: callback handler
769 (mCbf != NULL))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800770 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -0700771 // once denied, do not request again if IAudioTrack is re-created
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700772 flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten093000f2012-05-03 09:35:36 -0700773 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700774 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700775 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700776
Eric Laurentd1b449a2010-05-14 03:26:45 -0700777 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700778
Dima Zavinfce7a472011-04-19 22:30:36 -0700779 if (!audio_is_linear_pcm(format)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700780
Eric Laurentd1b449a2010-05-14 03:26:45 -0700781 if (sharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700782 // Same comment as below about ignoring frameCount parameter for set()
Eric Laurentd1b449a2010-05-14 03:26:45 -0700783 frameCount = sharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -0700784 } else if (frameCount == 0) {
Glenn Kastene33054e2012-11-14 12:54:39 -0800785 size_t afFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800786 status = AudioSystem::getFrameCount(output, streamType, &afFrameCount);
787 if (status != NO_ERROR) {
788 ALOGE("getFrameCount(output=%d, streamType=%d) status %d", output, streamType,
789 status);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700790 return NO_INIT;
791 }
792 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700793 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700794
795 } else if (sharedBuffer != 0) {
796
Glenn Kastena42ff002012-11-14 12:47:55 -0800797 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -0700798 // 8-bit data in shared memory is not currently supported by AudioFlinger
799 size_t alignment = /* format == AUDIO_FORMAT_PCM_8_BIT ? 1 : */ 2;
Glenn Kastena42ff002012-11-14 12:47:55 -0800800 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700801 // More than 2 channels does not require stronger alignment than stereo
802 alignment <<= 1;
803 }
Glenn Kastena42ff002012-11-14 12:47:55 -0800804 if (((size_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
805 ALOGE("Invalid buffer alignment: address %p, channel count %u",
806 sharedBuffer->pointer(), mChannelCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700807 return BAD_VALUE;
808 }
809
810 // When initializing a shared buffer AudioTrack via constructors,
811 // there's no frameCount parameter.
812 // But when initializing a shared buffer AudioTrack via set(),
813 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kastena42ff002012-11-14 12:47:55 -0800814 frameCount = sharedBuffer->size()/mChannelCount/sizeof(int16_t);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700815
816 } else if (!(flags & AUDIO_OUTPUT_FLAG_FAST)) {
817
818 // FIXME move these calculations and associated checks to server
Glenn Kasten3b16c762012-11-14 08:44:39 -0800819 uint32_t afSampleRate;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800820 status = AudioSystem::getSamplingRate(output, streamType, &afSampleRate);
821 if (status != NO_ERROR) {
822 ALOGE("getSamplingRate(output=%d, streamType=%d) status %d", output, streamType,
823 status);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700824 return NO_INIT;
825 }
Glenn Kastene33054e2012-11-14 12:54:39 -0800826 size_t afFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800827 status = AudioSystem::getFrameCount(output, streamType, &afFrameCount);
828 if (status != NO_ERROR) {
829 ALOGE("getFrameCount(output=%d, streamType=%d) status %d", output, streamType, status);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700830 return NO_INIT;
831 }
832
Eric Laurentd1b449a2010-05-14 03:26:45 -0700833 // Ensure that buffer depth covers at least audio hardware latency
834 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Glenn Kastenbb6f0a02013-06-03 15:00:29 -0700835 ALOGV("afFrameCount=%d, minBufCount=%d, afSampleRate=%u, afLatency=%d",
836 afFrameCount, minBufCount, afSampleRate, afLatency);
837 if (minBufCount <= 2) {
838 minBufCount = sampleRate == afSampleRate ? 2 : 3;
Glenn Kasten7c027242012-12-26 14:43:16 -0800839 }
Eric Laurentd1b449a2010-05-14 03:26:45 -0700840
Glenn Kastene33054e2012-11-14 12:54:39 -0800841 size_t minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
842 ALOGV("minFrameCount: %u, afFrameCount=%d, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -0800843 ", afLatency=%d",
844 minFrameCount, afFrameCount, minBufCount, sampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700845
846 if (frameCount == 0) {
847 frameCount = minFrameCount;
848 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700849 // Make sure that application is notified with sufficient margin
850 // before underrun
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800851 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/2) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700852 mNotificationFramesAct = frameCount/2;
853 }
854 if (frameCount < minFrameCount) {
855 // not ALOGW because it happens all the time when playing key clicks over A2DP
856 ALOGV("Minimum buffer size corrected from %d to %d",
857 frameCount, minFrameCount);
858 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800859 }
Eric Laurentd1b449a2010-05-14 03:26:45 -0700860
Glenn Kastene0fa4672012-04-24 14:35:14 -0700861 } else {
862 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -0700863 }
864
Glenn Kastena075db42012-03-06 11:22:44 -0800865 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
866 if (mIsTimed) {
867 trackFlags |= IAudioFlinger::TRACK_TIMED;
868 }
Glenn Kasten3acbd052012-02-28 10:39:56 -0800869
870 pid_t tid = -1;
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700871 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700872 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800873 if (mAudioTrackThread != 0) {
874 tid = mAudioTrackThread->getTid();
875 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700876 }
877
Glenn Kasten8d6cc842012-02-03 11:06:53 -0800878 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800879 sampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -0700880 // AudioFlinger only sees 16-bit PCM
881 format == AUDIO_FORMAT_PCM_8_BIT ?
882 AUDIO_FORMAT_PCM_16_BIT : format,
Glenn Kastena42ff002012-11-14 12:47:55 -0800883 mChannelMask,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800884 frameCount,
Glenn Kastene0b07172012-11-06 15:03:34 -0800885 &trackFlags,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800886 sharedBuffer,
887 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800888 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700889 &mSessionId,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800890 &status);
891
892 if (track == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000893 ALOGE("AudioFlinger could not create track, status: %d", status);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800894 return status;
895 }
Glenn Kastend2c38fc2012-11-01 14:58:02 -0700896 sp<IMemory> iMem = track->getCblk();
897 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000898 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800899 return NO_INIT;
900 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800901 if (mAudioTrack != 0) {
902 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
903 mDeathNotifier.clear();
904 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800905 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -0700906 mCblkMemory = iMem;
907 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMem->pointer());
908 mCblk = cblk;
Glenn Kastenb6037442012-11-14 13:42:25 -0800909 size_t temp = cblk->frameCount_;
910 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
911 // In current design, AudioTrack client checks and ensures frame count validity before
912 // passing it to AudioFlinger so AudioFlinger should not return a different value except
913 // for fast track as it uses a special method of assigning frame count.
914 ALOGW("Requested frameCount %u but received frameCount %u", frameCount, temp);
915 }
916 frameCount = temp;
Glenn Kastena07f17c2013-04-23 12:39:37 -0700917 mAwaitBoost = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800918 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -0800919 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Glenn Kastenb6037442012-11-14 13:42:25 -0800920 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %u", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -0700921 mAwaitBoost = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800922 if (sharedBuffer == 0) {
923 // double-buffering is not required for fast tracks, due to tighter scheduling
924 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount) {
925 mNotificationFramesAct = frameCount;
926 }
927 }
Glenn Kasten3acbd052012-02-28 10:39:56 -0800928 } else {
Glenn Kastenb6037442012-11-14 13:42:25 -0800929 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %u", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -0700930 // once denied, do not request again if IAudioTrack is re-created
931 flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST);
932 mFlags = flags;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800933 if (sharedBuffer == 0) {
934 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/2) {
935 mNotificationFramesAct = frameCount/2;
936 }
937 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700938 }
Glenn Kasten3acbd052012-02-28 10:39:56 -0800939 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800940 mRefreshRemaining = true;
941
942 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
943 // is the value of pointer() for the shared buffer, otherwise buffers points
944 // immediately after the control block. This address is for the mapping within client
945 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
946 void* buffers;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800947 if (sharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800948 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800949 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800950 buffers = sharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800951 }
952
Eric Laurent2beeb502010-07-16 07:43:46 -0700953 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700954 // FIXME don't believe this lie
Glenn Kastenb6037442012-11-14 13:42:25 -0800955 mLatency = afLatency + (1000*frameCount) / sampleRate;
956 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -0700957 // If IAudioTrack is re-created, don't let the requested frameCount
958 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -0800959 if (frameCount > mReqFrameCount) {
960 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -0700961 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800962
963 // update proxy
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800964 if (sharedBuffer == 0) {
965 mStaticProxy.clear();
966 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
967 } else {
968 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
969 mProxy = mStaticProxy;
970 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800971 mProxy->setVolumeLR((uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) |
972 uint16_t(mVolume[LEFT] * 0x1000));
973 mProxy->setSendLevel(mSendLevel);
974 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800975 mProxy->setEpoch(epoch);
976 mProxy->setMinimum(mNotificationFramesAct);
977
978 mDeathNotifier = new DeathNotifier(this);
979 mAudioTrack->asBinder()->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800980
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800981 return NO_ERROR;
982}
983
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800984status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
985{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800986 if (audioBuffer == NULL) {
987 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -0700988 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800989 if (mTransfer != TRANSFER_OBTAIN) {
990 audioBuffer->frameCount = 0;
991 audioBuffer->size = 0;
992 audioBuffer->raw = NULL;
993 return INVALID_OPERATION;
994 }
Eric Laurent9b7d9502011-03-21 11:49:00 -0700995
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800996 const struct timespec *requested;
997 if (waitCount == -1) {
998 requested = &ClientProxy::kForever;
999 } else if (waitCount == 0) {
1000 requested = &ClientProxy::kNonBlocking;
1001 } else if (waitCount > 0) {
1002 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
1003 struct timespec timeout;
1004 timeout.tv_sec = ms / 1000;
1005 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1006 requested = &timeout;
1007 } else {
1008 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1009 requested = NULL;
1010 }
1011 return obtainBuffer(audioBuffer, requested);
1012}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001013
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001014status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1015 struct timespec *elapsed, size_t *nonContig)
1016{
1017 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1018 uint32_t oldSequence = 0;
1019 uint32_t newSequence;
1020
1021 Proxy::Buffer buffer;
1022 status_t status = NO_ERROR;
1023
1024 static const int32_t kMaxTries = 5;
1025 int32_t tryCounter = kMaxTries;
1026
1027 do {
1028 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1029 // keep them from going away if another thread re-creates the track during obtainBuffer()
1030 sp<AudioTrackClientProxy> proxy;
1031 sp<IMemory> iMem;
1032
1033 { // start of lock scope
1034 AutoMutex lock(mLock);
1035
1036 newSequence = mSequence;
1037 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1038 if (status == DEAD_OBJECT) {
1039 // re-create track, unless someone else has already done so
1040 if (newSequence == oldSequence) {
1041 status = restoreTrack_l("obtainBuffer");
1042 if (status != NO_ERROR) {
1043 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001044 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001045 }
1046 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001047 oldSequence = newSequence;
1048
1049 // Keep the extra references
1050 proxy = mProxy;
1051 iMem = mCblkMemory;
1052
1053 // Non-blocking if track is stopped or paused
1054 if (mState != STATE_ACTIVE) {
1055 requested = &ClientProxy::kNonBlocking;
1056 }
1057
1058 } // end of lock scope
1059
1060 buffer.mFrameCount = audioBuffer->frameCount;
1061 // FIXME starts the requested timeout and elapsed over from scratch
1062 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1063
1064 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1065
1066 audioBuffer->frameCount = buffer.mFrameCount;
1067 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1068 audioBuffer->raw = buffer.mRaw;
1069 if (nonContig != NULL) {
1070 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001071 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001072 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001073}
1074
1075void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1076{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001077 if (mTransfer == TRANSFER_SHARED) {
1078 return;
1079 }
1080
1081 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1082 if (stepCount == 0) {
1083 return;
1084 }
1085
1086 Proxy::Buffer buffer;
1087 buffer.mFrameCount = stepCount;
1088 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001089
Eric Laurent1703cdf2011-03-07 14:52:59 -08001090 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001091 mInUnderrun = false;
1092 mProxy->releaseBuffer(&buffer);
1093
1094 // restart track if it was disabled by audioflinger due to previous underrun
1095 if (mState == STATE_ACTIVE) {
1096 audio_track_cblk_t* cblk = mCblk;
1097 if (android_atomic_and(~CBLK_DISABLED, &cblk->flags) & CBLK_DISABLED) {
1098 ALOGW("releaseBuffer() track %p name=%#x disabled due to previous underrun, restarting",
1099 this, cblk->mName);
1100 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001101 mAudioTrack->start();
1102 }
1103 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001104}
1105
1106// -------------------------------------------------------------------------
1107
1108ssize_t AudioTrack::write(const void* buffer, size_t userSize)
1109{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001110 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001111 return INVALID_OPERATION;
1112 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001113
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001114 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001115 // Sanity-check: user is most-likely passing an error code, and it would
1116 // make the return value ambiguous (actualSize vs error).
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001117 ALOGE("AudioTrack::write(buffer=%p, size=%u (%d)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001118 return BAD_VALUE;
1119 }
1120
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001121 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001122 Buffer audioBuffer;
1123
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001124 while (userSize >= mFrameSize) {
1125 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001126
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001127 status_t err = obtainBuffer(&audioBuffer, &ClientProxy::kForever);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001128 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001129 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001130 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001131 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001132 return ssize_t(err);
1133 }
1134
1135 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001136 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001137 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001138 toWrite = audioBuffer.size >> 1;
1139 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001140 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001141 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001142 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001143 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001144 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001145 userSize -= toWrite;
1146 written += toWrite;
1147
1148 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001149 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001150
1151 return written;
1152}
1153
1154// -------------------------------------------------------------------------
1155
John Grossman4ff14ba2012-02-08 16:37:41 -08001156TimedAudioTrack::TimedAudioTrack() {
1157 mIsTimed = true;
1158}
1159
1160status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1161{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001162 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001163 status_t result = UNKNOWN_ERROR;
1164
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001165#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001166 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1167 // while we are accessing the cblk
1168 sp<IAudioTrack> audioTrack = mAudioTrack;
1169 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001170#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001171
John Grossman4ff14ba2012-02-08 16:37:41 -08001172 // If the track is not invalid already, try to allocate a buffer. alloc
1173 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001174 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001175 audio_track_cblk_t* cblk = mCblk;
1176 if (!(cblk->flags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001177 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1178 if (result == DEAD_OBJECT) {
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001179 android_atomic_or(CBLK_INVALID, &cblk->flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001180 }
1181 }
1182
1183 // If the track is invalid at this point, attempt to restore it. and try the
1184 // allocation one more time.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001185 if (cblk->flags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001186 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001187
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001188 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001189 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001190 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001191 }
1192
1193 return result;
1194}
1195
1196status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1197 int64_t pts)
1198{
Eric Laurentdf839842012-05-31 14:27:14 -07001199 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1200 {
1201 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001202 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001203 // restart track if it was disabled by audioflinger due to previous underrun
1204 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001205 (mState == STATE_ACTIVE) && (cblk->flags & CBLK_DISABLED)) {
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001206 android_atomic_and(~CBLK_DISABLED, &cblk->flags);
Eric Laurentdf839842012-05-31 14:27:14 -07001207 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001208 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001209 mAudioTrack->start();
1210 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001211 }
Eric Laurentdf839842012-05-31 14:27:14 -07001212 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001213}
1214
1215status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1216 TargetTimeline target)
1217{
1218 return mAudioTrack->setMediaTimeTransform(xform, target);
1219}
1220
1221// -------------------------------------------------------------------------
1222
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001223nsecs_t AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001224{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001225 // Currently the AudioTrack thread is not created if there are no callbacks.
1226 // Would it ever make sense to run the thread, even without callbacks?
1227 // If so, then replace this by checks at each use for mCbf != NULL.
1228 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1229
Eric Laurent1703cdf2011-03-07 14:52:59 -08001230 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001231 if (mAwaitBoost) {
1232 mAwaitBoost = false;
1233 mLock.unlock();
1234 static const int32_t kMaxTries = 5;
1235 int32_t tryCounter = kMaxTries;
1236 uint32_t pollUs = 10000;
1237 do {
1238 int policy = sched_getscheduler(0);
1239 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1240 break;
1241 }
1242 usleep(pollUs);
1243 pollUs <<= 1;
1244 } while (tryCounter-- > 0);
1245 if (tryCounter < 0) {
1246 ALOGE("did not receive expected priority boost on time");
1247 }
1248 return true;
1249 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001250
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001251 // Can only reference mCblk while locked
1252 int32_t flags = android_atomic_and(
1253 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->flags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001254
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001255 // Check for track invalidation
1256 if (flags & CBLK_INVALID) {
1257 (void) restoreTrack_l("processAudioBuffer");
1258 mLock.unlock();
1259 // Run again immediately, but with a new IAudioTrack
1260 return 0;
1261 }
1262
1263 bool active = mState == STATE_ACTIVE;
1264
1265 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1266 bool newUnderrun = false;
1267 if (flags & CBLK_UNDERRUN) {
1268#if 0
1269 // Currently in shared buffer mode, when the server reaches the end of buffer,
1270 // the track stays active in continuous underrun state. It's up to the application
1271 // to pause or stop the track, or set the position to a new offset within buffer.
1272 // This was some experimental code to auto-pause on underrun. Keeping it here
1273 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1274 if (mTransfer == TRANSFER_SHARED) {
1275 mState = STATE_PAUSED;
1276 active = false;
1277 }
1278#endif
1279 if (!mInUnderrun) {
1280 mInUnderrun = true;
1281 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001282 }
1283 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001284
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001285 // Get current position of server
1286 size_t position = mProxy->getPosition();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001287
1288 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001289 bool markerReached = false;
1290 size_t markerPosition = mMarkerPosition;
1291 // FIXME fails for wraparound, need 64 bits
1292 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1293 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001294 }
1295
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001296 // Determine number of new position callback(s) that will be needed, while locked
1297 size_t newPosCount = 0;
1298 size_t newPosition = mNewPosition;
1299 size_t updatePeriod = mUpdatePeriod;
1300 // FIXME fails for wraparound, need 64 bits
1301 if (updatePeriod > 0 && position >= newPosition) {
1302 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1303 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001304 }
1305
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001306 // Cache other fields that will be needed soon
1307 uint32_t loopPeriod = mLoopPeriod;
1308 uint32_t sampleRate = mSampleRate;
1309 size_t notificationFrames = mNotificationFramesAct;
1310 if (mRefreshRemaining) {
1311 mRefreshRemaining = false;
1312 mRemainingFrames = notificationFrames;
1313 mRetryOnPartialBuffer = false;
1314 }
1315 size_t misalignment = mProxy->getMisalignment();
1316 int32_t sequence = mSequence;
1317
1318 // These fields don't need to be cached, because they are assigned only by set():
1319 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1320 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1321
1322 mLock.unlock();
1323
1324 // perform callbacks while unlocked
1325 if (newUnderrun) {
1326 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1327 }
1328 // FIXME we will miss loops if loop cycle was signaled several times since last call
1329 // to processAudioBuffer()
1330 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1331 mCbf(EVENT_LOOP_END, mUserData, NULL);
1332 }
1333 if (flags & CBLK_BUFFER_END) {
1334 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1335 }
1336 if (markerReached) {
1337 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1338 }
1339 while (newPosCount > 0) {
1340 size_t temp = newPosition;
1341 mCbf(EVENT_NEW_POS, mUserData, &temp);
1342 newPosition += updatePeriod;
1343 newPosCount--;
1344 }
1345 if (mObservedSequence != sequence) {
1346 mObservedSequence = sequence;
1347 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001348 }
1349
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001350 // if inactive, then don't run me again until re-started
1351 if (!active) {
1352 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001353 }
1354
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001355 // Compute the estimated time until the next timed event (position, markers, loops)
1356 // FIXME only for non-compressed audio
1357 uint32_t minFrames = ~0;
1358 if (!markerReached && position < markerPosition) {
1359 minFrames = markerPosition - position;
1360 }
1361 if (loopPeriod > 0 && loopPeriod < minFrames) {
1362 minFrames = loopPeriod;
1363 }
1364 if (updatePeriod > 0 && updatePeriod < minFrames) {
1365 minFrames = updatePeriod;
1366 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001367
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001368 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1369 static const uint32_t kPoll = 0;
1370 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1371 minFrames = kPoll * notificationFrames;
1372 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001373
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001374 // Convert frame units to time units
1375 nsecs_t ns = NS_WHENEVER;
1376 if (minFrames != (uint32_t) ~0) {
1377 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1378 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1379 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1380 }
1381
1382 // If not supplying data by EVENT_MORE_DATA, then we're done
1383 if (mTransfer != TRANSFER_CALLBACK) {
1384 return ns;
1385 }
1386
1387 struct timespec timeout;
1388 const struct timespec *requested = &ClientProxy::kForever;
1389 if (ns != NS_WHENEVER) {
1390 timeout.tv_sec = ns / 1000000000LL;
1391 timeout.tv_nsec = ns % 1000000000LL;
1392 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1393 requested = &timeout;
1394 }
1395
1396 while (mRemainingFrames > 0) {
1397
1398 Buffer audioBuffer;
1399 audioBuffer.frameCount = mRemainingFrames;
1400 size_t nonContig;
1401 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1402 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1403 "obtainBuffer() err=%d frameCount=%u", err, audioBuffer.frameCount);
1404 requested = &ClientProxy::kNonBlocking;
1405 size_t avail = audioBuffer.frameCount + nonContig;
1406 ALOGV("obtainBuffer(%u) returned %u = %u + %u",
1407 mRemainingFrames, avail, audioBuffer.frameCount, nonContig);
1408 if (err != NO_ERROR) {
1409 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR) {
1410 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001411 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001412 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1413 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001414 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001415
1416 if (mRetryOnPartialBuffer) {
1417 mRetryOnPartialBuffer = false;
1418 if (avail < mRemainingFrames) {
1419 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1420 if (ns < 0 || myns < ns) {
1421 ns = myns;
1422 }
1423 return ns;
1424 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001425 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001426
1427 // Divide buffer size by 2 to take into account the expansion
1428 // due to 8 to 16 bit conversion: the callback must fill only half
1429 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001430 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001431 audioBuffer.size >>= 1;
1432 }
1433
1434 size_t reqSize = audioBuffer.size;
1435 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001436 size_t writtenSize = audioBuffer.size;
1437 size_t writtenFrames = writtenSize / mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001438
1439 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001440 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
1441 ALOGE("EVENT_MORE_DATA requested %u bytes but callback returned %d bytes",
1442 reqSize, (int) writtenSize);
1443 return NS_NEVER;
1444 }
1445
1446 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001447 // The callback is done filling buffers
1448 // Keep this thread going to handle timed events and
1449 // still try to get more data in intervals of WAIT_PERIOD_MS
1450 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001451 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001452 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001453
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001454 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001455 // 8 to 16 bit conversion, note that source and destination are the same address
1456 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001457 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001458 }
1459
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001460 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1461 audioBuffer.frameCount = releasedFrames;
1462 mRemainingFrames -= releasedFrames;
1463 if (misalignment >= releasedFrames) {
1464 misalignment -= releasedFrames;
1465 } else {
1466 misalignment = 0;
1467 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001468
1469 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001470
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001471 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1472 // if callback doesn't like to accept the full chunk
1473 if (writtenSize < reqSize) {
1474 continue;
1475 }
1476
1477 // There could be enough non-contiguous frames available to satisfy the remaining request
1478 if (mRemainingFrames <= nonContig) {
1479 continue;
1480 }
1481
1482#if 0
1483 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1484 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1485 // that total to a sum == notificationFrames.
1486 if (0 < misalignment && misalignment <= mRemainingFrames) {
1487 mRemainingFrames = misalignment;
1488 return (mRemainingFrames * 1100000000LL) / sampleRate;
1489 }
1490#endif
1491
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001492 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001493 mRemainingFrames = notificationFrames;
1494 mRetryOnPartialBuffer = true;
1495
1496 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1497 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001498}
1499
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001500status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001501{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001502 ALOGW("dead IAudioTrack, creating a new one from %s()", from);
1503 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001504 status_t result;
1505
Glenn Kastena47f3162012-11-07 10:13:08 -08001506 // refresh the audio configuration cache in this process to make sure we get new
1507 // output parameters in getOutput_l() and createTrack_l()
1508 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001509
Glenn Kastena47f3162012-11-07 10:13:08 -08001510 // if the new IAudioTrack is created, createTrack_l() will modify the
1511 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1512 // It will also delete the strong references on previous IAudioTrack and IMemory
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001513 size_t position = mProxy->getPosition();
1514 mNewPosition = position + mUpdatePeriod;
1515 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
Glenn Kastena47f3162012-11-07 10:13:08 -08001516 result = createTrack_l(mStreamType,
Glenn Kastene3aa6592012-12-04 12:22:46 -08001517 mSampleRate,
Glenn Kastena47f3162012-11-07 10:13:08 -08001518 mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001519 mReqFrameCount, // so that frame count never goes down
Glenn Kastena47f3162012-11-07 10:13:08 -08001520 mFlags,
1521 mSharedBuffer,
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001522 getOutput_l(),
1523 position /*epoch*/);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001524
Glenn Kastena47f3162012-11-07 10:13:08 -08001525 if (result == NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001526 // continue playback from last known position, but
1527 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1528 if (mStaticProxy != NULL) {
1529 mLoopPeriod = 0;
1530 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1531 }
1532 // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1533 // track destruction have been played? This is critical for SoundPool implementation
1534 // This must be broken, and needs to be tested/debugged.
1535#if 0
Glenn Kastena47f3162012-11-07 10:13:08 -08001536 // restore write index and set other indexes to reflect empty buffer status
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001537 if (!strcmp(from, "start")) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001538 // Make sure that a client relying on callback events indicating underrun or
1539 // the actual amount of audio frames played (e.g SoundPool) receives them.
1540 if (mSharedBuffer == 0) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001541 // restart playback even if buffer is not completely filled.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001542 android_atomic_or(CBLK_FORCEREADY, &mCblk->flags);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001543 }
1544 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001545#endif
1546 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001547 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001548 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001549 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001550 if (result != NO_ERROR) {
1551 ALOGW("restoreTrack_l() failed status %d", result);
1552 mState = STATE_STOPPED;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001553 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001554
1555 return result;
1556}
1557
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001558status_t AudioTrack::setParameters(const String8& keyValuePairs)
1559{
1560 AutoMutex lock(mLock);
1561 if (mAudioTrack != 0) {
1562 return mAudioTrack->setParameters(keyValuePairs);
1563 } else {
1564 return NO_INIT;
1565 }
1566}
1567
1568String8 AudioTrack::getParameters(const String8& keys)
1569{
1570 return String8::empty();
1571}
1572
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001573status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1574{
1575
1576 const size_t SIZE = 256;
1577 char buffer[SIZE];
1578 String8 result;
1579
1580 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001581 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
1582 mVolume[0], mVolume[1]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001583 result.append(buffer);
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001584 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001585 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001586 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001587 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001588 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001589 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001590 result.append(buffer);
1591 ::write(fd, result.string(), result.size());
1592 return NO_ERROR;
1593}
1594
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001595uint32_t AudioTrack::getUnderrunFrames() const
1596{
1597 AutoMutex lock(mLock);
1598 return mProxy->getUnderrunFrames();
1599}
1600
1601// =========================================================================
1602
1603void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who)
1604{
1605 sp<AudioTrack> audioTrack = mAudioTrack.promote();
1606 if (audioTrack != 0) {
1607 AutoMutex lock(audioTrack->mLock);
1608 audioTrack->mProxy->binderDied();
1609 }
1610}
1611
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001612// =========================================================================
1613
1614AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001615 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mResumeLatch(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08001616{
1617}
1618
1619AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001620{
1621}
1622
1623bool AudioTrack::AudioTrackThread::threadLoop()
1624{
Glenn Kasten3acbd052012-02-28 10:39:56 -08001625 {
1626 AutoMutex _l(mMyLock);
1627 if (mPaused) {
1628 mMyCond.wait(mMyLock);
1629 // caller will check for exitPending()
1630 return true;
1631 }
1632 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001633 nsecs_t ns = mReceiver.processAudioBuffer(this);
1634 switch (ns) {
1635 case 0:
1636 return true;
1637 case NS_WHENEVER:
1638 sleep(1);
1639 return true;
1640 case NS_INACTIVE:
1641 pauseConditional();
1642 return true;
1643 case NS_NEVER:
1644 return false;
1645 default:
1646 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns);
1647 struct timespec req;
1648 req.tv_sec = ns / 1000000000LL;
1649 req.tv_nsec = ns % 1000000000LL;
1650 nanosleep(&req, NULL /*rem*/);
1651 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07001652 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001653}
1654
Glenn Kasten3acbd052012-02-28 10:39:56 -08001655void AudioTrack::AudioTrackThread::requestExit()
1656{
1657 // must be in this order to avoid a race condition
1658 Thread::requestExit();
Glenn Kastenf4022f92012-05-02 10:34:59 -07001659 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08001660}
1661
1662void AudioTrack::AudioTrackThread::pause()
1663{
1664 AutoMutex _l(mMyLock);
1665 mPaused = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001666 mResumeLatch = false;
1667}
1668
1669void AudioTrack::AudioTrackThread::pauseConditional()
1670{
1671 AutoMutex _l(mMyLock);
1672 if (mResumeLatch) {
1673 mResumeLatch = false;
1674 } else {
1675 mPaused = true;
1676 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001677}
1678
1679void AudioTrack::AudioTrackThread::resume()
1680{
1681 AutoMutex _l(mMyLock);
1682 if (mPaused) {
1683 mPaused = false;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001684 mResumeLatch = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001685 mMyCond.signal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001686 } else {
1687 mResumeLatch = true;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001688 }
1689}
1690
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001691}; // namespace android