blob: 6ea09de409a202cf8444ba01200c67765c699bae [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,
181 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700182 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800183 mIsTimed(false),
184 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800185 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700186 mPausedPosition(0),
187 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800188{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700189 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700190 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800191 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700192 offloadInfo, uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800193}
194
Andreas Huberc8139852012-01-18 10:51:55 -0800195AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800196 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800197 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800198 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700199 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800200 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700201 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800202 callback_t cbf,
203 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800204 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800205 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000206 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800207 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800208 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700209 pid_t pid,
210 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700211 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800212 mIsTimed(false),
213 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800214 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700215 mPausedPosition(0),
216 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800217{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700218 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800219 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800220 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700221 uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800222}
223
224AudioTrack::~AudioTrack()
225{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800226 if (mStatus == NO_ERROR) {
227 // Make sure that callback function exits in the case where
228 // it is looping on buffer full condition in obtainBuffer().
229 // Otherwise the callback thread will never exit.
230 stop();
231 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100232 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800233 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800234 mAudioTrackThread->requestExitAndWait();
235 mAudioTrackThread.clear();
236 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800237 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700238 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700239 mCblkMemory.clear();
240 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800241 IPCThreadState::self()->flushCommands();
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700242 ALOGV("~AudioTrack, releasing session id %d from %d on behalf of %d",
243 mSessionId, IPCThreadState::self()->getCallingPid(), mClientPid);
Marco Nelissend457c972014-02-11 08:47:07 -0800244 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800245 }
246}
247
248status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800249 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800250 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800251 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700252 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800253 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700254 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800255 callback_t cbf,
256 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800257 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800258 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700259 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800260 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000261 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800262 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800263 int uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700264 pid_t pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700265 const audio_attributes_t* pAttributes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800266{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800267 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700268 "flags #%x, notificationFrames %u, sessionId %d, transferType %d, uid %d, pid %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800269 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700270 sessionId, transferType, uid, pid);
Glenn Kasten86f04662014-02-24 15:13:05 -0800271
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800272 switch (transferType) {
273 case TRANSFER_DEFAULT:
274 if (sharedBuffer != 0) {
275 transferType = TRANSFER_SHARED;
276 } else if (cbf == NULL || threadCanCallJava) {
277 transferType = TRANSFER_SYNC;
278 } else {
279 transferType = TRANSFER_CALLBACK;
280 }
281 break;
282 case TRANSFER_CALLBACK:
283 if (cbf == NULL || sharedBuffer != 0) {
284 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
285 return BAD_VALUE;
286 }
287 break;
288 case TRANSFER_OBTAIN:
289 case TRANSFER_SYNC:
290 if (sharedBuffer != 0) {
291 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
292 return BAD_VALUE;
293 }
294 break;
295 case TRANSFER_SHARED:
296 if (sharedBuffer == 0) {
297 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
298 return BAD_VALUE;
299 }
300 break;
301 default:
302 ALOGE("Invalid transfer type %d", transferType);
303 return BAD_VALUE;
304 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800305 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800306 mTransfer = transferType;
307
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700308 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
309 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800310
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700311 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700312
Glenn Kasten53cec222013-08-29 09:01:02 -0700313 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700314 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000315 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800316 return INVALID_OPERATION;
317 }
318
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800319 // handle default values first.
Eric Laurente83b55d2014-11-14 10:06:21 -0800320 if (streamType == AUDIO_STREAM_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700321 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800322 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700323 if (pAttributes == NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800324 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700325 ALOGE("Invalid stream type %d", streamType);
326 return BAD_VALUE;
327 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700328 mStreamType = streamType;
Eric Laurente83b55d2014-11-14 10:06:21 -0800329
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700330 } else {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700331 // stream type shouldn't be looked at, this track has audio attributes
332 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700333 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
334 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800335 mStreamType = AUDIO_STREAM_DEFAULT;
Eric Laurentc6bd5db2015-03-09 16:29:33 -0700336 if ((mAttributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
337 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
338 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800339 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700340
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800341 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800342 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700343 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800344 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800345
346 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700347 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800348 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800349 return BAD_VALUE;
350 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800351 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700352
Glenn Kasten8ba90322013-10-30 11:29:27 -0700353 if (!audio_is_output_channel(channelMask)) {
354 ALOGE("Invalid channel mask %#x", channelMask);
355 return BAD_VALUE;
356 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800357 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700358 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800359 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700360
Eric Laurentc2f1f072009-07-17 12:17:14 -0700361 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100362 // or offload was requested
363 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
364 || !audio_is_linear_pcm(format)) {
365 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
366 ? "Offload request, forcing to Direct Output"
367 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700368 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800369 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700370 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700371 }
372
Eric Laurentd1f69b02014-12-15 14:33:13 -0800373 // force direct flag if HW A/V sync requested
374 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
375 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
376 }
377
Glenn Kastenb7730382014-04-30 15:50:31 -0700378 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
379 if (audio_is_linear_pcm(format)) {
380 mFrameSize = channelCount * audio_bytes_per_sample(format);
381 } else {
382 mFrameSize = sizeof(uint8_t);
383 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800384 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700385 ALOG_ASSERT(audio_is_linear_pcm(format));
386 mFrameSize = channelCount * audio_bytes_per_sample(format);
Glenn Kastenb7730382014-04-30 15:50:31 -0700387 // createTrack will return an error if PCM format is not supported by server,
388 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800389 }
390
Eric Laurent0d6db582014-11-12 18:39:44 -0800391 // sampling rate must be specified for direct outputs
392 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
393 return BAD_VALUE;
394 }
395 mSampleRate = sampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700396 mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT;
Eric Laurent0d6db582014-11-12 18:39:44 -0800397
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800398 // Make copy of input parameter offloadInfo so that in the future:
399 // (a) createTrack_l doesn't need it as an input parameter
400 // (b) we can support re-creation of offloaded tracks
401 if (offloadInfo != NULL) {
402 mOffloadInfoCopy = *offloadInfo;
403 mOffloadInfo = &mOffloadInfoCopy;
404 } else {
405 mOffloadInfo = NULL;
406 }
407
Glenn Kasten66e46352014-01-16 17:44:23 -0800408 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
409 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800410 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800411 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800412 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700413 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800414 mNotificationFramesAct = 0;
Eric Laurentcaf7f482014-11-25 17:50:47 -0800415 if (sessionId == AUDIO_SESSION_ALLOCATE) {
416 mSessionId = AudioSystem::newAudioUniqueId();
417 } else {
418 mSessionId = sessionId;
419 }
Marco Nelissend457c972014-02-11 08:47:07 -0800420 int callingpid = IPCThreadState::self()->getCallingPid();
421 int mypid = getpid();
422 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800423 mClientUid = IPCThreadState::self()->getCallingUid();
424 } else {
425 mClientUid = uid;
426 }
Marco Nelissend457c972014-02-11 08:47:07 -0800427 if (pid == -1 || (callingpid != mypid)) {
428 mClientPid = callingpid;
429 } else {
430 mClientPid = pid;
431 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700432 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700433 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700434 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700435
Glenn Kastena997e7a2012-08-07 09:44:19 -0700436 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700437 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700438 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
Glenn Kastenbfd31842015-03-20 09:01:44 -0700439 // thread begins in paused state, and will not reference us until start()
Glenn Kastena997e7a2012-08-07 09:44:19 -0700440 }
441
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800442 // create the IAudioTrack
Eric Laurent0d6db582014-11-12 18:39:44 -0800443 status_t status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800444
Glenn Kastena997e7a2012-08-07 09:44:19 -0700445 if (status != NO_ERROR) {
446 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100447 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
448 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700449 mAudioTrackThread.clear();
450 }
451 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700452 }
453
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800454 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800455 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800456 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800457 mLoopCount = 0;
458 mLoopStart = 0;
459 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800460 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800461 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700462 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800463 mNewPosition = 0;
464 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700465 mServer = 0;
466 mPosition = 0;
467 mReleased = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700468 mStartUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800469 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800470 mSequence = 1;
471 mObservedSequence = mSequence;
472 mInUnderrun = false;
473
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800474 return NO_ERROR;
475}
476
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800477// -------------------------------------------------------------------------
478
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100479status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800480{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800481 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100482
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800483 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100484 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800485 }
486
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800487 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800488
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800489 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100490 if (previousState == STATE_PAUSED_STOPPING) {
491 mState = STATE_STOPPING;
492 } else {
493 mState = STATE_ACTIVE;
494 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700495 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800496 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
497 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700498 mPosition = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700499 // For offloaded tracks, we don't know if the hardware counters are really zero here,
500 // since the flush is asynchronous and stop may not fully drain.
501 // We save the time when the track is started to later verify whether
502 // the counters are realistic (i.e. start from zero after this time).
503 mStartUs = getNowUs();
504
Eric Laurentec9a0322013-08-28 10:23:01 -0700505 // force refresh of remaining frames by processAudioBuffer() as last
506 // write before stop could be partial.
507 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800508 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700509 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700510 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800511
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800512 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800513 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100514 if (previousState == STATE_STOPPING) {
515 mProxy->interrupt();
516 } else {
517 t->resume();
518 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800519 } else {
520 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
521 get_sched_policy(0, &mPreviousSchedulingGroup);
522 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
523 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800524
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800525 status_t status = NO_ERROR;
526 if (!(flags & CBLK_INVALID)) {
527 status = mAudioTrack->start();
528 if (status == DEAD_OBJECT) {
529 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800530 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800531 }
532 if (flags & CBLK_INVALID) {
533 status = restoreTrack_l("start");
534 }
535
536 if (status != NO_ERROR) {
537 ALOGE("start() status %d", status);
538 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800539 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100540 if (previousState != STATE_STOPPING) {
541 t->pause();
542 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800543 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700544 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700545 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800546 }
547 }
548
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100549 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800550}
551
552void AudioTrack::stop()
553{
554 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700555 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800556 return;
557 }
558
Glenn Kasten23a75452014-01-13 10:37:17 -0800559 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100560 mState = STATE_STOPPING;
561 } else {
562 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -0700563 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100564 }
565
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800566 mProxy->interrupt();
567 mAudioTrack->stop();
568 // the playback head position will reset to 0, so if a marker is set, we need
569 // to activate it again
570 mMarkerReached = false;
Andy Hung9b461582014-12-01 17:56:29 -0800571
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800572 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800573 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800574 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
575 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800576 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100577
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800578 sp<AudioTrackThread> t = mAudioTrackThread;
579 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800580 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100581 t->pause();
582 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800583 } else {
584 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
585 set_sched_policy(0, mPreviousSchedulingGroup);
586 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800587}
588
589bool AudioTrack::stopped() const
590{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800591 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800592 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800593}
594
595void AudioTrack::flush()
596{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800597 if (mSharedBuffer != 0) {
598 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800599 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800600 AutoMutex lock(mLock);
601 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
602 return;
603 }
604 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800605}
606
Eric Laurent1703cdf2011-03-07 14:52:59 -0800607void AudioTrack::flush_l()
608{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800609 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700610
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700611 // clear playback marker and periodic update counter
612 mMarkerPosition = 0;
613 mMarkerReached = false;
614 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100615 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700616
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800617 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700618 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800619 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100620 mProxy->interrupt();
621 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800622 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800623 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800624}
625
626void AudioTrack::pause()
627{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800628 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100629 if (mState == STATE_ACTIVE) {
630 mState = STATE_PAUSED;
631 } else if (mState == STATE_STOPPING) {
632 mState = STATE_PAUSED_STOPPING;
633 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800634 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800635 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800636 mProxy->interrupt();
637 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800638
Marco Nelissen3a90f282014-03-10 11:21:43 -0700639 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700640 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700641 // An offload output can be re-used between two audio tracks having
642 // the same configuration. A timestamp query for a paused track
643 // while the other is running would return an incorrect time.
644 // To fix this, cache the playback position on a pause() and return
645 // this time when requested until the track is resumed.
646
647 // OffloadThread sends HAL pause in its threadLoop. Time saved
648 // here can be slightly off.
649
650 // TODO: check return code for getRenderPosition.
651
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800652 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800653 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
654 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
655 }
656 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800657}
658
Eric Laurentbe916aa2010-06-01 23:49:17 -0700659status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800660{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700661 // This duplicates a test by AudioTrack JNI, but that is not the only caller
662 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
663 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700664 return BAD_VALUE;
665 }
666
Eric Laurent1703cdf2011-03-07 14:52:59 -0800667 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800668 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
669 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800670
Glenn Kastenc56f3422014-03-21 17:53:17 -0700671 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700672
Glenn Kasten23a75452014-01-13 10:37:17 -0800673 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700674 mAudioTrack->signal();
675 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700676 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800677}
678
Glenn Kastenb1c09932012-02-27 16:21:04 -0800679status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800680{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800681 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700682}
683
Eric Laurent2beeb502010-07-16 07:43:46 -0700684status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700685{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700686 // This duplicates a test by AudioTrack JNI, but that is not the only caller
687 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700688 return BAD_VALUE;
689 }
690
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800691 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700692 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800693 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700694
695 return NO_ERROR;
696}
697
Glenn Kastena5224f32012-01-04 12:41:44 -0800698void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700699{
700 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800701 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700702 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800703}
704
Glenn Kasten3b16c762012-11-14 08:44:39 -0800705status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800706{
Andy Hung5cbb5782015-03-27 18:39:59 -0700707 AutoMutex lock(mLock);
708 if (rate == mSampleRate) {
709 return NO_ERROR;
710 }
711 if (mIsTimed || isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800712 return INVALID_OPERATION;
713 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800714 if (mOutput == AUDIO_IO_HANDLE_NONE) {
715 return NO_INIT;
716 }
Andy Hung5cbb5782015-03-27 18:39:59 -0700717 // NOTE: it is theoretically possible, but highly unlikely, that a device change
718 // could mean a previously allowed sampling rate is no longer allowed.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800719 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800720 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700721 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800722 }
Andy Hung26145642015-04-15 21:56:53 -0700723 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700724 const uint32_t effectiveSampleRate = adjustSampleRate(rate, mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -0700725 if (rate == 0 || effectiveSampleRate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700726 return BAD_VALUE;
727 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700728 // TODO: Should we also check if the buffer size is compatible?
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800729
Glenn Kastene3aa6592012-12-04 12:22:46 -0800730 mSampleRate = rate;
Andy Hung26145642015-04-15 21:56:53 -0700731 mProxy->setSampleRate(effectiveSampleRate);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800732
Eric Laurent57326622009-07-07 07:10:45 -0700733 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800734}
735
Glenn Kastena5224f32012-01-04 12:41:44 -0800736uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800737{
John Grossman4ff14ba2012-02-08 16:37:41 -0800738 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800739 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800740 }
741
Eric Laurent1703cdf2011-03-07 14:52:59 -0800742 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700743
744 // sample rate can be updated during playback by the offloaded decoder so we need to
745 // query the HAL and update if needed.
746// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700747 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700748 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700749 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700750 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700751 if (status == NO_ERROR) {
752 mSampleRate = sampleRate;
753 }
754 }
755 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800756 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800757}
758
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700759status_t AudioTrack::setPlaybackRate(const AudioPlaybackRate &playbackRate)
Andy Hung8edb8dc2015-03-26 19:13:55 -0700760{
Andy Hung8edb8dc2015-03-26 19:13:55 -0700761 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700762 if (isAudioPlaybackRateEqual(playbackRate, mPlaybackRate)) {
Andy Hung8edb8dc2015-03-26 19:13:55 -0700763 return NO_ERROR;
764 }
765 if (mIsTimed || isOffloadedOrDirect_l()) {
766 return INVALID_OPERATION;
767 }
768 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
769 return INVALID_OPERATION;
770 }
Andy Hung26145642015-04-15 21:56:53 -0700771 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700772 const uint32_t effectiveRate = adjustSampleRate(mSampleRate, playbackRate.mPitch);
773 const float effectiveSpeed = adjustSpeed(playbackRate.mSpeed, playbackRate.mPitch);
774 const float effectivePitch = adjustPitch(playbackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -0700775 if (effectiveSpeed < AUDIO_TIMESTRETCH_SPEED_MIN
776 || effectiveSpeed > AUDIO_TIMESTRETCH_SPEED_MAX
777 || effectivePitch < AUDIO_TIMESTRETCH_PITCH_MIN
778 || effectivePitch > AUDIO_TIMESTRETCH_PITCH_MAX) {
779 return BAD_VALUE;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700780 //TODO: add function in AudioResamplerPublic.h to check for validity.
Andy Hung26145642015-04-15 21:56:53 -0700781 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700782 // Check if the buffer size is compatible.
Andy Hung26145642015-04-15 21:56:53 -0700783 if (!isSampleRateSpeedAllowed_l(effectiveRate, effectiveSpeed)) {
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700784 ALOGV("setPlaybackRate(%f, %f) failed", playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung8edb8dc2015-03-26 19:13:55 -0700785 return BAD_VALUE;
786 }
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700787 mPlaybackRate = playbackRate;
788 mProxy->setPlaybackRate(playbackRate);
789
790 //modify this
791 AudioPlaybackRate playbackRateTemp = playbackRate;
792 playbackRateTemp.mSpeed = effectiveSpeed;
793 playbackRateTemp.mPitch = effectivePitch;
794 mProxy->setPlaybackRate(playbackRateTemp);
Andy Hung26145642015-04-15 21:56:53 -0700795 mProxy->setSampleRate(effectiveRate); // FIXME: not quite "atomic" with setPlaybackRate
Andy Hung8edb8dc2015-03-26 19:13:55 -0700796 return NO_ERROR;
797}
798
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700799const AudioPlaybackRate& AudioTrack::getPlaybackRate() const
Andy Hung8edb8dc2015-03-26 19:13:55 -0700800{
801 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700802 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700803}
804
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800805status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
806{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700807 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800808 return INVALID_OPERATION;
809 }
810
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800811 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800812 ;
813 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
814 loopEnd - loopStart >= MIN_LOOP) {
815 ;
816 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800817 return BAD_VALUE;
818 }
819
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800820 AutoMutex lock(mLock);
821 // See setPosition() regarding setting parameters such as loop points or position while active
822 if (mState == STATE_ACTIVE) {
823 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700824 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800825 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800826 return NO_ERROR;
827}
828
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800829void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
830{
Andy Hung4ede21d2014-12-12 15:37:34 -0800831 // We do not update the periodic notification point.
832 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
833 mLoopCount = loopCount;
834 mLoopEnd = loopEnd;
835 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800836 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800837 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -0800838
839 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800840}
841
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800842status_t AudioTrack::setMarkerPosition(uint32_t marker)
843{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700844 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700845 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700846 return INVALID_OPERATION;
847 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800848
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800849 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800850 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700851 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800852
Andy Hung3c09c782014-12-29 18:39:32 -0800853 sp<AudioTrackThread> t = mAudioTrackThread;
854 if (t != 0) {
855 t->wake();
856 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800857 return NO_ERROR;
858}
859
Glenn Kastena5224f32012-01-04 12:41:44 -0800860status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800861{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700862 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100863 return INVALID_OPERATION;
864 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700865 if (marker == NULL) {
866 return BAD_VALUE;
867 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800868
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800869 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800870 *marker = mMarkerPosition;
871
872 return NO_ERROR;
873}
874
875status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
876{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700877 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700878 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700879 return INVALID_OPERATION;
880 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800881
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800882 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700883 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800884 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800885
Andy Hung3c09c782014-12-29 18:39:32 -0800886 sp<AudioTrackThread> t = mAudioTrackThread;
887 if (t != 0) {
888 t->wake();
889 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800890 return NO_ERROR;
891}
892
Glenn Kastena5224f32012-01-04 12:41:44 -0800893status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800894{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700895 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100896 return INVALID_OPERATION;
897 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700898 if (updatePeriod == NULL) {
899 return BAD_VALUE;
900 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800901
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800902 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800903 *updatePeriod = mUpdatePeriod;
904
905 return NO_ERROR;
906}
907
908status_t AudioTrack::setPosition(uint32_t position)
909{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700910 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700911 return INVALID_OPERATION;
912 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800913 if (position > mFrameCount) {
914 return BAD_VALUE;
915 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800916
Eric Laurent1703cdf2011-03-07 14:52:59 -0800917 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800918 // Currently we require that the player is inactive before setting parameters such as position
919 // or loop points. Otherwise, there could be a race condition: the application could read the
920 // current position, compute a new position or loop parameters, and then set that position or
921 // loop parameters but it would do the "wrong" thing since the position has continued to advance
922 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
923 // to specify how it wants to handle such scenarios.
924 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700925 return INVALID_OPERATION;
926 }
Andy Hung9b461582014-12-01 17:56:29 -0800927 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -0700928 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800929 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -0800930
931 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800932 return NO_ERROR;
933}
934
Glenn Kasten200092b2014-08-15 15:13:30 -0700935status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800936{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700937 if (position == NULL) {
938 return BAD_VALUE;
939 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800940
Eric Laurent1703cdf2011-03-07 14:52:59 -0800941 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700942 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100943 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800944
Eric Laurentab5cdba2014-06-09 17:22:27 -0700945 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800946 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
947 *position = mPausedPosition;
948 return NO_ERROR;
949 }
950
Glenn Kasten142f5192014-03-25 17:44:59 -0700951 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100952 uint32_t halFrames;
953 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
954 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700955 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
956 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100957 *position = dspFrames;
958 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -0800959 if (mCblk->mFlags & CBLK_INVALID) {
960 restoreTrack_l("getPosition");
961 }
962
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100963 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700964 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
965 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100966 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800967 return NO_ERROR;
968}
969
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000970status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800971{
972 if (mSharedBuffer == 0 || mIsTimed) {
973 return INVALID_OPERATION;
974 }
975 if (position == NULL) {
976 return BAD_VALUE;
977 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800978
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800979 AutoMutex lock(mLock);
980 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800981 return NO_ERROR;
982}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800983
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800984status_t AudioTrack::reload()
985{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700986 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800987 return INVALID_OPERATION;
988 }
989
Eric Laurent1703cdf2011-03-07 14:52:59 -0800990 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800991 // See setPosition() regarding setting parameters such as loop points or position while active
992 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700993 return INVALID_OPERATION;
994 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800995 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800996 (void) updateAndGetPosition_l();
997 mPosition = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800998#if 0
Andy Hung9b461582014-12-01 17:56:29 -0800999 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -08001000 // of loop count. Historically we have not restored loop count, start, end,
1001 // but it makes sense if one desires to repeat playing a particular sound.
1002 if (mLoopCount != 0) {
1003 mLoopCountNotified = mLoopCount;
1004 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
1005 }
1006#endif
Andy Hung9b461582014-12-01 17:56:29 -08001007 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001008 return NO_ERROR;
1009}
1010
Glenn Kasten38e905b2014-01-13 10:21:48 -08001011audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -07001012{
Eric Laurent1703cdf2011-03-07 14:52:59 -08001013 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001014 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001015}
1016
Paul McLeanaa981192015-03-21 09:55:15 -07001017status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
1018 AutoMutex lock(mLock);
1019 if (mSelectedDeviceId != deviceId) {
1020 mSelectedDeviceId = deviceId;
Eric Laurent493404d2015-04-21 15:07:36 -07001021 android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
Paul McLeanaa981192015-03-21 09:55:15 -07001022 }
Eric Laurent493404d2015-04-21 15:07:36 -07001023 return NO_ERROR;
Paul McLeanaa981192015-03-21 09:55:15 -07001024}
1025
1026audio_port_handle_t AudioTrack::getOutputDevice() {
1027 AutoMutex lock(mLock);
1028 return mSelectedDeviceId;
1029}
1030
Eric Laurentbe916aa2010-06-01 23:49:17 -07001031status_t AudioTrack::attachAuxEffect(int effectId)
1032{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001033 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001034 status_t status = mAudioTrack->attachAuxEffect(effectId);
1035 if (status == NO_ERROR) {
1036 mAuxEffectId = effectId;
1037 }
1038 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -07001039}
1040
Eric Laurente83b55d2014-11-14 10:06:21 -08001041audio_stream_type_t AudioTrack::streamType() const
1042{
1043 if (mStreamType == AUDIO_STREAM_DEFAULT) {
1044 return audio_attributes_to_stream_type(&mAttributes);
1045 }
1046 return mStreamType;
1047}
1048
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001049// -------------------------------------------------------------------------
1050
Eric Laurent1703cdf2011-03-07 14:52:59 -08001051// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -07001052status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001053{
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001054 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
1055 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001056 ALOGE("Could not get audioflinger");
1057 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001058 }
1059
Eric Laurente83b55d2014-11-14 10:06:21 -08001060 audio_io_handle_t output;
1061 audio_stream_type_t streamType = mStreamType;
1062 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
Eric Laurente83b55d2014-11-14 10:06:21 -08001063
Paul McLeanaa981192015-03-21 09:55:15 -07001064 status_t status;
1065 status = AudioSystem::getOutputForAttr(attr, &output,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001066 (audio_session_t)mSessionId, &streamType, mClientUid,
Paul McLeanaa981192015-03-21 09:55:15 -07001067 mSampleRate, mFormat, mChannelMask,
1068 mFlags, mSelectedDeviceId, mOffloadInfo);
Eric Laurente83b55d2014-11-14 10:06:21 -08001069
1070 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001071 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 -07001072 " channel mask %#x, flags %#x",
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001073 mSessionId, streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001074 return BAD_VALUE;
1075 }
1076 {
1077 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
1078 // we must release it ourselves if anything goes wrong.
1079
Glenn Kastence8828a2013-09-16 18:07:38 -07001080 // Not all of these values are needed under all conditions, but it is easier to get them all
1081
Eric Laurentd1b449a2010-05-14 03:26:45 -07001082 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -07001083 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001084 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001085 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001086 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001087 }
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001088 ALOGV("createTrack_l() output %d afLatency %u", output, afLatency);
Eric Laurentd1b449a2010-05-14 03:26:45 -07001089
Glenn Kastence8828a2013-09-16 18:07:38 -07001090 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001091 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -07001092 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001093 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001094 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001095 }
1096
1097 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001098 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -07001099 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001100 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001101 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001102 }
Eric Laurent0d6db582014-11-12 18:39:44 -08001103 if (mSampleRate == 0) {
1104 mSampleRate = afSampleRate;
1105 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001106 // Client decides whether the track is TIMED (see below), but can only express a preference
1107 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001108 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001109 // either of these use cases:
1110 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -08001111 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001112 // use case 2: callback transfer mode
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001113 (mTransfer == TRANSFER_CALLBACK) ||
1114 // use case 3: obtain/release mode
1115 (mTransfer == TRANSFER_OBTAIN)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001116 // matching sample rate
1117 (mSampleRate == afSampleRate))) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001118 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client; transfer %d, track %u Hz, output %u Hz",
1119 mTransfer, mSampleRate, afSampleRate);
Glenn Kasten093000f2012-05-03 09:35:36 -07001120 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001121 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001122 }
1123
Glenn Kastence8828a2013-09-16 18:07:38 -07001124 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -08001125 // n = 1 fast track with single buffering; nBuffering is ignored
1126 // n = 2 fast track with double buffering
Andy Hung0e48d252015-01-26 11:43:15 -08001127 // n = 2 normal track, (including those with sample rate conversion)
1128 // n >= 3 very high latency or very small notification interval (unused).
1129 const uint32_t nBuffering = 2;
Glenn Kastence8828a2013-09-16 18:07:38 -07001130
Eric Laurentd1b449a2010-05-14 03:26:45 -07001131 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001132
Glenn Kasten363fb752014-01-15 12:27:31 -08001133 size_t frameCount = mReqFrameCount;
1134 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001135
Glenn Kasten363fb752014-01-15 12:27:31 -08001136 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001137 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001138 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001139 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001140 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001141 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001142 if (mNotificationFramesAct != frameCount) {
1143 mNotificationFramesAct = frameCount;
1144 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001145 } else if (mSharedBuffer != 0) {
Andy Hungabdb9902015-01-12 15:08:22 -08001146 // FIXME: Ensure client side memory buffers need
1147 // not have additional alignment beyond sample
1148 // (e.g. 16 bit stereo accessed as 32 bit frame).
1149 size_t alignment = audio_bytes_per_sample(mFormat);
Glenn Kastenb7730382014-04-30 15:50:31 -07001150 if (alignment & 1) {
Andy Hungabdb9902015-01-12 15:08:22 -08001151 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
Glenn Kastenb7730382014-04-30 15:50:31 -07001152 alignment = 1;
1153 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001154 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001155 // More than 2 channels does not require stronger alignment than stereo
1156 alignment <<= 1;
1157 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001158 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001159 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001160 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001161 status = BAD_VALUE;
1162 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001163 }
1164
1165 // When initializing a shared buffer AudioTrack via constructors,
1166 // there's no frameCount parameter.
1167 // But when initializing a shared buffer AudioTrack via set(),
1168 // there _is_ a frameCount parameter. We silently ignore it.
Andy Hungabdb9902015-01-12 15:08:22 -08001169 frameCount = mSharedBuffer->size() / mFrameSize;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001170 } else {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001171 // For fast tracks the frame count calculations and checks are done by server
1172
1173 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1174 // for normal tracks precompute the frame count based on speed.
1175 const size_t minFrameCount = calculateMinFrameCount(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001176 afLatency, afFrameCount, afSampleRate, mSampleRate,
1177 mPlaybackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07001178 if (frameCount < minFrameCount) {
1179 frameCount = minFrameCount;
1180 }
1181 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001182 }
1183
Glenn Kastena075db42012-03-06 11:22:44 -08001184 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1185 if (mIsTimed) {
1186 trackFlags |= IAudioFlinger::TRACK_TIMED;
1187 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001188
1189 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001190 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001191 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001192 if (mAudioTrackThread != 0) {
1193 tid = mAudioTrackThread->getTid();
1194 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001195 }
1196
Glenn Kasten363fb752014-01-15 12:27:31 -08001197 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001198 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1199 }
1200
Eric Laurentab5cdba2014-06-09 17:22:27 -07001201 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1202 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1203 }
1204
Glenn Kasten74935e42013-12-19 08:56:45 -08001205 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1206 // but we will still need the original value also
Glenn Kasten138d6f92015-03-20 10:54:51 -07001207 int originalSessionId = mSessionId;
Eric Laurente83b55d2014-11-14 10:06:21 -08001208 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001209 mSampleRate,
Andy Hungabdb9902015-01-12 15:08:22 -08001210 mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001211 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001212 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001213 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001214 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001215 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001216 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001217 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001218 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001219 &status);
Glenn Kasten138d6f92015-03-20 10:54:51 -07001220 ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
1221 "session ID changed from %d to %d", originalSessionId, mSessionId);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001222
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001223 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001224 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001225 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001226 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001227 ALOG_ASSERT(track != 0);
1228
Glenn Kasten38e905b2014-01-13 10:21:48 -08001229 // AudioFlinger now owns the reference to the I/O handle,
1230 // so we are no longer responsible for releasing it.
1231
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001232 sp<IMemory> iMem = track->getCblk();
1233 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001234 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001235 return NO_INIT;
1236 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001237 void *iMemPointer = iMem->pointer();
1238 if (iMemPointer == NULL) {
1239 ALOGE("Could not get control block pointer");
1240 return NO_INIT;
1241 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001242 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001243 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001244 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001245 mDeathNotifier.clear();
1246 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001247 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001248 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001249 IPCThreadState::self()->flushCommands();
1250
Glenn Kasten0cde0762014-01-16 15:06:36 -08001251 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001252 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001253 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001254 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1255 // In current design, AudioTrack client checks and ensures frame count validity before
1256 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1257 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001258 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001259 }
1260 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001261
Glenn Kastena07f17c2013-04-23 12:39:37 -07001262 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001263 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001264 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001265 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001266 mAwaitBoost = true;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001267 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001268 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001269 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001270 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001271 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001272 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001273 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001274 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1275 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1276 } else {
1277 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001278 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001279 // FIXME This is a warning, not an error, so don't return error status
1280 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001281 }
1282 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001283 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1284 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1285 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1286 } else {
1287 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1288 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1289 // FIXME This is a warning, not an error, so don't return error status
1290 //return NO_INIT;
1291 }
1292 }
Andy Hung0e48d252015-01-26 11:43:15 -08001293 // Make sure that application is notified with sufficient margin before underrun
1294 if (mSharedBuffer == 0 && audio_is_linear_pcm(mFormat)) {
1295 // Theoretically double-buffering is not required for fast tracks,
1296 // due to tighter scheduling. But in practice, to accommodate kernels with
1297 // scheduling jitter, and apps with computation jitter, we use double-buffering
1298 // for fast tracks just like normal streaming tracks.
1299 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount / nBuffering) {
1300 mNotificationFramesAct = frameCount / nBuffering;
1301 }
1302 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001303
Glenn Kasten38e905b2014-01-13 10:21:48 -08001304 // We retain a copy of the I/O handle, but don't own the reference
1305 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001306 mRefreshRemaining = true;
1307
1308 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1309 // is the value of pointer() for the shared buffer, otherwise buffers points
1310 // immediately after the control block. This address is for the mapping within client
1311 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1312 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001313 if (mSharedBuffer == 0) {
Glenn Kasten138d6f92015-03-20 10:54:51 -07001314 buffers = cblk + 1;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001315 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001316 buffers = mSharedBuffer->pointer();
Glenn Kasten138d6f92015-03-20 10:54:51 -07001317 if (buffers == NULL) {
1318 ALOGE("Could not get buffer pointer");
1319 return NO_INIT;
1320 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001321 }
1322
Eric Laurent2beeb502010-07-16 07:43:46 -07001323 mAudioTrack->attachAuxEffect(mAuxEffectId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07001324 // FIXME doesn't take into account speed or future sample rate changes (until restoreTrack)
Glenn Kastene0fa4672012-04-24 14:35:14 -07001325 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001326 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001327
Glenn Kastenb6037442012-11-14 13:42:25 -08001328 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001329 // If IAudioTrack is re-created, don't let the requested frameCount
1330 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001331 if (frameCount > mReqFrameCount) {
1332 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001333 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001334
1335 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001336 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001337 mStaticProxy.clear();
Andy Hungabdb9902015-01-12 15:08:22 -08001338 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001339 } else {
Andy Hungabdb9902015-01-12 15:08:22 -08001340 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001341 mProxy = mStaticProxy;
1342 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001343
1344 mProxy->setVolumeLR(gain_minifloat_pack(
1345 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1346 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1347
Glenn Kastene3aa6592012-12-04 12:22:46 -08001348 mProxy->setSendLevel(mSendLevel);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001349 const uint32_t effectiveSampleRate = adjustSampleRate(mSampleRate, mPlaybackRate.mPitch);
1350 const float effectiveSpeed = adjustSpeed(mPlaybackRate.mSpeed, mPlaybackRate.mPitch);
1351 const float effectivePitch = adjustPitch(mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001352 mProxy->setSampleRate(effectiveSampleRate);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001353
1354 AudioPlaybackRate playbackRateTemp = mPlaybackRate;
1355 playbackRateTemp.mSpeed = effectiveSpeed;
1356 playbackRateTemp.mPitch = effectivePitch;
1357 mProxy->setPlaybackRate(playbackRateTemp);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001358 mProxy->setMinimum(mNotificationFramesAct);
1359
1360 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001361 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001362
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001363 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001364 }
1365
1366release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001367 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001368 if (status == NO_ERROR) {
1369 status = NO_INIT;
1370 }
1371 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001372}
1373
Glenn Kastenb46f3942015-03-09 12:00:30 -07001374status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001375{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001376 if (audioBuffer == NULL) {
Glenn Kasten551b5352015-03-20 11:30:28 -07001377 if (nonContig != NULL) {
1378 *nonContig = 0;
1379 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001380 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001381 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001382 if (mTransfer != TRANSFER_OBTAIN) {
1383 audioBuffer->frameCount = 0;
1384 audioBuffer->size = 0;
1385 audioBuffer->raw = NULL;
Glenn Kasten551b5352015-03-20 11:30:28 -07001386 if (nonContig != NULL) {
1387 *nonContig = 0;
1388 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001389 return INVALID_OPERATION;
1390 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001391
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001392 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001393 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001394 if (waitCount == -1) {
1395 requested = &ClientProxy::kForever;
1396 } else if (waitCount == 0) {
1397 requested = &ClientProxy::kNonBlocking;
1398 } else if (waitCount > 0) {
1399 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001400 timeout.tv_sec = ms / 1000;
1401 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1402 requested = &timeout;
1403 } else {
1404 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1405 requested = NULL;
1406 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001407 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001408}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001409
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001410status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1411 struct timespec *elapsed, size_t *nonContig)
1412{
1413 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1414 uint32_t oldSequence = 0;
1415 uint32_t newSequence;
1416
1417 Proxy::Buffer buffer;
1418 status_t status = NO_ERROR;
1419
1420 static const int32_t kMaxTries = 5;
1421 int32_t tryCounter = kMaxTries;
1422
1423 do {
1424 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1425 // keep them from going away if another thread re-creates the track during obtainBuffer()
1426 sp<AudioTrackClientProxy> proxy;
1427 sp<IMemory> iMem;
1428
1429 { // start of lock scope
1430 AutoMutex lock(mLock);
1431
1432 newSequence = mSequence;
1433 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1434 if (status == DEAD_OBJECT) {
1435 // re-create track, unless someone else has already done so
1436 if (newSequence == oldSequence) {
1437 status = restoreTrack_l("obtainBuffer");
1438 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001439 buffer.mFrameCount = 0;
1440 buffer.mRaw = NULL;
1441 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001442 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001443 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001444 }
1445 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001446 oldSequence = newSequence;
1447
1448 // Keep the extra references
1449 proxy = mProxy;
1450 iMem = mCblkMemory;
1451
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001452 if (mState == STATE_STOPPING) {
1453 status = -EINTR;
1454 buffer.mFrameCount = 0;
1455 buffer.mRaw = NULL;
1456 buffer.mNonContig = 0;
1457 break;
1458 }
1459
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001460 // Non-blocking if track is stopped or paused
1461 if (mState != STATE_ACTIVE) {
1462 requested = &ClientProxy::kNonBlocking;
1463 }
1464
1465 } // end of lock scope
1466
1467 buffer.mFrameCount = audioBuffer->frameCount;
1468 // FIXME starts the requested timeout and elapsed over from scratch
1469 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1470
1471 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1472
1473 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001474 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001475 audioBuffer->raw = buffer.mRaw;
1476 if (nonContig != NULL) {
1477 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001478 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001479 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001480}
1481
Glenn Kasten54a8a452015-03-09 12:03:00 -07001482void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001483{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001484 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001485 if (mTransfer == TRANSFER_SHARED) {
1486 return;
1487 }
1488
Andy Hungabdb9902015-01-12 15:08:22 -08001489 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001490 if (stepCount == 0) {
1491 return;
1492 }
1493
1494 Proxy::Buffer buffer;
1495 buffer.mFrameCount = stepCount;
1496 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001497
Eric Laurent1703cdf2011-03-07 14:52:59 -08001498 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001499 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001500 mInUnderrun = false;
1501 mProxy->releaseBuffer(&buffer);
1502
1503 // restart track if it was disabled by audioflinger due to previous underrun
1504 if (mState == STATE_ACTIVE) {
1505 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001506 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001507 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001508 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001509 mAudioTrack->start();
1510 }
1511 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001512}
1513
1514// -------------------------------------------------------------------------
1515
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001516ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001517{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001518 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001519 return INVALID_OPERATION;
1520 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001521
Eric Laurentab5cdba2014-06-09 17:22:27 -07001522 if (isDirect()) {
1523 AutoMutex lock(mLock);
1524 int32_t flags = android_atomic_and(
1525 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1526 &mCblk->mFlags);
1527 if (flags & CBLK_INVALID) {
1528 return DEAD_OBJECT;
1529 }
1530 }
1531
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001532 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001533 // Sanity-check: user is most-likely passing an error code, and it would
1534 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001535 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001536 return BAD_VALUE;
1537 }
1538
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001539 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001540 Buffer audioBuffer;
1541
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001542 while (userSize >= mFrameSize) {
1543 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001544
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001545 status_t err = obtainBuffer(&audioBuffer,
1546 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001547 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001548 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001549 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001550 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001551 return ssize_t(err);
1552 }
1553
Glenn Kastenae4b8792015-03-20 09:04:21 -07001554 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08001555 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001556 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001557 userSize -= toWrite;
1558 written += toWrite;
1559
1560 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001561 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001562
1563 return written;
1564}
1565
1566// -------------------------------------------------------------------------
1567
John Grossman4ff14ba2012-02-08 16:37:41 -08001568TimedAudioTrack::TimedAudioTrack() {
1569 mIsTimed = true;
1570}
1571
1572status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1573{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001574 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001575 status_t result = UNKNOWN_ERROR;
1576
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001577#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001578 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1579 // while we are accessing the cblk
1580 sp<IAudioTrack> audioTrack = mAudioTrack;
1581 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001582#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001583
John Grossman4ff14ba2012-02-08 16:37:41 -08001584 // If the track is not invalid already, try to allocate a buffer. alloc
1585 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001586 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001587 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001588 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001589 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1590 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001591 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001592 }
1593 }
1594
1595 // If the track is invalid at this point, attempt to restore it. and try the
1596 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001597 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001598 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001599
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001600 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001601 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001602 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001603 }
1604
1605 return result;
1606}
1607
1608status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1609 int64_t pts)
1610{
Eric Laurentdf839842012-05-31 14:27:14 -07001611 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1612 {
1613 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001614 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001615 // restart track if it was disabled by audioflinger due to previous underrun
1616 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001617 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1618 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001619 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001620 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001621 mAudioTrack->start();
1622 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001623 }
Eric Laurentdf839842012-05-31 14:27:14 -07001624 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001625}
1626
1627status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1628 TargetTimeline target)
1629{
1630 return mAudioTrack->setMediaTimeTransform(xform, target);
1631}
1632
1633// -------------------------------------------------------------------------
1634
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001635nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001636{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001637 // Currently the AudioTrack thread is not created if there are no callbacks.
1638 // Would it ever make sense to run the thread, even without callbacks?
1639 // If so, then replace this by checks at each use for mCbf != NULL.
1640 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1641
Eric Laurent1703cdf2011-03-07 14:52:59 -08001642 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001643 if (mAwaitBoost) {
1644 mAwaitBoost = false;
1645 mLock.unlock();
1646 static const int32_t kMaxTries = 5;
1647 int32_t tryCounter = kMaxTries;
1648 uint32_t pollUs = 10000;
1649 do {
1650 int policy = sched_getscheduler(0);
1651 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1652 break;
1653 }
1654 usleep(pollUs);
1655 pollUs <<= 1;
1656 } while (tryCounter-- > 0);
1657 if (tryCounter < 0) {
1658 ALOGE("did not receive expected priority boost on time");
1659 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001660 // Run again immediately
1661 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001662 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001663
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001664 // Can only reference mCblk while locked
1665 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001666 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001667
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001668 // Check for track invalidation
1669 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001670 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1671 // AudioSystem cache. We should not exit here but after calling the callback so
1672 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001673 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Lajos Molnarf1063e22015-04-17 15:19:42 -07001674 status_t status __unused = restoreTrack_l("processAudioBuffer");
1675 // FIXME unused status
Andy Hung53c3b5f2014-12-15 16:42:05 -08001676 // after restoration, continue below to make sure that the loop and buffer events
1677 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001678 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001679 }
1680
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001681 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001682 bool active = mState == STATE_ACTIVE;
1683
1684 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1685 bool newUnderrun = false;
1686 if (flags & CBLK_UNDERRUN) {
1687#if 0
1688 // Currently in shared buffer mode, when the server reaches the end of buffer,
1689 // the track stays active in continuous underrun state. It's up to the application
1690 // to pause or stop the track, or set the position to a new offset within buffer.
1691 // This was some experimental code to auto-pause on underrun. Keeping it here
1692 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1693 if (mTransfer == TRANSFER_SHARED) {
1694 mState = STATE_PAUSED;
1695 active = false;
1696 }
1697#endif
1698 if (!mInUnderrun) {
1699 mInUnderrun = true;
1700 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001701 }
1702 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001703
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001704 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001705 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001706
1707 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001708 bool markerReached = false;
1709 size_t markerPosition = mMarkerPosition;
1710 // FIXME fails for wraparound, need 64 bits
1711 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1712 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001713 }
1714
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001715 // Determine number of new position callback(s) that will be needed, while locked
1716 size_t newPosCount = 0;
1717 size_t newPosition = mNewPosition;
1718 size_t updatePeriod = mUpdatePeriod;
1719 // FIXME fails for wraparound, need 64 bits
1720 if (updatePeriod > 0 && position >= newPosition) {
1721 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1722 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001723 }
1724
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001725 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001726 uint32_t sampleRate = mSampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001727 float speed = mPlaybackRate.mSpeed;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001728 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001729 if (mRefreshRemaining) {
1730 mRefreshRemaining = false;
1731 mRemainingFrames = notificationFrames;
1732 mRetryOnPartialBuffer = false;
1733 }
1734 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001735 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001736 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001737
Andy Hung53c3b5f2014-12-15 16:42:05 -08001738 // Determine the number of new loop callback(s) that will be needed, while locked.
1739 int loopCountNotifications = 0;
1740 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1741
1742 if (mLoopCount > 0) {
1743 int loopCount;
1744 size_t bufferPosition;
1745 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1746 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1747 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1748 mLoopCountNotified = loopCount; // discard any excess notifications
1749 } else if (mLoopCount < 0) {
1750 // FIXME: We're not accurate with notification count and position with infinite looping
1751 // since loopCount from server side will always return -1 (we could decrement it).
1752 size_t bufferPosition = mStaticProxy->getBufferPosition();
1753 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1754 loopPeriod = mLoopEnd - bufferPosition;
1755 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1756 size_t bufferPosition = mStaticProxy->getBufferPosition();
1757 loopPeriod = mFrameCount - bufferPosition;
1758 }
1759
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001760 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08001761 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001762 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1763
1764 mLock.unlock();
1765
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001766 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001767 struct timespec timeout;
1768 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1769 timeout.tv_nsec = 0;
1770
Glenn Kasten96f04882013-09-20 09:28:56 -07001771 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001772 switch (status) {
1773 case NO_ERROR:
1774 case DEAD_OBJECT:
1775 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001776 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001777 {
1778 AutoMutex lock(mLock);
1779 // The previously assigned value of waitStreamEnd is no longer valid,
1780 // since the mutex has been unlocked and either the callback handler
1781 // or another thread could have re-started the AudioTrack during that time.
1782 waitStreamEnd = mState == STATE_STOPPING;
1783 if (waitStreamEnd) {
1784 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001785 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001786 }
1787 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001788 if (waitStreamEnd && status != DEAD_OBJECT) {
1789 return NS_INACTIVE;
1790 }
1791 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001792 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001793 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001794 }
1795
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001796 // perform callbacks while unlocked
1797 if (newUnderrun) {
1798 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1799 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001800 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001801 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001802 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001803 }
1804 if (flags & CBLK_BUFFER_END) {
1805 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1806 }
1807 if (markerReached) {
1808 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1809 }
1810 while (newPosCount > 0) {
1811 size_t temp = newPosition;
1812 mCbf(EVENT_NEW_POS, mUserData, &temp);
1813 newPosition += updatePeriod;
1814 newPosCount--;
1815 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001816
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001817 if (mObservedSequence != sequence) {
1818 mObservedSequence = sequence;
1819 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001820 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001821 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001822 return NS_INACTIVE;
1823 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001824 }
1825
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001826 // if inactive, then don't run me again until re-started
1827 if (!active) {
1828 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001829 }
1830
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001831 // Compute the estimated time until the next timed event (position, markers, loops)
1832 // FIXME only for non-compressed audio
1833 uint32_t minFrames = ~0;
1834 if (!markerReached && position < markerPosition) {
1835 minFrames = markerPosition - position;
1836 }
1837 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08001838 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001839 minFrames = loopPeriod;
1840 }
Andy Hung2d85f092015-01-07 12:45:13 -08001841 if (updatePeriod > 0) {
1842 minFrames = min(minFrames, uint32_t(newPosition - position));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001843 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001844
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001845 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1846 static const uint32_t kPoll = 0;
1847 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1848 minFrames = kPoll * notificationFrames;
1849 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001850
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001851 // Convert frame units to time units
1852 nsecs_t ns = NS_WHENEVER;
1853 if (minFrames != (uint32_t) ~0) {
1854 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1855 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
Andy Hung8edb8dc2015-03-26 19:13:55 -07001856 ns = ((double)minFrames * 1000000000) / ((double)sampleRate * speed) + kFudgeNs;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001857 }
1858
1859 // If not supplying data by EVENT_MORE_DATA, then we're done
1860 if (mTransfer != TRANSFER_CALLBACK) {
1861 return ns;
1862 }
1863
1864 struct timespec timeout;
1865 const struct timespec *requested = &ClientProxy::kForever;
1866 if (ns != NS_WHENEVER) {
1867 timeout.tv_sec = ns / 1000000000LL;
1868 timeout.tv_nsec = ns % 1000000000LL;
1869 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1870 requested = &timeout;
1871 }
1872
1873 while (mRemainingFrames > 0) {
1874
1875 Buffer audioBuffer;
1876 audioBuffer.frameCount = mRemainingFrames;
1877 size_t nonContig;
1878 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1879 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001880 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001881 requested = &ClientProxy::kNonBlocking;
1882 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001883 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001884 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001885 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001886 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1887 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001888 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001889 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001890 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1891 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001892 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001893
Eric Laurent42a6f422013-08-29 14:35:05 -07001894 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001895 mRetryOnPartialBuffer = false;
1896 if (avail < mRemainingFrames) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001897 int64_t myns = ((double)(mRemainingFrames - avail) * 1100000000)
1898 / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001899 if (ns < 0 || myns < ns) {
1900 ns = myns;
1901 }
1902 return ns;
1903 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001904 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001905
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001906 size_t reqSize = audioBuffer.size;
1907 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001908 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001909
1910 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001911 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001912 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1913 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001914 return NS_NEVER;
1915 }
1916
1917 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001918 // The callback is done filling buffers
1919 // Keep this thread going to handle timed events and
1920 // still try to get more data in intervals of WAIT_PERIOD_MS
1921 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001922 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001923 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001924
Glenn Kasten138d6f92015-03-20 10:54:51 -07001925 size_t releasedFrames = writtenSize / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001926 audioBuffer.frameCount = releasedFrames;
1927 mRemainingFrames -= releasedFrames;
1928 if (misalignment >= releasedFrames) {
1929 misalignment -= releasedFrames;
1930 } else {
1931 misalignment = 0;
1932 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001933
1934 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001935
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001936 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1937 // if callback doesn't like to accept the full chunk
1938 if (writtenSize < reqSize) {
1939 continue;
1940 }
1941
1942 // There could be enough non-contiguous frames available to satisfy the remaining request
1943 if (mRemainingFrames <= nonContig) {
1944 continue;
1945 }
1946
1947#if 0
1948 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1949 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1950 // that total to a sum == notificationFrames.
1951 if (0 < misalignment && misalignment <= mRemainingFrames) {
1952 mRemainingFrames = misalignment;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001953 return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001954 }
1955#endif
1956
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001957 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001958 mRemainingFrames = notificationFrames;
1959 mRetryOnPartialBuffer = true;
1960
1961 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1962 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001963}
1964
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001965status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001966{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001967 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001968 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001969 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001970
Glenn Kastena47f3162012-11-07 10:13:08 -08001971 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08001972 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001973 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001974
Eric Laurentab5cdba2014-06-09 17:22:27 -07001975 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001976 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001977 return DEAD_OBJECT;
1978 }
1979
Glenn Kasten200092b2014-08-15 15:13:30 -07001980 // save the old static buffer position
Andy Hung4ede21d2014-12-12 15:37:34 -08001981 size_t bufferPosition = 0;
1982 int loopCount = 0;
1983 if (mStaticProxy != 0) {
1984 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1985 }
Glenn Kasten200092b2014-08-15 15:13:30 -07001986
1987 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001988 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001989 // It will also delete the strong references on previous IAudioTrack and IMemory.
1990 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Glenn Kastenae4b8792015-03-20 09:04:21 -07001991 status_t result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001992
1993 // take the frames that will be lost by track recreation into account in saved position
Andy Hung9b461582014-12-01 17:56:29 -08001994 // For streaming tracks, this is the amount we obtained from the user/client
1995 // (not the number actually consumed at the server - those are already lost).
Glenn Kasten200092b2014-08-15 15:13:30 -07001996 (void) updateAndGetPosition_l();
Andy Hung7ccdaad2015-03-20 00:38:32 -07001997 if (mStaticProxy == 0) {
Andy Hung9b461582014-12-01 17:56:29 -08001998 mPosition = mReleased;
1999 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002000
Glenn Kastena47f3162012-11-07 10:13:08 -08002001 if (result == NO_ERROR) {
Andy Hung4ede21d2014-12-12 15:37:34 -08002002 // Continue playback from last known position and restore loop.
2003 if (mStaticProxy != 0) {
2004 if (loopCount != 0) {
2005 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
2006 mLoopStart, mLoopEnd, loopCount);
2007 } else {
2008 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002009 if (bufferPosition == mFrameCount) {
2010 ALOGD("restoring track at end of static buffer");
2011 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002012 }
2013 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002014 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08002015 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08002016 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002017 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002018 if (result != NO_ERROR) {
2019 ALOGW("restoreTrack_l() failed status %d", result);
2020 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07002021 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002022 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002023
2024 return result;
2025}
2026
Glenn Kasten200092b2014-08-15 15:13:30 -07002027uint32_t AudioTrack::updateAndGetPosition_l()
2028{
2029 // This is the sole place to read server consumed frames
2030 uint32_t newServer = mProxy->getPosition();
2031 int32_t delta = newServer - mServer;
2032 mServer = newServer;
2033 // TODO There is controversy about whether there can be "negative jitter" in server position.
2034 // This should be investigated further, and if possible, it should be addressed.
2035 // A more definite failure mode is infrequent polling by client.
2036 // One could call (void)getPosition_l() in releaseBuffer(),
2037 // so mReleased and mPosition are always lock-step as best possible.
2038 // That should ensure delta never goes negative for infrequent polling
2039 // unless the server has more than 2^31 frames in its buffer,
2040 // in which case the use of uint32_t for these counters has bigger issues.
2041 if (delta < 0) {
2042 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
2043 delta = 0;
2044 }
2045 return mPosition += (uint32_t) delta;
2046}
2047
Andy Hung8edb8dc2015-03-26 19:13:55 -07002048bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed) const
2049{
2050 // applicable for mixing tracks only (not offloaded or direct)
2051 if (mStaticProxy != 0) {
2052 return true; // static tracks do not have issues with buffer sizing.
2053 }
2054 status_t status;
2055 uint32_t afLatency;
2056 status = AudioSystem::getLatency(mOutput, &afLatency);
2057 if (status != NO_ERROR) {
2058 ALOGE("getLatency(%d) failed status %d", mOutput, status);
2059 return false;
2060 }
2061
2062 size_t afFrameCount;
2063 status = AudioSystem::getFrameCount(mOutput, &afFrameCount);
2064 if (status != NO_ERROR) {
2065 ALOGE("getFrameCount(output=%d) status %d", mOutput, status);
2066 return false;
2067 }
2068
2069 uint32_t afSampleRate;
2070 status = AudioSystem::getSamplingRate(mOutput, &afSampleRate);
2071 if (status != NO_ERROR) {
2072 ALOGE("getSamplingRate(output=%d) status %d", mOutput, status);
2073 return false;
2074 }
2075
2076 const size_t minFrameCount =
2077 calculateMinFrameCount(afLatency, afFrameCount, afSampleRate, sampleRate, speed);
2078 ALOGV("isSampleRateSpeedAllowed_l mFrameCount %zu minFrameCount %zu",
2079 mFrameCount, minFrameCount);
2080 return mFrameCount >= minFrameCount;
2081}
2082
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002083status_t AudioTrack::setParameters(const String8& keyValuePairs)
2084{
2085 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07002086 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002087}
2088
Glenn Kastence703742013-07-19 16:33:58 -07002089status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
2090{
Glenn Kasten53cec222013-08-29 09:01:02 -07002091 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07002092 // FIXME not implemented for fast tracks; should use proxy and SSQ
2093 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
2094 return INVALID_OPERATION;
2095 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002096
2097 switch (mState) {
2098 case STATE_ACTIVE:
2099 case STATE_PAUSED:
2100 break; // handle below
2101 case STATE_FLUSHED:
2102 case STATE_STOPPED:
2103 return WOULD_BLOCK;
2104 case STATE_STOPPING:
2105 case STATE_PAUSED_STOPPING:
2106 if (!isOffloaded_l()) {
2107 return INVALID_OPERATION;
2108 }
2109 break; // offloaded tracks handled below
2110 default:
2111 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
2112 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07002113 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002114
Eric Laurent275e8e92014-11-30 15:14:47 -08002115 if (mCblk->mFlags & CBLK_INVALID) {
2116 restoreTrack_l("getTimestamp");
2117 }
2118
Glenn Kasten200092b2014-08-15 15:13:30 -07002119 // The presented frame count must always lag behind the consumed frame count.
2120 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002121 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002122 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07002123 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002124 return status;
2125 }
2126 if (isOffloadedOrDirect_l()) {
2127 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
2128 // use cached paused position in case another offloaded track is running.
2129 timestamp.mPosition = mPausedPosition;
2130 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
2131 return NO_ERROR;
2132 }
2133
2134 // Check whether a pending flush or stop has completed, as those commands may
2135 // be asynchronous or return near finish.
2136 if (mStartUs != 0 && mSampleRate != 0) {
2137 static const int kTimeJitterUs = 100000; // 100 ms
2138 static const int k1SecUs = 1000000;
2139
2140 const int64_t timeNow = getNowUs();
2141
2142 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
2143 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
2144 if (timestampTimeUs < mStartUs) {
2145 return WOULD_BLOCK; // stale timestamp time, occurs before start.
2146 }
2147 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002148 const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002149 / ((double)mSampleRate * mPlaybackRate.mSpeed);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002150
2151 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2152 // Verify that the counter can't count faster than the sample rate
2153 // since the start time. If greater, then that means we have failed
2154 // to completely flush or stop the previous playing track.
2155 ALOGW("incomplete flush or stop:"
2156 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2157 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2158 timestamp.mPosition);
2159 return WOULD_BLOCK;
2160 }
2161 }
2162 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
2163 }
2164 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002165 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2166 (void) updateAndGetPosition_l();
2167 // Server consumed (mServer) and presented both use the same server time base,
2168 // and server consumed is always >= presented.
2169 // The delta between these represents the number of frames in the buffer pipeline.
2170 // If this delta between these is greater than the client position, it means that
2171 // actually presented is still stuck at the starting line (figuratively speaking),
2172 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
2173 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2174 return INVALID_OPERATION;
2175 }
2176 // Convert timestamp position from server time base to client time base.
2177 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2178 // But if we change it to 64-bit then this could fail.
2179 // If (mPosition - mServer) can be negative then should use:
2180 // (int32_t)(mPosition - mServer)
2181 timestamp.mPosition += mPosition - mServer;
2182 // Immediately after a call to getPosition_l(), mPosition and
2183 // mServer both represent the same frame position. mPosition is
2184 // in client's point of view, and mServer is in server's point of
2185 // view. So the difference between them is the "fudge factor"
2186 // between client and server views due to stop() and/or new
2187 // IAudioTrack. And timestamp.mPosition is initially in server's
2188 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002189 }
2190 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002191}
2192
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002193String8 AudioTrack::getParameters(const String8& keys)
2194{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002195 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002196 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002197 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002198 } else {
2199 return String8::empty();
2200 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002201}
2202
Glenn Kasten23a75452014-01-13 10:37:17 -08002203bool AudioTrack::isOffloaded() const
2204{
2205 AutoMutex lock(mLock);
2206 return isOffloaded_l();
2207}
2208
Eric Laurentab5cdba2014-06-09 17:22:27 -07002209bool AudioTrack::isDirect() const
2210{
2211 AutoMutex lock(mLock);
2212 return isDirect_l();
2213}
2214
2215bool AudioTrack::isOffloadedOrDirect() const
2216{
2217 AutoMutex lock(mLock);
2218 return isOffloadedOrDirect_l();
2219}
2220
2221
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002222status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002223{
2224
2225 const size_t SIZE = 256;
2226 char buffer[SIZE];
2227 String8 result;
2228
2229 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002230 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002231 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002232 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002233 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002234 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002235 result.append(buffer);
Andy Hung8edb8dc2015-03-26 19:13:55 -07002236 snprintf(buffer, 255, " sample rate(%u), speed(%f), status(%d)\n",
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002237 mSampleRate, mPlaybackRate.mSpeed, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002238 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002239 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002240 result.append(buffer);
2241 ::write(fd, result.string(), result.size());
2242 return NO_ERROR;
2243}
2244
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002245uint32_t AudioTrack::getUnderrunFrames() const
2246{
2247 AutoMutex lock(mLock);
2248 return mProxy->getUnderrunFrames();
2249}
2250
2251// =========================================================================
2252
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002253void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002254{
2255 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2256 if (audioTrack != 0) {
2257 AutoMutex lock(audioTrack->mLock);
2258 audioTrack->mProxy->binderDied();
2259 }
2260}
2261
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002262// =========================================================================
2263
2264AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002265 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2266 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002267{
2268}
2269
2270AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002271{
2272}
2273
2274bool AudioTrack::AudioTrackThread::threadLoop()
2275{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002276 {
2277 AutoMutex _l(mMyLock);
2278 if (mPaused) {
2279 mMyCond.wait(mMyLock);
2280 // caller will check for exitPending()
2281 return true;
2282 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002283 if (mIgnoreNextPausedInt) {
2284 mIgnoreNextPausedInt = false;
2285 mPausedInt = false;
2286 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002287 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002288 if (mPausedNs > 0) {
2289 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2290 } else {
2291 mMyCond.wait(mMyLock);
2292 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002293 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002294 return true;
2295 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002296 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002297 if (exitPending()) {
2298 return false;
2299 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002300 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002301 switch (ns) {
2302 case 0:
2303 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002304 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002305 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002306 return true;
2307 case NS_NEVER:
2308 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002309 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08002310 // Event driven: call wake() when callback notifications conditions change.
2311 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002312 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002313 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002314 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002315 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002316 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002317 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002318}
2319
Glenn Kasten3acbd052012-02-28 10:39:56 -08002320void AudioTrack::AudioTrackThread::requestExit()
2321{
2322 // must be in this order to avoid a race condition
2323 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002324 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002325}
2326
2327void AudioTrack::AudioTrackThread::pause()
2328{
2329 AutoMutex _l(mMyLock);
2330 mPaused = true;
2331}
2332
2333void AudioTrack::AudioTrackThread::resume()
2334{
2335 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002336 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002337 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002338 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002339 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002340 mMyCond.signal();
2341 }
2342}
2343
Andy Hung3c09c782014-12-29 18:39:32 -08002344void AudioTrack::AudioTrackThread::wake()
2345{
2346 AutoMutex _l(mMyLock);
2347 if (!mPaused && mPausedInt && mPausedNs > 0) {
2348 // audio track is active and internally paused with timeout.
2349 mIgnoreNextPausedInt = true;
2350 mPausedInt = false;
2351 mMyCond.signal();
2352 }
2353}
2354
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002355void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2356{
2357 AutoMutex _l(mMyLock);
2358 mPausedInt = true;
2359 mPausedNs = ns;
2360}
2361
Glenn Kasten40bc9062015-03-20 09:09:33 -07002362} // namespace android