blob: faf59359caa58889c9df5ee214776ade6f05f1e1 [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
Andy Hung26145642015-04-15 21:56:53 -070059// FIXME: we don't use the pitch setting in the time stretcher (not working);
60// instead we emulate it using our sample rate converter.
61static const bool kFixPitch = true; // enable pitch fix
62static inline uint32_t adjustSampleRate(uint32_t sampleRate, float pitch)
63{
64 return kFixPitch ? (sampleRate * pitch + 0.5) : sampleRate;
65}
66
67static inline float adjustSpeed(float speed, float pitch)
68{
69 return kFixPitch ? (speed / pitch) : speed;
70}
71
72static inline float adjustPitch(float pitch)
73{
74 return kFixPitch ? AUDIO_TIMESTRETCH_PITCH_NORMAL : pitch;
75}
76
Andy Hung8edb8dc2015-03-26 19:13:55 -070077// Must match similar computation in createTrack_l in Threads.cpp.
78// TODO: Move to a common library
79static size_t calculateMinFrameCount(
80 uint32_t afLatencyMs, uint32_t afFrameCount, uint32_t afSampleRate,
81 uint32_t sampleRate, float speed)
82{
83 // Ensure that buffer depth covers at least audio hardware latency
84 uint32_t minBufCount = afLatencyMs / ((1000 * afFrameCount) / afSampleRate);
85 if (minBufCount < 2) {
86 minBufCount = 2;
87 }
88 ALOGV("calculateMinFrameCount afLatency %u afFrameCount %u afSampleRate %u "
89 "sampleRate %u speed %f minBufCount: %u",
90 afLatencyMs, afFrameCount, afSampleRate, sampleRate, speed, minBufCount);
91 return minBufCount * sourceFramesNeededWithTimestretch(
92 sampleRate, afFrameCount, afSampleRate, speed);
93}
94
Chia-chi Yeh33005a92010-06-16 06:33:13 +080095// static
96status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080097 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080098 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080099 uint32_t sampleRate)
100{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700101 if (frameCount == NULL) {
102 return BAD_VALUE;
103 }
Glenn Kasten04cd0182012-06-25 11:49:27 -0700104
Andy Hung0e48d252015-01-26 11:43:15 -0800105 // FIXME handle in server, like createTrack_l(), possible missing info:
Glenn Kastene0fa4672012-04-24 14:35:14 -0700106 // audio_io_handle_t output
107 // audio_format_t format
108 // audio_channel_mask_t channelMask
Andy Hung0e48d252015-01-26 11:43:15 -0800109 // audio_output_flags_t flags (FAST)
Glenn Kasten3b16c762012-11-14 08:44:39 -0800110 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -0800111 status_t status;
112 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
113 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -0800114 ALOGE("Unable to query output sample rate for stream type %d; status %d",
115 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800116 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800117 }
Glenn Kastene33054e2012-11-14 12:54:39 -0800118 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -0800119 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
120 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -0800121 ALOGE("Unable to query output frame count for stream type %d; status %d",
122 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800123 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800124 }
125 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -0800126 status = AudioSystem::getOutputLatency(&afLatency, streamType);
127 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -0800128 ALOGE("Unable to query output latency for stream type %d; status %d",
129 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800130 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800131 }
132
Andy Hung8edb8dc2015-03-26 19:13:55 -0700133 // When called from createTrack, speed is 1.0f (normal speed).
134 // This is rechecked again on setting playback rate (TODO: on setting sample rate, too).
135 *frameCount = calculateMinFrameCount(afLatency, afFrameCount, afSampleRate, sampleRate, 1.0f);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800136
Andy Hung0e48d252015-01-26 11:43:15 -0800137 // The formula above should always produce a non-zero value under normal circumstances:
138 // AudioTrack.SAMPLE_RATE_HZ_MIN <= sampleRate <= AudioTrack.SAMPLE_RATE_HZ_MAX.
139 // Return error in the unlikely event that it does not, as that's part of the API contract.
Glenn Kasten66a04672014-01-08 08:53:44 -0800140 if (*frameCount == 0) {
Andy Hung0e48d252015-01-26 11:43:15 -0800141 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %u",
Glenn Kasten66a04672014-01-08 08:53:44 -0800142 streamType, sampleRate);
143 return BAD_VALUE;
144 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700145 ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, afSampleRate=%u, afLatency=%u",
146 *frameCount, afFrameCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800147 return NO_ERROR;
148}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800149
150// ---------------------------------------------------------------------------
151
152AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700153 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800154 mIsTimed(false),
155 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800156 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700157 mPausedPosition(0),
158 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800159{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700160 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
161 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
162 mAttributes.flags = 0x0;
163 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800164}
165
166AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800167 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800168 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800169 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700170 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800171 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700172 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800173 callback_t cbf,
174 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800175 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800176 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000177 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800178 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800179 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700180 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700181 const audio_attributes_t* pAttributes,
182 bool doNotReconnect)
Glenn Kasten87913512011-06-22 16:15:25 -0700183 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800184 mIsTimed(false),
185 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800186 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700187 mPausedPosition(0),
188 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800189{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700190 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700191 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800192 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700193 offloadInfo, uid, pid, pAttributes, doNotReconnect);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800194}
195
Andreas Huberc8139852012-01-18 10:51:55 -0800196AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800197 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800198 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800199 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700200 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800201 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700202 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800203 callback_t cbf,
204 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800205 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800206 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000207 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800208 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800209 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700210 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700211 const audio_attributes_t* pAttributes,
212 bool doNotReconnect)
Glenn Kasten87913512011-06-22 16:15:25 -0700213 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800214 mIsTimed(false),
215 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800216 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700217 mPausedPosition(0),
218 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800219{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700220 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800221 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800222 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700223 uid, pid, pAttributes, doNotReconnect);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800224}
225
226AudioTrack::~AudioTrack()
227{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800228 if (mStatus == NO_ERROR) {
229 // Make sure that callback function exits in the case where
230 // it is looping on buffer full condition in obtainBuffer().
231 // Otherwise the callback thread will never exit.
232 stop();
233 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100234 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800235 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800236 mAudioTrackThread->requestExitAndWait();
237 mAudioTrackThread.clear();
238 }
Eric Laurent296fb132015-05-01 11:38:42 -0700239 // No lock here: worst case we remove a NULL callback which will be a nop
240 if (mDeviceCallback != 0 && mOutput != AUDIO_IO_HANDLE_NONE) {
241 AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
242 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800243 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700244 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700245 mCblkMemory.clear();
246 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800247 IPCThreadState::self()->flushCommands();
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700248 ALOGV("~AudioTrack, releasing session id %d from %d on behalf of %d",
249 mSessionId, IPCThreadState::self()->getCallingPid(), mClientPid);
Marco Nelissend457c972014-02-11 08:47:07 -0800250 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800251 }
252}
253
254status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800255 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800256 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800257 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700258 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800259 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700260 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800261 callback_t cbf,
262 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800263 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800264 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700265 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800266 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000267 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800268 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800269 int uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700270 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700271 const audio_attributes_t* pAttributes,
272 bool doNotReconnect)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800273{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800274 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700275 "flags #%x, notificationFrames %u, sessionId %d, transferType %d, uid %d, pid %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800276 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700277 sessionId, transferType, uid, pid);
Glenn Kasten86f04662014-02-24 15:13:05 -0800278
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800279 switch (transferType) {
280 case TRANSFER_DEFAULT:
281 if (sharedBuffer != 0) {
282 transferType = TRANSFER_SHARED;
283 } else if (cbf == NULL || threadCanCallJava) {
284 transferType = TRANSFER_SYNC;
285 } else {
286 transferType = TRANSFER_CALLBACK;
287 }
288 break;
289 case TRANSFER_CALLBACK:
290 if (cbf == NULL || sharedBuffer != 0) {
291 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
292 return BAD_VALUE;
293 }
294 break;
295 case TRANSFER_OBTAIN:
296 case TRANSFER_SYNC:
297 if (sharedBuffer != 0) {
298 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
299 return BAD_VALUE;
300 }
301 break;
302 case TRANSFER_SHARED:
303 if (sharedBuffer == 0) {
304 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
305 return BAD_VALUE;
306 }
307 break;
308 default:
309 ALOGE("Invalid transfer type %d", transferType);
310 return BAD_VALUE;
311 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800312 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800313 mTransfer = transferType;
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700314 mDoNotReconnect = doNotReconnect;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800315
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700316 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
317 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800318
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700319 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700320
Glenn Kasten53cec222013-08-29 09:01:02 -0700321 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700322 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000323 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800324 return INVALID_OPERATION;
325 }
326
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800327 // handle default values first.
Eric Laurente83b55d2014-11-14 10:06:21 -0800328 if (streamType == AUDIO_STREAM_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700329 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800330 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700331 if (pAttributes == NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800332 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700333 ALOGE("Invalid stream type %d", streamType);
334 return BAD_VALUE;
335 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700336 mStreamType = streamType;
Eric Laurente83b55d2014-11-14 10:06:21 -0800337
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700338 } else {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700339 // stream type shouldn't be looked at, this track has audio attributes
340 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700341 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
342 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800343 mStreamType = AUDIO_STREAM_DEFAULT;
Eric Laurentc6bd5db2015-03-09 16:29:33 -0700344 if ((mAttributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
345 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
346 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800347 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700348
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800349 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800350 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700351 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800352 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800353
354 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700355 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800356 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800357 return BAD_VALUE;
358 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800359 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700360
Glenn Kasten8ba90322013-10-30 11:29:27 -0700361 if (!audio_is_output_channel(channelMask)) {
362 ALOGE("Invalid channel mask %#x", channelMask);
363 return BAD_VALUE;
364 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800365 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700366 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800367 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700368
Eric Laurentc2f1f072009-07-17 12:17:14 -0700369 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100370 // or offload was requested
371 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
372 || !audio_is_linear_pcm(format)) {
373 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
374 ? "Offload request, forcing to Direct Output"
375 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700376 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800377 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700378 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700379 }
380
Eric Laurentd1f69b02014-12-15 14:33:13 -0800381 // force direct flag if HW A/V sync requested
382 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
383 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
384 }
385
Glenn Kastenb7730382014-04-30 15:50:31 -0700386 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
387 if (audio_is_linear_pcm(format)) {
388 mFrameSize = channelCount * audio_bytes_per_sample(format);
389 } else {
390 mFrameSize = sizeof(uint8_t);
391 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800392 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700393 ALOG_ASSERT(audio_is_linear_pcm(format));
394 mFrameSize = channelCount * audio_bytes_per_sample(format);
Glenn Kastenb7730382014-04-30 15:50:31 -0700395 // createTrack will return an error if PCM format is not supported by server,
396 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800397 }
398
Eric Laurent0d6db582014-11-12 18:39:44 -0800399 // sampling rate must be specified for direct outputs
400 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
401 return BAD_VALUE;
402 }
403 mSampleRate = sampleRate;
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700404 mOriginalSampleRate = sampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700405 mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT;
Eric Laurent0d6db582014-11-12 18:39:44 -0800406
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800407 // Make copy of input parameter offloadInfo so that in the future:
408 // (a) createTrack_l doesn't need it as an input parameter
409 // (b) we can support re-creation of offloaded tracks
410 if (offloadInfo != NULL) {
411 mOffloadInfoCopy = *offloadInfo;
412 mOffloadInfo = &mOffloadInfoCopy;
413 } else {
414 mOffloadInfo = NULL;
415 }
416
Glenn Kasten66e46352014-01-16 17:44:23 -0800417 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
418 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800419 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800420 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800421 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700422 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800423 mNotificationFramesAct = 0;
Eric Laurentcaf7f482014-11-25 17:50:47 -0800424 if (sessionId == AUDIO_SESSION_ALLOCATE) {
425 mSessionId = AudioSystem::newAudioUniqueId();
426 } else {
427 mSessionId = sessionId;
428 }
Marco Nelissend457c972014-02-11 08:47:07 -0800429 int callingpid = IPCThreadState::self()->getCallingPid();
430 int mypid = getpid();
431 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800432 mClientUid = IPCThreadState::self()->getCallingUid();
433 } else {
434 mClientUid = uid;
435 }
Marco Nelissend457c972014-02-11 08:47:07 -0800436 if (pid == -1 || (callingpid != mypid)) {
437 mClientPid = callingpid;
438 } else {
439 mClientPid = pid;
440 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700441 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700442 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700443 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700444
Glenn Kastena997e7a2012-08-07 09:44:19 -0700445 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700446 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700447 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
Glenn Kastenbfd31842015-03-20 09:01:44 -0700448 // thread begins in paused state, and will not reference us until start()
Glenn Kastena997e7a2012-08-07 09:44:19 -0700449 }
450
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800451 // create the IAudioTrack
Eric Laurent0d6db582014-11-12 18:39:44 -0800452 status_t status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800453
Glenn Kastena997e7a2012-08-07 09:44:19 -0700454 if (status != NO_ERROR) {
455 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100456 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
457 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700458 mAudioTrackThread.clear();
459 }
460 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700461 }
462
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800463 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800464 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800465 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800466 mLoopCount = 0;
467 mLoopStart = 0;
468 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800469 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800470 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700471 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800472 mNewPosition = 0;
473 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700474 mServer = 0;
475 mPosition = 0;
476 mReleased = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700477 mStartUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800478 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800479 mSequence = 1;
480 mObservedSequence = mSequence;
481 mInUnderrun = false;
Phil Burk1b420972015-04-22 10:52:21 -0700482 mPreviousTimestampValid = false;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800483
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800484 return NO_ERROR;
485}
486
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800487// -------------------------------------------------------------------------
488
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100489status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800490{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800491 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100492
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800493 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100494 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800495 }
496
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800497 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800498
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800499 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100500 if (previousState == STATE_PAUSED_STOPPING) {
501 mState = STATE_STOPPING;
502 } else {
503 mState = STATE_ACTIVE;
504 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700505 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800506 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
507 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700508 mPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -0700509 mPreviousTimestampValid = false;
510
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700511 // For offloaded tracks, we don't know if the hardware counters are really zero here,
512 // since the flush is asynchronous and stop may not fully drain.
513 // We save the time when the track is started to later verify whether
514 // the counters are realistic (i.e. start from zero after this time).
515 mStartUs = getNowUs();
516
Eric Laurentec9a0322013-08-28 10:23:01 -0700517 // force refresh of remaining frames by processAudioBuffer() as last
518 // write before stop could be partial.
519 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800520 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700521 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700522 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800523
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800524 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800525 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100526 if (previousState == STATE_STOPPING) {
527 mProxy->interrupt();
528 } else {
529 t->resume();
530 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800531 } else {
532 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
533 get_sched_policy(0, &mPreviousSchedulingGroup);
534 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
535 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800536
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800537 status_t status = NO_ERROR;
538 if (!(flags & CBLK_INVALID)) {
539 status = mAudioTrack->start();
540 if (status == DEAD_OBJECT) {
541 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800542 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800543 }
544 if (flags & CBLK_INVALID) {
545 status = restoreTrack_l("start");
546 }
547
548 if (status != NO_ERROR) {
549 ALOGE("start() status %d", status);
550 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800551 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100552 if (previousState != STATE_STOPPING) {
553 t->pause();
554 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800555 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700556 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700557 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800558 }
559 }
560
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100561 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800562}
563
564void AudioTrack::stop()
565{
566 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700567 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800568 return;
569 }
570
Glenn Kasten23a75452014-01-13 10:37:17 -0800571 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100572 mState = STATE_STOPPING;
573 } else {
574 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -0700575 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100576 }
577
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800578 mProxy->interrupt();
579 mAudioTrack->stop();
580 // the playback head position will reset to 0, so if a marker is set, we need
581 // to activate it again
582 mMarkerReached = false;
Andy Hung9b461582014-12-01 17:56:29 -0800583
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800584 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800585 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800586 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
587 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800588 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100589
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800590 sp<AudioTrackThread> t = mAudioTrackThread;
591 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800592 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100593 t->pause();
594 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800595 } else {
596 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
597 set_sched_policy(0, mPreviousSchedulingGroup);
598 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800599}
600
601bool AudioTrack::stopped() const
602{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800603 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800604 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800605}
606
607void AudioTrack::flush()
608{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800609 if (mSharedBuffer != 0) {
610 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800611 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800612 AutoMutex lock(mLock);
613 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
614 return;
615 }
616 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800617}
618
Eric Laurent1703cdf2011-03-07 14:52:59 -0800619void AudioTrack::flush_l()
620{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800621 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700622
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700623 // clear playback marker and periodic update counter
624 mMarkerPosition = 0;
625 mMarkerReached = false;
626 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100627 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700628
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800629 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700630 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800631 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100632 mProxy->interrupt();
633 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800634 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800635 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800636}
637
638void AudioTrack::pause()
639{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800640 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100641 if (mState == STATE_ACTIVE) {
642 mState = STATE_PAUSED;
643 } else if (mState == STATE_STOPPING) {
644 mState = STATE_PAUSED_STOPPING;
645 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800646 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800647 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800648 mProxy->interrupt();
649 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800650
Marco Nelissen3a90f282014-03-10 11:21:43 -0700651 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700652 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700653 // An offload output can be re-used between two audio tracks having
654 // the same configuration. A timestamp query for a paused track
655 // while the other is running would return an incorrect time.
656 // To fix this, cache the playback position on a pause() and return
657 // this time when requested until the track is resumed.
658
659 // OffloadThread sends HAL pause in its threadLoop. Time saved
660 // here can be slightly off.
661
662 // TODO: check return code for getRenderPosition.
663
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800664 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800665 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
666 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
667 }
668 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800669}
670
Eric Laurentbe916aa2010-06-01 23:49:17 -0700671status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800672{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700673 // This duplicates a test by AudioTrack JNI, but that is not the only caller
674 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
675 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700676 return BAD_VALUE;
677 }
678
Eric Laurent1703cdf2011-03-07 14:52:59 -0800679 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800680 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
681 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800682
Glenn Kastenc56f3422014-03-21 17:53:17 -0700683 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700684
Glenn Kasten23a75452014-01-13 10:37:17 -0800685 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700686 mAudioTrack->signal();
687 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700688 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800689}
690
Glenn Kastenb1c09932012-02-27 16:21:04 -0800691status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800692{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800693 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700694}
695
Eric Laurent2beeb502010-07-16 07:43:46 -0700696status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700697{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700698 // This duplicates a test by AudioTrack JNI, but that is not the only caller
699 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700700 return BAD_VALUE;
701 }
702
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800703 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700704 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800705 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700706
707 return NO_ERROR;
708}
709
Glenn Kastena5224f32012-01-04 12:41:44 -0800710void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700711{
712 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800713 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700714 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800715}
716
Glenn Kasten3b16c762012-11-14 08:44:39 -0800717status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800718{
Andy Hung5cbb5782015-03-27 18:39:59 -0700719 AutoMutex lock(mLock);
720 if (rate == mSampleRate) {
721 return NO_ERROR;
722 }
723 if (mIsTimed || isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800724 return INVALID_OPERATION;
725 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800726 if (mOutput == AUDIO_IO_HANDLE_NONE) {
727 return NO_INIT;
728 }
Andy Hung5cbb5782015-03-27 18:39:59 -0700729 // NOTE: it is theoretically possible, but highly unlikely, that a device change
730 // could mean a previously allowed sampling rate is no longer allowed.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800731 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800732 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700733 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800734 }
Andy Hung26145642015-04-15 21:56:53 -0700735 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700736 const uint32_t effectiveSampleRate = adjustSampleRate(rate, mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -0700737 if (rate == 0 || effectiveSampleRate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700738 return BAD_VALUE;
739 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700740 // TODO: Should we also check if the buffer size is compatible?
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800741
Glenn Kastene3aa6592012-12-04 12:22:46 -0800742 mSampleRate = rate;
Andy Hung26145642015-04-15 21:56:53 -0700743 mProxy->setSampleRate(effectiveSampleRate);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800744
Eric Laurent57326622009-07-07 07:10:45 -0700745 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800746}
747
Glenn Kastena5224f32012-01-04 12:41:44 -0800748uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800749{
John Grossman4ff14ba2012-02-08 16:37:41 -0800750 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800751 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800752 }
753
Eric Laurent1703cdf2011-03-07 14:52:59 -0800754 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700755
756 // sample rate can be updated during playback by the offloaded decoder so we need to
757 // query the HAL and update if needed.
758// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700759 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700760 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700761 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700762 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700763 if (status == NO_ERROR) {
764 mSampleRate = sampleRate;
765 }
766 }
767 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800768 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800769}
770
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700771uint32_t AudioTrack::getOriginalSampleRate() const
772{
773 if (mIsTimed) {
774 return 0;
775 }
776
777 return mOriginalSampleRate;
778}
779
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700780status_t AudioTrack::setPlaybackRate(const AudioPlaybackRate &playbackRate)
Andy Hung8edb8dc2015-03-26 19:13:55 -0700781{
Andy Hung8edb8dc2015-03-26 19:13:55 -0700782 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700783 if (isAudioPlaybackRateEqual(playbackRate, mPlaybackRate)) {
Andy Hung8edb8dc2015-03-26 19:13:55 -0700784 return NO_ERROR;
785 }
786 if (mIsTimed || isOffloadedOrDirect_l()) {
787 return INVALID_OPERATION;
788 }
789 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
790 return INVALID_OPERATION;
791 }
Andy Hung26145642015-04-15 21:56:53 -0700792 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700793 const uint32_t effectiveRate = adjustSampleRate(mSampleRate, playbackRate.mPitch);
794 const float effectiveSpeed = adjustSpeed(playbackRate.mSpeed, playbackRate.mPitch);
795 const float effectivePitch = adjustPitch(playbackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -0700796 if (effectiveSpeed < AUDIO_TIMESTRETCH_SPEED_MIN
797 || effectiveSpeed > AUDIO_TIMESTRETCH_SPEED_MAX
798 || effectivePitch < AUDIO_TIMESTRETCH_PITCH_MIN
799 || effectivePitch > AUDIO_TIMESTRETCH_PITCH_MAX) {
800 return BAD_VALUE;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700801 //TODO: add function in AudioResamplerPublic.h to check for validity.
Andy Hung26145642015-04-15 21:56:53 -0700802 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700803 // Check if the buffer size is compatible.
Andy Hung26145642015-04-15 21:56:53 -0700804 if (!isSampleRateSpeedAllowed_l(effectiveRate, effectiveSpeed)) {
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700805 ALOGV("setPlaybackRate(%f, %f) failed", playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung8edb8dc2015-03-26 19:13:55 -0700806 return BAD_VALUE;
807 }
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700808 mPlaybackRate = playbackRate;
809 mProxy->setPlaybackRate(playbackRate);
810
811 //modify this
812 AudioPlaybackRate playbackRateTemp = playbackRate;
813 playbackRateTemp.mSpeed = effectiveSpeed;
814 playbackRateTemp.mPitch = effectivePitch;
815 mProxy->setPlaybackRate(playbackRateTemp);
Andy Hung26145642015-04-15 21:56:53 -0700816 mProxy->setSampleRate(effectiveRate); // FIXME: not quite "atomic" with setPlaybackRate
Andy Hung8edb8dc2015-03-26 19:13:55 -0700817 return NO_ERROR;
818}
819
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700820const AudioPlaybackRate& AudioTrack::getPlaybackRate() const
Andy Hung8edb8dc2015-03-26 19:13:55 -0700821{
822 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700823 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700824}
825
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800826status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
827{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700828 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800829 return INVALID_OPERATION;
830 }
831
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800832 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800833 ;
834 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
835 loopEnd - loopStart >= MIN_LOOP) {
836 ;
837 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800838 return BAD_VALUE;
839 }
840
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800841 AutoMutex lock(mLock);
842 // See setPosition() regarding setting parameters such as loop points or position while active
843 if (mState == STATE_ACTIVE) {
844 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700845 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800846 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800847 return NO_ERROR;
848}
849
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800850void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
851{
Andy Hung4ede21d2014-12-12 15:37:34 -0800852 // We do not update the periodic notification point.
853 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
854 mLoopCount = loopCount;
855 mLoopEnd = loopEnd;
856 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800857 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800858 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -0800859
860 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800861}
862
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800863status_t AudioTrack::setMarkerPosition(uint32_t marker)
864{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700865 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700866 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700867 return INVALID_OPERATION;
868 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800869
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800870 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800871 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700872 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800873
Andy Hung3c09c782014-12-29 18:39:32 -0800874 sp<AudioTrackThread> t = mAudioTrackThread;
875 if (t != 0) {
876 t->wake();
877 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800878 return NO_ERROR;
879}
880
Glenn Kastena5224f32012-01-04 12:41:44 -0800881status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800882{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700883 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100884 return INVALID_OPERATION;
885 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700886 if (marker == NULL) {
887 return BAD_VALUE;
888 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800889
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800890 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800891 *marker = mMarkerPosition;
892
893 return NO_ERROR;
894}
895
896status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
897{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700898 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700899 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700900 return INVALID_OPERATION;
901 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800902
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800903 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700904 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800905 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800906
Andy Hung3c09c782014-12-29 18:39:32 -0800907 sp<AudioTrackThread> t = mAudioTrackThread;
908 if (t != 0) {
909 t->wake();
910 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800911 return NO_ERROR;
912}
913
Glenn Kastena5224f32012-01-04 12:41:44 -0800914status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800915{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700916 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100917 return INVALID_OPERATION;
918 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700919 if (updatePeriod == NULL) {
920 return BAD_VALUE;
921 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800922
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800923 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800924 *updatePeriod = mUpdatePeriod;
925
926 return NO_ERROR;
927}
928
929status_t AudioTrack::setPosition(uint32_t position)
930{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700931 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700932 return INVALID_OPERATION;
933 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800934 if (position > mFrameCount) {
935 return BAD_VALUE;
936 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800937
Eric Laurent1703cdf2011-03-07 14:52:59 -0800938 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800939 // Currently we require that the player is inactive before setting parameters such as position
940 // or loop points. Otherwise, there could be a race condition: the application could read the
941 // current position, compute a new position or loop parameters, and then set that position or
942 // loop parameters but it would do the "wrong" thing since the position has continued to advance
943 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
944 // to specify how it wants to handle such scenarios.
945 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700946 return INVALID_OPERATION;
947 }
Andy Hung9b461582014-12-01 17:56:29 -0800948 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -0700949 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800950 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -0800951
952 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800953 return NO_ERROR;
954}
955
Glenn Kasten200092b2014-08-15 15:13:30 -0700956status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800957{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700958 if (position == NULL) {
959 return BAD_VALUE;
960 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800961
Eric Laurent1703cdf2011-03-07 14:52:59 -0800962 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700963 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100964 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800965
Eric Laurentab5cdba2014-06-09 17:22:27 -0700966 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800967 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
968 *position = mPausedPosition;
969 return NO_ERROR;
970 }
971
Glenn Kasten142f5192014-03-25 17:44:59 -0700972 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100973 uint32_t halFrames;
974 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
975 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700976 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
977 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100978 *position = dspFrames;
979 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -0800980 if (mCblk->mFlags & CBLK_INVALID) {
981 restoreTrack_l("getPosition");
982 }
983
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100984 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700985 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
986 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100987 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800988 return NO_ERROR;
989}
990
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000991status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800992{
993 if (mSharedBuffer == 0 || mIsTimed) {
994 return INVALID_OPERATION;
995 }
996 if (position == NULL) {
997 return BAD_VALUE;
998 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800999
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001000 AutoMutex lock(mLock);
1001 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001002 return NO_ERROR;
1003}
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001004
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001005status_t AudioTrack::reload()
1006{
Eric Laurentab5cdba2014-06-09 17:22:27 -07001007 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -08001008 return INVALID_OPERATION;
1009 }
1010
Eric Laurent1703cdf2011-03-07 14:52:59 -08001011 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001012 // See setPosition() regarding setting parameters such as loop points or position while active
1013 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001014 return INVALID_OPERATION;
1015 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001016 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -08001017 (void) updateAndGetPosition_l();
1018 mPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -07001019 mPreviousTimestampValid = false;
Andy Hung53c3b5f2014-12-15 16:42:05 -08001020#if 0
Andy Hung9b461582014-12-01 17:56:29 -08001021 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -08001022 // of loop count. Historically we have not restored loop count, start, end,
1023 // but it makes sense if one desires to repeat playing a particular sound.
1024 if (mLoopCount != 0) {
1025 mLoopCountNotified = mLoopCount;
1026 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
1027 }
1028#endif
Andy Hung9b461582014-12-01 17:56:29 -08001029 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001030 return NO_ERROR;
1031}
1032
Glenn Kasten38e905b2014-01-13 10:21:48 -08001033audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -07001034{
Eric Laurent1703cdf2011-03-07 14:52:59 -08001035 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001036 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001037}
1038
Paul McLeanaa981192015-03-21 09:55:15 -07001039status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
1040 AutoMutex lock(mLock);
1041 if (mSelectedDeviceId != deviceId) {
1042 mSelectedDeviceId = deviceId;
Eric Laurent493404d2015-04-21 15:07:36 -07001043 android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
Paul McLeanaa981192015-03-21 09:55:15 -07001044 }
Eric Laurent493404d2015-04-21 15:07:36 -07001045 return NO_ERROR;
Paul McLeanaa981192015-03-21 09:55:15 -07001046}
1047
1048audio_port_handle_t AudioTrack::getOutputDevice() {
1049 AutoMutex lock(mLock);
1050 return mSelectedDeviceId;
1051}
1052
Eric Laurent296fb132015-05-01 11:38:42 -07001053audio_port_handle_t AudioTrack::getRoutedDeviceId() {
1054 AutoMutex lock(mLock);
1055 if (mOutput == AUDIO_IO_HANDLE_NONE) {
1056 return AUDIO_PORT_HANDLE_NONE;
1057 }
1058 return AudioSystem::getDeviceIdForIo(mOutput);
1059}
1060
Eric Laurentbe916aa2010-06-01 23:49:17 -07001061status_t AudioTrack::attachAuxEffect(int effectId)
1062{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001063 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001064 status_t status = mAudioTrack->attachAuxEffect(effectId);
1065 if (status == NO_ERROR) {
1066 mAuxEffectId = effectId;
1067 }
1068 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -07001069}
1070
Eric Laurente83b55d2014-11-14 10:06:21 -08001071audio_stream_type_t AudioTrack::streamType() const
1072{
1073 if (mStreamType == AUDIO_STREAM_DEFAULT) {
1074 return audio_attributes_to_stream_type(&mAttributes);
1075 }
1076 return mStreamType;
1077}
1078
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001079// -------------------------------------------------------------------------
1080
Eric Laurent1703cdf2011-03-07 14:52:59 -08001081// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -07001082status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001083{
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001084 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
1085 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001086 ALOGE("Could not get audioflinger");
1087 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001088 }
1089
Eric Laurent296fb132015-05-01 11:38:42 -07001090 if (mDeviceCallback != 0 && mOutput != AUDIO_IO_HANDLE_NONE) {
1091 AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
1092 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001093 audio_io_handle_t output;
1094 audio_stream_type_t streamType = mStreamType;
1095 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
Eric Laurente83b55d2014-11-14 10:06:21 -08001096
Paul McLeanaa981192015-03-21 09:55:15 -07001097 status_t status;
1098 status = AudioSystem::getOutputForAttr(attr, &output,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001099 (audio_session_t)mSessionId, &streamType, mClientUid,
Paul McLeanaa981192015-03-21 09:55:15 -07001100 mSampleRate, mFormat, mChannelMask,
1101 mFlags, mSelectedDeviceId, mOffloadInfo);
Eric Laurente83b55d2014-11-14 10:06:21 -08001102
1103 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001104 ALOGE("Could not get audio output for session %d, stream type %d, usage %d, sample rate %u, format %#x,"
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001105 " channel mask %#x, flags %#x",
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001106 mSessionId, streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001107 return BAD_VALUE;
1108 }
1109 {
1110 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
1111 // we must release it ourselves if anything goes wrong.
1112
Glenn Kastence8828a2013-09-16 18:07:38 -07001113 // Not all of these values are needed under all conditions, but it is easier to get them all
1114
Eric Laurentd1b449a2010-05-14 03:26:45 -07001115 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -07001116 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001117 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001118 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001119 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001120 }
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001121 ALOGV("createTrack_l() output %d afLatency %u", output, afLatency);
Eric Laurentd1b449a2010-05-14 03:26:45 -07001122
Glenn Kastence8828a2013-09-16 18:07:38 -07001123 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001124 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -07001125 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001126 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001127 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001128 }
1129
1130 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001131 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -07001132 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001133 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001134 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001135 }
Eric Laurent0d6db582014-11-12 18:39:44 -08001136 if (mSampleRate == 0) {
1137 mSampleRate = afSampleRate;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001138 mOriginalSampleRate = afSampleRate;
Eric Laurent0d6db582014-11-12 18:39:44 -08001139 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001140 // Client decides whether the track is TIMED (see below), but can only express a preference
1141 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001142 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001143 // either of these use cases:
1144 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -08001145 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001146 // use case 2: callback transfer mode
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001147 (mTransfer == TRANSFER_CALLBACK) ||
1148 // use case 3: obtain/release mode
1149 (mTransfer == TRANSFER_OBTAIN)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001150 // matching sample rate
1151 (mSampleRate == afSampleRate))) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001152 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client; transfer %d, track %u Hz, output %u Hz",
1153 mTransfer, mSampleRate, afSampleRate);
Glenn Kasten093000f2012-05-03 09:35:36 -07001154 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001155 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001156 }
1157
Glenn Kastence8828a2013-09-16 18:07:38 -07001158 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -08001159 // n = 1 fast track with single buffering; nBuffering is ignored
1160 // n = 2 fast track with double buffering
Andy Hung0e48d252015-01-26 11:43:15 -08001161 // n = 2 normal track, (including those with sample rate conversion)
1162 // n >= 3 very high latency or very small notification interval (unused).
1163 const uint32_t nBuffering = 2;
Glenn Kastence8828a2013-09-16 18:07:38 -07001164
Eric Laurentd1b449a2010-05-14 03:26:45 -07001165 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001166
Glenn Kasten363fb752014-01-15 12:27:31 -08001167 size_t frameCount = mReqFrameCount;
1168 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001169
Glenn Kasten363fb752014-01-15 12:27:31 -08001170 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001171 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001172 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001173 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001174 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001175 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001176 if (mNotificationFramesAct != frameCount) {
1177 mNotificationFramesAct = frameCount;
1178 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001179 } else if (mSharedBuffer != 0) {
Andy Hungabdb9902015-01-12 15:08:22 -08001180 // FIXME: Ensure client side memory buffers need
1181 // not have additional alignment beyond sample
1182 // (e.g. 16 bit stereo accessed as 32 bit frame).
1183 size_t alignment = audio_bytes_per_sample(mFormat);
Glenn Kastenb7730382014-04-30 15:50:31 -07001184 if (alignment & 1) {
Andy Hungabdb9902015-01-12 15:08:22 -08001185 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
Glenn Kastenb7730382014-04-30 15:50:31 -07001186 alignment = 1;
1187 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001188 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001189 // More than 2 channels does not require stronger alignment than stereo
1190 alignment <<= 1;
1191 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001192 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001193 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001194 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001195 status = BAD_VALUE;
1196 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001197 }
1198
1199 // When initializing a shared buffer AudioTrack via constructors,
1200 // there's no frameCount parameter.
1201 // But when initializing a shared buffer AudioTrack via set(),
1202 // there _is_ a frameCount parameter. We silently ignore it.
Andy Hungabdb9902015-01-12 15:08:22 -08001203 frameCount = mSharedBuffer->size() / mFrameSize;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001204 } else {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001205 // For fast tracks the frame count calculations and checks are done by server
1206
1207 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1208 // for normal tracks precompute the frame count based on speed.
1209 const size_t minFrameCount = calculateMinFrameCount(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001210 afLatency, afFrameCount, afSampleRate, mSampleRate,
1211 mPlaybackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07001212 if (frameCount < minFrameCount) {
1213 frameCount = minFrameCount;
1214 }
1215 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001216 }
1217
Glenn Kastena075db42012-03-06 11:22:44 -08001218 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1219 if (mIsTimed) {
1220 trackFlags |= IAudioFlinger::TRACK_TIMED;
1221 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001222
1223 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001224 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001225 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001226 if (mAudioTrackThread != 0) {
1227 tid = mAudioTrackThread->getTid();
1228 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001229 }
1230
Glenn Kasten363fb752014-01-15 12:27:31 -08001231 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001232 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1233 }
1234
Eric Laurentab5cdba2014-06-09 17:22:27 -07001235 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1236 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1237 }
1238
Glenn Kasten74935e42013-12-19 08:56:45 -08001239 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1240 // but we will still need the original value also
Glenn Kasten138d6f92015-03-20 10:54:51 -07001241 int originalSessionId = mSessionId;
Eric Laurente83b55d2014-11-14 10:06:21 -08001242 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001243 mSampleRate,
Andy Hungabdb9902015-01-12 15:08:22 -08001244 mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001245 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001246 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001247 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001248 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001249 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001250 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001251 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001252 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001253 &status);
Glenn Kasten138d6f92015-03-20 10:54:51 -07001254 ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
1255 "session ID changed from %d to %d", originalSessionId, mSessionId);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001256
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001257 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001258 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001259 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001260 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001261 ALOG_ASSERT(track != 0);
1262
Glenn Kasten38e905b2014-01-13 10:21:48 -08001263 // AudioFlinger now owns the reference to the I/O handle,
1264 // so we are no longer responsible for releasing it.
1265
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001266 sp<IMemory> iMem = track->getCblk();
1267 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001268 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001269 return NO_INIT;
1270 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001271 void *iMemPointer = iMem->pointer();
1272 if (iMemPointer == NULL) {
1273 ALOGE("Could not get control block pointer");
1274 return NO_INIT;
1275 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001276 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001277 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001278 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001279 mDeathNotifier.clear();
1280 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001281 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001282 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001283 IPCThreadState::self()->flushCommands();
1284
Glenn Kasten0cde0762014-01-16 15:06:36 -08001285 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001286 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001287 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001288 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1289 // In current design, AudioTrack client checks and ensures frame count validity before
1290 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1291 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001292 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001293 }
1294 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001295
Glenn Kastena07f17c2013-04-23 12:39:37 -07001296 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001297 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001298 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001299 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001300 mAwaitBoost = true;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001301 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001302 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001303 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001304 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001305 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001306 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001307 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001308 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1309 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1310 } else {
1311 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001312 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001313 // FIXME This is a warning, not an error, so don't return error status
1314 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001315 }
1316 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001317 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1318 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1319 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1320 } else {
1321 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1322 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1323 // FIXME This is a warning, not an error, so don't return error status
1324 //return NO_INIT;
1325 }
1326 }
Andy Hung0e48d252015-01-26 11:43:15 -08001327 // Make sure that application is notified with sufficient margin before underrun
1328 if (mSharedBuffer == 0 && audio_is_linear_pcm(mFormat)) {
1329 // Theoretically double-buffering is not required for fast tracks,
1330 // due to tighter scheduling. But in practice, to accommodate kernels with
1331 // scheduling jitter, and apps with computation jitter, we use double-buffering
1332 // for fast tracks just like normal streaming tracks.
1333 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount / nBuffering) {
1334 mNotificationFramesAct = frameCount / nBuffering;
1335 }
1336 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001337
Glenn Kasten38e905b2014-01-13 10:21:48 -08001338 // We retain a copy of the I/O handle, but don't own the reference
1339 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001340 mRefreshRemaining = true;
1341
1342 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1343 // is the value of pointer() for the shared buffer, otherwise buffers points
1344 // immediately after the control block. This address is for the mapping within client
1345 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1346 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001347 if (mSharedBuffer == 0) {
Glenn Kasten138d6f92015-03-20 10:54:51 -07001348 buffers = cblk + 1;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001349 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001350 buffers = mSharedBuffer->pointer();
Glenn Kasten138d6f92015-03-20 10:54:51 -07001351 if (buffers == NULL) {
1352 ALOGE("Could not get buffer pointer");
1353 return NO_INIT;
1354 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001355 }
1356
Eric Laurent2beeb502010-07-16 07:43:46 -07001357 mAudioTrack->attachAuxEffect(mAuxEffectId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07001358 // FIXME doesn't take into account speed or future sample rate changes (until restoreTrack)
Glenn Kastene0fa4672012-04-24 14:35:14 -07001359 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001360 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001361
Glenn Kastenb6037442012-11-14 13:42:25 -08001362 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001363 // If IAudioTrack is re-created, don't let the requested frameCount
1364 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001365 if (frameCount > mReqFrameCount) {
1366 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001367 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001368
1369 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001370 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001371 mStaticProxy.clear();
Andy Hungabdb9902015-01-12 15:08:22 -08001372 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001373 } else {
Andy Hungabdb9902015-01-12 15:08:22 -08001374 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001375 mProxy = mStaticProxy;
1376 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001377
1378 mProxy->setVolumeLR(gain_minifloat_pack(
1379 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1380 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1381
Glenn Kastene3aa6592012-12-04 12:22:46 -08001382 mProxy->setSendLevel(mSendLevel);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001383 const uint32_t effectiveSampleRate = adjustSampleRate(mSampleRate, mPlaybackRate.mPitch);
1384 const float effectiveSpeed = adjustSpeed(mPlaybackRate.mSpeed, mPlaybackRate.mPitch);
1385 const float effectivePitch = adjustPitch(mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001386 mProxy->setSampleRate(effectiveSampleRate);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001387
1388 AudioPlaybackRate playbackRateTemp = mPlaybackRate;
1389 playbackRateTemp.mSpeed = effectiveSpeed;
1390 playbackRateTemp.mPitch = effectivePitch;
1391 mProxy->setPlaybackRate(playbackRateTemp);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001392 mProxy->setMinimum(mNotificationFramesAct);
1393
1394 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001395 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001396
Eric Laurent296fb132015-05-01 11:38:42 -07001397 if (mDeviceCallback != 0) {
1398 AudioSystem::addAudioDeviceCallback(mDeviceCallback, mOutput);
1399 }
1400
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001401 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001402 }
1403
1404release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001405 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001406 if (status == NO_ERROR) {
1407 status = NO_INIT;
1408 }
1409 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001410}
1411
Glenn Kastenb46f3942015-03-09 12:00:30 -07001412status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001413{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001414 if (audioBuffer == NULL) {
Glenn Kasten551b5352015-03-20 11:30:28 -07001415 if (nonContig != NULL) {
1416 *nonContig = 0;
1417 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001418 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001419 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001420 if (mTransfer != TRANSFER_OBTAIN) {
1421 audioBuffer->frameCount = 0;
1422 audioBuffer->size = 0;
1423 audioBuffer->raw = NULL;
Glenn Kasten551b5352015-03-20 11:30:28 -07001424 if (nonContig != NULL) {
1425 *nonContig = 0;
1426 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001427 return INVALID_OPERATION;
1428 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001429
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001430 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001431 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001432 if (waitCount == -1) {
1433 requested = &ClientProxy::kForever;
1434 } else if (waitCount == 0) {
1435 requested = &ClientProxy::kNonBlocking;
1436 } else if (waitCount > 0) {
1437 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001438 timeout.tv_sec = ms / 1000;
1439 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1440 requested = &timeout;
1441 } else {
1442 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1443 requested = NULL;
1444 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001445 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001446}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001447
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001448status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1449 struct timespec *elapsed, size_t *nonContig)
1450{
1451 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1452 uint32_t oldSequence = 0;
1453 uint32_t newSequence;
1454
1455 Proxy::Buffer buffer;
1456 status_t status = NO_ERROR;
1457
1458 static const int32_t kMaxTries = 5;
1459 int32_t tryCounter = kMaxTries;
1460
1461 do {
1462 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1463 // keep them from going away if another thread re-creates the track during obtainBuffer()
1464 sp<AudioTrackClientProxy> proxy;
1465 sp<IMemory> iMem;
1466
1467 { // start of lock scope
1468 AutoMutex lock(mLock);
1469
1470 newSequence = mSequence;
1471 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1472 if (status == DEAD_OBJECT) {
1473 // re-create track, unless someone else has already done so
1474 if (newSequence == oldSequence) {
1475 status = restoreTrack_l("obtainBuffer");
1476 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001477 buffer.mFrameCount = 0;
1478 buffer.mRaw = NULL;
1479 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001480 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001481 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001482 }
1483 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001484 oldSequence = newSequence;
1485
1486 // Keep the extra references
1487 proxy = mProxy;
1488 iMem = mCblkMemory;
1489
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001490 if (mState == STATE_STOPPING) {
1491 status = -EINTR;
1492 buffer.mFrameCount = 0;
1493 buffer.mRaw = NULL;
1494 buffer.mNonContig = 0;
1495 break;
1496 }
1497
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001498 // Non-blocking if track is stopped or paused
1499 if (mState != STATE_ACTIVE) {
1500 requested = &ClientProxy::kNonBlocking;
1501 }
1502
1503 } // end of lock scope
1504
1505 buffer.mFrameCount = audioBuffer->frameCount;
1506 // FIXME starts the requested timeout and elapsed over from scratch
1507 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1508
1509 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1510
1511 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001512 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001513 audioBuffer->raw = buffer.mRaw;
1514 if (nonContig != NULL) {
1515 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001516 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001517 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001518}
1519
Glenn Kasten54a8a452015-03-09 12:03:00 -07001520void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001521{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001522 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001523 if (mTransfer == TRANSFER_SHARED) {
1524 return;
1525 }
1526
Andy Hungabdb9902015-01-12 15:08:22 -08001527 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001528 if (stepCount == 0) {
1529 return;
1530 }
1531
1532 Proxy::Buffer buffer;
1533 buffer.mFrameCount = stepCount;
1534 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001535
Eric Laurent1703cdf2011-03-07 14:52:59 -08001536 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001537 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001538 mInUnderrun = false;
1539 mProxy->releaseBuffer(&buffer);
1540
1541 // restart track if it was disabled by audioflinger due to previous underrun
1542 if (mState == STATE_ACTIVE) {
1543 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001544 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001545 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001546 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001547 mAudioTrack->start();
1548 }
1549 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001550}
1551
1552// -------------------------------------------------------------------------
1553
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001554ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001555{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001556 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001557 return INVALID_OPERATION;
1558 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001559
Eric Laurentab5cdba2014-06-09 17:22:27 -07001560 if (isDirect()) {
1561 AutoMutex lock(mLock);
1562 int32_t flags = android_atomic_and(
1563 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1564 &mCblk->mFlags);
1565 if (flags & CBLK_INVALID) {
1566 return DEAD_OBJECT;
1567 }
1568 }
1569
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001570 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001571 // Sanity-check: user is most-likely passing an error code, and it would
1572 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001573 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001574 return BAD_VALUE;
1575 }
1576
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001577 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001578 Buffer audioBuffer;
1579
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001580 while (userSize >= mFrameSize) {
1581 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001582
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001583 status_t err = obtainBuffer(&audioBuffer,
1584 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001585 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001586 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001587 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001588 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001589 return ssize_t(err);
1590 }
1591
Glenn Kastenae4b8792015-03-20 09:04:21 -07001592 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08001593 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001594 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001595 userSize -= toWrite;
1596 written += toWrite;
1597
1598 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001599 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001600
1601 return written;
1602}
1603
1604// -------------------------------------------------------------------------
1605
John Grossman4ff14ba2012-02-08 16:37:41 -08001606TimedAudioTrack::TimedAudioTrack() {
1607 mIsTimed = true;
1608}
1609
1610status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1611{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001612 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001613 status_t result = UNKNOWN_ERROR;
1614
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001615#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001616 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1617 // while we are accessing the cblk
1618 sp<IAudioTrack> audioTrack = mAudioTrack;
1619 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001620#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001621
John Grossman4ff14ba2012-02-08 16:37:41 -08001622 // If the track is not invalid already, try to allocate a buffer. alloc
1623 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001624 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001625 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001626 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001627 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1628 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001629 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001630 }
1631 }
1632
1633 // If the track is invalid at this point, attempt to restore it. and try the
1634 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001635 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001636 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001637
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001638 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001639 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001640 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001641 }
1642
1643 return result;
1644}
1645
1646status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1647 int64_t pts)
1648{
Eric Laurentdf839842012-05-31 14:27:14 -07001649 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1650 {
1651 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001652 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001653 // restart track if it was disabled by audioflinger due to previous underrun
1654 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001655 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1656 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001657 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001658 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001659 mAudioTrack->start();
1660 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001661 }
Eric Laurentdf839842012-05-31 14:27:14 -07001662 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001663}
1664
1665status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1666 TargetTimeline target)
1667{
1668 return mAudioTrack->setMediaTimeTransform(xform, target);
1669}
1670
1671// -------------------------------------------------------------------------
1672
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001673nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001674{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001675 // Currently the AudioTrack thread is not created if there are no callbacks.
1676 // Would it ever make sense to run the thread, even without callbacks?
1677 // If so, then replace this by checks at each use for mCbf != NULL.
1678 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1679
Eric Laurent1703cdf2011-03-07 14:52:59 -08001680 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001681 if (mAwaitBoost) {
1682 mAwaitBoost = false;
1683 mLock.unlock();
1684 static const int32_t kMaxTries = 5;
1685 int32_t tryCounter = kMaxTries;
1686 uint32_t pollUs = 10000;
1687 do {
1688 int policy = sched_getscheduler(0);
1689 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1690 break;
1691 }
1692 usleep(pollUs);
1693 pollUs <<= 1;
1694 } while (tryCounter-- > 0);
1695 if (tryCounter < 0) {
1696 ALOGE("did not receive expected priority boost on time");
1697 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001698 // Run again immediately
1699 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001700 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001701
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001702 // Can only reference mCblk while locked
1703 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001704 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001705
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001706 // Check for track invalidation
1707 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001708 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1709 // AudioSystem cache. We should not exit here but after calling the callback so
1710 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001711 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Lajos Molnarf1063e22015-04-17 15:19:42 -07001712 status_t status __unused = restoreTrack_l("processAudioBuffer");
1713 // FIXME unused status
Andy Hung53c3b5f2014-12-15 16:42:05 -08001714 // after restoration, continue below to make sure that the loop and buffer events
1715 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001716 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001717 }
1718
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001719 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001720 bool active = mState == STATE_ACTIVE;
1721
1722 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1723 bool newUnderrun = false;
1724 if (flags & CBLK_UNDERRUN) {
1725#if 0
1726 // Currently in shared buffer mode, when the server reaches the end of buffer,
1727 // the track stays active in continuous underrun state. It's up to the application
1728 // to pause or stop the track, or set the position to a new offset within buffer.
1729 // This was some experimental code to auto-pause on underrun. Keeping it here
1730 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1731 if (mTransfer == TRANSFER_SHARED) {
1732 mState = STATE_PAUSED;
1733 active = false;
1734 }
1735#endif
1736 if (!mInUnderrun) {
1737 mInUnderrun = true;
1738 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001739 }
1740 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001741
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001742 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001743 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001744
1745 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001746 bool markerReached = false;
1747 size_t markerPosition = mMarkerPosition;
1748 // FIXME fails for wraparound, need 64 bits
1749 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1750 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001751 }
1752
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001753 // Determine number of new position callback(s) that will be needed, while locked
1754 size_t newPosCount = 0;
1755 size_t newPosition = mNewPosition;
1756 size_t updatePeriod = mUpdatePeriod;
1757 // FIXME fails for wraparound, need 64 bits
1758 if (updatePeriod > 0 && position >= newPosition) {
1759 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1760 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001761 }
1762
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001763 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001764 uint32_t sampleRate = mSampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001765 float speed = mPlaybackRate.mSpeed;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001766 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001767 if (mRefreshRemaining) {
1768 mRefreshRemaining = false;
1769 mRemainingFrames = notificationFrames;
1770 mRetryOnPartialBuffer = false;
1771 }
1772 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001773 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001774 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001775
Andy Hung53c3b5f2014-12-15 16:42:05 -08001776 // Determine the number of new loop callback(s) that will be needed, while locked.
1777 int loopCountNotifications = 0;
1778 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1779
1780 if (mLoopCount > 0) {
1781 int loopCount;
1782 size_t bufferPosition;
1783 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1784 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1785 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1786 mLoopCountNotified = loopCount; // discard any excess notifications
1787 } else if (mLoopCount < 0) {
1788 // FIXME: We're not accurate with notification count and position with infinite looping
1789 // since loopCount from server side will always return -1 (we could decrement it).
1790 size_t bufferPosition = mStaticProxy->getBufferPosition();
1791 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1792 loopPeriod = mLoopEnd - bufferPosition;
1793 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1794 size_t bufferPosition = mStaticProxy->getBufferPosition();
1795 loopPeriod = mFrameCount - bufferPosition;
1796 }
1797
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001798 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08001799 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001800 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1801
1802 mLock.unlock();
1803
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001804 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001805 struct timespec timeout;
1806 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1807 timeout.tv_nsec = 0;
1808
Glenn Kasten96f04882013-09-20 09:28:56 -07001809 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001810 switch (status) {
1811 case NO_ERROR:
1812 case DEAD_OBJECT:
1813 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001814 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001815 {
1816 AutoMutex lock(mLock);
1817 // The previously assigned value of waitStreamEnd is no longer valid,
1818 // since the mutex has been unlocked and either the callback handler
1819 // or another thread could have re-started the AudioTrack during that time.
1820 waitStreamEnd = mState == STATE_STOPPING;
1821 if (waitStreamEnd) {
1822 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001823 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001824 }
1825 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001826 if (waitStreamEnd && status != DEAD_OBJECT) {
1827 return NS_INACTIVE;
1828 }
1829 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001830 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001831 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001832 }
1833
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001834 // perform callbacks while unlocked
1835 if (newUnderrun) {
1836 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1837 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001838 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001839 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001840 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001841 }
1842 if (flags & CBLK_BUFFER_END) {
1843 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1844 }
1845 if (markerReached) {
1846 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1847 }
1848 while (newPosCount > 0) {
1849 size_t temp = newPosition;
1850 mCbf(EVENT_NEW_POS, mUserData, &temp);
1851 newPosition += updatePeriod;
1852 newPosCount--;
1853 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001854
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001855 if (mObservedSequence != sequence) {
1856 mObservedSequence = sequence;
1857 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001858 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001859 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001860 return NS_INACTIVE;
1861 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001862 }
1863
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001864 // if inactive, then don't run me again until re-started
1865 if (!active) {
1866 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001867 }
1868
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001869 // Compute the estimated time until the next timed event (position, markers, loops)
1870 // FIXME only for non-compressed audio
1871 uint32_t minFrames = ~0;
1872 if (!markerReached && position < markerPosition) {
1873 minFrames = markerPosition - position;
1874 }
1875 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08001876 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001877 minFrames = loopPeriod;
1878 }
Andy Hung2d85f092015-01-07 12:45:13 -08001879 if (updatePeriod > 0) {
1880 minFrames = min(minFrames, uint32_t(newPosition - position));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001881 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001882
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001883 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1884 static const uint32_t kPoll = 0;
1885 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1886 minFrames = kPoll * notificationFrames;
1887 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001888
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001889 // Convert frame units to time units
1890 nsecs_t ns = NS_WHENEVER;
1891 if (minFrames != (uint32_t) ~0) {
1892 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1893 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
Andy Hung8edb8dc2015-03-26 19:13:55 -07001894 ns = ((double)minFrames * 1000000000) / ((double)sampleRate * speed) + kFudgeNs;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001895 }
1896
1897 // If not supplying data by EVENT_MORE_DATA, then we're done
1898 if (mTransfer != TRANSFER_CALLBACK) {
1899 return ns;
1900 }
1901
1902 struct timespec timeout;
1903 const struct timespec *requested = &ClientProxy::kForever;
1904 if (ns != NS_WHENEVER) {
1905 timeout.tv_sec = ns / 1000000000LL;
1906 timeout.tv_nsec = ns % 1000000000LL;
1907 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1908 requested = &timeout;
1909 }
1910
1911 while (mRemainingFrames > 0) {
1912
1913 Buffer audioBuffer;
1914 audioBuffer.frameCount = mRemainingFrames;
1915 size_t nonContig;
1916 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1917 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001918 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001919 requested = &ClientProxy::kNonBlocking;
1920 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001921 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001922 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001923 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001924 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1925 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001926 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001927 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001928 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1929 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001930 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001931
Eric Laurent42a6f422013-08-29 14:35:05 -07001932 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001933 mRetryOnPartialBuffer = false;
1934 if (avail < mRemainingFrames) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001935 int64_t myns = ((double)(mRemainingFrames - avail) * 1100000000)
1936 / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001937 if (ns < 0 || myns < ns) {
1938 ns = myns;
1939 }
1940 return ns;
1941 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001942 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001943
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001944 size_t reqSize = audioBuffer.size;
1945 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001946 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001947
1948 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001949 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001950 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1951 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001952 return NS_NEVER;
1953 }
1954
1955 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001956 // The callback is done filling buffers
1957 // Keep this thread going to handle timed events and
1958 // still try to get more data in intervals of WAIT_PERIOD_MS
1959 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001960 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001961 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001962
Glenn Kasten138d6f92015-03-20 10:54:51 -07001963 size_t releasedFrames = writtenSize / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001964 audioBuffer.frameCount = releasedFrames;
1965 mRemainingFrames -= releasedFrames;
1966 if (misalignment >= releasedFrames) {
1967 misalignment -= releasedFrames;
1968 } else {
1969 misalignment = 0;
1970 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001971
1972 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001973
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001974 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1975 // if callback doesn't like to accept the full chunk
1976 if (writtenSize < reqSize) {
1977 continue;
1978 }
1979
1980 // There could be enough non-contiguous frames available to satisfy the remaining request
1981 if (mRemainingFrames <= nonContig) {
1982 continue;
1983 }
1984
1985#if 0
1986 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1987 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1988 // that total to a sum == notificationFrames.
1989 if (0 < misalignment && misalignment <= mRemainingFrames) {
1990 mRemainingFrames = misalignment;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001991 return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001992 }
1993#endif
1994
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001995 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001996 mRemainingFrames = notificationFrames;
1997 mRetryOnPartialBuffer = true;
1998
1999 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
2000 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002001}
2002
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002003status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08002004{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002005 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07002006 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002007 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002008
Glenn Kastena47f3162012-11-07 10:13:08 -08002009 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08002010 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08002011 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07002012
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002013 if (isOffloadedOrDirect_l() || mDoNotReconnect) {
Glenn Kasten23a75452014-01-13 10:37:17 -08002014 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002015 return DEAD_OBJECT;
2016 }
2017
Glenn Kasten200092b2014-08-15 15:13:30 -07002018 // save the old static buffer position
Andy Hung4ede21d2014-12-12 15:37:34 -08002019 size_t bufferPosition = 0;
2020 int loopCount = 0;
2021 if (mStaticProxy != 0) {
2022 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
2023 }
Glenn Kasten200092b2014-08-15 15:13:30 -07002024
2025 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08002026 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07002027 // It will also delete the strong references on previous IAudioTrack and IMemory.
2028 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Glenn Kastenae4b8792015-03-20 09:04:21 -07002029 status_t result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07002030
2031 // take the frames that will be lost by track recreation into account in saved position
Andy Hung9b461582014-12-01 17:56:29 -08002032 // For streaming tracks, this is the amount we obtained from the user/client
2033 // (not the number actually consumed at the server - those are already lost).
Glenn Kasten200092b2014-08-15 15:13:30 -07002034 (void) updateAndGetPosition_l();
Andy Hung7ccdaad2015-03-20 00:38:32 -07002035 if (mStaticProxy == 0) {
Andy Hung9b461582014-12-01 17:56:29 -08002036 mPosition = mReleased;
2037 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002038
Glenn Kastena47f3162012-11-07 10:13:08 -08002039 if (result == NO_ERROR) {
Andy Hung4ede21d2014-12-12 15:37:34 -08002040 // Continue playback from last known position and restore loop.
2041 if (mStaticProxy != 0) {
2042 if (loopCount != 0) {
2043 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
2044 mLoopStart, mLoopEnd, loopCount);
2045 } else {
2046 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002047 if (bufferPosition == mFrameCount) {
2048 ALOGD("restoring track at end of static buffer");
2049 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002050 }
2051 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002052 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08002053 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08002054 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002055 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002056 if (result != NO_ERROR) {
2057 ALOGW("restoreTrack_l() failed status %d", result);
2058 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07002059 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002060 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002061
2062 return result;
2063}
2064
Glenn Kasten200092b2014-08-15 15:13:30 -07002065uint32_t AudioTrack::updateAndGetPosition_l()
2066{
2067 // This is the sole place to read server consumed frames
2068 uint32_t newServer = mProxy->getPosition();
2069 int32_t delta = newServer - mServer;
2070 mServer = newServer;
2071 // TODO There is controversy about whether there can be "negative jitter" in server position.
2072 // This should be investigated further, and if possible, it should be addressed.
2073 // A more definite failure mode is infrequent polling by client.
2074 // One could call (void)getPosition_l() in releaseBuffer(),
2075 // so mReleased and mPosition are always lock-step as best possible.
2076 // That should ensure delta never goes negative for infrequent polling
2077 // unless the server has more than 2^31 frames in its buffer,
2078 // in which case the use of uint32_t for these counters has bigger issues.
2079 if (delta < 0) {
2080 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
2081 delta = 0;
2082 }
2083 return mPosition += (uint32_t) delta;
2084}
2085
Andy Hung8edb8dc2015-03-26 19:13:55 -07002086bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed) const
2087{
2088 // applicable for mixing tracks only (not offloaded or direct)
2089 if (mStaticProxy != 0) {
2090 return true; // static tracks do not have issues with buffer sizing.
2091 }
2092 status_t status;
2093 uint32_t afLatency;
2094 status = AudioSystem::getLatency(mOutput, &afLatency);
2095 if (status != NO_ERROR) {
2096 ALOGE("getLatency(%d) failed status %d", mOutput, status);
2097 return false;
2098 }
2099
2100 size_t afFrameCount;
2101 status = AudioSystem::getFrameCount(mOutput, &afFrameCount);
2102 if (status != NO_ERROR) {
2103 ALOGE("getFrameCount(output=%d) status %d", mOutput, status);
2104 return false;
2105 }
2106
2107 uint32_t afSampleRate;
2108 status = AudioSystem::getSamplingRate(mOutput, &afSampleRate);
2109 if (status != NO_ERROR) {
2110 ALOGE("getSamplingRate(output=%d) status %d", mOutput, status);
2111 return false;
2112 }
2113
2114 const size_t minFrameCount =
2115 calculateMinFrameCount(afLatency, afFrameCount, afSampleRate, sampleRate, speed);
2116 ALOGV("isSampleRateSpeedAllowed_l mFrameCount %zu minFrameCount %zu",
2117 mFrameCount, minFrameCount);
2118 return mFrameCount >= minFrameCount;
2119}
2120
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002121status_t AudioTrack::setParameters(const String8& keyValuePairs)
2122{
2123 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07002124 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002125}
2126
Glenn Kastence703742013-07-19 16:33:58 -07002127status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
2128{
Glenn Kasten53cec222013-08-29 09:01:02 -07002129 AutoMutex lock(mLock);
Phil Burk1b420972015-04-22 10:52:21 -07002130
2131 bool previousTimestampValid = mPreviousTimestampValid;
2132 // Set false here to cover all the error return cases.
2133 mPreviousTimestampValid = false;
2134
Glenn Kastenfe346c72013-08-30 13:28:22 -07002135 // FIXME not implemented for fast tracks; should use proxy and SSQ
2136 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
2137 return INVALID_OPERATION;
2138 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002139
2140 switch (mState) {
2141 case STATE_ACTIVE:
2142 case STATE_PAUSED:
2143 break; // handle below
2144 case STATE_FLUSHED:
2145 case STATE_STOPPED:
2146 return WOULD_BLOCK;
2147 case STATE_STOPPING:
2148 case STATE_PAUSED_STOPPING:
2149 if (!isOffloaded_l()) {
2150 return INVALID_OPERATION;
2151 }
2152 break; // offloaded tracks handled below
2153 default:
2154 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
2155 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07002156 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002157
Eric Laurent275e8e92014-11-30 15:14:47 -08002158 if (mCblk->mFlags & CBLK_INVALID) {
2159 restoreTrack_l("getTimestamp");
2160 }
2161
Glenn Kasten200092b2014-08-15 15:13:30 -07002162 // The presented frame count must always lag behind the consumed frame count.
2163 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002164 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002165 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07002166 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002167 return status;
2168 }
2169 if (isOffloadedOrDirect_l()) {
2170 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
2171 // use cached paused position in case another offloaded track is running.
2172 timestamp.mPosition = mPausedPosition;
2173 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
2174 return NO_ERROR;
2175 }
2176
2177 // Check whether a pending flush or stop has completed, as those commands may
2178 // be asynchronous or return near finish.
2179 if (mStartUs != 0 && mSampleRate != 0) {
2180 static const int kTimeJitterUs = 100000; // 100 ms
2181 static const int k1SecUs = 1000000;
2182
2183 const int64_t timeNow = getNowUs();
2184
2185 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
2186 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
2187 if (timestampTimeUs < mStartUs) {
2188 return WOULD_BLOCK; // stale timestamp time, occurs before start.
2189 }
2190 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002191 const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002192 / ((double)mSampleRate * mPlaybackRate.mSpeed);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002193
2194 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2195 // Verify that the counter can't count faster than the sample rate
2196 // since the start time. If greater, then that means we have failed
2197 // to completely flush or stop the previous playing track.
2198 ALOGW("incomplete flush or stop:"
2199 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2200 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2201 timestamp.mPosition);
2202 return WOULD_BLOCK;
2203 }
2204 }
2205 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
2206 }
2207 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002208 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2209 (void) updateAndGetPosition_l();
2210 // Server consumed (mServer) and presented both use the same server time base,
2211 // and server consumed is always >= presented.
2212 // The delta between these represents the number of frames in the buffer pipeline.
2213 // If this delta between these is greater than the client position, it means that
2214 // actually presented is still stuck at the starting line (figuratively speaking),
2215 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
2216 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2217 return INVALID_OPERATION;
2218 }
2219 // Convert timestamp position from server time base to client time base.
2220 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2221 // But if we change it to 64-bit then this could fail.
2222 // If (mPosition - mServer) can be negative then should use:
2223 // (int32_t)(mPosition - mServer)
2224 timestamp.mPosition += mPosition - mServer;
2225 // Immediately after a call to getPosition_l(), mPosition and
2226 // mServer both represent the same frame position. mPosition is
2227 // in client's point of view, and mServer is in server's point of
2228 // view. So the difference between them is the "fudge factor"
2229 // between client and server views due to stop() and/or new
2230 // IAudioTrack. And timestamp.mPosition is initially in server's
2231 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002232 }
Phil Burk1b420972015-04-22 10:52:21 -07002233
2234 // Prevent retrograde motion in timestamp.
2235 // This is sometimes caused by erratic reports of the available space in the ALSA drivers.
2236 if (status == NO_ERROR) {
2237 if (previousTimestampValid) {
2238#define TIME_TO_NANOS(time) ((uint64_t)time.tv_sec * 1000000000 + time.tv_nsec)
2239 const uint64_t previousTimeNanos = TIME_TO_NANOS(mPreviousTimestamp.mTime);
2240 const uint64_t currentTimeNanos = TIME_TO_NANOS(timestamp.mTime);
2241#undef TIME_TO_NANOS
2242 if (currentTimeNanos < previousTimeNanos) {
2243 ALOGW("retrograde timestamp time");
2244 // FIXME Consider blocking this from propagating upwards.
2245 }
2246
2247 // Looking at signed delta will work even when the timestamps
2248 // are wrapping around.
2249 int32_t deltaPosition = static_cast<int32_t>(timestamp.mPosition
2250 - mPreviousTimestamp.mPosition);
2251 // position can bobble slightly as an artifact; this hides the bobble
2252 static const int32_t MINIMUM_POSITION_DELTA = 8;
Phil Burk4c5a3672015-04-30 16:18:53 -07002253 if (deltaPosition < 0) {
2254 // Only report once per position instead of spamming the log.
2255 if (!mRetrogradeMotionReported) {
2256 ALOGW("retrograde timestamp position corrected, %d = %u - %u",
2257 deltaPosition,
2258 timestamp.mPosition,
2259 mPreviousTimestamp.mPosition);
2260 mRetrogradeMotionReported = true;
2261 }
2262 } else {
2263 mRetrogradeMotionReported = false;
2264 }
Phil Burk1b420972015-04-22 10:52:21 -07002265 if (deltaPosition < MINIMUM_POSITION_DELTA) {
2266 timestamp = mPreviousTimestamp; // Use last valid timestamp.
2267 }
2268 }
2269 mPreviousTimestamp = timestamp;
2270 mPreviousTimestampValid = true;
2271 }
2272
Glenn Kastenfe346c72013-08-30 13:28:22 -07002273 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002274}
2275
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002276String8 AudioTrack::getParameters(const String8& keys)
2277{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002278 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002279 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002280 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002281 } else {
2282 return String8::empty();
2283 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002284}
2285
Glenn Kasten23a75452014-01-13 10:37:17 -08002286bool AudioTrack::isOffloaded() const
2287{
2288 AutoMutex lock(mLock);
2289 return isOffloaded_l();
2290}
2291
Eric Laurentab5cdba2014-06-09 17:22:27 -07002292bool AudioTrack::isDirect() const
2293{
2294 AutoMutex lock(mLock);
2295 return isDirect_l();
2296}
2297
2298bool AudioTrack::isOffloadedOrDirect() const
2299{
2300 AutoMutex lock(mLock);
2301 return isOffloadedOrDirect_l();
2302}
2303
2304
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002305status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002306{
2307
2308 const size_t SIZE = 256;
2309 char buffer[SIZE];
2310 String8 result;
2311
2312 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002313 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002314 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002315 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002316 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002317 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002318 result.append(buffer);
Andy Hung8edb8dc2015-03-26 19:13:55 -07002319 snprintf(buffer, 255, " sample rate(%u), speed(%f), status(%d)\n",
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002320 mSampleRate, mPlaybackRate.mSpeed, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002321 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002322 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002323 result.append(buffer);
2324 ::write(fd, result.string(), result.size());
2325 return NO_ERROR;
2326}
2327
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002328uint32_t AudioTrack::getUnderrunFrames() const
2329{
2330 AutoMutex lock(mLock);
2331 return mProxy->getUnderrunFrames();
2332}
2333
Eric Laurent296fb132015-05-01 11:38:42 -07002334status_t AudioTrack::addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback)
2335{
2336 if (callback == 0) {
2337 ALOGW("%s adding NULL callback!", __FUNCTION__);
2338 return BAD_VALUE;
2339 }
2340 AutoMutex lock(mLock);
2341 if (mDeviceCallback == callback) {
2342 ALOGW("%s adding same callback!", __FUNCTION__);
2343 return INVALID_OPERATION;
2344 }
2345 status_t status = NO_ERROR;
2346 if (mOutput != AUDIO_IO_HANDLE_NONE) {
2347 if (mDeviceCallback != 0) {
2348 ALOGW("%s callback already present!", __FUNCTION__);
2349 AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
2350 }
2351 status = AudioSystem::addAudioDeviceCallback(callback, mOutput);
2352 }
2353 mDeviceCallback = callback;
2354 return status;
2355}
2356
2357status_t AudioTrack::removeAudioDeviceCallback(
2358 const sp<AudioSystem::AudioDeviceCallback>& callback)
2359{
2360 if (callback == 0) {
2361 ALOGW("%s removing NULL callback!", __FUNCTION__);
2362 return BAD_VALUE;
2363 }
2364 AutoMutex lock(mLock);
2365 if (mDeviceCallback != callback) {
2366 ALOGW("%s removing different callback!", __FUNCTION__);
2367 return INVALID_OPERATION;
2368 }
2369 if (mOutput != AUDIO_IO_HANDLE_NONE) {
2370 AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
2371 }
2372 mDeviceCallback = 0;
2373 return NO_ERROR;
2374}
2375
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002376// =========================================================================
2377
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002378void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002379{
2380 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2381 if (audioTrack != 0) {
2382 AutoMutex lock(audioTrack->mLock);
2383 audioTrack->mProxy->binderDied();
2384 }
2385}
2386
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002387// =========================================================================
2388
2389AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002390 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2391 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002392{
2393}
2394
2395AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002396{
2397}
2398
2399bool AudioTrack::AudioTrackThread::threadLoop()
2400{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002401 {
2402 AutoMutex _l(mMyLock);
2403 if (mPaused) {
2404 mMyCond.wait(mMyLock);
2405 // caller will check for exitPending()
2406 return true;
2407 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002408 if (mIgnoreNextPausedInt) {
2409 mIgnoreNextPausedInt = false;
2410 mPausedInt = false;
2411 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002412 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002413 if (mPausedNs > 0) {
2414 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2415 } else {
2416 mMyCond.wait(mMyLock);
2417 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002418 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002419 return true;
2420 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002421 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002422 if (exitPending()) {
2423 return false;
2424 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002425 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002426 switch (ns) {
2427 case 0:
2428 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002429 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002430 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002431 return true;
2432 case NS_NEVER:
2433 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002434 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08002435 // Event driven: call wake() when callback notifications conditions change.
2436 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002437 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002438 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002439 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002440 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002441 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002442 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002443}
2444
Glenn Kasten3acbd052012-02-28 10:39:56 -08002445void AudioTrack::AudioTrackThread::requestExit()
2446{
2447 // must be in this order to avoid a race condition
2448 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002449 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002450}
2451
2452void AudioTrack::AudioTrackThread::pause()
2453{
2454 AutoMutex _l(mMyLock);
2455 mPaused = true;
2456}
2457
2458void AudioTrack::AudioTrackThread::resume()
2459{
2460 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002461 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002462 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002463 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002464 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002465 mMyCond.signal();
2466 }
2467}
2468
Andy Hung3c09c782014-12-29 18:39:32 -08002469void AudioTrack::AudioTrackThread::wake()
2470{
2471 AutoMutex _l(mMyLock);
2472 if (!mPaused && mPausedInt && mPausedNs > 0) {
2473 // audio track is active and internally paused with timeout.
2474 mIgnoreNextPausedInt = true;
2475 mPausedInt = false;
2476 mMyCond.signal();
2477 }
2478}
2479
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002480void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2481{
2482 AutoMutex _l(mMyLock);
2483 mPausedInt = true;
2484 mPausedNs = ns;
2485}
2486
Glenn Kasten40bc9062015-03-20 09:09:33 -07002487} // namespace android