blob: 99750bd2a98c08069e50e315cb49fb90ce8b43ff [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
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080018//#define LOG_NDEBUG 0
19#define LOG_TAG "AudioTrack"
20
Mark Salyzyn34fb2962014-06-18 16:30:56 -070021#include <inttypes.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070022#include <math.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080023#include <sys/resource.h>
Mark Salyzyn34fb2962014-06-18 16:30:56 -070024
Glenn Kasten9f80dd22012-12-18 15:57:32 -080025#include <audio_utils/primitives.h>
26#include <binder/IPCThreadState.h>
27#include <media/AudioTrack.h>
28#include <utils/Log.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080029#include <private/media/AudioTrackShared.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/IAudioFlinger.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080031#include <media/AudioPolicyHelper.h>
Andy Hungcd044842014-08-07 11:04:34 -070032#include <media/AudioResamplerPublic.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080033
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010034#define WAIT_PERIOD_MS 10
35#define WAIT_STREAM_END_TIMEOUT_SEC 120
Andy Hung53c3b5f2014-12-15 16:42:05 -080036static const int kMaxLoopCountNotifications = 32;
Glenn Kasten511754b2012-01-11 09:52:19 -080037
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080038namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080039// ---------------------------------------------------------------------------
40
Andy Hung4ede21d2014-12-12 15:37:34 -080041template <typename T>
42const T &min(const T &x, const T &y) {
43 return x < y ? x : y;
44}
45
Andy Hung7f1bc8a2014-09-12 14:43:11 -070046static int64_t convertTimespecToUs(const struct timespec &tv)
47{
48 return tv.tv_sec * 1000000ll + tv.tv_nsec / 1000;
49}
50
51// current monotonic time in microseconds.
52static int64_t getNowUs()
53{
54 struct timespec tv;
55 (void) clock_gettime(CLOCK_MONOTONIC, &tv);
56 return convertTimespecToUs(tv);
57}
58
Chia-chi Yeh33005a92010-06-16 06:33:13 +080059// static
60status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080061 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080062 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080063 uint32_t sampleRate)
64{
Glenn Kastend65d73c2012-06-22 17:21:07 -070065 if (frameCount == NULL) {
66 return BAD_VALUE;
67 }
Glenn Kasten04cd0182012-06-25 11:49:27 -070068
Glenn Kastene0fa4672012-04-24 14:35:14 -070069 // FIXME merge with similar code in createTrack_l(), except we're missing
70 // some information here that is available in createTrack_l():
71 // audio_io_handle_t output
72 // audio_format_t format
73 // audio_channel_mask_t channelMask
74 // audio_output_flags_t flags
Glenn Kasten3b16c762012-11-14 08:44:39 -080075 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080076 status_t status;
77 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
78 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080079 ALOGE("Unable to query output sample rate for stream type %d; status %d",
80 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080081 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080082 }
Glenn Kastene33054e2012-11-14 12:54:39 -080083 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -080084 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
85 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080086 ALOGE("Unable to query output frame count for stream type %d; status %d",
87 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080088 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080089 }
90 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -080091 status = AudioSystem::getOutputLatency(&afLatency, streamType);
92 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080093 ALOGE("Unable to query output latency for stream type %d; status %d",
94 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080095 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080096 }
97
98 // Ensure that buffer depth covers at least audio hardware latency
99 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800100 if (minBufCount < 2) {
101 minBufCount = 2;
102 }
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800103
104 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
Andy Hungcd044842014-08-07 11:04:34 -0700105 afFrameCount * minBufCount * uint64_t(sampleRate) / afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -0800106 // The formula above should always produce a non-zero value, but return an error
107 // in the unlikely event that it does not, as that's part of the API contract.
108 if (*frameCount == 0) {
109 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %d",
110 streamType, sampleRate);
111 return BAD_VALUE;
112 }
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700113 ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, minBufCount=%d, afSampleRate=%d, afLatency=%d",
Glenn Kasten3acbd052012-02-28 10:39:56 -0800114 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800115 return NO_ERROR;
116}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800117
118// ---------------------------------------------------------------------------
119
120AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700121 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800122 mIsTimed(false),
123 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800124 mPreviousSchedulingGroup(SP_DEFAULT),
125 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800126{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700127 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
128 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
129 mAttributes.flags = 0x0;
130 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800131}
132
133AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800134 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800135 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800136 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700137 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800138 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700139 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800140 callback_t cbf,
141 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800142 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800143 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000144 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800145 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800146 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700147 pid_t pid,
148 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700149 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800150 mIsTimed(false),
151 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800152 mPreviousSchedulingGroup(SP_DEFAULT),
153 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800154{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700155 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700156 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800157 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700158 offloadInfo, uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800159}
160
Andreas Huberc8139852012-01-18 10:51:55 -0800161AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800162 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800163 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800164 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700165 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800166 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700167 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800168 callback_t cbf,
169 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800170 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800171 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000172 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800173 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800174 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700175 pid_t pid,
176 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700177 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800178 mIsTimed(false),
179 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800180 mPreviousSchedulingGroup(SP_DEFAULT),
181 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800182{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700183 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800184 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800185 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700186 uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800187}
188
189AudioTrack::~AudioTrack()
190{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800191 if (mStatus == NO_ERROR) {
192 // Make sure that callback function exits in the case where
193 // it is looping on buffer full condition in obtainBuffer().
194 // Otherwise the callback thread will never exit.
195 stop();
196 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100197 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800198 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800199 mAudioTrackThread->requestExitAndWait();
200 mAudioTrackThread.clear();
201 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800202 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700203 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700204 mCblkMemory.clear();
205 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800206 IPCThreadState::self()->flushCommands();
Marco Nelissend457c972014-02-11 08:47:07 -0800207 ALOGV("~AudioTrack, releasing session id from %d on behalf of %d",
208 IPCThreadState::self()->getCallingPid(), mClientPid);
209 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800210 }
211}
212
213status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800214 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800215 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800216 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700217 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800218 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700219 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800220 callback_t cbf,
221 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800222 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800223 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700224 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800225 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000226 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800227 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800228 int uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700229 pid_t pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700230 const audio_attributes_t* pAttributes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800231{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800232 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten838b3d82014-02-27 15:30:41 -0800233 "flags #%x, notificationFrames %u, sessionId %d, transferType %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800234 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten86f04662014-02-24 15:13:05 -0800235 sessionId, transferType);
236
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800237 switch (transferType) {
238 case TRANSFER_DEFAULT:
239 if (sharedBuffer != 0) {
240 transferType = TRANSFER_SHARED;
241 } else if (cbf == NULL || threadCanCallJava) {
242 transferType = TRANSFER_SYNC;
243 } else {
244 transferType = TRANSFER_CALLBACK;
245 }
246 break;
247 case TRANSFER_CALLBACK:
248 if (cbf == NULL || sharedBuffer != 0) {
249 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
250 return BAD_VALUE;
251 }
252 break;
253 case TRANSFER_OBTAIN:
254 case TRANSFER_SYNC:
255 if (sharedBuffer != 0) {
256 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
257 return BAD_VALUE;
258 }
259 break;
260 case TRANSFER_SHARED:
261 if (sharedBuffer == 0) {
262 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
263 return BAD_VALUE;
264 }
265 break;
266 default:
267 ALOGE("Invalid transfer type %d", transferType);
268 return BAD_VALUE;
269 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800270 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800271 mTransfer = transferType;
272
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700273 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
274 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800275
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700276 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700277
Eric Laurent1703cdf2011-03-07 14:52:59 -0800278 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800279
Glenn Kasten53cec222013-08-29 09:01:02 -0700280 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700281 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000282 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800283 return INVALID_OPERATION;
284 }
285
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800286 // handle default values first.
Eric Laurente83b55d2014-11-14 10:06:21 -0800287 if (streamType == AUDIO_STREAM_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700288 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800289 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700290 if (pAttributes == NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800291 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700292 ALOGE("Invalid stream type %d", streamType);
293 return BAD_VALUE;
294 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700295 mStreamType = streamType;
Eric Laurente83b55d2014-11-14 10:06:21 -0800296
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700297 } else {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700298 // stream type shouldn't be looked at, this track has audio attributes
299 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700300 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
301 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800302 mStreamType = AUDIO_STREAM_DEFAULT;
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800303 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700304
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800305 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800306 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700307 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800308 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800309
310 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700311 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800312 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800313 return BAD_VALUE;
314 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800315 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700316
Glenn Kasten8ba90322013-10-30 11:29:27 -0700317 if (!audio_is_output_channel(channelMask)) {
318 ALOGE("Invalid channel mask %#x", channelMask);
319 return BAD_VALUE;
320 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800321 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700322 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800323 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700324
Glenn Kastene0fa4672012-04-24 14:35:14 -0700325 // AudioFlinger does not currently support 8-bit data in shared memory
326 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
327 ALOGE("8-bit data in shared memory is not supported");
328 return BAD_VALUE;
329 }
330
Eric Laurentc2f1f072009-07-17 12:17:14 -0700331 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100332 // or offload was requested
333 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
334 || !audio_is_linear_pcm(format)) {
335 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
336 ? "Offload request, forcing to Direct Output"
337 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700338 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800339 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700340 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700341 }
342
Eric Laurentd1f69b02014-12-15 14:33:13 -0800343 // force direct flag if HW A/V sync requested
344 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
345 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
346 }
347
Glenn Kastenb7730382014-04-30 15:50:31 -0700348 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
349 if (audio_is_linear_pcm(format)) {
350 mFrameSize = channelCount * audio_bytes_per_sample(format);
351 } else {
352 mFrameSize = sizeof(uint8_t);
353 }
354 mFrameSizeAF = mFrameSize;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800355 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700356 ALOG_ASSERT(audio_is_linear_pcm(format));
357 mFrameSize = channelCount * audio_bytes_per_sample(format);
358 mFrameSizeAF = channelCount * audio_bytes_per_sample(
359 format == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : format);
360 // createTrack will return an error if PCM format is not supported by server,
361 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800362 }
363
Eric Laurent0d6db582014-11-12 18:39:44 -0800364 // sampling rate must be specified for direct outputs
365 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
366 return BAD_VALUE;
367 }
368 mSampleRate = sampleRate;
369
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800370 // Make copy of input parameter offloadInfo so that in the future:
371 // (a) createTrack_l doesn't need it as an input parameter
372 // (b) we can support re-creation of offloaded tracks
373 if (offloadInfo != NULL) {
374 mOffloadInfoCopy = *offloadInfo;
375 mOffloadInfo = &mOffloadInfoCopy;
376 } else {
377 mOffloadInfo = NULL;
378 }
379
Glenn Kasten66e46352014-01-16 17:44:23 -0800380 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
381 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800382 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800383 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800384 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700385 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800386 mNotificationFramesAct = 0;
Eric Laurentcaf7f482014-11-25 17:50:47 -0800387 if (sessionId == AUDIO_SESSION_ALLOCATE) {
388 mSessionId = AudioSystem::newAudioUniqueId();
389 } else {
390 mSessionId = sessionId;
391 }
Marco Nelissend457c972014-02-11 08:47:07 -0800392 int callingpid = IPCThreadState::self()->getCallingPid();
393 int mypid = getpid();
394 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800395 mClientUid = IPCThreadState::self()->getCallingUid();
396 } else {
397 mClientUid = uid;
398 }
Marco Nelissend457c972014-02-11 08:47:07 -0800399 if (pid == -1 || (callingpid != mypid)) {
400 mClientPid = callingpid;
401 } else {
402 mClientPid = pid;
403 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700404 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700405 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700406 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700407
Glenn Kastena997e7a2012-08-07 09:44:19 -0700408 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700409 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700410 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
411 }
412
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800413 // create the IAudioTrack
Eric Laurent0d6db582014-11-12 18:39:44 -0800414 status_t status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800415
Glenn Kastena997e7a2012-08-07 09:44:19 -0700416 if (status != NO_ERROR) {
417 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100418 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
419 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700420 mAudioTrackThread.clear();
421 }
422 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700423 }
424
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800425 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800426 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800427 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800428 mLoopCount = 0;
429 mLoopStart = 0;
430 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800431 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800432 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700433 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800434 mNewPosition = 0;
435 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700436 mServer = 0;
437 mPosition = 0;
438 mReleased = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700439 mStartUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800440 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800441 mSequence = 1;
442 mObservedSequence = mSequence;
443 mInUnderrun = false;
444
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800445 return NO_ERROR;
446}
447
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800448// -------------------------------------------------------------------------
449
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100450status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800451{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800452 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100453
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800454 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100455 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800456 }
457
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800458 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800459
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800460 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100461 if (previousState == STATE_PAUSED_STOPPING) {
462 mState = STATE_STOPPING;
463 } else {
464 mState = STATE_ACTIVE;
465 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700466 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800467 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
468 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700469 mPosition = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700470 // For offloaded tracks, we don't know if the hardware counters are really zero here,
471 // since the flush is asynchronous and stop may not fully drain.
472 // We save the time when the track is started to later verify whether
473 // the counters are realistic (i.e. start from zero after this time).
474 mStartUs = getNowUs();
475
Eric Laurentec9a0322013-08-28 10:23:01 -0700476 // force refresh of remaining frames by processAudioBuffer() as last
477 // write before stop could be partial.
478 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800479 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700480 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700481 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800482
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800483 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800484 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100485 if (previousState == STATE_STOPPING) {
486 mProxy->interrupt();
487 } else {
488 t->resume();
489 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800490 } else {
491 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
492 get_sched_policy(0, &mPreviousSchedulingGroup);
493 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
494 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800495
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800496 status_t status = NO_ERROR;
497 if (!(flags & CBLK_INVALID)) {
498 status = mAudioTrack->start();
499 if (status == DEAD_OBJECT) {
500 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800501 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800502 }
503 if (flags & CBLK_INVALID) {
504 status = restoreTrack_l("start");
505 }
506
507 if (status != NO_ERROR) {
508 ALOGE("start() status %d", status);
509 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800510 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100511 if (previousState != STATE_STOPPING) {
512 t->pause();
513 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800514 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700515 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700516 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800517 }
518 }
519
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100520 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800521}
522
523void AudioTrack::stop()
524{
525 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700526 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800527 return;
528 }
529
Glenn Kasten23a75452014-01-13 10:37:17 -0800530 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100531 mState = STATE_STOPPING;
532 } else {
533 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -0700534 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100535 }
536
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800537 mProxy->interrupt();
538 mAudioTrack->stop();
539 // the playback head position will reset to 0, so if a marker is set, we need
540 // to activate it again
541 mMarkerReached = false;
Andy Hung9b461582014-12-01 17:56:29 -0800542
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800543 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800544 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800545 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
546 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800547 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100548
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800549 sp<AudioTrackThread> t = mAudioTrackThread;
550 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800551 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100552 t->pause();
553 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800554 } else {
555 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
556 set_sched_policy(0, mPreviousSchedulingGroup);
557 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800558}
559
560bool AudioTrack::stopped() const
561{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800562 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800563 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800564}
565
566void AudioTrack::flush()
567{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800568 if (mSharedBuffer != 0) {
569 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800570 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800571 AutoMutex lock(mLock);
572 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
573 return;
574 }
575 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800576}
577
Eric Laurent1703cdf2011-03-07 14:52:59 -0800578void AudioTrack::flush_l()
579{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800580 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700581
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700582 // clear playback marker and periodic update counter
583 mMarkerPosition = 0;
584 mMarkerReached = false;
585 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100586 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700587
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800588 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700589 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800590 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100591 mProxy->interrupt();
592 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800593 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800594 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800595}
596
597void AudioTrack::pause()
598{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800599 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100600 if (mState == STATE_ACTIVE) {
601 mState = STATE_PAUSED;
602 } else if (mState == STATE_STOPPING) {
603 mState = STATE_PAUSED_STOPPING;
604 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800605 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800606 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800607 mProxy->interrupt();
608 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800609
Marco Nelissen3a90f282014-03-10 11:21:43 -0700610 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700611 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700612 // An offload output can be re-used between two audio tracks having
613 // the same configuration. A timestamp query for a paused track
614 // while the other is running would return an incorrect time.
615 // To fix this, cache the playback position on a pause() and return
616 // this time when requested until the track is resumed.
617
618 // OffloadThread sends HAL pause in its threadLoop. Time saved
619 // here can be slightly off.
620
621 // TODO: check return code for getRenderPosition.
622
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800623 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800624 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
625 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
626 }
627 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800628}
629
Eric Laurentbe916aa2010-06-01 23:49:17 -0700630status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800631{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700632 // This duplicates a test by AudioTrack JNI, but that is not the only caller
633 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
634 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700635 return BAD_VALUE;
636 }
637
Eric Laurent1703cdf2011-03-07 14:52:59 -0800638 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800639 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
640 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800641
Glenn Kastenc56f3422014-03-21 17:53:17 -0700642 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700643
Glenn Kasten23a75452014-01-13 10:37:17 -0800644 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700645 mAudioTrack->signal();
646 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700647 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800648}
649
Glenn Kastenb1c09932012-02-27 16:21:04 -0800650status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800651{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800652 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700653}
654
Eric Laurent2beeb502010-07-16 07:43:46 -0700655status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700656{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700657 // This duplicates a test by AudioTrack JNI, but that is not the only caller
658 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700659 return BAD_VALUE;
660 }
661
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800662 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700663 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800664 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700665
666 return NO_ERROR;
667}
668
Glenn Kastena5224f32012-01-04 12:41:44 -0800669void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700670{
671 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800672 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700673 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800674}
675
Glenn Kasten3b16c762012-11-14 08:44:39 -0800676status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800677{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700678 if (mIsTimed || isOffloadedOrDirect()) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800679 return INVALID_OPERATION;
680 }
681
Eric Laurent0d6db582014-11-12 18:39:44 -0800682 AutoMutex lock(mLock);
683 if (mOutput == AUDIO_IO_HANDLE_NONE) {
684 return NO_INIT;
685 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800686 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800687 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700688 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800689 }
Andy Hungcd044842014-08-07 11:04:34 -0700690 if (rate == 0 || rate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700691 return BAD_VALUE;
692 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800693
Glenn Kastene3aa6592012-12-04 12:22:46 -0800694 mSampleRate = rate;
695 mProxy->setSampleRate(rate);
696
Eric Laurent57326622009-07-07 07:10:45 -0700697 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800698}
699
Glenn Kastena5224f32012-01-04 12:41:44 -0800700uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800701{
John Grossman4ff14ba2012-02-08 16:37:41 -0800702 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800703 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800704 }
705
Eric Laurent1703cdf2011-03-07 14:52:59 -0800706 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700707
708 // sample rate can be updated during playback by the offloaded decoder so we need to
709 // query the HAL and update if needed.
710// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700711 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700712 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700713 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700714 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700715 if (status == NO_ERROR) {
716 mSampleRate = sampleRate;
717 }
718 }
719 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800720 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800721}
722
723status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
724{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700725 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800726 return INVALID_OPERATION;
727 }
728
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800729 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800730 ;
731 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
732 loopEnd - loopStart >= MIN_LOOP) {
733 ;
734 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800735 return BAD_VALUE;
736 }
737
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800738 AutoMutex lock(mLock);
739 // See setPosition() regarding setting parameters such as loop points or position while active
740 if (mState == STATE_ACTIVE) {
741 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700742 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800743 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800744 return NO_ERROR;
745}
746
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800747void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
748{
Andy Hung4ede21d2014-12-12 15:37:34 -0800749 // We do not update the periodic notification point.
750 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
751 mLoopCount = loopCount;
752 mLoopEnd = loopEnd;
753 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800754 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800755 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -0800756
757 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800758}
759
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800760status_t AudioTrack::setMarkerPosition(uint32_t marker)
761{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700762 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700763 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700764 return INVALID_OPERATION;
765 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800766
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800767 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800768 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700769 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800770
Andy Hung3c09c782014-12-29 18:39:32 -0800771 sp<AudioTrackThread> t = mAudioTrackThread;
772 if (t != 0) {
773 t->wake();
774 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800775 return NO_ERROR;
776}
777
Glenn Kastena5224f32012-01-04 12:41:44 -0800778status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800779{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700780 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100781 return INVALID_OPERATION;
782 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700783 if (marker == NULL) {
784 return BAD_VALUE;
785 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800786
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800787 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800788 *marker = mMarkerPosition;
789
790 return NO_ERROR;
791}
792
793status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
794{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700795 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700796 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700797 return INVALID_OPERATION;
798 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800799
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800800 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700801 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800802 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800803
Andy Hung3c09c782014-12-29 18:39:32 -0800804 sp<AudioTrackThread> t = mAudioTrackThread;
805 if (t != 0) {
806 t->wake();
807 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800808 return NO_ERROR;
809}
810
Glenn Kastena5224f32012-01-04 12:41:44 -0800811status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800812{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700813 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100814 return INVALID_OPERATION;
815 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700816 if (updatePeriod == NULL) {
817 return BAD_VALUE;
818 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800819
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800820 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800821 *updatePeriod = mUpdatePeriod;
822
823 return NO_ERROR;
824}
825
826status_t AudioTrack::setPosition(uint32_t position)
827{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700828 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700829 return INVALID_OPERATION;
830 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800831 if (position > mFrameCount) {
832 return BAD_VALUE;
833 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800834
Eric Laurent1703cdf2011-03-07 14:52:59 -0800835 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800836 // Currently we require that the player is inactive before setting parameters such as position
837 // or loop points. Otherwise, there could be a race condition: the application could read the
838 // current position, compute a new position or loop parameters, and then set that position or
839 // loop parameters but it would do the "wrong" thing since the position has continued to advance
840 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
841 // to specify how it wants to handle such scenarios.
842 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700843 return INVALID_OPERATION;
844 }
Andy Hung9b461582014-12-01 17:56:29 -0800845 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -0700846 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800847 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -0800848
849 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800850 return NO_ERROR;
851}
852
Glenn Kasten200092b2014-08-15 15:13:30 -0700853status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800854{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700855 if (position == NULL) {
856 return BAD_VALUE;
857 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800858
Eric Laurent1703cdf2011-03-07 14:52:59 -0800859 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700860 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100861 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800862
Eric Laurentab5cdba2014-06-09 17:22:27 -0700863 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800864 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
865 *position = mPausedPosition;
866 return NO_ERROR;
867 }
868
Glenn Kasten142f5192014-03-25 17:44:59 -0700869 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100870 uint32_t halFrames;
871 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
872 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700873 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
874 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100875 *position = dspFrames;
876 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -0800877 if (mCblk->mFlags & CBLK_INVALID) {
878 restoreTrack_l("getPosition");
879 }
880
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100881 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700882 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
883 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100884 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800885 return NO_ERROR;
886}
887
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000888status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800889{
890 if (mSharedBuffer == 0 || mIsTimed) {
891 return INVALID_OPERATION;
892 }
893 if (position == NULL) {
894 return BAD_VALUE;
895 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800896
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800897 AutoMutex lock(mLock);
898 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800899 return NO_ERROR;
900}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800901
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800902status_t AudioTrack::reload()
903{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700904 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800905 return INVALID_OPERATION;
906 }
907
Eric Laurent1703cdf2011-03-07 14:52:59 -0800908 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800909 // See setPosition() regarding setting parameters such as loop points or position while active
910 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700911 return INVALID_OPERATION;
912 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800913 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800914 (void) updateAndGetPosition_l();
915 mPosition = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800916#if 0
Andy Hung9b461582014-12-01 17:56:29 -0800917 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -0800918 // of loop count. Historically we have not restored loop count, start, end,
919 // but it makes sense if one desires to repeat playing a particular sound.
920 if (mLoopCount != 0) {
921 mLoopCountNotified = mLoopCount;
922 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
923 }
924#endif
Andy Hung9b461582014-12-01 17:56:29 -0800925 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800926 return NO_ERROR;
927}
928
Glenn Kasten38e905b2014-01-13 10:21:48 -0800929audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700930{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800931 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100932 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800933}
934
Eric Laurentbe916aa2010-06-01 23:49:17 -0700935status_t AudioTrack::attachAuxEffect(int effectId)
936{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800937 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -0700938 status_t status = mAudioTrack->attachAuxEffect(effectId);
939 if (status == NO_ERROR) {
940 mAuxEffectId = effectId;
941 }
942 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700943}
944
Eric Laurente83b55d2014-11-14 10:06:21 -0800945audio_stream_type_t AudioTrack::streamType() const
946{
947 if (mStreamType == AUDIO_STREAM_DEFAULT) {
948 return audio_attributes_to_stream_type(&mAttributes);
949 }
950 return mStreamType;
951}
952
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800953// -------------------------------------------------------------------------
954
Eric Laurent1703cdf2011-03-07 14:52:59 -0800955// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -0700956status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800957{
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800958 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
959 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700960 ALOGE("Could not get audioflinger");
961 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800962 }
963
Eric Laurente83b55d2014-11-14 10:06:21 -0800964 audio_io_handle_t output;
965 audio_stream_type_t streamType = mStreamType;
966 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
967 status_t status = AudioSystem::getOutputForAttr(attr, &output,
968 (audio_session_t)mSessionId, &streamType,
969 mSampleRate, mFormat, mChannelMask,
970 mFlags, mOffloadInfo);
971
972
973 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700974 ALOGE("Could not get audio output for stream type %d, usage %d, sample rate %u, format %#x,"
975 " channel mask %#x, flags %#x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800976 streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800977 return BAD_VALUE;
978 }
979 {
980 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
981 // we must release it ourselves if anything goes wrong.
982
Glenn Kastence8828a2013-09-16 18:07:38 -0700983 // Not all of these values are needed under all conditions, but it is easier to get them all
984
Eric Laurentd1b449a2010-05-14 03:26:45 -0700985 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -0700986 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -0700987 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800988 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800989 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700990 }
991
Glenn Kastence8828a2013-09-16 18:07:38 -0700992 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700993 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -0700994 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700995 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -0800996 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -0700997 }
998
999 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001000 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -07001001 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001002 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001003 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001004 }
Eric Laurent0d6db582014-11-12 18:39:44 -08001005 if (mSampleRate == 0) {
1006 mSampleRate = afSampleRate;
1007 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001008 // Client decides whether the track is TIMED (see below), but can only express a preference
1009 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001010 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001011 // either of these use cases:
1012 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -08001013 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001014 // use case 2: callback transfer mode
1015 (mTransfer == TRANSFER_CALLBACK)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001016 // matching sample rate
1017 (mSampleRate == afSampleRate))) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08001018 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
Glenn Kasten093000f2012-05-03 09:35:36 -07001019 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001020 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001021 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001022 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001023
Glenn Kastence8828a2013-09-16 18:07:38 -07001024 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -08001025 // n = 1 fast track with single buffering; nBuffering is ignored
1026 // n = 2 fast track with double buffering
Glenn Kastence8828a2013-09-16 18:07:38 -07001027 // n = 2 normal track, no sample rate conversion
1028 // n = 3 normal track, with sample rate conversion
1029 // (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering)
1030 // n > 3 very high latency or very small notification interval; nBuffering is ignored
Glenn Kasten363fb752014-01-15 12:27:31 -08001031 const uint32_t nBuffering = (mSampleRate == afSampleRate) ? 2 : 3;
Glenn Kastence8828a2013-09-16 18:07:38 -07001032
Eric Laurentd1b449a2010-05-14 03:26:45 -07001033 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001034
Glenn Kasten363fb752014-01-15 12:27:31 -08001035 size_t frameCount = mReqFrameCount;
1036 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001037
Glenn Kasten363fb752014-01-15 12:27:31 -08001038 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001039 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001040 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001041 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001042 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001043 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001044 if (mNotificationFramesAct != frameCount) {
1045 mNotificationFramesAct = frameCount;
1046 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001047 } else if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001048
Glenn Kastena42ff002012-11-14 12:47:55 -08001049 // Ensure that buffer alignment matches channel count
Glenn Kastene0fa4672012-04-24 14:35:14 -07001050 // 8-bit data in shared memory is not currently supported by AudioFlinger
Glenn Kastenb7730382014-04-30 15:50:31 -07001051 size_t alignment = audio_bytes_per_sample(
1052 mFormat == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : mFormat);
1053 if (alignment & 1) {
1054 alignment = 1;
1055 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001056 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001057 // More than 2 channels does not require stronger alignment than stereo
1058 alignment <<= 1;
1059 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001060 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001061 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001062 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001063 status = BAD_VALUE;
1064 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001065 }
1066
1067 // When initializing a shared buffer AudioTrack via constructors,
1068 // there's no frameCount parameter.
1069 // But when initializing a shared buffer AudioTrack via set(),
1070 // there _is_ a frameCount parameter. We silently ignore it.
Glenn Kastenb7730382014-04-30 15:50:31 -07001071 frameCount = mSharedBuffer->size() / mFrameSizeAF;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001072
Glenn Kasten363fb752014-01-15 12:27:31 -08001073 } else if (!(mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001074
1075 // FIXME move these calculations and associated checks to server
Glenn Kastene0fa4672012-04-24 14:35:14 -07001076
Eric Laurentd1b449a2010-05-14 03:26:45 -07001077 // Ensure that buffer depth covers at least audio hardware latency
1078 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001079 ALOGV("afFrameCount=%zu, minBufCount=%d, afSampleRate=%u, afLatency=%d",
Glenn Kastenbb6f0a02013-06-03 15:00:29 -07001080 afFrameCount, minBufCount, afSampleRate, afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001081 if (minBufCount <= nBuffering) {
1082 minBufCount = nBuffering;
Glenn Kasten7c027242012-12-26 14:43:16 -08001083 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001084
Andy Hungcd044842014-08-07 11:04:34 -07001085 size_t minFrameCount = afFrameCount * minBufCount * uint64_t(mSampleRate) / afSampleRate;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001086 ALOGV("minFrameCount: %zu, afFrameCount=%zu, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
Glenn Kasten3acbd052012-02-28 10:39:56 -08001087 ", afLatency=%d",
Glenn Kasten363fb752014-01-15 12:27:31 -08001088 minFrameCount, afFrameCount, minBufCount, mSampleRate, afSampleRate, afLatency);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001089
1090 if (frameCount == 0) {
1091 frameCount = minFrameCount;
Glenn Kastence8828a2013-09-16 18:07:38 -07001092 } else if (frameCount < minFrameCount) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001093 // not ALOGW because it happens all the time when playing key clicks over A2DP
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001094 ALOGV("Minimum buffer size corrected from %zu to %zu",
Glenn Kastene0fa4672012-04-24 14:35:14 -07001095 frameCount, minFrameCount);
1096 frameCount = minFrameCount;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001097 }
Glenn Kastence8828a2013-09-16 18:07:38 -07001098 // Make sure that application is notified with sufficient margin before underrun
1099 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1100 mNotificationFramesAct = frameCount/nBuffering;
1101 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001102
Glenn Kastene0fa4672012-04-24 14:35:14 -07001103 } else {
1104 // For fast tracks, the frame count calculations and checks are done by server
Eric Laurentd1b449a2010-05-14 03:26:45 -07001105 }
1106
Glenn Kastena075db42012-03-06 11:22:44 -08001107 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1108 if (mIsTimed) {
1109 trackFlags |= IAudioFlinger::TRACK_TIMED;
1110 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001111
1112 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001113 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001114 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001115 if (mAudioTrackThread != 0) {
1116 tid = mAudioTrackThread->getTid();
1117 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001118 }
1119
Glenn Kasten363fb752014-01-15 12:27:31 -08001120 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001121 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1122 }
1123
Eric Laurentab5cdba2014-06-09 17:22:27 -07001124 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1125 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1126 }
1127
Glenn Kasten74935e42013-12-19 08:56:45 -08001128 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1129 // but we will still need the original value also
Eric Laurente83b55d2014-11-14 10:06:21 -08001130 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001131 mSampleRate,
Glenn Kasten60a83922012-06-21 12:56:37 -07001132 // AudioFlinger only sees 16-bit PCM
Glenn Kastenc4b88a82014-04-30 16:54:30 -07001133 mFormat == AUDIO_FORMAT_PCM_8_BIT &&
1134 !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ?
Glenn Kasten363fb752014-01-15 12:27:31 -08001135 AUDIO_FORMAT_PCM_16_BIT : mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001136 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001137 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001138 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001139 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001140 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001141 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001142 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001143 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001144 &status);
1145
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001146 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001147 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001148 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001149 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001150 ALOG_ASSERT(track != 0);
1151
Glenn Kasten38e905b2014-01-13 10:21:48 -08001152 // AudioFlinger now owns the reference to the I/O handle,
1153 // so we are no longer responsible for releasing it.
1154
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001155 sp<IMemory> iMem = track->getCblk();
1156 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001157 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001158 return NO_INIT;
1159 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001160 void *iMemPointer = iMem->pointer();
1161 if (iMemPointer == NULL) {
1162 ALOGE("Could not get control block pointer");
1163 return NO_INIT;
1164 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001165 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001166 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001167 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001168 mDeathNotifier.clear();
1169 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001170 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001171 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001172 IPCThreadState::self()->flushCommands();
1173
Glenn Kasten0cde0762014-01-16 15:06:36 -08001174 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001175 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001176 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001177 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1178 // In current design, AudioTrack client checks and ensures frame count validity before
1179 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1180 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001181 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001182 }
1183 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001184
Glenn Kastena07f17c2013-04-23 12:39:37 -07001185 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001186 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001187 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001188 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001189 mAwaitBoost = true;
Glenn Kasten363fb752014-01-15 12:27:31 -08001190 if (mSharedBuffer == 0) {
Glenn Kastenb5fed682013-12-03 09:06:43 -08001191 // Theoretically double-buffering is not required for fast tracks,
1192 // due to tighter scheduling. But in practice, to accommodate kernels with
1193 // scheduling jitter, and apps with computation jitter, we use double-buffering.
1194 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1195 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001196 }
1197 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001198 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001199 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001200 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001201 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1202 if (mSharedBuffer == 0) {
Glenn Kastence8828a2013-09-16 18:07:38 -07001203 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1204 mNotificationFramesAct = frameCount/nBuffering;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001205 }
1206 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001207 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001208 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001209 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001210 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1211 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1212 } else {
1213 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001214 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001215 // FIXME This is a warning, not an error, so don't return error status
1216 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001217 }
1218 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001219 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1220 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1221 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1222 } else {
1223 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1224 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1225 // FIXME This is a warning, not an error, so don't return error status
1226 //return NO_INIT;
1227 }
1228 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001229
Glenn Kasten38e905b2014-01-13 10:21:48 -08001230 // We retain a copy of the I/O handle, but don't own the reference
1231 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001232 mRefreshRemaining = true;
1233
1234 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1235 // is the value of pointer() for the shared buffer, otherwise buffers points
1236 // immediately after the control block. This address is for the mapping within client
1237 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1238 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001239 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001240 buffers = (char*)cblk + sizeof(audio_track_cblk_t);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001241 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001242 buffers = mSharedBuffer->pointer();
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001243 }
1244
Eric Laurent2beeb502010-07-16 07:43:46 -07001245 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001246 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001247 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001248
Glenn Kastenb6037442012-11-14 13:42:25 -08001249 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001250 // If IAudioTrack is re-created, don't let the requested frameCount
1251 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001252 if (frameCount > mReqFrameCount) {
1253 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001254 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001255
1256 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001257 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001258 mStaticProxy.clear();
1259 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1260 } else {
1261 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1262 mProxy = mStaticProxy;
1263 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001264
1265 mProxy->setVolumeLR(gain_minifloat_pack(
1266 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1267 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1268
Glenn Kastene3aa6592012-12-04 12:22:46 -08001269 mProxy->setSendLevel(mSendLevel);
1270 mProxy->setSampleRate(mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001271 mProxy->setMinimum(mNotificationFramesAct);
1272
1273 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001274 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001275
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001276 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001277 }
1278
1279release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001280 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001281 if (status == NO_ERROR) {
1282 status = NO_INIT;
1283 }
1284 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001285}
1286
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001287status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1288{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001289 if (audioBuffer == NULL) {
1290 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001291 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001292 if (mTransfer != TRANSFER_OBTAIN) {
1293 audioBuffer->frameCount = 0;
1294 audioBuffer->size = 0;
1295 audioBuffer->raw = NULL;
1296 return INVALID_OPERATION;
1297 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001298
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001299 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001300 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001301 if (waitCount == -1) {
1302 requested = &ClientProxy::kForever;
1303 } else if (waitCount == 0) {
1304 requested = &ClientProxy::kNonBlocking;
1305 } else if (waitCount > 0) {
1306 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001307 timeout.tv_sec = ms / 1000;
1308 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1309 requested = &timeout;
1310 } else {
1311 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1312 requested = NULL;
1313 }
1314 return obtainBuffer(audioBuffer, requested);
1315}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001316
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001317status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1318 struct timespec *elapsed, size_t *nonContig)
1319{
1320 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1321 uint32_t oldSequence = 0;
1322 uint32_t newSequence;
1323
1324 Proxy::Buffer buffer;
1325 status_t status = NO_ERROR;
1326
1327 static const int32_t kMaxTries = 5;
1328 int32_t tryCounter = kMaxTries;
1329
1330 do {
1331 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1332 // keep them from going away if another thread re-creates the track during obtainBuffer()
1333 sp<AudioTrackClientProxy> proxy;
1334 sp<IMemory> iMem;
1335
1336 { // start of lock scope
1337 AutoMutex lock(mLock);
1338
1339 newSequence = mSequence;
1340 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1341 if (status == DEAD_OBJECT) {
1342 // re-create track, unless someone else has already done so
1343 if (newSequence == oldSequence) {
1344 status = restoreTrack_l("obtainBuffer");
1345 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001346 buffer.mFrameCount = 0;
1347 buffer.mRaw = NULL;
1348 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001349 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001350 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001351 }
1352 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001353 oldSequence = newSequence;
1354
1355 // Keep the extra references
1356 proxy = mProxy;
1357 iMem = mCblkMemory;
1358
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001359 if (mState == STATE_STOPPING) {
1360 status = -EINTR;
1361 buffer.mFrameCount = 0;
1362 buffer.mRaw = NULL;
1363 buffer.mNonContig = 0;
1364 break;
1365 }
1366
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001367 // Non-blocking if track is stopped or paused
1368 if (mState != STATE_ACTIVE) {
1369 requested = &ClientProxy::kNonBlocking;
1370 }
1371
1372 } // end of lock scope
1373
1374 buffer.mFrameCount = audioBuffer->frameCount;
1375 // FIXME starts the requested timeout and elapsed over from scratch
1376 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1377
1378 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1379
1380 audioBuffer->frameCount = buffer.mFrameCount;
1381 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1382 audioBuffer->raw = buffer.mRaw;
1383 if (nonContig != NULL) {
1384 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001385 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001386 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001387}
1388
1389void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1390{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001391 if (mTransfer == TRANSFER_SHARED) {
1392 return;
1393 }
1394
1395 size_t stepCount = audioBuffer->size / mFrameSizeAF;
1396 if (stepCount == 0) {
1397 return;
1398 }
1399
1400 Proxy::Buffer buffer;
1401 buffer.mFrameCount = stepCount;
1402 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001403
Eric Laurent1703cdf2011-03-07 14:52:59 -08001404 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001405 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001406 mInUnderrun = false;
1407 mProxy->releaseBuffer(&buffer);
1408
1409 // restart track if it was disabled by audioflinger due to previous underrun
1410 if (mState == STATE_ACTIVE) {
1411 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001412 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001413 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001414 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001415 mAudioTrack->start();
1416 }
1417 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001418}
1419
1420// -------------------------------------------------------------------------
1421
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001422ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001423{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001424 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001425 return INVALID_OPERATION;
1426 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001427
Eric Laurentab5cdba2014-06-09 17:22:27 -07001428 if (isDirect()) {
1429 AutoMutex lock(mLock);
1430 int32_t flags = android_atomic_and(
1431 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1432 &mCblk->mFlags);
1433 if (flags & CBLK_INVALID) {
1434 return DEAD_OBJECT;
1435 }
1436 }
1437
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001438 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001439 // Sanity-check: user is most-likely passing an error code, and it would
1440 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001441 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001442 return BAD_VALUE;
1443 }
1444
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001445 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001446 Buffer audioBuffer;
1447
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001448 while (userSize >= mFrameSize) {
1449 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001450
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001451 status_t err = obtainBuffer(&audioBuffer,
1452 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001453 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001454 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001455 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001456 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001457 return ssize_t(err);
1458 }
1459
1460 size_t toWrite;
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001461 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001462 // Divide capacity by 2 to take expansion into account
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001463 toWrite = audioBuffer.size >> 1;
1464 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
Eric Laurent33025262009-08-04 10:42:26 -07001465 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001466 toWrite = audioBuffer.size;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001467 memcpy(audioBuffer.i8, buffer, toWrite);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001468 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001469 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001470 userSize -= toWrite;
1471 written += toWrite;
1472
1473 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001474 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001475
1476 return written;
1477}
1478
1479// -------------------------------------------------------------------------
1480
John Grossman4ff14ba2012-02-08 16:37:41 -08001481TimedAudioTrack::TimedAudioTrack() {
1482 mIsTimed = true;
1483}
1484
1485status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1486{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001487 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001488 status_t result = UNKNOWN_ERROR;
1489
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001490#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001491 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1492 // while we are accessing the cblk
1493 sp<IAudioTrack> audioTrack = mAudioTrack;
1494 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001495#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001496
John Grossman4ff14ba2012-02-08 16:37:41 -08001497 // If the track is not invalid already, try to allocate a buffer. alloc
1498 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001499 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001500 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001501 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001502 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1503 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001504 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001505 }
1506 }
1507
1508 // If the track is invalid at this point, attempt to restore it. and try the
1509 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001510 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001511 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001512
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001513 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001514 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001515 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001516 }
1517
1518 return result;
1519}
1520
1521status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1522 int64_t pts)
1523{
Eric Laurentdf839842012-05-31 14:27:14 -07001524 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1525 {
1526 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001527 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001528 // restart track if it was disabled by audioflinger due to previous underrun
1529 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001530 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1531 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001532 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001533 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001534 mAudioTrack->start();
1535 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001536 }
Eric Laurentdf839842012-05-31 14:27:14 -07001537 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001538}
1539
1540status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1541 TargetTimeline target)
1542{
1543 return mAudioTrack->setMediaTimeTransform(xform, target);
1544}
1545
1546// -------------------------------------------------------------------------
1547
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001548nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001549{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001550 // Currently the AudioTrack thread is not created if there are no callbacks.
1551 // Would it ever make sense to run the thread, even without callbacks?
1552 // If so, then replace this by checks at each use for mCbf != NULL.
1553 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1554
Eric Laurent1703cdf2011-03-07 14:52:59 -08001555 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001556 if (mAwaitBoost) {
1557 mAwaitBoost = false;
1558 mLock.unlock();
1559 static const int32_t kMaxTries = 5;
1560 int32_t tryCounter = kMaxTries;
1561 uint32_t pollUs = 10000;
1562 do {
1563 int policy = sched_getscheduler(0);
1564 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1565 break;
1566 }
1567 usleep(pollUs);
1568 pollUs <<= 1;
1569 } while (tryCounter-- > 0);
1570 if (tryCounter < 0) {
1571 ALOGE("did not receive expected priority boost on time");
1572 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001573 // Run again immediately
1574 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001575 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001576
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001577 // Can only reference mCblk while locked
1578 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001579 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001580
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001581 // Check for track invalidation
1582 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001583 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1584 // AudioSystem cache. We should not exit here but after calling the callback so
1585 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001586 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001587 status_t status = restoreTrack_l("processAudioBuffer");
Andy Hung53c3b5f2014-12-15 16:42:05 -08001588 // after restoration, continue below to make sure that the loop and buffer events
1589 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001590 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001591 }
1592
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001593 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001594 bool active = mState == STATE_ACTIVE;
1595
1596 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1597 bool newUnderrun = false;
1598 if (flags & CBLK_UNDERRUN) {
1599#if 0
1600 // Currently in shared buffer mode, when the server reaches the end of buffer,
1601 // the track stays active in continuous underrun state. It's up to the application
1602 // to pause or stop the track, or set the position to a new offset within buffer.
1603 // This was some experimental code to auto-pause on underrun. Keeping it here
1604 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1605 if (mTransfer == TRANSFER_SHARED) {
1606 mState = STATE_PAUSED;
1607 active = false;
1608 }
1609#endif
1610 if (!mInUnderrun) {
1611 mInUnderrun = true;
1612 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001613 }
1614 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001615
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001616 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001617 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001618
1619 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001620 bool markerReached = false;
1621 size_t markerPosition = mMarkerPosition;
1622 // FIXME fails for wraparound, need 64 bits
1623 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1624 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001625 }
1626
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001627 // Determine number of new position callback(s) that will be needed, while locked
1628 size_t newPosCount = 0;
1629 size_t newPosition = mNewPosition;
1630 size_t updatePeriod = mUpdatePeriod;
1631 // FIXME fails for wraparound, need 64 bits
1632 if (updatePeriod > 0 && position >= newPosition) {
1633 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1634 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001635 }
1636
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001637 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001638 uint32_t sampleRate = mSampleRate;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001639 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001640 if (mRefreshRemaining) {
1641 mRefreshRemaining = false;
1642 mRemainingFrames = notificationFrames;
1643 mRetryOnPartialBuffer = false;
1644 }
1645 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001646 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001647 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001648
Andy Hung53c3b5f2014-12-15 16:42:05 -08001649 // Determine the number of new loop callback(s) that will be needed, while locked.
1650 int loopCountNotifications = 0;
1651 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1652
1653 if (mLoopCount > 0) {
1654 int loopCount;
1655 size_t bufferPosition;
1656 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1657 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1658 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1659 mLoopCountNotified = loopCount; // discard any excess notifications
1660 } else if (mLoopCount < 0) {
1661 // FIXME: We're not accurate with notification count and position with infinite looping
1662 // since loopCount from server side will always return -1 (we could decrement it).
1663 size_t bufferPosition = mStaticProxy->getBufferPosition();
1664 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1665 loopPeriod = mLoopEnd - bufferPosition;
1666 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1667 size_t bufferPosition = mStaticProxy->getBufferPosition();
1668 loopPeriod = mFrameCount - bufferPosition;
1669 }
1670
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001671 // These fields don't need to be cached, because they are assigned only by set():
1672 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1673 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1674
1675 mLock.unlock();
1676
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001677 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001678 struct timespec timeout;
1679 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1680 timeout.tv_nsec = 0;
1681
Glenn Kasten96f04882013-09-20 09:28:56 -07001682 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001683 switch (status) {
1684 case NO_ERROR:
1685 case DEAD_OBJECT:
1686 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001687 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001688 {
1689 AutoMutex lock(mLock);
1690 // The previously assigned value of waitStreamEnd is no longer valid,
1691 // since the mutex has been unlocked and either the callback handler
1692 // or another thread could have re-started the AudioTrack during that time.
1693 waitStreamEnd = mState == STATE_STOPPING;
1694 if (waitStreamEnd) {
1695 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001696 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001697 }
1698 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001699 if (waitStreamEnd && status != DEAD_OBJECT) {
1700 return NS_INACTIVE;
1701 }
1702 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001703 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001704 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001705 }
1706
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001707 // perform callbacks while unlocked
1708 if (newUnderrun) {
1709 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1710 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001711 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001712 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001713 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001714 }
1715 if (flags & CBLK_BUFFER_END) {
1716 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1717 }
1718 if (markerReached) {
1719 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1720 }
1721 while (newPosCount > 0) {
1722 size_t temp = newPosition;
1723 mCbf(EVENT_NEW_POS, mUserData, &temp);
1724 newPosition += updatePeriod;
1725 newPosCount--;
1726 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001727
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001728 if (mObservedSequence != sequence) {
1729 mObservedSequence = sequence;
1730 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001731 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001732 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001733 return NS_INACTIVE;
1734 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001735 }
1736
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001737 // if inactive, then don't run me again until re-started
1738 if (!active) {
1739 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001740 }
1741
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001742 // Compute the estimated time until the next timed event (position, markers, loops)
1743 // FIXME only for non-compressed audio
1744 uint32_t minFrames = ~0;
1745 if (!markerReached && position < markerPosition) {
1746 minFrames = markerPosition - position;
1747 }
1748 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08001749 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001750 minFrames = loopPeriod;
1751 }
Andy Hung2d85f092015-01-07 12:45:13 -08001752 if (updatePeriod > 0) {
1753 minFrames = min(minFrames, uint32_t(newPosition - position));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001754 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001755
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001756 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1757 static const uint32_t kPoll = 0;
1758 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1759 minFrames = kPoll * notificationFrames;
1760 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001761
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001762 // Convert frame units to time units
1763 nsecs_t ns = NS_WHENEVER;
1764 if (minFrames != (uint32_t) ~0) {
1765 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1766 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1767 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1768 }
1769
1770 // If not supplying data by EVENT_MORE_DATA, then we're done
1771 if (mTransfer != TRANSFER_CALLBACK) {
1772 return ns;
1773 }
1774
1775 struct timespec timeout;
1776 const struct timespec *requested = &ClientProxy::kForever;
1777 if (ns != NS_WHENEVER) {
1778 timeout.tv_sec = ns / 1000000000LL;
1779 timeout.tv_nsec = ns % 1000000000LL;
1780 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1781 requested = &timeout;
1782 }
1783
1784 while (mRemainingFrames > 0) {
1785
1786 Buffer audioBuffer;
1787 audioBuffer.frameCount = mRemainingFrames;
1788 size_t nonContig;
1789 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1790 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001791 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001792 requested = &ClientProxy::kNonBlocking;
1793 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001794 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001795 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001796 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001797 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1798 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001799 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001800 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001801 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1802 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001803 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001804
Eric Laurent42a6f422013-08-29 14:35:05 -07001805 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001806 mRetryOnPartialBuffer = false;
1807 if (avail < mRemainingFrames) {
1808 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1809 if (ns < 0 || myns < ns) {
1810 ns = myns;
1811 }
1812 return ns;
1813 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001814 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001815
1816 // Divide buffer size by 2 to take into account the expansion
1817 // due to 8 to 16 bit conversion: the callback must fill only half
1818 // of the destination buffer
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001819 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001820 audioBuffer.size >>= 1;
1821 }
1822
1823 size_t reqSize = audioBuffer.size;
1824 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001825 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001826
1827 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001828 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001829 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1830 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001831 return NS_NEVER;
1832 }
1833
1834 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001835 // The callback is done filling buffers
1836 // Keep this thread going to handle timed events and
1837 // still try to get more data in intervals of WAIT_PERIOD_MS
1838 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001839 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001840 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001841
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001842 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
Glenn Kasten511754b2012-01-11 09:52:19 -08001843 // 8 to 16 bit conversion, note that source and destination are the same address
1844 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001845 audioBuffer.size <<= 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001846 }
1847
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001848 size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1849 audioBuffer.frameCount = releasedFrames;
1850 mRemainingFrames -= releasedFrames;
1851 if (misalignment >= releasedFrames) {
1852 misalignment -= releasedFrames;
1853 } else {
1854 misalignment = 0;
1855 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001856
1857 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001858
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001859 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1860 // if callback doesn't like to accept the full chunk
1861 if (writtenSize < reqSize) {
1862 continue;
1863 }
1864
1865 // There could be enough non-contiguous frames available to satisfy the remaining request
1866 if (mRemainingFrames <= nonContig) {
1867 continue;
1868 }
1869
1870#if 0
1871 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1872 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1873 // that total to a sum == notificationFrames.
1874 if (0 < misalignment && misalignment <= mRemainingFrames) {
1875 mRemainingFrames = misalignment;
1876 return (mRemainingFrames * 1100000000LL) / sampleRate;
1877 }
1878#endif
1879
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001880 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001881 mRemainingFrames = notificationFrames;
1882 mRetryOnPartialBuffer = true;
1883
1884 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1885 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001886}
1887
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001888status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001889{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001890 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001891 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001892 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001893 status_t result;
1894
Glenn Kastena47f3162012-11-07 10:13:08 -08001895 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08001896 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001897 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001898
Eric Laurentab5cdba2014-06-09 17:22:27 -07001899 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001900 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001901 return DEAD_OBJECT;
1902 }
1903
Glenn Kasten200092b2014-08-15 15:13:30 -07001904 // save the old static buffer position
Andy Hung4ede21d2014-12-12 15:37:34 -08001905 size_t bufferPosition = 0;
1906 int loopCount = 0;
1907 if (mStaticProxy != 0) {
1908 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1909 }
Glenn Kasten200092b2014-08-15 15:13:30 -07001910
1911 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001912 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001913 // It will also delete the strong references on previous IAudioTrack and IMemory.
1914 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
1915 result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001916
1917 // take the frames that will be lost by track recreation into account in saved position
Andy Hung9b461582014-12-01 17:56:29 -08001918 // For streaming tracks, this is the amount we obtained from the user/client
1919 // (not the number actually consumed at the server - those are already lost).
Glenn Kasten200092b2014-08-15 15:13:30 -07001920 (void) updateAndGetPosition_l();
Andy Hung9b461582014-12-01 17:56:29 -08001921 if (mStaticProxy != 0) {
1922 mPosition = mReleased;
1923 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001924
Glenn Kastena47f3162012-11-07 10:13:08 -08001925 if (result == NO_ERROR) {
Andy Hung4ede21d2014-12-12 15:37:34 -08001926 // Continue playback from last known position and restore loop.
1927 if (mStaticProxy != 0) {
1928 if (loopCount != 0) {
1929 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
1930 mLoopStart, mLoopEnd, loopCount);
1931 } else {
1932 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001933 if (bufferPosition == mFrameCount) {
1934 ALOGD("restoring track at end of static buffer");
1935 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001936 }
1937 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001938 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001939 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001940 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001941 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001942 if (result != NO_ERROR) {
1943 ALOGW("restoreTrack_l() failed status %d", result);
1944 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001945 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001946 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001947
1948 return result;
1949}
1950
Glenn Kasten200092b2014-08-15 15:13:30 -07001951uint32_t AudioTrack::updateAndGetPosition_l()
1952{
1953 // This is the sole place to read server consumed frames
1954 uint32_t newServer = mProxy->getPosition();
1955 int32_t delta = newServer - mServer;
1956 mServer = newServer;
1957 // TODO There is controversy about whether there can be "negative jitter" in server position.
1958 // This should be investigated further, and if possible, it should be addressed.
1959 // A more definite failure mode is infrequent polling by client.
1960 // One could call (void)getPosition_l() in releaseBuffer(),
1961 // so mReleased and mPosition are always lock-step as best possible.
1962 // That should ensure delta never goes negative for infrequent polling
1963 // unless the server has more than 2^31 frames in its buffer,
1964 // in which case the use of uint32_t for these counters has bigger issues.
1965 if (delta < 0) {
1966 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
1967 delta = 0;
1968 }
1969 return mPosition += (uint32_t) delta;
1970}
1971
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001972status_t AudioTrack::setParameters(const String8& keyValuePairs)
1973{
1974 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07001975 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001976}
1977
Glenn Kastence703742013-07-19 16:33:58 -07001978status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1979{
Glenn Kasten53cec222013-08-29 09:01:02 -07001980 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07001981 // FIXME not implemented for fast tracks; should use proxy and SSQ
1982 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1983 return INVALID_OPERATION;
1984 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001985
1986 switch (mState) {
1987 case STATE_ACTIVE:
1988 case STATE_PAUSED:
1989 break; // handle below
1990 case STATE_FLUSHED:
1991 case STATE_STOPPED:
1992 return WOULD_BLOCK;
1993 case STATE_STOPPING:
1994 case STATE_PAUSED_STOPPING:
1995 if (!isOffloaded_l()) {
1996 return INVALID_OPERATION;
1997 }
1998 break; // offloaded tracks handled below
1999 default:
2000 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
2001 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07002002 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002003
Eric Laurent275e8e92014-11-30 15:14:47 -08002004 if (mCblk->mFlags & CBLK_INVALID) {
2005 restoreTrack_l("getTimestamp");
2006 }
2007
Glenn Kasten200092b2014-08-15 15:13:30 -07002008 // The presented frame count must always lag behind the consumed frame count.
2009 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002010 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002011 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07002012 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002013 return status;
2014 }
2015 if (isOffloadedOrDirect_l()) {
2016 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
2017 // use cached paused position in case another offloaded track is running.
2018 timestamp.mPosition = mPausedPosition;
2019 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
2020 return NO_ERROR;
2021 }
2022
2023 // Check whether a pending flush or stop has completed, as those commands may
2024 // be asynchronous or return near finish.
2025 if (mStartUs != 0 && mSampleRate != 0) {
2026 static const int kTimeJitterUs = 100000; // 100 ms
2027 static const int k1SecUs = 1000000;
2028
2029 const int64_t timeNow = getNowUs();
2030
2031 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
2032 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
2033 if (timestampTimeUs < mStartUs) {
2034 return WOULD_BLOCK; // stale timestamp time, occurs before start.
2035 }
2036 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
2037 const int64_t deltaPositionByUs = timestamp.mPosition * 1000000LL / mSampleRate;
2038
2039 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2040 // Verify that the counter can't count faster than the sample rate
2041 // since the start time. If greater, then that means we have failed
2042 // to completely flush or stop the previous playing track.
2043 ALOGW("incomplete flush or stop:"
2044 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2045 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2046 timestamp.mPosition);
2047 return WOULD_BLOCK;
2048 }
2049 }
2050 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
2051 }
2052 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002053 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2054 (void) updateAndGetPosition_l();
2055 // Server consumed (mServer) and presented both use the same server time base,
2056 // and server consumed is always >= presented.
2057 // The delta between these represents the number of frames in the buffer pipeline.
2058 // If this delta between these is greater than the client position, it means that
2059 // actually presented is still stuck at the starting line (figuratively speaking),
2060 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
2061 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2062 return INVALID_OPERATION;
2063 }
2064 // Convert timestamp position from server time base to client time base.
2065 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2066 // But if we change it to 64-bit then this could fail.
2067 // If (mPosition - mServer) can be negative then should use:
2068 // (int32_t)(mPosition - mServer)
2069 timestamp.mPosition += mPosition - mServer;
2070 // Immediately after a call to getPosition_l(), mPosition and
2071 // mServer both represent the same frame position. mPosition is
2072 // in client's point of view, and mServer is in server's point of
2073 // view. So the difference between them is the "fudge factor"
2074 // between client and server views due to stop() and/or new
2075 // IAudioTrack. And timestamp.mPosition is initially in server's
2076 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002077 }
2078 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002079}
2080
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002081String8 AudioTrack::getParameters(const String8& keys)
2082{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002083 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002084 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002085 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002086 } else {
2087 return String8::empty();
2088 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002089}
2090
Glenn Kasten23a75452014-01-13 10:37:17 -08002091bool AudioTrack::isOffloaded() const
2092{
2093 AutoMutex lock(mLock);
2094 return isOffloaded_l();
2095}
2096
Eric Laurentab5cdba2014-06-09 17:22:27 -07002097bool AudioTrack::isDirect() const
2098{
2099 AutoMutex lock(mLock);
2100 return isDirect_l();
2101}
2102
2103bool AudioTrack::isOffloadedOrDirect() const
2104{
2105 AutoMutex lock(mLock);
2106 return isOffloadedOrDirect_l();
2107}
2108
2109
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002110status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002111{
2112
2113 const size_t SIZE = 256;
2114 char buffer[SIZE];
2115 String8 result;
2116
2117 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002118 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002119 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002120 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002121 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002122 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002123 result.append(buffer);
Glenn Kastene3aa6592012-12-04 12:22:46 -08002124 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002125 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002126 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002127 result.append(buffer);
2128 ::write(fd, result.string(), result.size());
2129 return NO_ERROR;
2130}
2131
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002132uint32_t AudioTrack::getUnderrunFrames() const
2133{
2134 AutoMutex lock(mLock);
2135 return mProxy->getUnderrunFrames();
2136}
2137
2138// =========================================================================
2139
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002140void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002141{
2142 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2143 if (audioTrack != 0) {
2144 AutoMutex lock(audioTrack->mLock);
2145 audioTrack->mProxy->binderDied();
2146 }
2147}
2148
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002149// =========================================================================
2150
2151AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002152 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2153 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002154{
2155}
2156
2157AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002158{
2159}
2160
2161bool AudioTrack::AudioTrackThread::threadLoop()
2162{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002163 {
2164 AutoMutex _l(mMyLock);
2165 if (mPaused) {
2166 mMyCond.wait(mMyLock);
2167 // caller will check for exitPending()
2168 return true;
2169 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002170 if (mIgnoreNextPausedInt) {
2171 mIgnoreNextPausedInt = false;
2172 mPausedInt = false;
2173 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002174 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002175 if (mPausedNs > 0) {
2176 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2177 } else {
2178 mMyCond.wait(mMyLock);
2179 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002180 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002181 return true;
2182 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002183 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002184 if (exitPending()) {
2185 return false;
2186 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002187 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002188 switch (ns) {
2189 case 0:
2190 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002191 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002192 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002193 return true;
2194 case NS_NEVER:
2195 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002196 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08002197 // Event driven: call wake() when callback notifications conditions change.
2198 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002199 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002200 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002201 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002202 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002203 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002204 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002205}
2206
Glenn Kasten3acbd052012-02-28 10:39:56 -08002207void AudioTrack::AudioTrackThread::requestExit()
2208{
2209 // must be in this order to avoid a race condition
2210 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002211 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002212}
2213
2214void AudioTrack::AudioTrackThread::pause()
2215{
2216 AutoMutex _l(mMyLock);
2217 mPaused = true;
2218}
2219
2220void AudioTrack::AudioTrackThread::resume()
2221{
2222 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002223 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002224 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002225 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002226 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002227 mMyCond.signal();
2228 }
2229}
2230
Andy Hung3c09c782014-12-29 18:39:32 -08002231void AudioTrack::AudioTrackThread::wake()
2232{
2233 AutoMutex _l(mMyLock);
2234 if (!mPaused && mPausedInt && mPausedNs > 0) {
2235 // audio track is active and internally paused with timeout.
2236 mIgnoreNextPausedInt = true;
2237 mPausedInt = false;
2238 mMyCond.signal();
2239 }
2240}
2241
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002242void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2243{
2244 AutoMutex _l(mMyLock);
2245 mPausedInt = true;
2246 mPausedNs = ns;
2247}
2248
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002249}; // namespace android