blob: 2af162cf84747d8923bc38ecf355e5cdea98b79c [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>
28
Glenn Kasten9f80dd22012-12-18 15:57:32 -080029#define WAIT_PERIOD_MS 10
Glenn Kasten511754b2012-01-11 09:52:19 -080030
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080031namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080032// ---------------------------------------------------------------------------
33
34// static
35status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080036 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080037 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080038 uint32_t sampleRate)
39{
Glenn Kastend65d73c2012-06-22 17:21:07 -070040 if (frameCount == NULL) {
41 return BAD_VALUE;
42 }
Glenn Kasten04cd0182012-06-25 11:49:27 -070043
44 // default to 0 in case of error
45 *frameCount = 0;
46
Glenn Kastene0fa4672012-04-24 14:35:14 -070047 // FIXME merge with similar code in createTrack_l(), except we're missing
48 // some information here that is available in createTrack_l():
49 // audio_io_handle_t output
50 // audio_format_t format
51 // audio_channel_mask_t channelMask
52 // audio_output_flags_t flags
Glenn Kasten3b16c762012-11-14 08:44:39 -080053 uint32_t afSampleRate;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080054 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
55 return NO_INIT;
56 }
Glenn Kastene33054e2012-11-14 12:54:39 -080057 size_t afFrameCount;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080058 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
59 return NO_INIT;
60 }
61 uint32_t afLatency;
62 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
63 return NO_INIT;
64 }
65
66 // Ensure that buffer depth covers at least audio hardware latency
67 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080068 if (minBufCount < 2) {
69 minBufCount = 2;
70 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +080071
72 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
Glenn Kastene53b9ea2012-03-12 16:29:55 -070073 afFrameCount * minBufCount * sampleRate / afSampleRate;
Glenn Kasten3acbd052012-02-28 10:39:56 -080074 ALOGV("getMinFrameCount=%d: afFrameCount=%d, minBufCount=%d, afSampleRate=%d, afLatency=%d",
75 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +080076 return NO_ERROR;
77}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080078
79// ---------------------------------------------------------------------------
80
81AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -070082 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -080083 mIsTimed(false),
84 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Glenn Kasten9f80dd22012-12-18 15:57:32 -080085 mPreviousSchedulingGroup(SP_DEFAULT)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080086{
87}
88
89AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -080090 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080091 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -080092 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -070093 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080094 int frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -070095 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080096 callback_t cbf,
97 void* user,
Eric Laurentbe916aa2010-06-01 23:49:17 -070098 int notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -080099 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000100 transfer_type transferType,
101 const audio_offload_info_t *offloadInfo)
Glenn Kasten87913512011-06-22 16:15:25 -0700102 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800103 mIsTimed(false),
104 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800105 mPreviousSchedulingGroup(SP_DEFAULT)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800106{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700107 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700108 frameCount, flags, cbf, user, notificationFrames,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000109 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800110}
111
Andreas Huberc8139852012-01-18 10:51:55 -0800112AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800113 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800114 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800115 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700116 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800117 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700118 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800119 callback_t cbf,
120 void* user,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700121 int notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800122 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000123 transfer_type transferType,
124 const audio_offload_info_t *offloadInfo)
Glenn Kasten87913512011-06-22 16:15:25 -0700125 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800126 mIsTimed(false),
127 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800128 mPreviousSchedulingGroup(SP_DEFAULT)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800129{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700130 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800131 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000132 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800133}
134
135AudioTrack::~AudioTrack()
136{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800137 if (mStatus == NO_ERROR) {
138 // Make sure that callback function exits in the case where
139 // it is looping on buffer full condition in obtainBuffer().
140 // Otherwise the callback thread will never exit.
141 stop();
142 if (mAudioTrackThread != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800143 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800144 mAudioTrackThread->requestExitAndWait();
145 mAudioTrackThread.clear();
146 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800147 if (mAudioTrack != 0) {
148 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
149 mAudioTrack.clear();
150 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800151 IPCThreadState::self()->flushCommands();
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700152 AudioSystem::releaseAudioSessionId(mSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800153 }
154}
155
156status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800157 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800158 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800159 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700160 audio_channel_mask_t channelMask,
Glenn Kastene33054e2012-11-14 12:54:39 -0800161 int frameCountInt,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700162 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800163 callback_t cbf,
164 void* user,
165 int notificationFrames,
166 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700167 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800168 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000169 transfer_type transferType,
170 const audio_offload_info_t *offloadInfo)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800171{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800172 switch (transferType) {
173 case TRANSFER_DEFAULT:
174 if (sharedBuffer != 0) {
175 transferType = TRANSFER_SHARED;
176 } else if (cbf == NULL || threadCanCallJava) {
177 transferType = TRANSFER_SYNC;
178 } else {
179 transferType = TRANSFER_CALLBACK;
180 }
181 break;
182 case TRANSFER_CALLBACK:
183 if (cbf == NULL || sharedBuffer != 0) {
184 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
185 return BAD_VALUE;
186 }
187 break;
188 case TRANSFER_OBTAIN:
189 case TRANSFER_SYNC:
190 if (sharedBuffer != 0) {
191 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
192 return BAD_VALUE;
193 }
194 break;
195 case TRANSFER_SHARED:
196 if (sharedBuffer == 0) {
197 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
198 return BAD_VALUE;
199 }
200 break;
201 default:
202 ALOGE("Invalid transfer type %d", transferType);
203 return BAD_VALUE;
204 }
205 mTransfer = transferType;
206
Glenn Kastene33054e2012-11-14 12:54:39 -0800207 // FIXME "int" here is legacy and will be replaced by size_t later
208 if (frameCountInt < 0) {
209 ALOGE("Invalid frame count %d", frameCountInt);
210 return BAD_VALUE;
211 }
212 size_t frameCount = frameCountInt;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800213
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700214 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
215 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800216
Glenn Kastene33054e2012-11-14 12:54:39 -0800217 ALOGV("set() streamType %d frameCount %u flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700218
Eric Laurent1703cdf2011-03-07 14:52:59 -0800219 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800220
Eric Laurent1dd70b92009-04-21 07:56:33 -0700221 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000222 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800223 return INVALID_OPERATION;
224 }
225
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800226 // handle default values first.
Dima Zavinfce7a472011-04-19 22:30:36 -0700227 if (streamType == AUDIO_STREAM_DEFAULT) {
228 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800229 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700230
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800231 if (sampleRate == 0) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800232 uint32_t afSampleRate;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700233 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
234 return NO_INIT;
235 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800236 sampleRate = afSampleRate;
237 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800238 mSampleRate = sampleRate;
Glenn Kastenea7939a2012-03-14 12:56:26 -0700239
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800240 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800241 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700242 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800243 }
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700244 if (channelMask == 0) {
245 channelMask = AUDIO_CHANNEL_OUT_STEREO;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800246 }
247
248 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700249 if (!audio_is_valid_format(format)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800250 ALOGE("Invalid format %d", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800251 return BAD_VALUE;
252 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700253
Glenn Kastene0fa4672012-04-24 14:35:14 -0700254 // AudioFlinger does not currently support 8-bit data in shared memory
255 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
256 ALOGE("8-bit data in shared memory is not supported");
257 return BAD_VALUE;
258 }
259
Eric Laurentc2f1f072009-07-17 12:17:14 -0700260 // force direct flag if format is not linear PCM
Dima Zavinfce7a472011-04-19 22:30:36 -0700261 if (!audio_is_linear_pcm(format)) {
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700262 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800263 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700264 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700265 }
Eric Laurent1948eb32012-04-13 16:50:19 -0700266 // only allow deep buffering for music stream type
267 if (streamType != AUDIO_STREAM_MUSIC) {
268 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
269 }
Eric Laurentc2f1f072009-07-17 12:17:14 -0700270
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700271 if (!audio_is_output_channel(channelMask)) {
Glenn Kasten28b76b32012-07-03 17:24:41 -0700272 ALOGE("Invalid channel mask %#x", channelMask);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700273 return BAD_VALUE;
274 }
Glenn Kastena42ff002012-11-14 12:47:55 -0800275 mChannelMask = channelMask;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700276 uint32_t channelCount = popcount(channelMask);
Glenn Kastena42ff002012-11-14 12:47:55 -0800277 mChannelCount = channelCount;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700278
Glenn Kastene3aa6592012-12-04 12:22:46 -0800279 if (audio_is_linear_pcm(format)) {
280 mFrameSize = channelCount * audio_bytes_per_sample(format);
281 mFrameSizeAF = channelCount * sizeof(int16_t);
282 } else {
283 mFrameSize = sizeof(uint8_t);
284 mFrameSizeAF = sizeof(uint8_t);
285 }
286
Dima Zavinfce7a472011-04-19 22:30:36 -0700287 audio_io_handle_t output = AudioSystem::getOutput(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800288 streamType,
Glenn Kastene1c39622012-01-04 09:36:37 -0800289 sampleRate, format, channelMask,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000290 flags,
291 offloadInfo);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700292
293 if (output == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000294 ALOGE("Could not get audio output for stream type %d", streamType);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800295 return BAD_VALUE;
296 }
297
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800298 mVolume[LEFT] = 1.0f;
299 mVolume[RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800300 mSendLevel = 0.0f;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700301 mFrameCount = frameCount;
Glenn Kastenb6037442012-11-14 13:42:25 -0800302 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700303 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800304 mNotificationFramesAct = 0;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700305 mSessionId = sessionId;
Eric Laurent2beeb502010-07-16 07:43:46 -0700306 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700307 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700308 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700309
Glenn Kastena997e7a2012-08-07 09:44:19 -0700310 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700311 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700312 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
313 }
314
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800315 // create the IAudioTrack
Eric Laurent1703cdf2011-03-07 14:52:59 -0800316 status_t status = createTrack_l(streamType,
317 sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800318 format,
Eric Laurent1703cdf2011-03-07 14:52:59 -0800319 frameCount,
320 flags,
321 sharedBuffer,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800322 output,
323 0 /*epoch*/);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800324
Glenn Kastena997e7a2012-08-07 09:44:19 -0700325 if (status != NO_ERROR) {
326 if (mAudioTrackThread != 0) {
327 mAudioTrackThread->requestExit();
328 mAudioTrackThread.clear();
329 }
330 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700331 }
332
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800333 mStatus = NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800334 mStreamType = streamType;
Glenn Kastene1c39622012-01-04 09:36:37 -0800335 mFormat = format;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800336 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800337 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800338 mUserData = user;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800339 mLoopPeriod = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800340 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700341 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800342 mNewPosition = 0;
343 mUpdatePeriod = 0;
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700344 AudioSystem::acquireAudioSessionId(mSessionId);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800345 mSequence = 1;
346 mObservedSequence = mSequence;
347 mInUnderrun = false;
348
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800349 return NO_ERROR;
350}
351
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800352// -------------------------------------------------------------------------
353
354void AudioTrack::start()
355{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800356 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800357 if (mState == STATE_ACTIVE) {
358 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800359 }
360
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800361 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800362
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800363 State previousState = mState;
364 mState = STATE_ACTIVE;
365 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
366 // reset current position as seen by client to 0
367 mProxy->setEpoch(mProxy->getEpoch() - mProxy->getPosition());
368 }
369 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
370 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->flags);
371
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800372 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800373 if (t != 0) {
374 t->resume();
375 } else {
376 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
377 get_sched_policy(0, &mPreviousSchedulingGroup);
378 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
379 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800380
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800381 status_t status = NO_ERROR;
382 if (!(flags & CBLK_INVALID)) {
383 status = mAudioTrack->start();
384 if (status == DEAD_OBJECT) {
385 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800386 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800387 }
388 if (flags & CBLK_INVALID) {
389 status = restoreTrack_l("start");
390 }
391
392 if (status != NO_ERROR) {
393 ALOGE("start() status %d", status);
394 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800395 if (t != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800396 t->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800397 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700398 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700399 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800400 }
401 }
402
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800403 // FIXME discarding status
404}
405
406void AudioTrack::stop()
407{
408 AutoMutex lock(mLock);
409 // FIXME pause then stop should not be a nop
410 if (mState != STATE_ACTIVE) {
411 return;
412 }
413
414 mState = STATE_STOPPED;
415 mProxy->interrupt();
416 mAudioTrack->stop();
417 // the playback head position will reset to 0, so if a marker is set, we need
418 // to activate it again
419 mMarkerReached = false;
420#if 0
421 // Force flush if a shared buffer is used otherwise audioflinger
422 // will not stop before end of buffer is reached.
423 // It may be needed to make sure that we stop playback, likely in case looping is on.
424 if (mSharedBuffer != 0) {
425 flush_l();
426 }
427#endif
428 sp<AudioTrackThread> t = mAudioTrackThread;
429 if (t != 0) {
430 t->pause();
431 } else {
432 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
433 set_sched_policy(0, mPreviousSchedulingGroup);
434 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800435}
436
437bool AudioTrack::stopped() const
438{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800439 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800440 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800441}
442
443void AudioTrack::flush()
444{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800445 if (mSharedBuffer != 0) {
446 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800447 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800448 AutoMutex lock(mLock);
449 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
450 return;
451 }
452 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800453}
454
Eric Laurent1703cdf2011-03-07 14:52:59 -0800455void AudioTrack::flush_l()
456{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800457 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700458
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700459 // clear playback marker and periodic update counter
460 mMarkerPosition = 0;
461 mMarkerReached = false;
462 mUpdatePeriod = 0;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700463
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800464 mState = STATE_FLUSHED;
465 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800466 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800467}
468
469void AudioTrack::pause()
470{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800471 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800472 if (mState != STATE_ACTIVE) {
473 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800474 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800475 mState = STATE_PAUSED;
476 mProxy->interrupt();
477 mAudioTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800478}
479
Eric Laurentbe916aa2010-06-01 23:49:17 -0700480status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800481{
Glenn Kastenf0c49502011-11-30 09:46:04 -0800482 if (left < 0.0f || left > 1.0f || right < 0.0f || right > 1.0f) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700483 return BAD_VALUE;
484 }
485
Eric Laurent1703cdf2011-03-07 14:52:59 -0800486 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800487 mVolume[LEFT] = left;
488 mVolume[RIGHT] = right;
489
Glenn Kastene3aa6592012-12-04 12:22:46 -0800490 mProxy->setVolumeLR((uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700491
492 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800493}
494
Glenn Kastenb1c09932012-02-27 16:21:04 -0800495status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800496{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800497 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700498}
499
Eric Laurent2beeb502010-07-16 07:43:46 -0700500status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700501{
Glenn Kasten05632a52012-01-03 14:22:33 -0800502 if (level < 0.0f || level > 1.0f) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700503 return BAD_VALUE;
504 }
505
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800506 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700507 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800508 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700509
510 return NO_ERROR;
511}
512
Glenn Kastena5224f32012-01-04 12:41:44 -0800513void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700514{
515 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800516 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700517 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800518}
519
Glenn Kasten3b16c762012-11-14 08:44:39 -0800520status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800521{
John Grossman4ff14ba2012-02-08 16:37:41 -0800522 if (mIsTimed) {
523 return INVALID_OPERATION;
524 }
525
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800526 uint32_t afSamplingRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800527 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700528 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800529 }
530 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Glenn Kastend65d73c2012-06-22 17:21:07 -0700531 if (rate == 0 || rate > afSamplingRate*2 ) {
532 return BAD_VALUE;
533 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800534
Eric Laurent1703cdf2011-03-07 14:52:59 -0800535 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800536 mSampleRate = rate;
537 mProxy->setSampleRate(rate);
538
Eric Laurent57326622009-07-07 07:10:45 -0700539 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800540}
541
Glenn Kastena5224f32012-01-04 12:41:44 -0800542uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800543{
John Grossman4ff14ba2012-02-08 16:37:41 -0800544 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800545 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800546 }
547
Eric Laurent1703cdf2011-03-07 14:52:59 -0800548 AutoMutex lock(mLock);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800549 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800550}
551
552status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
553{
Glenn Kasten083d1c12012-11-30 15:00:36 -0800554 if (mSharedBuffer == 0 || mIsTimed) {
555 return INVALID_OPERATION;
556 }
557
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800558 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800559 ;
560 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
561 loopEnd - loopStart >= MIN_LOOP) {
562 ;
563 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800564 return BAD_VALUE;
565 }
566
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800567 AutoMutex lock(mLock);
568 // See setPosition() regarding setting parameters such as loop points or position while active
569 if (mState == STATE_ACTIVE) {
570 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700571 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800572 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800573 return NO_ERROR;
574}
575
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800576void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
577{
578 // FIXME If setting a loop also sets position to start of loop, then
579 // this is correct. Otherwise it should be removed.
580 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
581 mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0;
582 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
583}
584
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800585status_t AudioTrack::setMarkerPosition(uint32_t marker)
586{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700587 if (mCbf == NULL) {
588 return INVALID_OPERATION;
589 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800590
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800591 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800592 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700593 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800594
595 return NO_ERROR;
596}
597
Glenn Kastena5224f32012-01-04 12:41:44 -0800598status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800599{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700600 if (marker == NULL) {
601 return BAD_VALUE;
602 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800603
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800604 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800605 *marker = mMarkerPosition;
606
607 return NO_ERROR;
608}
609
610status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
611{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700612 if (mCbf == NULL) {
613 return INVALID_OPERATION;
614 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800615
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800616 AutoMutex lock(mLock);
617 mNewPosition = mProxy->getPosition() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800618 mUpdatePeriod = updatePeriod;
619
620 return NO_ERROR;
621}
622
Glenn Kastena5224f32012-01-04 12:41:44 -0800623status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800624{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700625 if (updatePeriod == NULL) {
626 return BAD_VALUE;
627 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800628
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800629 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800630 *updatePeriod = mUpdatePeriod;
631
632 return NO_ERROR;
633}
634
635status_t AudioTrack::setPosition(uint32_t position)
636{
Glenn Kasten083d1c12012-11-30 15:00:36 -0800637 if (mSharedBuffer == 0 || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700638 return INVALID_OPERATION;
639 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800640 if (position > mFrameCount) {
641 return BAD_VALUE;
642 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800643
Eric Laurent1703cdf2011-03-07 14:52:59 -0800644 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800645 // Currently we require that the player is inactive before setting parameters such as position
646 // or loop points. Otherwise, there could be a race condition: the application could read the
647 // current position, compute a new position or loop parameters, and then set that position or
648 // loop parameters but it would do the "wrong" thing since the position has continued to advance
649 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
650 // to specify how it wants to handle such scenarios.
651 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700652 return INVALID_OPERATION;
653 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800654 mNewPosition = mProxy->getPosition() + mUpdatePeriod;
655 mLoopPeriod = 0;
656 // FIXME Check whether loops and setting position are incompatible in old code.
657 // If we use setLoop for both purposes we lose the capability to set the position while looping.
658 mStaticProxy->setLoop(position, mFrameCount, 0);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700659
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800660 return NO_ERROR;
661}
662
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800663status_t AudioTrack::getPosition(uint32_t *position) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800664{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700665 if (position == NULL) {
666 return BAD_VALUE;
667 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800668
Eric Laurent1703cdf2011-03-07 14:52:59 -0800669 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800670 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
671 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ? 0 :
672 mProxy->getPosition();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800673
674 return NO_ERROR;
675}
676
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800677status_t AudioTrack::getBufferPosition(size_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800678{
679 if (mSharedBuffer == 0 || mIsTimed) {
680 return INVALID_OPERATION;
681 }
682 if (position == NULL) {
683 return BAD_VALUE;
684 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800685
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800686 AutoMutex lock(mLock);
687 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800688 return NO_ERROR;
689}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800690
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800691status_t AudioTrack::reload()
692{
Glenn Kasten083d1c12012-11-30 15:00:36 -0800693 if (mSharedBuffer == 0 || mIsTimed) {
694 return INVALID_OPERATION;
695 }
696
Eric Laurent1703cdf2011-03-07 14:52:59 -0800697 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800698 // See setPosition() regarding setting parameters such as loop points or position while active
699 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700700 return INVALID_OPERATION;
701 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800702 mNewPosition = mUpdatePeriod;
703 mLoopPeriod = 0;
704 // FIXME The new code cannot reload while keeping a loop specified.
705 // Need to check how the old code handled this, and whether it's a significant change.
706 mStaticProxy->setLoop(0, mFrameCount, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800707 return NO_ERROR;
708}
709
Eric Laurentc2f1f072009-07-17 12:17:14 -0700710audio_io_handle_t AudioTrack::getOutput()
711{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800712 AutoMutex lock(mLock);
713 return getOutput_l();
714}
715
716// must be called with mLock held
717audio_io_handle_t AudioTrack::getOutput_l()
718{
Glenn Kastenfff6d712012-01-12 16:38:12 -0800719 return AudioSystem::getOutput(mStreamType,
Glenn Kastene3aa6592012-12-04 12:22:46 -0800720 mSampleRate, mFormat, mChannelMask, mFlags);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700721}
722
Eric Laurentbe916aa2010-06-01 23:49:17 -0700723status_t AudioTrack::attachAuxEffect(int effectId)
724{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800725 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700726 status_t status = mAudioTrack->attachAuxEffect(effectId);
727 if (status == NO_ERROR) {
728 mAuxEffectId = effectId;
729 }
730 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700731}
732
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800733// -------------------------------------------------------------------------
734
Eric Laurent1703cdf2011-03-07 14:52:59 -0800735// must be called with mLock held
736status_t AudioTrack::createTrack_l(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800737 audio_stream_type_t streamType,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800738 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800739 audio_format_t format,
Glenn Kastene33054e2012-11-14 12:54:39 -0800740 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700741 audio_output_flags_t flags,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800742 const sp<IMemory>& sharedBuffer,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800743 audio_io_handle_t output,
744 size_t epoch)
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800745{
746 status_t status;
747 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
748 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700749 ALOGE("Could not get audioflinger");
750 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800751 }
752
Eric Laurentd1b449a2010-05-14 03:26:45 -0700753 uint32_t afLatency;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800754 if ((status = AudioSystem::getLatency(output, streamType, &afLatency)) != NO_ERROR) {
755 ALOGE("getLatency(%d) failed status %d", output, status);
Eric Laurentd1b449a2010-05-14 03:26:45 -0700756 return NO_INIT;
757 }
758
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700759 // Client decides whether the track is TIMED (see below), but can only express a preference
760 // for FAST. Server will perform additional tests.
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700761 if ((flags & AUDIO_OUTPUT_FLAG_FAST) && !(
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700762 // either of these use cases:
763 // use case 1: shared buffer
764 (sharedBuffer != 0) ||
765 // use case 2: callback handler
766 (mCbf != NULL))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -0800767 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -0700768 // once denied, do not request again if IAudioTrack is re-created
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700769 flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten093000f2012-05-03 09:35:36 -0700770 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700771 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700772 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700773
Eric Laurentd1b449a2010-05-14 03:26:45 -0700774 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -0700775
Dima Zavinfce7a472011-04-19 22:30:36 -0700776 if (!audio_is_linear_pcm(format)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700777
Eric Laurentd1b449a2010-05-14 03:26:45 -0700778 if (sharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700779 // Same comment as below about ignoring frameCount parameter for set()
Eric Laurentd1b449a2010-05-14 03:26:45 -0700780 frameCount = sharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -0700781 } else if (frameCount == 0) {
Glenn Kastene33054e2012-11-14 12:54:39 -0800782 size_t afFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800783 status = AudioSystem::getFrameCount(output, streamType, &afFrameCount);
784 if (status != NO_ERROR) {
785 ALOGE("getFrameCount(output=%d, streamType=%d) status %d", output, streamType,
786 status);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700787 return NO_INIT;
788 }
789 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700790 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700791
792 } else if (sharedBuffer != 0) {
793
Glenn Kastena42ff002012-11-14 12:47:55 -0800794 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -0700795 // 8-bit data in shared memory is not currently supported by AudioFlinger
796 size_t alignment = /* format == AUDIO_FORMAT_PCM_8_BIT ? 1 : */ 2;
Glenn Kastena42ff002012-11-14 12:47:55 -0800797 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700798 // More than 2 channels does not require stronger alignment than stereo
799 alignment <<= 1;
800 }
Glenn Kastena42ff002012-11-14 12:47:55 -0800801 if (((size_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
802 ALOGE("Invalid buffer alignment: address %p, channel count %u",
803 sharedBuffer->pointer(), mChannelCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700804 return BAD_VALUE;
805 }
806
807 // When initializing a shared buffer AudioTrack via constructors,
808 // there's no frameCount parameter.
809 // But when initializing a shared buffer AudioTrack via set(),
810 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kastena42ff002012-11-14 12:47:55 -0800811 frameCount = sharedBuffer->size()/mChannelCount/sizeof(int16_t);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700812
813 } else if (!(flags & AUDIO_OUTPUT_FLAG_FAST)) {
814
815 // FIXME move these calculations and associated checks to server
Glenn Kasten3b16c762012-11-14 08:44:39 -0800816 uint32_t afSampleRate;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800817 status = AudioSystem::getSamplingRate(output, streamType, &afSampleRate);
818 if (status != NO_ERROR) {
819 ALOGE("getSamplingRate(output=%d, streamType=%d) status %d", output, streamType,
820 status);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700821 return NO_INIT;
822 }
Glenn Kastene33054e2012-11-14 12:54:39 -0800823 size_t afFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800824 status = AudioSystem::getFrameCount(output, streamType, &afFrameCount);
825 if (status != NO_ERROR) {
826 ALOGE("getFrameCount(output=%d, streamType=%d) status %d", output, streamType, status);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700827 return NO_INIT;
828 }
829
Eric Laurentd1b449a2010-05-14 03:26:45 -0700830 // Ensure that buffer depth covers at least audio hardware latency
831 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Glenn Kastenbb6f0a02013-06-03 15:00:29 -0700832 ALOGV("afFrameCount=%d, minBufCount=%d, afSampleRate=%u, afLatency=%d",
833 afFrameCount, minBufCount, afSampleRate, afLatency);
834 if (minBufCount <= 2) {
835 minBufCount = sampleRate == afSampleRate ? 2 : 3;
Glenn Kasten7c027242012-12-26 14:43:16 -0800836 }
Eric Laurentd1b449a2010-05-14 03:26:45 -0700837
Glenn Kastene33054e2012-11-14 12:54:39 -0800838 size_t minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
839 ALOGV("minFrameCount: %u, afFrameCount=%d, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -0800840 ", afLatency=%d",
841 minFrameCount, afFrameCount, minBufCount, sampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700842
843 if (frameCount == 0) {
844 frameCount = minFrameCount;
845 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700846 // Make sure that application is notified with sufficient margin
847 // before underrun
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800848 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/2) {
Glenn Kastene0fa4672012-04-24 14:35:14 -0700849 mNotificationFramesAct = frameCount/2;
850 }
851 if (frameCount < minFrameCount) {
852 // not ALOGW because it happens all the time when playing key clicks over A2DP
853 ALOGV("Minimum buffer size corrected from %d to %d",
854 frameCount, minFrameCount);
855 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800856 }
Eric Laurentd1b449a2010-05-14 03:26:45 -0700857
Glenn Kastene0fa4672012-04-24 14:35:14 -0700858 } else {
859 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -0700860 }
861
Glenn Kastena075db42012-03-06 11:22:44 -0800862 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
863 if (mIsTimed) {
864 trackFlags |= IAudioFlinger::TRACK_TIMED;
865 }
Glenn Kasten3acbd052012-02-28 10:39:56 -0800866
867 pid_t tid = -1;
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700868 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700869 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800870 if (mAudioTrackThread != 0) {
871 tid = mAudioTrackThread->getTid();
872 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700873 }
874
Glenn Kasten8d6cc842012-02-03 11:06:53 -0800875 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800876 sampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -0700877 // AudioFlinger only sees 16-bit PCM
878 format == AUDIO_FORMAT_PCM_8_BIT ?
879 AUDIO_FORMAT_PCM_16_BIT : format,
Glenn Kastena42ff002012-11-14 12:47:55 -0800880 mChannelMask,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800881 frameCount,
Glenn Kastene0b07172012-11-06 15:03:34 -0800882 &trackFlags,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800883 sharedBuffer,
884 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800885 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700886 &mSessionId,
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800887 &status);
888
889 if (track == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000890 ALOGE("AudioFlinger could not create track, status: %d", status);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800891 return status;
892 }
Glenn Kastend2c38fc2012-11-01 14:58:02 -0700893 sp<IMemory> iMem = track->getCblk();
894 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000895 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800896 return NO_INIT;
897 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800898 if (mAudioTrack != 0) {
899 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
900 mDeathNotifier.clear();
901 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800902 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -0700903 mCblkMemory = iMem;
904 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMem->pointer());
905 mCblk = cblk;
Glenn Kastenb6037442012-11-14 13:42:25 -0800906 size_t temp = cblk->frameCount_;
907 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
908 // In current design, AudioTrack client checks and ensures frame count validity before
909 // passing it to AudioFlinger so AudioFlinger should not return a different value except
910 // for fast track as it uses a special method of assigning frame count.
911 ALOGW("Requested frameCount %u but received frameCount %u", frameCount, temp);
912 }
913 frameCount = temp;
Glenn Kastena07f17c2013-04-23 12:39:37 -0700914 mAwaitBoost = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -0800915 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -0800916 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Glenn Kastenb6037442012-11-14 13:42:25 -0800917 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %u", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -0700918 mAwaitBoost = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800919 if (sharedBuffer == 0) {
920 // double-buffering is not required for fast tracks, due to tighter scheduling
921 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount) {
922 mNotificationFramesAct = frameCount;
923 }
924 }
Glenn Kasten3acbd052012-02-28 10:39:56 -0800925 } else {
Glenn Kastenb6037442012-11-14 13:42:25 -0800926 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %u", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -0700927 // once denied, do not request again if IAudioTrack is re-created
928 flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST);
929 mFlags = flags;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800930 if (sharedBuffer == 0) {
931 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/2) {
932 mNotificationFramesAct = frameCount/2;
933 }
934 }
Glenn Kastene0fa4672012-04-24 14:35:14 -0700935 }
Glenn Kasten3acbd052012-02-28 10:39:56 -0800936 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800937 mRefreshRemaining = true;
938
939 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
940 // is the value of pointer() for the shared buffer, otherwise buffers points
941 // immediately after the control block. This address is for the mapping within client
942 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
943 void* buffers;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800944 if (sharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800945 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800946 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800947 buffers = sharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800948 }
949
Eric Laurent2beeb502010-07-16 07:43:46 -0700950 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -0700951 // FIXME don't believe this lie
Glenn Kastenb6037442012-11-14 13:42:25 -0800952 mLatency = afLatency + (1000*frameCount) / sampleRate;
953 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -0700954 // If IAudioTrack is re-created, don't let the requested frameCount
955 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -0800956 if (frameCount > mReqFrameCount) {
957 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -0700958 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800959
960 // update proxy
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800961 if (sharedBuffer == 0) {
962 mStaticProxy.clear();
963 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
964 } else {
965 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
966 mProxy = mStaticProxy;
967 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800968 mProxy->setVolumeLR((uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) |
969 uint16_t(mVolume[LEFT] * 0x1000));
970 mProxy->setSendLevel(mSendLevel);
971 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800972 mProxy->setEpoch(epoch);
973 mProxy->setMinimum(mNotificationFramesAct);
974
975 mDeathNotifier = new DeathNotifier(this);
976 mAudioTrack->asBinder()->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800977
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800978 return NO_ERROR;
979}
980
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800981status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
982{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800983 if (audioBuffer == NULL) {
984 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -0700985 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800986 if (mTransfer != TRANSFER_OBTAIN) {
987 audioBuffer->frameCount = 0;
988 audioBuffer->size = 0;
989 audioBuffer->raw = NULL;
990 return INVALID_OPERATION;
991 }
Eric Laurent9b7d9502011-03-21 11:49:00 -0700992
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800993 const struct timespec *requested;
994 if (waitCount == -1) {
995 requested = &ClientProxy::kForever;
996 } else if (waitCount == 0) {
997 requested = &ClientProxy::kNonBlocking;
998 } else if (waitCount > 0) {
999 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
1000 struct timespec timeout;
1001 timeout.tv_sec = ms / 1000;
1002 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1003 requested = &timeout;
1004 } else {
1005 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1006 requested = NULL;
1007 }
1008 return obtainBuffer(audioBuffer, requested);
1009}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001010
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001011status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1012 struct timespec *elapsed, size_t *nonContig)
1013{
1014 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1015 uint32_t oldSequence = 0;
1016 uint32_t newSequence;
1017
1018 Proxy::Buffer buffer;
1019 status_t status = NO_ERROR;
1020
1021 static const int32_t kMaxTries = 5;
1022 int32_t tryCounter = kMaxTries;
1023
1024 do {
1025 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1026 // keep them from going away if another thread re-creates the track during obtainBuffer()
1027 sp<AudioTrackClientProxy> proxy;
1028 sp<IMemory> iMem;
1029
1030 { // start of lock scope
1031 AutoMutex lock(mLock);
1032
1033 newSequence = mSequence;
1034 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1035 if (status == DEAD_OBJECT) {
1036 // re-create track, unless someone else has already done so
1037 if (newSequence == oldSequence) {
1038 status = restoreTrack_l("obtainBuffer");
1039 if (status != NO_ERROR) {
1040 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001041 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001042 }
1043 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001044 oldSequence = newSequence;
1045
1046 // Keep the extra references
1047 proxy = mProxy;
1048 iMem = mCblkMemory;
1049
1050 // Non-blocking if track is stopped or paused
1051 if (mState != STATE_ACTIVE) {
1052 requested = &ClientProxy::kNonBlocking;
1053 }
1054
1055 } // end of lock scope
1056
1057 buffer.mFrameCount = audioBuffer->frameCount;
1058 // FIXME starts the requested timeout and elapsed over from scratch
1059 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1060
1061 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1062
1063 audioBuffer->frameCount = buffer.mFrameCount;
1064 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1065 audioBuffer->raw = buffer.mRaw;
1066 if (nonContig != NULL) {
1067 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001068 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001069 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001070}
1071
1072void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1073{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001074 if (mTransfer == TRANSFER_SHARED) {
1075 return;
1076 }
1077
1078 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1079 if (stepCount == 0) {
1080 return;
1081 }
1082
1083 Proxy::Buffer buffer;
1084 buffer.mFrameCount = stepCount;
1085 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001086
Eric Laurent1703cdf2011-03-07 14:52:59 -08001087 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001088 mInUnderrun = false;
1089 mProxy->releaseBuffer(&buffer);
1090
1091 // restart track if it was disabled by audioflinger due to previous underrun
1092 if (mState == STATE_ACTIVE) {
1093 audio_track_cblk_t* cblk = mCblk;
1094 if (android_atomic_and(~CBLK_DISABLED, &cblk->flags) & CBLK_DISABLED) {
1095 ALOGW("releaseBuffer() track %p name=%#x disabled due to previous underrun, restarting",
1096 this, cblk->mName);
1097 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001098 mAudioTrack->start();
1099 }
1100 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001101}
1102
1103// -------------------------------------------------------------------------
1104
1105ssize_t AudioTrack::write(const void* buffer, size_t userSize)
1106{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001107 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001108 return INVALID_OPERATION;
1109 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001110
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001111 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001112 // Sanity-check: user is most-likely passing an error code, and it would
1113 // make the return value ambiguous (actualSize vs error).
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001114 ALOGE("AudioTrack::write(buffer=%p, size=%u (%d)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001115 return BAD_VALUE;
1116 }
1117
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001118 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001119 Buffer audioBuffer;
1120
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001121 while (userSize >= mFrameSize) {
1122 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001123
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001124 status_t err = obtainBuffer(&audioBuffer, &ClientProxy::kForever);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001125 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001126 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001127 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001128 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001129 return ssize_t(err);
1130 }
1131
1132 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001133 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001134 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001135 toWrite = audioBuffer.size >> 1;
1136 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001137 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001138 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001139 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001140 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001141 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001142 userSize -= toWrite;
1143 written += toWrite;
1144
1145 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001146 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001147
1148 return written;
1149}
1150
1151// -------------------------------------------------------------------------
1152
John Grossman4ff14ba2012-02-08 16:37:41 -08001153TimedAudioTrack::TimedAudioTrack() {
1154 mIsTimed = true;
1155}
1156
1157status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1158{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001159 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001160 status_t result = UNKNOWN_ERROR;
1161
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001162#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001163 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1164 // while we are accessing the cblk
1165 sp<IAudioTrack> audioTrack = mAudioTrack;
1166 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001167#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001168
John Grossman4ff14ba2012-02-08 16:37:41 -08001169 // If the track is not invalid already, try to allocate a buffer. alloc
1170 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001171 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001172 audio_track_cblk_t* cblk = mCblk;
1173 if (!(cblk->flags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001174 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1175 if (result == DEAD_OBJECT) {
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001176 android_atomic_or(CBLK_INVALID, &cblk->flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001177 }
1178 }
1179
1180 // If the track is invalid at this point, attempt to restore it. and try the
1181 // allocation one more time.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001182 if (cblk->flags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001183 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001184
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001185 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001186 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001187 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001188 }
1189
1190 return result;
1191}
1192
1193status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1194 int64_t pts)
1195{
Eric Laurentdf839842012-05-31 14:27:14 -07001196 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1197 {
1198 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001199 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001200 // restart track if it was disabled by audioflinger due to previous underrun
1201 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001202 (mState == STATE_ACTIVE) && (cblk->flags & CBLK_DISABLED)) {
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001203 android_atomic_and(~CBLK_DISABLED, &cblk->flags);
Eric Laurentdf839842012-05-31 14:27:14 -07001204 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001205 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001206 mAudioTrack->start();
1207 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001208 }
Eric Laurentdf839842012-05-31 14:27:14 -07001209 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001210}
1211
1212status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1213 TargetTimeline target)
1214{
1215 return mAudioTrack->setMediaTimeTransform(xform, target);
1216}
1217
1218// -------------------------------------------------------------------------
1219
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001220nsecs_t AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001221{
Eric Laurent1703cdf2011-03-07 14:52:59 -08001222 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001223 if (mAwaitBoost) {
1224 mAwaitBoost = false;
1225 mLock.unlock();
1226 static const int32_t kMaxTries = 5;
1227 int32_t tryCounter = kMaxTries;
1228 uint32_t pollUs = 10000;
1229 do {
1230 int policy = sched_getscheduler(0);
1231 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1232 break;
1233 }
1234 usleep(pollUs);
1235 pollUs <<= 1;
1236 } while (tryCounter-- > 0);
1237 if (tryCounter < 0) {
1238 ALOGE("did not receive expected priority boost on time");
1239 }
1240 return true;
1241 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001242
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001243 // Can only reference mCblk while locked
1244 int32_t flags = android_atomic_and(
1245 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->flags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001246
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001247 // Check for track invalidation
1248 if (flags & CBLK_INVALID) {
1249 (void) restoreTrack_l("processAudioBuffer");
1250 mLock.unlock();
1251 // Run again immediately, but with a new IAudioTrack
1252 return 0;
1253 }
1254
1255 bool active = mState == STATE_ACTIVE;
1256
1257 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1258 bool newUnderrun = false;
1259 if (flags & CBLK_UNDERRUN) {
1260#if 0
1261 // Currently in shared buffer mode, when the server reaches the end of buffer,
1262 // the track stays active in continuous underrun state. It's up to the application
1263 // to pause or stop the track, or set the position to a new offset within buffer.
1264 // This was some experimental code to auto-pause on underrun. Keeping it here
1265 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1266 if (mTransfer == TRANSFER_SHARED) {
1267 mState = STATE_PAUSED;
1268 active = false;
1269 }
1270#endif
1271 if (!mInUnderrun) {
1272 mInUnderrun = true;
1273 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001274 }
1275 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001276
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001277 // Get current position of server
1278 size_t position = mProxy->getPosition();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001279
1280 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001281 bool markerReached = false;
1282 size_t markerPosition = mMarkerPosition;
1283 // FIXME fails for wraparound, need 64 bits
1284 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1285 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001286 }
1287
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001288 // Determine number of new position callback(s) that will be needed, while locked
1289 size_t newPosCount = 0;
1290 size_t newPosition = mNewPosition;
1291 size_t updatePeriod = mUpdatePeriod;
1292 // FIXME fails for wraparound, need 64 bits
1293 if (updatePeriod > 0 && position >= newPosition) {
1294 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1295 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001296 }
1297
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001298 // Cache other fields that will be needed soon
1299 uint32_t loopPeriod = mLoopPeriod;
1300 uint32_t sampleRate = mSampleRate;
1301 size_t notificationFrames = mNotificationFramesAct;
1302 if (mRefreshRemaining) {
1303 mRefreshRemaining = false;
1304 mRemainingFrames = notificationFrames;
1305 mRetryOnPartialBuffer = false;
1306 }
1307 size_t misalignment = mProxy->getMisalignment();
1308 int32_t sequence = mSequence;
1309
1310 // These fields don't need to be cached, because they are assigned only by set():
1311 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1312 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1313
1314 mLock.unlock();
1315
1316 // perform callbacks while unlocked
1317 if (newUnderrun) {
1318 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1319 }
1320 // FIXME we will miss loops if loop cycle was signaled several times since last call
1321 // to processAudioBuffer()
1322 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1323 mCbf(EVENT_LOOP_END, mUserData, NULL);
1324 }
1325 if (flags & CBLK_BUFFER_END) {
1326 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1327 }
1328 if (markerReached) {
1329 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1330 }
1331 while (newPosCount > 0) {
1332 size_t temp = newPosition;
1333 mCbf(EVENT_NEW_POS, mUserData, &temp);
1334 newPosition += updatePeriod;
1335 newPosCount--;
1336 }
1337 if (mObservedSequence != sequence) {
1338 mObservedSequence = sequence;
1339 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001340 }
1341
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001342 // if inactive, then don't run me again until re-started
1343 if (!active) {
1344 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001345 }
1346
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001347 // Compute the estimated time until the next timed event (position, markers, loops)
1348 // FIXME only for non-compressed audio
1349 uint32_t minFrames = ~0;
1350 if (!markerReached && position < markerPosition) {
1351 minFrames = markerPosition - position;
1352 }
1353 if (loopPeriod > 0 && loopPeriod < minFrames) {
1354 minFrames = loopPeriod;
1355 }
1356 if (updatePeriod > 0 && updatePeriod < minFrames) {
1357 minFrames = updatePeriod;
1358 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001359
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001360 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1361 static const uint32_t kPoll = 0;
1362 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1363 minFrames = kPoll * notificationFrames;
1364 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001365
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001366 // Convert frame units to time units
1367 nsecs_t ns = NS_WHENEVER;
1368 if (minFrames != (uint32_t) ~0) {
1369 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1370 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1371 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1372 }
1373
1374 // If not supplying data by EVENT_MORE_DATA, then we're done
1375 if (mTransfer != TRANSFER_CALLBACK) {
1376 return ns;
1377 }
1378
1379 struct timespec timeout;
1380 const struct timespec *requested = &ClientProxy::kForever;
1381 if (ns != NS_WHENEVER) {
1382 timeout.tv_sec = ns / 1000000000LL;
1383 timeout.tv_nsec = ns % 1000000000LL;
1384 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1385 requested = &timeout;
1386 }
1387
1388 while (mRemainingFrames > 0) {
1389
1390 Buffer audioBuffer;
1391 audioBuffer.frameCount = mRemainingFrames;
1392 size_t nonContig;
1393 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1394 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1395 "obtainBuffer() err=%d frameCount=%u", err, audioBuffer.frameCount);
1396 requested = &ClientProxy::kNonBlocking;
1397 size_t avail = audioBuffer.frameCount + nonContig;
1398 ALOGV("obtainBuffer(%u) returned %u = %u + %u",
1399 mRemainingFrames, avail, audioBuffer.frameCount, nonContig);
1400 if (err != NO_ERROR) {
1401 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR) {
1402 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001403 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001404 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1405 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001406 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001407
1408 if (mRetryOnPartialBuffer) {
1409 mRetryOnPartialBuffer = false;
1410 if (avail < mRemainingFrames) {
1411 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1412 if (ns < 0 || myns < ns) {
1413 ns = myns;
1414 }
1415 return ns;
1416 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001417 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001418
1419 // Divide buffer size by 2 to take into account the expansion
1420 // due to 8 to 16 bit conversion: the callback must fill only half
1421 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001422 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001423 audioBuffer.size >>= 1;
1424 }
1425
1426 size_t reqSize = audioBuffer.size;
1427 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001428 size_t writtenSize = audioBuffer.size;
1429 size_t writtenFrames = writtenSize / mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001430
1431 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001432 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
1433 ALOGE("EVENT_MORE_DATA requested %u bytes but callback returned %d bytes",
1434 reqSize, (int) writtenSize);
1435 return NS_NEVER;
1436 }
1437
1438 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001439 // The callback is done filling buffers
1440 // Keep this thread going to handle timed events and
1441 // still try to get more data in intervals of WAIT_PERIOD_MS
1442 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001443 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001444 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001445
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001446 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001447 // 8 to 16 bit conversion, note that source and destination are the same address
1448 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001449 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001450 }
1451
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001452 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1453 audioBuffer.frameCount = releasedFrames;
1454 mRemainingFrames -= releasedFrames;
1455 if (misalignment >= releasedFrames) {
1456 misalignment -= releasedFrames;
1457 } else {
1458 misalignment = 0;
1459 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001460
1461 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001462
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001463 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1464 // if callback doesn't like to accept the full chunk
1465 if (writtenSize < reqSize) {
1466 continue;
1467 }
1468
1469 // There could be enough non-contiguous frames available to satisfy the remaining request
1470 if (mRemainingFrames <= nonContig) {
1471 continue;
1472 }
1473
1474#if 0
1475 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1476 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1477 // that total to a sum == notificationFrames.
1478 if (0 < misalignment && misalignment <= mRemainingFrames) {
1479 mRemainingFrames = misalignment;
1480 return (mRemainingFrames * 1100000000LL) / sampleRate;
1481 }
1482#endif
1483
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001484 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001485 mRemainingFrames = notificationFrames;
1486 mRetryOnPartialBuffer = true;
1487
1488 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1489 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001490}
1491
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001492status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001493{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001494 ALOGW("dead IAudioTrack, creating a new one from %s()", from);
1495 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001496 status_t result;
1497
Glenn Kastena47f3162012-11-07 10:13:08 -08001498 // refresh the audio configuration cache in this process to make sure we get new
1499 // output parameters in getOutput_l() and createTrack_l()
1500 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001501
Glenn Kastena47f3162012-11-07 10:13:08 -08001502 // if the new IAudioTrack is created, createTrack_l() will modify the
1503 // following member variables: mAudioTrack, mCblkMemory and mCblk.
1504 // It will also delete the strong references on previous IAudioTrack and IMemory
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001505 size_t position = mProxy->getPosition();
1506 mNewPosition = position + mUpdatePeriod;
1507 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
Glenn Kastena47f3162012-11-07 10:13:08 -08001508 result = createTrack_l(mStreamType,
Glenn Kastene3aa6592012-12-04 12:22:46 -08001509 mSampleRate,
Glenn Kastena47f3162012-11-07 10:13:08 -08001510 mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001511 mReqFrameCount, // so that frame count never goes down
Glenn Kastena47f3162012-11-07 10:13:08 -08001512 mFlags,
1513 mSharedBuffer,
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001514 getOutput_l(),
1515 position /*epoch*/);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001516
Glenn Kastena47f3162012-11-07 10:13:08 -08001517 if (result == NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001518 // continue playback from last known position, but
1519 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1520 if (mStaticProxy != NULL) {
1521 mLoopPeriod = 0;
1522 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1523 }
1524 // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1525 // track destruction have been played? This is critical for SoundPool implementation
1526 // This must be broken, and needs to be tested/debugged.
1527#if 0
Glenn Kastena47f3162012-11-07 10:13:08 -08001528 // restore write index and set other indexes to reflect empty buffer status
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001529 if (!strcmp(from, "start")) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001530 // Make sure that a client relying on callback events indicating underrun or
1531 // the actual amount of audio frames played (e.g SoundPool) receives them.
1532 if (mSharedBuffer == 0) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001533 // restart playback even if buffer is not completely filled.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001534 android_atomic_or(CBLK_FORCEREADY, &mCblk->flags);
Eric Laurent1703cdf2011-03-07 14:52:59 -08001535 }
1536 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001537#endif
1538 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001539 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001540 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001541 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001542 if (result != NO_ERROR) {
1543 ALOGW("restoreTrack_l() failed status %d", result);
1544 mState = STATE_STOPPED;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001545 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001546
1547 return result;
1548}
1549
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001550status_t AudioTrack::setParameters(const String8& keyValuePairs)
1551{
1552 AutoMutex lock(mLock);
1553 if (mAudioTrack != 0) {
1554 return mAudioTrack->setParameters(keyValuePairs);
1555 } else {
1556 return NO_INIT;
1557 }
1558}
1559
1560String8 AudioTrack::getParameters(const String8& keys)
1561{
1562 return String8::empty();
1563}
1564
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001565status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1566{
1567
1568 const size_t SIZE = 256;
1569 char buffer[SIZE];
1570 String8 result;
1571
1572 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001573 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
1574 mVolume[0], mVolume[1]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001575 result.append(buffer);
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001576 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08001577 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001578 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001579 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001580 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001581 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001582 result.append(buffer);
1583 ::write(fd, result.string(), result.size());
1584 return NO_ERROR;
1585}
1586
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001587uint32_t AudioTrack::getUnderrunFrames() const
1588{
1589 AutoMutex lock(mLock);
1590 return mProxy->getUnderrunFrames();
1591}
1592
1593// =========================================================================
1594
1595void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who)
1596{
1597 sp<AudioTrack> audioTrack = mAudioTrack.promote();
1598 if (audioTrack != 0) {
1599 AutoMutex lock(audioTrack->mLock);
1600 audioTrack->mProxy->binderDied();
1601 }
1602}
1603
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001604// =========================================================================
1605
1606AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001607 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mResumeLatch(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08001608{
1609}
1610
1611AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001612{
1613}
1614
1615bool AudioTrack::AudioTrackThread::threadLoop()
1616{
Glenn Kasten3acbd052012-02-28 10:39:56 -08001617 {
1618 AutoMutex _l(mMyLock);
1619 if (mPaused) {
1620 mMyCond.wait(mMyLock);
1621 // caller will check for exitPending()
1622 return true;
1623 }
1624 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001625 nsecs_t ns = mReceiver.processAudioBuffer(this);
1626 switch (ns) {
1627 case 0:
1628 return true;
1629 case NS_WHENEVER:
1630 sleep(1);
1631 return true;
1632 case NS_INACTIVE:
1633 pauseConditional();
1634 return true;
1635 case NS_NEVER:
1636 return false;
1637 default:
1638 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns);
1639 struct timespec req;
1640 req.tv_sec = ns / 1000000000LL;
1641 req.tv_nsec = ns % 1000000000LL;
1642 nanosleep(&req, NULL /*rem*/);
1643 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07001644 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001645}
1646
Glenn Kasten3acbd052012-02-28 10:39:56 -08001647void AudioTrack::AudioTrackThread::requestExit()
1648{
1649 // must be in this order to avoid a race condition
1650 Thread::requestExit();
Glenn Kastenf4022f92012-05-02 10:34:59 -07001651 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08001652}
1653
1654void AudioTrack::AudioTrackThread::pause()
1655{
1656 AutoMutex _l(mMyLock);
1657 mPaused = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001658 mResumeLatch = false;
1659}
1660
1661void AudioTrack::AudioTrackThread::pauseConditional()
1662{
1663 AutoMutex _l(mMyLock);
1664 if (mResumeLatch) {
1665 mResumeLatch = false;
1666 } else {
1667 mPaused = true;
1668 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001669}
1670
1671void AudioTrack::AudioTrackThread::resume()
1672{
1673 AutoMutex _l(mMyLock);
1674 if (mPaused) {
1675 mPaused = false;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001676 mResumeLatch = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001677 mMyCond.signal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001678 } else {
1679 mResumeLatch = true;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001680 }
1681}
1682
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001683}; // namespace android