blob: 070baa1d83919d1481abc28bb04f614e136e4df8 [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
Andy Hung9f9e21e2015-05-31 21:45:36 -07001114 status = AudioSystem::getLatency(output, &mAfLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001115 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001116 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001117 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001118 }
Andy Hung9f9e21e2015-05-31 21:45:36 -07001119 ALOGV("createTrack_l() output %d afLatency %u", output, mAfLatency);
Eric Laurentd1b449a2010-05-14 03:26:45 -07001120
Andy Hung9f9e21e2015-05-31 21:45:36 -07001121 status = AudioSystem::getFrameCount(output, &mAfFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -07001122 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001123 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001124 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001125 }
1126
Andy Hung9f9e21e2015-05-31 21:45:36 -07001127 status = AudioSystem::getSamplingRate(output, &mAfSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -07001128 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001129 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001130 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001131 }
Eric Laurent0d6db582014-11-12 18:39:44 -08001132 if (mSampleRate == 0) {
Andy Hung9f9e21e2015-05-31 21:45:36 -07001133 mSampleRate = mAfSampleRate;
1134 mOriginalSampleRate = mAfSampleRate;
Eric Laurent0d6db582014-11-12 18:39:44 -08001135 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001136 // Client decides whether the track is TIMED (see below), but can only express a preference
1137 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001138 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001139 // either of these use cases:
1140 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -08001141 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001142 // use case 2: callback transfer mode
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001143 (mTransfer == TRANSFER_CALLBACK) ||
1144 // use case 3: obtain/release mode
1145 (mTransfer == TRANSFER_OBTAIN)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001146 // matching sample rate
Andy Hung9f9e21e2015-05-31 21:45:36 -07001147 (mSampleRate == mAfSampleRate))) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001148 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client; transfer %d, track %u Hz, output %u Hz",
Andy Hung9f9e21e2015-05-31 21:45:36 -07001149 mTransfer, mSampleRate, mAfSampleRate);
Glenn Kasten093000f2012-05-03 09:35:36 -07001150 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001151 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001152 }
1153
Glenn Kastence8828a2013-09-16 18:07:38 -07001154 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -08001155 // n = 1 fast track with single buffering; nBuffering is ignored
1156 // n = 2 fast track with double buffering
Andy Hung0e48d252015-01-26 11:43:15 -08001157 // n = 2 normal track, (including those with sample rate conversion)
1158 // n >= 3 very high latency or very small notification interval (unused).
1159 const uint32_t nBuffering = 2;
Glenn Kastence8828a2013-09-16 18:07:38 -07001160
Eric Laurentd1b449a2010-05-14 03:26:45 -07001161 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001162
Glenn Kasten363fb752014-01-15 12:27:31 -08001163 size_t frameCount = mReqFrameCount;
1164 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001165
Glenn Kasten363fb752014-01-15 12:27:31 -08001166 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001167 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001168 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001169 } else if (frameCount == 0) {
Andy Hung9f9e21e2015-05-31 21:45:36 -07001170 frameCount = mAfFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001171 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001172 if (mNotificationFramesAct != frameCount) {
1173 mNotificationFramesAct = frameCount;
1174 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001175 } else if (mSharedBuffer != 0) {
Andy Hungabdb9902015-01-12 15:08:22 -08001176 // FIXME: Ensure client side memory buffers need
1177 // not have additional alignment beyond sample
1178 // (e.g. 16 bit stereo accessed as 32 bit frame).
1179 size_t alignment = audio_bytes_per_sample(mFormat);
Glenn Kastenb7730382014-04-30 15:50:31 -07001180 if (alignment & 1) {
Andy Hungabdb9902015-01-12 15:08:22 -08001181 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
Glenn Kastenb7730382014-04-30 15:50:31 -07001182 alignment = 1;
1183 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001184 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001185 // More than 2 channels does not require stronger alignment than stereo
1186 alignment <<= 1;
1187 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001188 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001189 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001190 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001191 status = BAD_VALUE;
1192 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001193 }
1194
1195 // When initializing a shared buffer AudioTrack via constructors,
1196 // there's no frameCount parameter.
1197 // But when initializing a shared buffer AudioTrack via set(),
1198 // there _is_ a frameCount parameter. We silently ignore it.
Andy Hungabdb9902015-01-12 15:08:22 -08001199 frameCount = mSharedBuffer->size() / mFrameSize;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001200 } else {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001201 // For fast tracks the frame count calculations and checks are done by server
1202
1203 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1204 // for normal tracks precompute the frame count based on speed.
1205 const size_t minFrameCount = calculateMinFrameCount(
Andy Hung9f9e21e2015-05-31 21:45:36 -07001206 mAfLatency, mAfFrameCount, mAfSampleRate, mSampleRate,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001207 mPlaybackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07001208 if (frameCount < minFrameCount) {
1209 frameCount = minFrameCount;
1210 }
1211 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001212 }
1213
Glenn Kastena075db42012-03-06 11:22:44 -08001214 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1215 if (mIsTimed) {
1216 trackFlags |= IAudioFlinger::TRACK_TIMED;
1217 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001218
1219 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001220 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001221 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001222 if (mAudioTrackThread != 0) {
1223 tid = mAudioTrackThread->getTid();
1224 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001225 }
1226
Glenn Kasten363fb752014-01-15 12:27:31 -08001227 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001228 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1229 }
1230
Eric Laurentab5cdba2014-06-09 17:22:27 -07001231 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1232 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1233 }
1234
Glenn Kasten74935e42013-12-19 08:56:45 -08001235 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1236 // but we will still need the original value also
Glenn Kasten138d6f92015-03-20 10:54:51 -07001237 int originalSessionId = mSessionId;
Eric Laurente83b55d2014-11-14 10:06:21 -08001238 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001239 mSampleRate,
Andy Hungabdb9902015-01-12 15:08:22 -08001240 mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001241 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001242 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001243 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001244 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001245 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001246 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001247 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001248 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001249 &status);
Glenn Kasten138d6f92015-03-20 10:54:51 -07001250 ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
1251 "session ID changed from %d to %d", originalSessionId, mSessionId);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001252
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001253 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001254 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001255 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001256 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001257 ALOG_ASSERT(track != 0);
1258
Glenn Kasten38e905b2014-01-13 10:21:48 -08001259 // AudioFlinger now owns the reference to the I/O handle,
1260 // so we are no longer responsible for releasing it.
1261
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001262 sp<IMemory> iMem = track->getCblk();
1263 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001264 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001265 return NO_INIT;
1266 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001267 void *iMemPointer = iMem->pointer();
1268 if (iMemPointer == NULL) {
1269 ALOGE("Could not get control block pointer");
1270 return NO_INIT;
1271 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001272 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001273 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001274 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001275 mDeathNotifier.clear();
1276 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001277 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001278 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001279 IPCThreadState::self()->flushCommands();
1280
Glenn Kasten0cde0762014-01-16 15:06:36 -08001281 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001282 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001283 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001284 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1285 // In current design, AudioTrack client checks and ensures frame count validity before
1286 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1287 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001288 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001289 }
1290 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001291
Glenn Kastena07f17c2013-04-23 12:39:37 -07001292 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001293 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001294 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001295 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001296 mAwaitBoost = true;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001297 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001298 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001299 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001300 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001301 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001302 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001303 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001304 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1305 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1306 } else {
1307 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001308 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001309 // FIXME This is a warning, not an error, so don't return error status
1310 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001311 }
1312 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001313 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1314 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1315 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1316 } else {
1317 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1318 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1319 // FIXME This is a warning, not an error, so don't return error status
1320 //return NO_INIT;
1321 }
1322 }
Andy Hung0e48d252015-01-26 11:43:15 -08001323 // Make sure that application is notified with sufficient margin before underrun
1324 if (mSharedBuffer == 0 && audio_is_linear_pcm(mFormat)) {
1325 // Theoretically double-buffering is not required for fast tracks,
1326 // due to tighter scheduling. But in practice, to accommodate kernels with
1327 // scheduling jitter, and apps with computation jitter, we use double-buffering
1328 // for fast tracks just like normal streaming tracks.
1329 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount / nBuffering) {
1330 mNotificationFramesAct = frameCount / nBuffering;
1331 }
1332 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001333
Glenn Kasten38e905b2014-01-13 10:21:48 -08001334 // We retain a copy of the I/O handle, but don't own the reference
1335 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001336 mRefreshRemaining = true;
1337
1338 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1339 // is the value of pointer() for the shared buffer, otherwise buffers points
1340 // immediately after the control block. This address is for the mapping within client
1341 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1342 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001343 if (mSharedBuffer == 0) {
Glenn Kasten138d6f92015-03-20 10:54:51 -07001344 buffers = cblk + 1;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001345 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001346 buffers = mSharedBuffer->pointer();
Glenn Kasten138d6f92015-03-20 10:54:51 -07001347 if (buffers == NULL) {
1348 ALOGE("Could not get buffer pointer");
1349 return NO_INIT;
1350 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001351 }
1352
Eric Laurent2beeb502010-07-16 07:43:46 -07001353 mAudioTrack->attachAuxEffect(mAuxEffectId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07001354 // FIXME doesn't take into account speed or future sample rate changes (until restoreTrack)
Glenn Kastene0fa4672012-04-24 14:35:14 -07001355 // FIXME don't believe this lie
Andy Hung9f9e21e2015-05-31 21:45:36 -07001356 mLatency = mAfLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001357
Glenn Kastenb6037442012-11-14 13:42:25 -08001358 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001359 // If IAudioTrack is re-created, don't let the requested frameCount
1360 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001361 if (frameCount > mReqFrameCount) {
1362 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001363 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001364
1365 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001366 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001367 mStaticProxy.clear();
Andy Hungabdb9902015-01-12 15:08:22 -08001368 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001369 } else {
Andy Hungabdb9902015-01-12 15:08:22 -08001370 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001371 mProxy = mStaticProxy;
1372 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001373
1374 mProxy->setVolumeLR(gain_minifloat_pack(
1375 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1376 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1377
Glenn Kastene3aa6592012-12-04 12:22:46 -08001378 mProxy->setSendLevel(mSendLevel);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001379 const uint32_t effectiveSampleRate = adjustSampleRate(mSampleRate, mPlaybackRate.mPitch);
1380 const float effectiveSpeed = adjustSpeed(mPlaybackRate.mSpeed, mPlaybackRate.mPitch);
1381 const float effectivePitch = adjustPitch(mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001382 mProxy->setSampleRate(effectiveSampleRate);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001383
1384 AudioPlaybackRate playbackRateTemp = mPlaybackRate;
1385 playbackRateTemp.mSpeed = effectiveSpeed;
1386 playbackRateTemp.mPitch = effectivePitch;
1387 mProxy->setPlaybackRate(playbackRateTemp);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001388 mProxy->setMinimum(mNotificationFramesAct);
1389
1390 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001391 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001392
Eric Laurent296fb132015-05-01 11:38:42 -07001393 if (mDeviceCallback != 0) {
1394 AudioSystem::addAudioDeviceCallback(mDeviceCallback, mOutput);
1395 }
1396
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001397 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001398 }
1399
1400release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001401 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001402 if (status == NO_ERROR) {
1403 status = NO_INIT;
1404 }
1405 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001406}
1407
Glenn Kastenb46f3942015-03-09 12:00:30 -07001408status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001409{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001410 if (audioBuffer == NULL) {
Glenn Kasten551b5352015-03-20 11:30:28 -07001411 if (nonContig != NULL) {
1412 *nonContig = 0;
1413 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001414 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001415 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001416 if (mTransfer != TRANSFER_OBTAIN) {
1417 audioBuffer->frameCount = 0;
1418 audioBuffer->size = 0;
1419 audioBuffer->raw = NULL;
Glenn Kasten551b5352015-03-20 11:30:28 -07001420 if (nonContig != NULL) {
1421 *nonContig = 0;
1422 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001423 return INVALID_OPERATION;
1424 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001425
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001426 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001427 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001428 if (waitCount == -1) {
1429 requested = &ClientProxy::kForever;
1430 } else if (waitCount == 0) {
1431 requested = &ClientProxy::kNonBlocking;
1432 } else if (waitCount > 0) {
1433 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001434 timeout.tv_sec = ms / 1000;
1435 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1436 requested = &timeout;
1437 } else {
1438 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1439 requested = NULL;
1440 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001441 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001442}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001443
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001444status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1445 struct timespec *elapsed, size_t *nonContig)
1446{
1447 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1448 uint32_t oldSequence = 0;
1449 uint32_t newSequence;
1450
1451 Proxy::Buffer buffer;
1452 status_t status = NO_ERROR;
1453
1454 static const int32_t kMaxTries = 5;
1455 int32_t tryCounter = kMaxTries;
1456
1457 do {
1458 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1459 // keep them from going away if another thread re-creates the track during obtainBuffer()
1460 sp<AudioTrackClientProxy> proxy;
1461 sp<IMemory> iMem;
1462
1463 { // start of lock scope
1464 AutoMutex lock(mLock);
1465
1466 newSequence = mSequence;
1467 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1468 if (status == DEAD_OBJECT) {
1469 // re-create track, unless someone else has already done so
1470 if (newSequence == oldSequence) {
1471 status = restoreTrack_l("obtainBuffer");
1472 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001473 buffer.mFrameCount = 0;
1474 buffer.mRaw = NULL;
1475 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001476 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001477 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001478 }
1479 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001480 oldSequence = newSequence;
1481
1482 // Keep the extra references
1483 proxy = mProxy;
1484 iMem = mCblkMemory;
1485
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001486 if (mState == STATE_STOPPING) {
1487 status = -EINTR;
1488 buffer.mFrameCount = 0;
1489 buffer.mRaw = NULL;
1490 buffer.mNonContig = 0;
1491 break;
1492 }
1493
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001494 // Non-blocking if track is stopped or paused
1495 if (mState != STATE_ACTIVE) {
1496 requested = &ClientProxy::kNonBlocking;
1497 }
1498
1499 } // end of lock scope
1500
1501 buffer.mFrameCount = audioBuffer->frameCount;
1502 // FIXME starts the requested timeout and elapsed over from scratch
1503 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1504
1505 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1506
1507 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001508 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001509 audioBuffer->raw = buffer.mRaw;
1510 if (nonContig != NULL) {
1511 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001512 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001513 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001514}
1515
Glenn Kasten54a8a452015-03-09 12:03:00 -07001516void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001517{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001518 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001519 if (mTransfer == TRANSFER_SHARED) {
1520 return;
1521 }
1522
Andy Hungabdb9902015-01-12 15:08:22 -08001523 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001524 if (stepCount == 0) {
1525 return;
1526 }
1527
1528 Proxy::Buffer buffer;
1529 buffer.mFrameCount = stepCount;
1530 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001531
Eric Laurent1703cdf2011-03-07 14:52:59 -08001532 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001533 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001534 mInUnderrun = false;
1535 mProxy->releaseBuffer(&buffer);
1536
1537 // restart track if it was disabled by audioflinger due to previous underrun
1538 if (mState == STATE_ACTIVE) {
1539 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001540 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001541 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001542 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001543 mAudioTrack->start();
1544 }
1545 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001546}
1547
1548// -------------------------------------------------------------------------
1549
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001550ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001551{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001552 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001553 return INVALID_OPERATION;
1554 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001555
Eric Laurentab5cdba2014-06-09 17:22:27 -07001556 if (isDirect()) {
1557 AutoMutex lock(mLock);
1558 int32_t flags = android_atomic_and(
1559 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1560 &mCblk->mFlags);
1561 if (flags & CBLK_INVALID) {
1562 return DEAD_OBJECT;
1563 }
1564 }
1565
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001566 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001567 // Sanity-check: user is most-likely passing an error code, and it would
1568 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001569 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001570 return BAD_VALUE;
1571 }
1572
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001573 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001574 Buffer audioBuffer;
1575
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001576 while (userSize >= mFrameSize) {
1577 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001578
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001579 status_t err = obtainBuffer(&audioBuffer,
1580 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001581 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001582 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001583 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001584 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001585 return ssize_t(err);
1586 }
1587
Glenn Kastenae4b8792015-03-20 09:04:21 -07001588 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08001589 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001590 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001591 userSize -= toWrite;
1592 written += toWrite;
1593
1594 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001595 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001596
1597 return written;
1598}
1599
1600// -------------------------------------------------------------------------
1601
John Grossman4ff14ba2012-02-08 16:37:41 -08001602TimedAudioTrack::TimedAudioTrack() {
1603 mIsTimed = true;
1604}
1605
1606status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1607{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001608 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001609 status_t result = UNKNOWN_ERROR;
1610
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001611#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001612 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1613 // while we are accessing the cblk
1614 sp<IAudioTrack> audioTrack = mAudioTrack;
1615 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001616#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001617
John Grossman4ff14ba2012-02-08 16:37:41 -08001618 // If the track is not invalid already, try to allocate a buffer. alloc
1619 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001620 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001621 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001622 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001623 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1624 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001625 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001626 }
1627 }
1628
1629 // If the track is invalid at this point, attempt to restore it. and try the
1630 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001631 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001632 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001633
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001634 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001635 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001636 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001637 }
1638
1639 return result;
1640}
1641
1642status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1643 int64_t pts)
1644{
Eric Laurentdf839842012-05-31 14:27:14 -07001645 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1646 {
1647 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001648 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001649 // restart track if it was disabled by audioflinger due to previous underrun
1650 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001651 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1652 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001653 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001654 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001655 mAudioTrack->start();
1656 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001657 }
Eric Laurentdf839842012-05-31 14:27:14 -07001658 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001659}
1660
1661status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1662 TargetTimeline target)
1663{
1664 return mAudioTrack->setMediaTimeTransform(xform, target);
1665}
1666
1667// -------------------------------------------------------------------------
1668
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001669nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001670{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001671 // Currently the AudioTrack thread is not created if there are no callbacks.
1672 // Would it ever make sense to run the thread, even without callbacks?
1673 // If so, then replace this by checks at each use for mCbf != NULL.
1674 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1675
Eric Laurent1703cdf2011-03-07 14:52:59 -08001676 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001677 if (mAwaitBoost) {
1678 mAwaitBoost = false;
1679 mLock.unlock();
1680 static const int32_t kMaxTries = 5;
1681 int32_t tryCounter = kMaxTries;
1682 uint32_t pollUs = 10000;
1683 do {
1684 int policy = sched_getscheduler(0);
1685 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1686 break;
1687 }
1688 usleep(pollUs);
1689 pollUs <<= 1;
1690 } while (tryCounter-- > 0);
1691 if (tryCounter < 0) {
1692 ALOGE("did not receive expected priority boost on time");
1693 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001694 // Run again immediately
1695 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001696 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001697
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001698 // Can only reference mCblk while locked
1699 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001700 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001701
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001702 // Check for track invalidation
1703 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001704 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1705 // AudioSystem cache. We should not exit here but after calling the callback so
1706 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001707 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Lajos Molnarf1063e22015-04-17 15:19:42 -07001708 status_t status __unused = restoreTrack_l("processAudioBuffer");
1709 // FIXME unused status
Andy Hung53c3b5f2014-12-15 16:42:05 -08001710 // after restoration, continue below to make sure that the loop and buffer events
1711 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001712 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001713 }
1714
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001715 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001716 bool active = mState == STATE_ACTIVE;
1717
1718 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1719 bool newUnderrun = false;
1720 if (flags & CBLK_UNDERRUN) {
1721#if 0
1722 // Currently in shared buffer mode, when the server reaches the end of buffer,
1723 // the track stays active in continuous underrun state. It's up to the application
1724 // to pause or stop the track, or set the position to a new offset within buffer.
1725 // This was some experimental code to auto-pause on underrun. Keeping it here
1726 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1727 if (mTransfer == TRANSFER_SHARED) {
1728 mState = STATE_PAUSED;
1729 active = false;
1730 }
1731#endif
1732 if (!mInUnderrun) {
1733 mInUnderrun = true;
1734 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001735 }
1736 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001737
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001738 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001739 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001740
1741 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001742 bool markerReached = false;
1743 size_t markerPosition = mMarkerPosition;
1744 // FIXME fails for wraparound, need 64 bits
1745 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1746 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001747 }
1748
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001749 // Determine number of new position callback(s) that will be needed, while locked
1750 size_t newPosCount = 0;
1751 size_t newPosition = mNewPosition;
1752 size_t updatePeriod = mUpdatePeriod;
1753 // FIXME fails for wraparound, need 64 bits
1754 if (updatePeriod > 0 && position >= newPosition) {
1755 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1756 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001757 }
1758
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001759 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001760 uint32_t sampleRate = mSampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001761 float speed = mPlaybackRate.mSpeed;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001762 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001763 if (mRefreshRemaining) {
1764 mRefreshRemaining = false;
1765 mRemainingFrames = notificationFrames;
1766 mRetryOnPartialBuffer = false;
1767 }
1768 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001769 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001770 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001771
Andy Hung53c3b5f2014-12-15 16:42:05 -08001772 // Determine the number of new loop callback(s) that will be needed, while locked.
1773 int loopCountNotifications = 0;
1774 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1775
1776 if (mLoopCount > 0) {
1777 int loopCount;
1778 size_t bufferPosition;
1779 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1780 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1781 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1782 mLoopCountNotified = loopCount; // discard any excess notifications
1783 } else if (mLoopCount < 0) {
1784 // FIXME: We're not accurate with notification count and position with infinite looping
1785 // since loopCount from server side will always return -1 (we could decrement it).
1786 size_t bufferPosition = mStaticProxy->getBufferPosition();
1787 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1788 loopPeriod = mLoopEnd - bufferPosition;
1789 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1790 size_t bufferPosition = mStaticProxy->getBufferPosition();
1791 loopPeriod = mFrameCount - bufferPosition;
1792 }
1793
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001794 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08001795 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001796 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1797
1798 mLock.unlock();
1799
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001800 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001801 struct timespec timeout;
1802 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1803 timeout.tv_nsec = 0;
1804
Glenn Kasten96f04882013-09-20 09:28:56 -07001805 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001806 switch (status) {
1807 case NO_ERROR:
1808 case DEAD_OBJECT:
1809 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001810 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001811 {
1812 AutoMutex lock(mLock);
1813 // The previously assigned value of waitStreamEnd is no longer valid,
1814 // since the mutex has been unlocked and either the callback handler
1815 // or another thread could have re-started the AudioTrack during that time.
1816 waitStreamEnd = mState == STATE_STOPPING;
1817 if (waitStreamEnd) {
1818 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001819 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001820 }
1821 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001822 if (waitStreamEnd && status != DEAD_OBJECT) {
1823 return NS_INACTIVE;
1824 }
1825 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001826 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001827 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001828 }
1829
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001830 // perform callbacks while unlocked
1831 if (newUnderrun) {
1832 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1833 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001834 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001835 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001836 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001837 }
1838 if (flags & CBLK_BUFFER_END) {
1839 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1840 }
1841 if (markerReached) {
1842 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1843 }
1844 while (newPosCount > 0) {
1845 size_t temp = newPosition;
1846 mCbf(EVENT_NEW_POS, mUserData, &temp);
1847 newPosition += updatePeriod;
1848 newPosCount--;
1849 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001850
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001851 if (mObservedSequence != sequence) {
1852 mObservedSequence = sequence;
1853 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001854 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001855 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001856 return NS_INACTIVE;
1857 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001858 }
1859
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001860 // if inactive, then don't run me again until re-started
1861 if (!active) {
1862 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001863 }
1864
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001865 // Compute the estimated time until the next timed event (position, markers, loops)
1866 // FIXME only for non-compressed audio
1867 uint32_t minFrames = ~0;
1868 if (!markerReached && position < markerPosition) {
1869 minFrames = markerPosition - position;
1870 }
1871 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08001872 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001873 minFrames = loopPeriod;
1874 }
Andy Hung2d85f092015-01-07 12:45:13 -08001875 if (updatePeriod > 0) {
1876 minFrames = min(minFrames, uint32_t(newPosition - position));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001877 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001878
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001879 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1880 static const uint32_t kPoll = 0;
1881 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1882 minFrames = kPoll * notificationFrames;
1883 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001884
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001885 // Convert frame units to time units
1886 nsecs_t ns = NS_WHENEVER;
1887 if (minFrames != (uint32_t) ~0) {
1888 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1889 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
Andy Hung8edb8dc2015-03-26 19:13:55 -07001890 ns = ((double)minFrames * 1000000000) / ((double)sampleRate * speed) + kFudgeNs;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001891 }
1892
1893 // If not supplying data by EVENT_MORE_DATA, then we're done
1894 if (mTransfer != TRANSFER_CALLBACK) {
1895 return ns;
1896 }
1897
1898 struct timespec timeout;
1899 const struct timespec *requested = &ClientProxy::kForever;
1900 if (ns != NS_WHENEVER) {
1901 timeout.tv_sec = ns / 1000000000LL;
1902 timeout.tv_nsec = ns % 1000000000LL;
1903 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1904 requested = &timeout;
1905 }
1906
1907 while (mRemainingFrames > 0) {
1908
1909 Buffer audioBuffer;
1910 audioBuffer.frameCount = mRemainingFrames;
1911 size_t nonContig;
1912 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1913 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001914 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001915 requested = &ClientProxy::kNonBlocking;
1916 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001917 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001918 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001919 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001920 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1921 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001922 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001923 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001924 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1925 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001926 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001927
Eric Laurent42a6f422013-08-29 14:35:05 -07001928 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001929 mRetryOnPartialBuffer = false;
1930 if (avail < mRemainingFrames) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001931 int64_t myns = ((double)(mRemainingFrames - avail) * 1100000000)
1932 / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001933 if (ns < 0 || myns < ns) {
1934 ns = myns;
1935 }
1936 return ns;
1937 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001938 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001939
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001940 size_t reqSize = audioBuffer.size;
1941 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001942 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001943
1944 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001945 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001946 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1947 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001948 return NS_NEVER;
1949 }
1950
1951 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001952 // The callback is done filling buffers
1953 // Keep this thread going to handle timed events and
1954 // still try to get more data in intervals of WAIT_PERIOD_MS
1955 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001956 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001957 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001958
Glenn Kasten138d6f92015-03-20 10:54:51 -07001959 size_t releasedFrames = writtenSize / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001960 audioBuffer.frameCount = releasedFrames;
1961 mRemainingFrames -= releasedFrames;
1962 if (misalignment >= releasedFrames) {
1963 misalignment -= releasedFrames;
1964 } else {
1965 misalignment = 0;
1966 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001967
1968 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001969
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001970 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1971 // if callback doesn't like to accept the full chunk
1972 if (writtenSize < reqSize) {
1973 continue;
1974 }
1975
1976 // There could be enough non-contiguous frames available to satisfy the remaining request
1977 if (mRemainingFrames <= nonContig) {
1978 continue;
1979 }
1980
1981#if 0
1982 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1983 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1984 // that total to a sum == notificationFrames.
1985 if (0 < misalignment && misalignment <= mRemainingFrames) {
1986 mRemainingFrames = misalignment;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001987 return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001988 }
1989#endif
1990
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001991 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001992 mRemainingFrames = notificationFrames;
1993 mRetryOnPartialBuffer = true;
1994
1995 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1996 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001997}
1998
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001999status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08002000{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002001 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07002002 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002003 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002004
Glenn Kastena47f3162012-11-07 10:13:08 -08002005 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08002006 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08002007 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07002008
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002009 if (isOffloadedOrDirect_l() || mDoNotReconnect) {
Glenn Kasten23a75452014-01-13 10:37:17 -08002010 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002011 return DEAD_OBJECT;
2012 }
2013
Glenn Kasten200092b2014-08-15 15:13:30 -07002014 // save the old static buffer position
Andy Hung4ede21d2014-12-12 15:37:34 -08002015 size_t bufferPosition = 0;
2016 int loopCount = 0;
2017 if (mStaticProxy != 0) {
2018 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
2019 }
Glenn Kasten200092b2014-08-15 15:13:30 -07002020
2021 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08002022 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07002023 // It will also delete the strong references on previous IAudioTrack and IMemory.
2024 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Glenn Kastenae4b8792015-03-20 09:04:21 -07002025 status_t result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07002026
2027 // take the frames that will be lost by track recreation into account in saved position
Andy Hung9b461582014-12-01 17:56:29 -08002028 // For streaming tracks, this is the amount we obtained from the user/client
2029 // (not the number actually consumed at the server - those are already lost).
Glenn Kasten200092b2014-08-15 15:13:30 -07002030 (void) updateAndGetPosition_l();
Andy Hung7ccdaad2015-03-20 00:38:32 -07002031 if (mStaticProxy == 0) {
Andy Hung9b461582014-12-01 17:56:29 -08002032 mPosition = mReleased;
2033 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002034
Glenn Kastena47f3162012-11-07 10:13:08 -08002035 if (result == NO_ERROR) {
Andy Hung4ede21d2014-12-12 15:37:34 -08002036 // Continue playback from last known position and restore loop.
2037 if (mStaticProxy != 0) {
2038 if (loopCount != 0) {
2039 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
2040 mLoopStart, mLoopEnd, loopCount);
2041 } else {
2042 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002043 if (bufferPosition == mFrameCount) {
2044 ALOGD("restoring track at end of static buffer");
2045 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002046 }
2047 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002048 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08002049 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08002050 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002051 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002052 if (result != NO_ERROR) {
2053 ALOGW("restoreTrack_l() failed status %d", result);
2054 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07002055 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002056 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002057
2058 return result;
2059}
2060
Glenn Kasten200092b2014-08-15 15:13:30 -07002061uint32_t AudioTrack::updateAndGetPosition_l()
2062{
2063 // This is the sole place to read server consumed frames
2064 uint32_t newServer = mProxy->getPosition();
2065 int32_t delta = newServer - mServer;
2066 mServer = newServer;
2067 // TODO There is controversy about whether there can be "negative jitter" in server position.
2068 // This should be investigated further, and if possible, it should be addressed.
2069 // A more definite failure mode is infrequent polling by client.
2070 // One could call (void)getPosition_l() in releaseBuffer(),
2071 // so mReleased and mPosition are always lock-step as best possible.
2072 // That should ensure delta never goes negative for infrequent polling
2073 // unless the server has more than 2^31 frames in its buffer,
2074 // in which case the use of uint32_t for these counters has bigger issues.
2075 if (delta < 0) {
2076 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
2077 delta = 0;
2078 }
2079 return mPosition += (uint32_t) delta;
2080}
2081
Andy Hung8edb8dc2015-03-26 19:13:55 -07002082bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed) const
2083{
2084 // applicable for mixing tracks only (not offloaded or direct)
2085 if (mStaticProxy != 0) {
2086 return true; // static tracks do not have issues with buffer sizing.
2087 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07002088 const size_t minFrameCount =
Andy Hung9f9e21e2015-05-31 21:45:36 -07002089 calculateMinFrameCount(mAfLatency, mAfFrameCount, mAfSampleRate, sampleRate, speed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07002090 ALOGV("isSampleRateSpeedAllowed_l mFrameCount %zu minFrameCount %zu",
2091 mFrameCount, minFrameCount);
2092 return mFrameCount >= minFrameCount;
2093}
2094
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002095status_t AudioTrack::setParameters(const String8& keyValuePairs)
2096{
2097 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07002098 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002099}
2100
Glenn Kastence703742013-07-19 16:33:58 -07002101status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
2102{
Glenn Kasten53cec222013-08-29 09:01:02 -07002103 AutoMutex lock(mLock);
Phil Burk1b420972015-04-22 10:52:21 -07002104
2105 bool previousTimestampValid = mPreviousTimestampValid;
2106 // Set false here to cover all the error return cases.
2107 mPreviousTimestampValid = false;
2108
Glenn Kastenfe346c72013-08-30 13:28:22 -07002109 // FIXME not implemented for fast tracks; should use proxy and SSQ
2110 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
2111 return INVALID_OPERATION;
2112 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002113
2114 switch (mState) {
2115 case STATE_ACTIVE:
2116 case STATE_PAUSED:
2117 break; // handle below
2118 case STATE_FLUSHED:
2119 case STATE_STOPPED:
2120 return WOULD_BLOCK;
2121 case STATE_STOPPING:
2122 case STATE_PAUSED_STOPPING:
2123 if (!isOffloaded_l()) {
2124 return INVALID_OPERATION;
2125 }
2126 break; // offloaded tracks handled below
2127 default:
2128 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
2129 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07002130 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002131
Eric Laurent275e8e92014-11-30 15:14:47 -08002132 if (mCblk->mFlags & CBLK_INVALID) {
2133 restoreTrack_l("getTimestamp");
2134 }
2135
Glenn Kasten200092b2014-08-15 15:13:30 -07002136 // The presented frame count must always lag behind the consumed frame count.
2137 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002138 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002139 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07002140 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002141 return status;
2142 }
2143 if (isOffloadedOrDirect_l()) {
2144 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
2145 // use cached paused position in case another offloaded track is running.
2146 timestamp.mPosition = mPausedPosition;
2147 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
2148 return NO_ERROR;
2149 }
2150
2151 // Check whether a pending flush or stop has completed, as those commands may
2152 // be asynchronous or return near finish.
2153 if (mStartUs != 0 && mSampleRate != 0) {
2154 static const int kTimeJitterUs = 100000; // 100 ms
2155 static const int k1SecUs = 1000000;
2156
2157 const int64_t timeNow = getNowUs();
2158
2159 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
2160 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
2161 if (timestampTimeUs < mStartUs) {
2162 return WOULD_BLOCK; // stale timestamp time, occurs before start.
2163 }
2164 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002165 const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002166 / ((double)mSampleRate * mPlaybackRate.mSpeed);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002167
2168 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2169 // Verify that the counter can't count faster than the sample rate
2170 // since the start time. If greater, then that means we have failed
2171 // to completely flush or stop the previous playing track.
2172 ALOGW("incomplete flush or stop:"
2173 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2174 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2175 timestamp.mPosition);
2176 return WOULD_BLOCK;
2177 }
2178 }
2179 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
2180 }
2181 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002182 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2183 (void) updateAndGetPosition_l();
2184 // Server consumed (mServer) and presented both use the same server time base,
2185 // and server consumed is always >= presented.
2186 // The delta between these represents the number of frames in the buffer pipeline.
2187 // If this delta between these is greater than the client position, it means that
2188 // actually presented is still stuck at the starting line (figuratively speaking),
2189 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
2190 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2191 return INVALID_OPERATION;
2192 }
2193 // Convert timestamp position from server time base to client time base.
2194 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2195 // But if we change it to 64-bit then this could fail.
2196 // If (mPosition - mServer) can be negative then should use:
2197 // (int32_t)(mPosition - mServer)
2198 timestamp.mPosition += mPosition - mServer;
2199 // Immediately after a call to getPosition_l(), mPosition and
2200 // mServer both represent the same frame position. mPosition is
2201 // in client's point of view, and mServer is in server's point of
2202 // view. So the difference between them is the "fudge factor"
2203 // between client and server views due to stop() and/or new
2204 // IAudioTrack. And timestamp.mPosition is initially in server's
2205 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002206 }
Phil Burk1b420972015-04-22 10:52:21 -07002207
2208 // Prevent retrograde motion in timestamp.
2209 // This is sometimes caused by erratic reports of the available space in the ALSA drivers.
2210 if (status == NO_ERROR) {
2211 if (previousTimestampValid) {
2212#define TIME_TO_NANOS(time) ((uint64_t)time.tv_sec * 1000000000 + time.tv_nsec)
2213 const uint64_t previousTimeNanos = TIME_TO_NANOS(mPreviousTimestamp.mTime);
2214 const uint64_t currentTimeNanos = TIME_TO_NANOS(timestamp.mTime);
2215#undef TIME_TO_NANOS
2216 if (currentTimeNanos < previousTimeNanos) {
2217 ALOGW("retrograde timestamp time");
2218 // FIXME Consider blocking this from propagating upwards.
2219 }
2220
2221 // Looking at signed delta will work even when the timestamps
2222 // are wrapping around.
2223 int32_t deltaPosition = static_cast<int32_t>(timestamp.mPosition
2224 - mPreviousTimestamp.mPosition);
2225 // position can bobble slightly as an artifact; this hides the bobble
2226 static const int32_t MINIMUM_POSITION_DELTA = 8;
Phil Burk4c5a3672015-04-30 16:18:53 -07002227 if (deltaPosition < 0) {
2228 // Only report once per position instead of spamming the log.
2229 if (!mRetrogradeMotionReported) {
2230 ALOGW("retrograde timestamp position corrected, %d = %u - %u",
2231 deltaPosition,
2232 timestamp.mPosition,
2233 mPreviousTimestamp.mPosition);
2234 mRetrogradeMotionReported = true;
2235 }
2236 } else {
2237 mRetrogradeMotionReported = false;
2238 }
Phil Burk1b420972015-04-22 10:52:21 -07002239 if (deltaPosition < MINIMUM_POSITION_DELTA) {
2240 timestamp = mPreviousTimestamp; // Use last valid timestamp.
2241 }
2242 }
2243 mPreviousTimestamp = timestamp;
2244 mPreviousTimestampValid = true;
2245 }
2246
Glenn Kastenfe346c72013-08-30 13:28:22 -07002247 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002248}
2249
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002250String8 AudioTrack::getParameters(const String8& keys)
2251{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002252 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002253 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002254 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002255 } else {
2256 return String8::empty();
2257 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002258}
2259
Glenn Kasten23a75452014-01-13 10:37:17 -08002260bool AudioTrack::isOffloaded() const
2261{
2262 AutoMutex lock(mLock);
2263 return isOffloaded_l();
2264}
2265
Eric Laurentab5cdba2014-06-09 17:22:27 -07002266bool AudioTrack::isDirect() const
2267{
2268 AutoMutex lock(mLock);
2269 return isDirect_l();
2270}
2271
2272bool AudioTrack::isOffloadedOrDirect() const
2273{
2274 AutoMutex lock(mLock);
2275 return isOffloadedOrDirect_l();
2276}
2277
2278
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002279status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002280{
2281
2282 const size_t SIZE = 256;
2283 char buffer[SIZE];
2284 String8 result;
2285
2286 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002287 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002288 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002289 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002290 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002291 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002292 result.append(buffer);
Andy Hung8edb8dc2015-03-26 19:13:55 -07002293 snprintf(buffer, 255, " sample rate(%u), speed(%f), status(%d)\n",
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002294 mSampleRate, mPlaybackRate.mSpeed, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002295 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002296 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002297 result.append(buffer);
2298 ::write(fd, result.string(), result.size());
2299 return NO_ERROR;
2300}
2301
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002302uint32_t AudioTrack::getUnderrunFrames() const
2303{
2304 AutoMutex lock(mLock);
2305 return mProxy->getUnderrunFrames();
2306}
2307
Eric Laurent296fb132015-05-01 11:38:42 -07002308status_t AudioTrack::addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback)
2309{
2310 if (callback == 0) {
2311 ALOGW("%s adding NULL callback!", __FUNCTION__);
2312 return BAD_VALUE;
2313 }
2314 AutoMutex lock(mLock);
2315 if (mDeviceCallback == callback) {
2316 ALOGW("%s adding same callback!", __FUNCTION__);
2317 return INVALID_OPERATION;
2318 }
2319 status_t status = NO_ERROR;
2320 if (mOutput != AUDIO_IO_HANDLE_NONE) {
2321 if (mDeviceCallback != 0) {
2322 ALOGW("%s callback already present!", __FUNCTION__);
2323 AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
2324 }
2325 status = AudioSystem::addAudioDeviceCallback(callback, mOutput);
2326 }
2327 mDeviceCallback = callback;
2328 return status;
2329}
2330
2331status_t AudioTrack::removeAudioDeviceCallback(
2332 const sp<AudioSystem::AudioDeviceCallback>& callback)
2333{
2334 if (callback == 0) {
2335 ALOGW("%s removing NULL callback!", __FUNCTION__);
2336 return BAD_VALUE;
2337 }
2338 AutoMutex lock(mLock);
2339 if (mDeviceCallback != callback) {
2340 ALOGW("%s removing different callback!", __FUNCTION__);
2341 return INVALID_OPERATION;
2342 }
2343 if (mOutput != AUDIO_IO_HANDLE_NONE) {
2344 AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
2345 }
2346 mDeviceCallback = 0;
2347 return NO_ERROR;
2348}
2349
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002350// =========================================================================
2351
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002352void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002353{
2354 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2355 if (audioTrack != 0) {
2356 AutoMutex lock(audioTrack->mLock);
2357 audioTrack->mProxy->binderDied();
2358 }
2359}
2360
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002361// =========================================================================
2362
2363AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002364 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2365 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002366{
2367}
2368
2369AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002370{
2371}
2372
2373bool AudioTrack::AudioTrackThread::threadLoop()
2374{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002375 {
2376 AutoMutex _l(mMyLock);
2377 if (mPaused) {
2378 mMyCond.wait(mMyLock);
2379 // caller will check for exitPending()
2380 return true;
2381 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002382 if (mIgnoreNextPausedInt) {
2383 mIgnoreNextPausedInt = false;
2384 mPausedInt = false;
2385 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002386 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002387 if (mPausedNs > 0) {
2388 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2389 } else {
2390 mMyCond.wait(mMyLock);
2391 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002392 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002393 return true;
2394 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002395 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002396 if (exitPending()) {
2397 return false;
2398 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002399 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002400 switch (ns) {
2401 case 0:
2402 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002403 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002404 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002405 return true;
2406 case NS_NEVER:
2407 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002408 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08002409 // Event driven: call wake() when callback notifications conditions change.
2410 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002411 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002412 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002413 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002414 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002415 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002416 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002417}
2418
Glenn Kasten3acbd052012-02-28 10:39:56 -08002419void AudioTrack::AudioTrackThread::requestExit()
2420{
2421 // must be in this order to avoid a race condition
2422 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002423 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002424}
2425
2426void AudioTrack::AudioTrackThread::pause()
2427{
2428 AutoMutex _l(mMyLock);
2429 mPaused = true;
2430}
2431
2432void AudioTrack::AudioTrackThread::resume()
2433{
2434 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002435 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002436 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002437 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002438 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002439 mMyCond.signal();
2440 }
2441}
2442
Andy Hung3c09c782014-12-29 18:39:32 -08002443void AudioTrack::AudioTrackThread::wake()
2444{
2445 AutoMutex _l(mMyLock);
2446 if (!mPaused && mPausedInt && mPausedNs > 0) {
2447 // audio track is active and internally paused with timeout.
2448 mIgnoreNextPausedInt = true;
2449 mPausedInt = false;
2450 mMyCond.signal();
2451 }
2452}
2453
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002454void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2455{
2456 AutoMutex _l(mMyLock);
2457 mPausedInt = true;
2458 mPausedNs = ns;
2459}
2460
Glenn Kasten40bc9062015-03-20 09:09:33 -07002461} // namespace android