blob: 76d9169559da0d6eaa87a62002ff6ca7d3b03995 [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;
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700396 mOriginalSampleRate = sampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700397 mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT;
Eric Laurent0d6db582014-11-12 18:39:44 -0800398
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800399 // Make copy of input parameter offloadInfo so that in the future:
400 // (a) createTrack_l doesn't need it as an input parameter
401 // (b) we can support re-creation of offloaded tracks
402 if (offloadInfo != NULL) {
403 mOffloadInfoCopy = *offloadInfo;
404 mOffloadInfo = &mOffloadInfoCopy;
405 } else {
406 mOffloadInfo = NULL;
407 }
408
Glenn Kasten66e46352014-01-16 17:44:23 -0800409 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
410 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800411 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800412 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800413 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700414 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800415 mNotificationFramesAct = 0;
Eric Laurentcaf7f482014-11-25 17:50:47 -0800416 if (sessionId == AUDIO_SESSION_ALLOCATE) {
417 mSessionId = AudioSystem::newAudioUniqueId();
418 } else {
419 mSessionId = sessionId;
420 }
Marco Nelissend457c972014-02-11 08:47:07 -0800421 int callingpid = IPCThreadState::self()->getCallingPid();
422 int mypid = getpid();
423 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800424 mClientUid = IPCThreadState::self()->getCallingUid();
425 } else {
426 mClientUid = uid;
427 }
Marco Nelissend457c972014-02-11 08:47:07 -0800428 if (pid == -1 || (callingpid != mypid)) {
429 mClientPid = callingpid;
430 } else {
431 mClientPid = pid;
432 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700433 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700434 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700435 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700436
Glenn Kastena997e7a2012-08-07 09:44:19 -0700437 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700438 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700439 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
Glenn Kastenbfd31842015-03-20 09:01:44 -0700440 // thread begins in paused state, and will not reference us until start()
Glenn Kastena997e7a2012-08-07 09:44:19 -0700441 }
442
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800443 // create the IAudioTrack
Eric Laurent0d6db582014-11-12 18:39:44 -0800444 status_t status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800445
Glenn Kastena997e7a2012-08-07 09:44:19 -0700446 if (status != NO_ERROR) {
447 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100448 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
449 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700450 mAudioTrackThread.clear();
451 }
452 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700453 }
454
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800455 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800456 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800457 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800458 mLoopCount = 0;
459 mLoopStart = 0;
460 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800461 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800462 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700463 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800464 mNewPosition = 0;
465 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700466 mServer = 0;
467 mPosition = 0;
468 mReleased = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700469 mStartUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800470 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800471 mSequence = 1;
472 mObservedSequence = mSequence;
473 mInUnderrun = false;
Phil Burk1b420972015-04-22 10:52:21 -0700474 mPreviousTimestampValid = false;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800475
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800476 return NO_ERROR;
477}
478
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800479// -------------------------------------------------------------------------
480
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100481status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800482{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800483 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100484
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800485 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100486 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800487 }
488
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800489 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800490
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800491 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100492 if (previousState == STATE_PAUSED_STOPPING) {
493 mState = STATE_STOPPING;
494 } else {
495 mState = STATE_ACTIVE;
496 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700497 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800498 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
499 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700500 mPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -0700501 mPreviousTimestampValid = false;
502
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700503 // For offloaded tracks, we don't know if the hardware counters are really zero here,
504 // since the flush is asynchronous and stop may not fully drain.
505 // We save the time when the track is started to later verify whether
506 // the counters are realistic (i.e. start from zero after this time).
507 mStartUs = getNowUs();
508
Eric Laurentec9a0322013-08-28 10:23:01 -0700509 // force refresh of remaining frames by processAudioBuffer() as last
510 // write before stop could be partial.
511 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800512 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700513 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700514 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800515
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800516 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800517 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100518 if (previousState == STATE_STOPPING) {
519 mProxy->interrupt();
520 } else {
521 t->resume();
522 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800523 } else {
524 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
525 get_sched_policy(0, &mPreviousSchedulingGroup);
526 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
527 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800528
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800529 status_t status = NO_ERROR;
530 if (!(flags & CBLK_INVALID)) {
531 status = mAudioTrack->start();
532 if (status == DEAD_OBJECT) {
533 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800534 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800535 }
536 if (flags & CBLK_INVALID) {
537 status = restoreTrack_l("start");
538 }
539
540 if (status != NO_ERROR) {
541 ALOGE("start() status %d", status);
542 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800543 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100544 if (previousState != STATE_STOPPING) {
545 t->pause();
546 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800547 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700548 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700549 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800550 }
551 }
552
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100553 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800554}
555
556void AudioTrack::stop()
557{
558 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700559 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800560 return;
561 }
562
Glenn Kasten23a75452014-01-13 10:37:17 -0800563 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100564 mState = STATE_STOPPING;
565 } else {
566 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -0700567 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100568 }
569
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800570 mProxy->interrupt();
571 mAudioTrack->stop();
572 // the playback head position will reset to 0, so if a marker is set, we need
573 // to activate it again
574 mMarkerReached = false;
Andy Hung9b461582014-12-01 17:56:29 -0800575
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800576 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800577 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800578 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
579 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800580 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100581
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800582 sp<AudioTrackThread> t = mAudioTrackThread;
583 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800584 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100585 t->pause();
586 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800587 } else {
588 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
589 set_sched_policy(0, mPreviousSchedulingGroup);
590 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800591}
592
593bool AudioTrack::stopped() const
594{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800595 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800596 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800597}
598
599void AudioTrack::flush()
600{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800601 if (mSharedBuffer != 0) {
602 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800603 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800604 AutoMutex lock(mLock);
605 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
606 return;
607 }
608 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800609}
610
Eric Laurent1703cdf2011-03-07 14:52:59 -0800611void AudioTrack::flush_l()
612{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800613 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700614
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700615 // clear playback marker and periodic update counter
616 mMarkerPosition = 0;
617 mMarkerReached = false;
618 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100619 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700620
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800621 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700622 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800623 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100624 mProxy->interrupt();
625 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800626 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800627 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800628}
629
630void AudioTrack::pause()
631{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800632 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100633 if (mState == STATE_ACTIVE) {
634 mState = STATE_PAUSED;
635 } else if (mState == STATE_STOPPING) {
636 mState = STATE_PAUSED_STOPPING;
637 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800638 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800639 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800640 mProxy->interrupt();
641 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800642
Marco Nelissen3a90f282014-03-10 11:21:43 -0700643 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700644 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700645 // An offload output can be re-used between two audio tracks having
646 // the same configuration. A timestamp query for a paused track
647 // while the other is running would return an incorrect time.
648 // To fix this, cache the playback position on a pause() and return
649 // this time when requested until the track is resumed.
650
651 // OffloadThread sends HAL pause in its threadLoop. Time saved
652 // here can be slightly off.
653
654 // TODO: check return code for getRenderPosition.
655
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800656 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800657 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
658 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
659 }
660 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800661}
662
Eric Laurentbe916aa2010-06-01 23:49:17 -0700663status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800664{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700665 // This duplicates a test by AudioTrack JNI, but that is not the only caller
666 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
667 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700668 return BAD_VALUE;
669 }
670
Eric Laurent1703cdf2011-03-07 14:52:59 -0800671 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800672 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
673 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800674
Glenn Kastenc56f3422014-03-21 17:53:17 -0700675 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700676
Glenn Kasten23a75452014-01-13 10:37:17 -0800677 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700678 mAudioTrack->signal();
679 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700680 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800681}
682
Glenn Kastenb1c09932012-02-27 16:21:04 -0800683status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800684{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800685 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700686}
687
Eric Laurent2beeb502010-07-16 07:43:46 -0700688status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700689{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700690 // This duplicates a test by AudioTrack JNI, but that is not the only caller
691 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700692 return BAD_VALUE;
693 }
694
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800695 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700696 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800697 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700698
699 return NO_ERROR;
700}
701
Glenn Kastena5224f32012-01-04 12:41:44 -0800702void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700703{
704 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800705 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700706 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800707}
708
Glenn Kasten3b16c762012-11-14 08:44:39 -0800709status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800710{
Andy Hung5cbb5782015-03-27 18:39:59 -0700711 AutoMutex lock(mLock);
712 if (rate == mSampleRate) {
713 return NO_ERROR;
714 }
715 if (mIsTimed || isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800716 return INVALID_OPERATION;
717 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800718 if (mOutput == AUDIO_IO_HANDLE_NONE) {
719 return NO_INIT;
720 }
Andy Hung5cbb5782015-03-27 18:39:59 -0700721 // NOTE: it is theoretically possible, but highly unlikely, that a device change
722 // could mean a previously allowed sampling rate is no longer allowed.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800723 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800724 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700725 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800726 }
Andy Hung26145642015-04-15 21:56:53 -0700727 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700728 const uint32_t effectiveSampleRate = adjustSampleRate(rate, mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -0700729 if (rate == 0 || effectiveSampleRate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700730 return BAD_VALUE;
731 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700732 // TODO: Should we also check if the buffer size is compatible?
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800733
Glenn Kastene3aa6592012-12-04 12:22:46 -0800734 mSampleRate = rate;
Andy Hung26145642015-04-15 21:56:53 -0700735 mProxy->setSampleRate(effectiveSampleRate);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800736
Eric Laurent57326622009-07-07 07:10:45 -0700737 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800738}
739
Glenn Kastena5224f32012-01-04 12:41:44 -0800740uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800741{
John Grossman4ff14ba2012-02-08 16:37:41 -0800742 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800743 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800744 }
745
Eric Laurent1703cdf2011-03-07 14:52:59 -0800746 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700747
748 // sample rate can be updated during playback by the offloaded decoder so we need to
749 // query the HAL and update if needed.
750// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700751 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700752 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700753 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700754 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700755 if (status == NO_ERROR) {
756 mSampleRate = sampleRate;
757 }
758 }
759 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800760 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800761}
762
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700763uint32_t AudioTrack::getOriginalSampleRate() const
764{
765 if (mIsTimed) {
766 return 0;
767 }
768
769 return mOriginalSampleRate;
770}
771
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700772status_t AudioTrack::setPlaybackRate(const AudioPlaybackRate &playbackRate)
Andy Hung8edb8dc2015-03-26 19:13:55 -0700773{
Andy Hung8edb8dc2015-03-26 19:13:55 -0700774 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700775 if (isAudioPlaybackRateEqual(playbackRate, mPlaybackRate)) {
Andy Hung8edb8dc2015-03-26 19:13:55 -0700776 return NO_ERROR;
777 }
778 if (mIsTimed || isOffloadedOrDirect_l()) {
779 return INVALID_OPERATION;
780 }
781 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
782 return INVALID_OPERATION;
783 }
Andy Hung26145642015-04-15 21:56:53 -0700784 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700785 const uint32_t effectiveRate = adjustSampleRate(mSampleRate, playbackRate.mPitch);
786 const float effectiveSpeed = adjustSpeed(playbackRate.mSpeed, playbackRate.mPitch);
787 const float effectivePitch = adjustPitch(playbackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -0700788 if (effectiveSpeed < AUDIO_TIMESTRETCH_SPEED_MIN
789 || effectiveSpeed > AUDIO_TIMESTRETCH_SPEED_MAX
790 || effectivePitch < AUDIO_TIMESTRETCH_PITCH_MIN
791 || effectivePitch > AUDIO_TIMESTRETCH_PITCH_MAX) {
792 return BAD_VALUE;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700793 //TODO: add function in AudioResamplerPublic.h to check for validity.
Andy Hung26145642015-04-15 21:56:53 -0700794 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700795 // Check if the buffer size is compatible.
Andy Hung26145642015-04-15 21:56:53 -0700796 if (!isSampleRateSpeedAllowed_l(effectiveRate, effectiveSpeed)) {
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700797 ALOGV("setPlaybackRate(%f, %f) failed", playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung8edb8dc2015-03-26 19:13:55 -0700798 return BAD_VALUE;
799 }
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700800 mPlaybackRate = playbackRate;
801 mProxy->setPlaybackRate(playbackRate);
802
803 //modify this
804 AudioPlaybackRate playbackRateTemp = playbackRate;
805 playbackRateTemp.mSpeed = effectiveSpeed;
806 playbackRateTemp.mPitch = effectivePitch;
807 mProxy->setPlaybackRate(playbackRateTemp);
Andy Hung26145642015-04-15 21:56:53 -0700808 mProxy->setSampleRate(effectiveRate); // FIXME: not quite "atomic" with setPlaybackRate
Andy Hung8edb8dc2015-03-26 19:13:55 -0700809 return NO_ERROR;
810}
811
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700812const AudioPlaybackRate& AudioTrack::getPlaybackRate() const
Andy Hung8edb8dc2015-03-26 19:13:55 -0700813{
814 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700815 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700816}
817
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800818status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
819{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700820 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800821 return INVALID_OPERATION;
822 }
823
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800824 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800825 ;
826 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
827 loopEnd - loopStart >= MIN_LOOP) {
828 ;
829 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800830 return BAD_VALUE;
831 }
832
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800833 AutoMutex lock(mLock);
834 // See setPosition() regarding setting parameters such as loop points or position while active
835 if (mState == STATE_ACTIVE) {
836 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700837 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800838 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800839 return NO_ERROR;
840}
841
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800842void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
843{
Andy Hung4ede21d2014-12-12 15:37:34 -0800844 // We do not update the periodic notification point.
845 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
846 mLoopCount = loopCount;
847 mLoopEnd = loopEnd;
848 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800849 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800850 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -0800851
852 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800853}
854
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800855status_t AudioTrack::setMarkerPosition(uint32_t marker)
856{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700857 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700858 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700859 return INVALID_OPERATION;
860 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800861
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800862 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800863 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700864 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800865
Andy Hung3c09c782014-12-29 18:39:32 -0800866 sp<AudioTrackThread> t = mAudioTrackThread;
867 if (t != 0) {
868 t->wake();
869 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800870 return NO_ERROR;
871}
872
Glenn Kastena5224f32012-01-04 12:41:44 -0800873status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800874{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700875 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100876 return INVALID_OPERATION;
877 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700878 if (marker == NULL) {
879 return BAD_VALUE;
880 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800881
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800882 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800883 *marker = mMarkerPosition;
884
885 return NO_ERROR;
886}
887
888status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
889{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700890 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700891 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700892 return INVALID_OPERATION;
893 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800894
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800895 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700896 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800897 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800898
Andy Hung3c09c782014-12-29 18:39:32 -0800899 sp<AudioTrackThread> t = mAudioTrackThread;
900 if (t != 0) {
901 t->wake();
902 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800903 return NO_ERROR;
904}
905
Glenn Kastena5224f32012-01-04 12:41:44 -0800906status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800907{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700908 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100909 return INVALID_OPERATION;
910 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700911 if (updatePeriod == NULL) {
912 return BAD_VALUE;
913 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800914
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800915 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800916 *updatePeriod = mUpdatePeriod;
917
918 return NO_ERROR;
919}
920
921status_t AudioTrack::setPosition(uint32_t position)
922{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700923 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700924 return INVALID_OPERATION;
925 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800926 if (position > mFrameCount) {
927 return BAD_VALUE;
928 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800929
Eric Laurent1703cdf2011-03-07 14:52:59 -0800930 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800931 // Currently we require that the player is inactive before setting parameters such as position
932 // or loop points. Otherwise, there could be a race condition: the application could read the
933 // current position, compute a new position or loop parameters, and then set that position or
934 // loop parameters but it would do the "wrong" thing since the position has continued to advance
935 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
936 // to specify how it wants to handle such scenarios.
937 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700938 return INVALID_OPERATION;
939 }
Andy Hung9b461582014-12-01 17:56:29 -0800940 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -0700941 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800942 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -0800943
944 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800945 return NO_ERROR;
946}
947
Glenn Kasten200092b2014-08-15 15:13:30 -0700948status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800949{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700950 if (position == NULL) {
951 return BAD_VALUE;
952 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800953
Eric Laurent1703cdf2011-03-07 14:52:59 -0800954 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700955 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100956 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800957
Eric Laurentab5cdba2014-06-09 17:22:27 -0700958 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800959 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
960 *position = mPausedPosition;
961 return NO_ERROR;
962 }
963
Glenn Kasten142f5192014-03-25 17:44:59 -0700964 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100965 uint32_t halFrames;
966 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
967 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700968 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
969 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100970 *position = dspFrames;
971 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -0800972 if (mCblk->mFlags & CBLK_INVALID) {
973 restoreTrack_l("getPosition");
974 }
975
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100976 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700977 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
978 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100979 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800980 return NO_ERROR;
981}
982
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000983status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800984{
985 if (mSharedBuffer == 0 || mIsTimed) {
986 return INVALID_OPERATION;
987 }
988 if (position == NULL) {
989 return BAD_VALUE;
990 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800991
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800992 AutoMutex lock(mLock);
993 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800994 return NO_ERROR;
995}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800996
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800997status_t AudioTrack::reload()
998{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700999 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -08001000 return INVALID_OPERATION;
1001 }
1002
Eric Laurent1703cdf2011-03-07 14:52:59 -08001003 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001004 // See setPosition() regarding setting parameters such as loop points or position while active
1005 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001006 return INVALID_OPERATION;
1007 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001008 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -08001009 (void) updateAndGetPosition_l();
1010 mPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -07001011 mPreviousTimestampValid = false;
Andy Hung53c3b5f2014-12-15 16:42:05 -08001012#if 0
Andy Hung9b461582014-12-01 17:56:29 -08001013 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -08001014 // of loop count. Historically we have not restored loop count, start, end,
1015 // but it makes sense if one desires to repeat playing a particular sound.
1016 if (mLoopCount != 0) {
1017 mLoopCountNotified = mLoopCount;
1018 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
1019 }
1020#endif
Andy Hung9b461582014-12-01 17:56:29 -08001021 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001022 return NO_ERROR;
1023}
1024
Glenn Kasten38e905b2014-01-13 10:21:48 -08001025audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -07001026{
Eric Laurent1703cdf2011-03-07 14:52:59 -08001027 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001028 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001029}
1030
Paul McLeanaa981192015-03-21 09:55:15 -07001031status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
1032 AutoMutex lock(mLock);
1033 if (mSelectedDeviceId != deviceId) {
1034 mSelectedDeviceId = deviceId;
Eric Laurent493404d2015-04-21 15:07:36 -07001035 android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
Paul McLeanaa981192015-03-21 09:55:15 -07001036 }
Eric Laurent493404d2015-04-21 15:07:36 -07001037 return NO_ERROR;
Paul McLeanaa981192015-03-21 09:55:15 -07001038}
1039
1040audio_port_handle_t AudioTrack::getOutputDevice() {
1041 AutoMutex lock(mLock);
1042 return mSelectedDeviceId;
1043}
1044
Eric Laurentbe916aa2010-06-01 23:49:17 -07001045status_t AudioTrack::attachAuxEffect(int effectId)
1046{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001047 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001048 status_t status = mAudioTrack->attachAuxEffect(effectId);
1049 if (status == NO_ERROR) {
1050 mAuxEffectId = effectId;
1051 }
1052 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -07001053}
1054
Eric Laurente83b55d2014-11-14 10:06:21 -08001055audio_stream_type_t AudioTrack::streamType() const
1056{
1057 if (mStreamType == AUDIO_STREAM_DEFAULT) {
1058 return audio_attributes_to_stream_type(&mAttributes);
1059 }
1060 return mStreamType;
1061}
1062
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001063// -------------------------------------------------------------------------
1064
Eric Laurent1703cdf2011-03-07 14:52:59 -08001065// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -07001066status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001067{
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001068 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
1069 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001070 ALOGE("Could not get audioflinger");
1071 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001072 }
1073
Eric Laurente83b55d2014-11-14 10:06:21 -08001074 audio_io_handle_t output;
1075 audio_stream_type_t streamType = mStreamType;
1076 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
Eric Laurente83b55d2014-11-14 10:06:21 -08001077
Paul McLeanaa981192015-03-21 09:55:15 -07001078 status_t status;
1079 status = AudioSystem::getOutputForAttr(attr, &output,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001080 (audio_session_t)mSessionId, &streamType, mClientUid,
Paul McLeanaa981192015-03-21 09:55:15 -07001081 mSampleRate, mFormat, mChannelMask,
1082 mFlags, mSelectedDeviceId, mOffloadInfo);
Eric Laurente83b55d2014-11-14 10:06:21 -08001083
1084 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001085 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 -07001086 " channel mask %#x, flags %#x",
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001087 mSessionId, streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001088 return BAD_VALUE;
1089 }
1090 {
1091 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
1092 // we must release it ourselves if anything goes wrong.
1093
Glenn Kastence8828a2013-09-16 18:07:38 -07001094 // Not all of these values are needed under all conditions, but it is easier to get them all
1095
Eric Laurentd1b449a2010-05-14 03:26:45 -07001096 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -07001097 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001098 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001099 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001100 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001101 }
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001102 ALOGV("createTrack_l() output %d afLatency %u", output, afLatency);
Eric Laurentd1b449a2010-05-14 03:26:45 -07001103
Glenn Kastence8828a2013-09-16 18:07:38 -07001104 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001105 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -07001106 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001107 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001108 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001109 }
1110
1111 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001112 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -07001113 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001114 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001115 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001116 }
Eric Laurent0d6db582014-11-12 18:39:44 -08001117 if (mSampleRate == 0) {
1118 mSampleRate = afSampleRate;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001119 mOriginalSampleRate = afSampleRate;
Eric Laurent0d6db582014-11-12 18:39:44 -08001120 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001121 // Client decides whether the track is TIMED (see below), but can only express a preference
1122 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001123 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001124 // either of these use cases:
1125 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -08001126 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001127 // use case 2: callback transfer mode
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001128 (mTransfer == TRANSFER_CALLBACK) ||
1129 // use case 3: obtain/release mode
1130 (mTransfer == TRANSFER_OBTAIN)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001131 // matching sample rate
1132 (mSampleRate == afSampleRate))) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001133 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client; transfer %d, track %u Hz, output %u Hz",
1134 mTransfer, mSampleRate, afSampleRate);
Glenn Kasten093000f2012-05-03 09:35:36 -07001135 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001136 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001137 }
1138
Glenn Kastence8828a2013-09-16 18:07:38 -07001139 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -08001140 // n = 1 fast track with single buffering; nBuffering is ignored
1141 // n = 2 fast track with double buffering
Andy Hung0e48d252015-01-26 11:43:15 -08001142 // n = 2 normal track, (including those with sample rate conversion)
1143 // n >= 3 very high latency or very small notification interval (unused).
1144 const uint32_t nBuffering = 2;
Glenn Kastence8828a2013-09-16 18:07:38 -07001145
Eric Laurentd1b449a2010-05-14 03:26:45 -07001146 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001147
Glenn Kasten363fb752014-01-15 12:27:31 -08001148 size_t frameCount = mReqFrameCount;
1149 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001150
Glenn Kasten363fb752014-01-15 12:27:31 -08001151 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001152 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001153 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001154 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001155 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001156 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001157 if (mNotificationFramesAct != frameCount) {
1158 mNotificationFramesAct = frameCount;
1159 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001160 } else if (mSharedBuffer != 0) {
Andy Hungabdb9902015-01-12 15:08:22 -08001161 // FIXME: Ensure client side memory buffers need
1162 // not have additional alignment beyond sample
1163 // (e.g. 16 bit stereo accessed as 32 bit frame).
1164 size_t alignment = audio_bytes_per_sample(mFormat);
Glenn Kastenb7730382014-04-30 15:50:31 -07001165 if (alignment & 1) {
Andy Hungabdb9902015-01-12 15:08:22 -08001166 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
Glenn Kastenb7730382014-04-30 15:50:31 -07001167 alignment = 1;
1168 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001169 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001170 // More than 2 channels does not require stronger alignment than stereo
1171 alignment <<= 1;
1172 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001173 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001174 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001175 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001176 status = BAD_VALUE;
1177 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001178 }
1179
1180 // When initializing a shared buffer AudioTrack via constructors,
1181 // there's no frameCount parameter.
1182 // But when initializing a shared buffer AudioTrack via set(),
1183 // there _is_ a frameCount parameter. We silently ignore it.
Andy Hungabdb9902015-01-12 15:08:22 -08001184 frameCount = mSharedBuffer->size() / mFrameSize;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001185 } else {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001186 // For fast tracks the frame count calculations and checks are done by server
1187
1188 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1189 // for normal tracks precompute the frame count based on speed.
1190 const size_t minFrameCount = calculateMinFrameCount(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001191 afLatency, afFrameCount, afSampleRate, mSampleRate,
1192 mPlaybackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07001193 if (frameCount < minFrameCount) {
1194 frameCount = minFrameCount;
1195 }
1196 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001197 }
1198
Glenn Kastena075db42012-03-06 11:22:44 -08001199 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1200 if (mIsTimed) {
1201 trackFlags |= IAudioFlinger::TRACK_TIMED;
1202 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001203
1204 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001205 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001206 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001207 if (mAudioTrackThread != 0) {
1208 tid = mAudioTrackThread->getTid();
1209 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001210 }
1211
Glenn Kasten363fb752014-01-15 12:27:31 -08001212 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001213 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1214 }
1215
Eric Laurentab5cdba2014-06-09 17:22:27 -07001216 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1217 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1218 }
1219
Glenn Kasten74935e42013-12-19 08:56:45 -08001220 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1221 // but we will still need the original value also
Glenn Kasten138d6f92015-03-20 10:54:51 -07001222 int originalSessionId = mSessionId;
Eric Laurente83b55d2014-11-14 10:06:21 -08001223 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001224 mSampleRate,
Andy Hungabdb9902015-01-12 15:08:22 -08001225 mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001226 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001227 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001228 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001229 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001230 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001231 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001232 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001233 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001234 &status);
Glenn Kasten138d6f92015-03-20 10:54:51 -07001235 ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
1236 "session ID changed from %d to %d", originalSessionId, mSessionId);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001237
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001238 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001239 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001240 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001241 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001242 ALOG_ASSERT(track != 0);
1243
Glenn Kasten38e905b2014-01-13 10:21:48 -08001244 // AudioFlinger now owns the reference to the I/O handle,
1245 // so we are no longer responsible for releasing it.
1246
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001247 sp<IMemory> iMem = track->getCblk();
1248 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001249 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001250 return NO_INIT;
1251 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001252 void *iMemPointer = iMem->pointer();
1253 if (iMemPointer == NULL) {
1254 ALOGE("Could not get control block pointer");
1255 return NO_INIT;
1256 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001257 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001258 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001259 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001260 mDeathNotifier.clear();
1261 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001262 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001263 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001264 IPCThreadState::self()->flushCommands();
1265
Glenn Kasten0cde0762014-01-16 15:06:36 -08001266 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001267 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001268 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001269 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1270 // In current design, AudioTrack client checks and ensures frame count validity before
1271 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1272 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001273 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001274 }
1275 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001276
Glenn Kastena07f17c2013-04-23 12:39:37 -07001277 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001278 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001279 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001280 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001281 mAwaitBoost = true;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001282 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001283 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001284 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001285 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001286 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001287 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001288 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001289 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1290 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1291 } else {
1292 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001293 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001294 // FIXME This is a warning, not an error, so don't return error status
1295 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001296 }
1297 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001298 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1299 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1300 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1301 } else {
1302 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1303 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1304 // FIXME This is a warning, not an error, so don't return error status
1305 //return NO_INIT;
1306 }
1307 }
Andy Hung0e48d252015-01-26 11:43:15 -08001308 // Make sure that application is notified with sufficient margin before underrun
1309 if (mSharedBuffer == 0 && audio_is_linear_pcm(mFormat)) {
1310 // Theoretically double-buffering is not required for fast tracks,
1311 // due to tighter scheduling. But in practice, to accommodate kernels with
1312 // scheduling jitter, and apps with computation jitter, we use double-buffering
1313 // for fast tracks just like normal streaming tracks.
1314 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount / nBuffering) {
1315 mNotificationFramesAct = frameCount / nBuffering;
1316 }
1317 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001318
Glenn Kasten38e905b2014-01-13 10:21:48 -08001319 // We retain a copy of the I/O handle, but don't own the reference
1320 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001321 mRefreshRemaining = true;
1322
1323 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1324 // is the value of pointer() for the shared buffer, otherwise buffers points
1325 // immediately after the control block. This address is for the mapping within client
1326 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1327 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001328 if (mSharedBuffer == 0) {
Glenn Kasten138d6f92015-03-20 10:54:51 -07001329 buffers = cblk + 1;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001330 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001331 buffers = mSharedBuffer->pointer();
Glenn Kasten138d6f92015-03-20 10:54:51 -07001332 if (buffers == NULL) {
1333 ALOGE("Could not get buffer pointer");
1334 return NO_INIT;
1335 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001336 }
1337
Eric Laurent2beeb502010-07-16 07:43:46 -07001338 mAudioTrack->attachAuxEffect(mAuxEffectId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07001339 // FIXME doesn't take into account speed or future sample rate changes (until restoreTrack)
Glenn Kastene0fa4672012-04-24 14:35:14 -07001340 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001341 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001342
Glenn Kastenb6037442012-11-14 13:42:25 -08001343 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001344 // If IAudioTrack is re-created, don't let the requested frameCount
1345 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001346 if (frameCount > mReqFrameCount) {
1347 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001348 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001349
1350 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001351 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001352 mStaticProxy.clear();
Andy Hungabdb9902015-01-12 15:08:22 -08001353 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001354 } else {
Andy Hungabdb9902015-01-12 15:08:22 -08001355 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001356 mProxy = mStaticProxy;
1357 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001358
1359 mProxy->setVolumeLR(gain_minifloat_pack(
1360 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1361 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1362
Glenn Kastene3aa6592012-12-04 12:22:46 -08001363 mProxy->setSendLevel(mSendLevel);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001364 const uint32_t effectiveSampleRate = adjustSampleRate(mSampleRate, mPlaybackRate.mPitch);
1365 const float effectiveSpeed = adjustSpeed(mPlaybackRate.mSpeed, mPlaybackRate.mPitch);
1366 const float effectivePitch = adjustPitch(mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001367 mProxy->setSampleRate(effectiveSampleRate);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001368
1369 AudioPlaybackRate playbackRateTemp = mPlaybackRate;
1370 playbackRateTemp.mSpeed = effectiveSpeed;
1371 playbackRateTemp.mPitch = effectivePitch;
1372 mProxy->setPlaybackRate(playbackRateTemp);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001373 mProxy->setMinimum(mNotificationFramesAct);
1374
1375 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001376 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001377
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001378 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001379 }
1380
1381release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001382 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001383 if (status == NO_ERROR) {
1384 status = NO_INIT;
1385 }
1386 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001387}
1388
Glenn Kastenb46f3942015-03-09 12:00:30 -07001389status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001390{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001391 if (audioBuffer == NULL) {
Glenn Kasten551b5352015-03-20 11:30:28 -07001392 if (nonContig != NULL) {
1393 *nonContig = 0;
1394 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001395 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001396 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001397 if (mTransfer != TRANSFER_OBTAIN) {
1398 audioBuffer->frameCount = 0;
1399 audioBuffer->size = 0;
1400 audioBuffer->raw = NULL;
Glenn Kasten551b5352015-03-20 11:30:28 -07001401 if (nonContig != NULL) {
1402 *nonContig = 0;
1403 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001404 return INVALID_OPERATION;
1405 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001406
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001407 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001408 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001409 if (waitCount == -1) {
1410 requested = &ClientProxy::kForever;
1411 } else if (waitCount == 0) {
1412 requested = &ClientProxy::kNonBlocking;
1413 } else if (waitCount > 0) {
1414 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001415 timeout.tv_sec = ms / 1000;
1416 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1417 requested = &timeout;
1418 } else {
1419 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1420 requested = NULL;
1421 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001422 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001423}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001424
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001425status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1426 struct timespec *elapsed, size_t *nonContig)
1427{
1428 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1429 uint32_t oldSequence = 0;
1430 uint32_t newSequence;
1431
1432 Proxy::Buffer buffer;
1433 status_t status = NO_ERROR;
1434
1435 static const int32_t kMaxTries = 5;
1436 int32_t tryCounter = kMaxTries;
1437
1438 do {
1439 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1440 // keep them from going away if another thread re-creates the track during obtainBuffer()
1441 sp<AudioTrackClientProxy> proxy;
1442 sp<IMemory> iMem;
1443
1444 { // start of lock scope
1445 AutoMutex lock(mLock);
1446
1447 newSequence = mSequence;
1448 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1449 if (status == DEAD_OBJECT) {
1450 // re-create track, unless someone else has already done so
1451 if (newSequence == oldSequence) {
1452 status = restoreTrack_l("obtainBuffer");
1453 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001454 buffer.mFrameCount = 0;
1455 buffer.mRaw = NULL;
1456 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001457 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001458 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001459 }
1460 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001461 oldSequence = newSequence;
1462
1463 // Keep the extra references
1464 proxy = mProxy;
1465 iMem = mCblkMemory;
1466
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001467 if (mState == STATE_STOPPING) {
1468 status = -EINTR;
1469 buffer.mFrameCount = 0;
1470 buffer.mRaw = NULL;
1471 buffer.mNonContig = 0;
1472 break;
1473 }
1474
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001475 // Non-blocking if track is stopped or paused
1476 if (mState != STATE_ACTIVE) {
1477 requested = &ClientProxy::kNonBlocking;
1478 }
1479
1480 } // end of lock scope
1481
1482 buffer.mFrameCount = audioBuffer->frameCount;
1483 // FIXME starts the requested timeout and elapsed over from scratch
1484 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1485
1486 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1487
1488 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001489 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001490 audioBuffer->raw = buffer.mRaw;
1491 if (nonContig != NULL) {
1492 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001493 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001494 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001495}
1496
Glenn Kasten54a8a452015-03-09 12:03:00 -07001497void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001498{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001499 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001500 if (mTransfer == TRANSFER_SHARED) {
1501 return;
1502 }
1503
Andy Hungabdb9902015-01-12 15:08:22 -08001504 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001505 if (stepCount == 0) {
1506 return;
1507 }
1508
1509 Proxy::Buffer buffer;
1510 buffer.mFrameCount = stepCount;
1511 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001512
Eric Laurent1703cdf2011-03-07 14:52:59 -08001513 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001514 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001515 mInUnderrun = false;
1516 mProxy->releaseBuffer(&buffer);
1517
1518 // restart track if it was disabled by audioflinger due to previous underrun
1519 if (mState == STATE_ACTIVE) {
1520 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001521 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001522 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001523 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001524 mAudioTrack->start();
1525 }
1526 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001527}
1528
1529// -------------------------------------------------------------------------
1530
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001531ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001532{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001533 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001534 return INVALID_OPERATION;
1535 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001536
Eric Laurentab5cdba2014-06-09 17:22:27 -07001537 if (isDirect()) {
1538 AutoMutex lock(mLock);
1539 int32_t flags = android_atomic_and(
1540 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1541 &mCblk->mFlags);
1542 if (flags & CBLK_INVALID) {
1543 return DEAD_OBJECT;
1544 }
1545 }
1546
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001547 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001548 // Sanity-check: user is most-likely passing an error code, and it would
1549 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001550 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001551 return BAD_VALUE;
1552 }
1553
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001554 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001555 Buffer audioBuffer;
1556
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001557 while (userSize >= mFrameSize) {
1558 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001559
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001560 status_t err = obtainBuffer(&audioBuffer,
1561 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001562 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001563 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001564 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001565 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001566 return ssize_t(err);
1567 }
1568
Glenn Kastenae4b8792015-03-20 09:04:21 -07001569 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08001570 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001571 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001572 userSize -= toWrite;
1573 written += toWrite;
1574
1575 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001576 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001577
1578 return written;
1579}
1580
1581// -------------------------------------------------------------------------
1582
John Grossman4ff14ba2012-02-08 16:37:41 -08001583TimedAudioTrack::TimedAudioTrack() {
1584 mIsTimed = true;
1585}
1586
1587status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1588{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001589 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001590 status_t result = UNKNOWN_ERROR;
1591
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001592#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001593 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1594 // while we are accessing the cblk
1595 sp<IAudioTrack> audioTrack = mAudioTrack;
1596 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001597#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001598
John Grossman4ff14ba2012-02-08 16:37:41 -08001599 // If the track is not invalid already, try to allocate a buffer. alloc
1600 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001601 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001602 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001603 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001604 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1605 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001606 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001607 }
1608 }
1609
1610 // If the track is invalid at this point, attempt to restore it. and try the
1611 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001612 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001613 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001614
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001615 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001616 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001617 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001618 }
1619
1620 return result;
1621}
1622
1623status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1624 int64_t pts)
1625{
Eric Laurentdf839842012-05-31 14:27:14 -07001626 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1627 {
1628 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001629 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001630 // restart track if it was disabled by audioflinger due to previous underrun
1631 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001632 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1633 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001634 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001635 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001636 mAudioTrack->start();
1637 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001638 }
Eric Laurentdf839842012-05-31 14:27:14 -07001639 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001640}
1641
1642status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1643 TargetTimeline target)
1644{
1645 return mAudioTrack->setMediaTimeTransform(xform, target);
1646}
1647
1648// -------------------------------------------------------------------------
1649
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001650nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001651{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001652 // Currently the AudioTrack thread is not created if there are no callbacks.
1653 // Would it ever make sense to run the thread, even without callbacks?
1654 // If so, then replace this by checks at each use for mCbf != NULL.
1655 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1656
Eric Laurent1703cdf2011-03-07 14:52:59 -08001657 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001658 if (mAwaitBoost) {
1659 mAwaitBoost = false;
1660 mLock.unlock();
1661 static const int32_t kMaxTries = 5;
1662 int32_t tryCounter = kMaxTries;
1663 uint32_t pollUs = 10000;
1664 do {
1665 int policy = sched_getscheduler(0);
1666 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1667 break;
1668 }
1669 usleep(pollUs);
1670 pollUs <<= 1;
1671 } while (tryCounter-- > 0);
1672 if (tryCounter < 0) {
1673 ALOGE("did not receive expected priority boost on time");
1674 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001675 // Run again immediately
1676 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001677 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001678
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001679 // Can only reference mCblk while locked
1680 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001681 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001682
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001683 // Check for track invalidation
1684 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001685 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1686 // AudioSystem cache. We should not exit here but after calling the callback so
1687 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001688 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Lajos Molnarf1063e22015-04-17 15:19:42 -07001689 status_t status __unused = restoreTrack_l("processAudioBuffer");
1690 // FIXME unused status
Andy Hung53c3b5f2014-12-15 16:42:05 -08001691 // after restoration, continue below to make sure that the loop and buffer events
1692 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001693 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001694 }
1695
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001696 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001697 bool active = mState == STATE_ACTIVE;
1698
1699 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1700 bool newUnderrun = false;
1701 if (flags & CBLK_UNDERRUN) {
1702#if 0
1703 // Currently in shared buffer mode, when the server reaches the end of buffer,
1704 // the track stays active in continuous underrun state. It's up to the application
1705 // to pause or stop the track, or set the position to a new offset within buffer.
1706 // This was some experimental code to auto-pause on underrun. Keeping it here
1707 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1708 if (mTransfer == TRANSFER_SHARED) {
1709 mState = STATE_PAUSED;
1710 active = false;
1711 }
1712#endif
1713 if (!mInUnderrun) {
1714 mInUnderrun = true;
1715 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001716 }
1717 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001718
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001719 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001720 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001721
1722 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001723 bool markerReached = false;
1724 size_t markerPosition = mMarkerPosition;
1725 // FIXME fails for wraparound, need 64 bits
1726 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1727 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001728 }
1729
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001730 // Determine number of new position callback(s) that will be needed, while locked
1731 size_t newPosCount = 0;
1732 size_t newPosition = mNewPosition;
1733 size_t updatePeriod = mUpdatePeriod;
1734 // FIXME fails for wraparound, need 64 bits
1735 if (updatePeriod > 0 && position >= newPosition) {
1736 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1737 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001738 }
1739
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001740 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001741 uint32_t sampleRate = mSampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001742 float speed = mPlaybackRate.mSpeed;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001743 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001744 if (mRefreshRemaining) {
1745 mRefreshRemaining = false;
1746 mRemainingFrames = notificationFrames;
1747 mRetryOnPartialBuffer = false;
1748 }
1749 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001750 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001751 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001752
Andy Hung53c3b5f2014-12-15 16:42:05 -08001753 // Determine the number of new loop callback(s) that will be needed, while locked.
1754 int loopCountNotifications = 0;
1755 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1756
1757 if (mLoopCount > 0) {
1758 int loopCount;
1759 size_t bufferPosition;
1760 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1761 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1762 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1763 mLoopCountNotified = loopCount; // discard any excess notifications
1764 } else if (mLoopCount < 0) {
1765 // FIXME: We're not accurate with notification count and position with infinite looping
1766 // since loopCount from server side will always return -1 (we could decrement it).
1767 size_t bufferPosition = mStaticProxy->getBufferPosition();
1768 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1769 loopPeriod = mLoopEnd - bufferPosition;
1770 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1771 size_t bufferPosition = mStaticProxy->getBufferPosition();
1772 loopPeriod = mFrameCount - bufferPosition;
1773 }
1774
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001775 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08001776 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001777 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1778
1779 mLock.unlock();
1780
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001781 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001782 struct timespec timeout;
1783 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1784 timeout.tv_nsec = 0;
1785
Glenn Kasten96f04882013-09-20 09:28:56 -07001786 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001787 switch (status) {
1788 case NO_ERROR:
1789 case DEAD_OBJECT:
1790 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001791 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001792 {
1793 AutoMutex lock(mLock);
1794 // The previously assigned value of waitStreamEnd is no longer valid,
1795 // since the mutex has been unlocked and either the callback handler
1796 // or another thread could have re-started the AudioTrack during that time.
1797 waitStreamEnd = mState == STATE_STOPPING;
1798 if (waitStreamEnd) {
1799 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001800 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001801 }
1802 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001803 if (waitStreamEnd && status != DEAD_OBJECT) {
1804 return NS_INACTIVE;
1805 }
1806 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001807 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001808 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001809 }
1810
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001811 // perform callbacks while unlocked
1812 if (newUnderrun) {
1813 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1814 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001815 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001816 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001817 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001818 }
1819 if (flags & CBLK_BUFFER_END) {
1820 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1821 }
1822 if (markerReached) {
1823 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1824 }
1825 while (newPosCount > 0) {
1826 size_t temp = newPosition;
1827 mCbf(EVENT_NEW_POS, mUserData, &temp);
1828 newPosition += updatePeriod;
1829 newPosCount--;
1830 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001831
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001832 if (mObservedSequence != sequence) {
1833 mObservedSequence = sequence;
1834 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001835 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001836 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001837 return NS_INACTIVE;
1838 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001839 }
1840
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001841 // if inactive, then don't run me again until re-started
1842 if (!active) {
1843 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001844 }
1845
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001846 // Compute the estimated time until the next timed event (position, markers, loops)
1847 // FIXME only for non-compressed audio
1848 uint32_t minFrames = ~0;
1849 if (!markerReached && position < markerPosition) {
1850 minFrames = markerPosition - position;
1851 }
1852 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08001853 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001854 minFrames = loopPeriod;
1855 }
Andy Hung2d85f092015-01-07 12:45:13 -08001856 if (updatePeriod > 0) {
1857 minFrames = min(minFrames, uint32_t(newPosition - position));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001858 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001859
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001860 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1861 static const uint32_t kPoll = 0;
1862 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1863 minFrames = kPoll * notificationFrames;
1864 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001865
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001866 // Convert frame units to time units
1867 nsecs_t ns = NS_WHENEVER;
1868 if (minFrames != (uint32_t) ~0) {
1869 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1870 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
Andy Hung8edb8dc2015-03-26 19:13:55 -07001871 ns = ((double)minFrames * 1000000000) / ((double)sampleRate * speed) + kFudgeNs;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001872 }
1873
1874 // If not supplying data by EVENT_MORE_DATA, then we're done
1875 if (mTransfer != TRANSFER_CALLBACK) {
1876 return ns;
1877 }
1878
1879 struct timespec timeout;
1880 const struct timespec *requested = &ClientProxy::kForever;
1881 if (ns != NS_WHENEVER) {
1882 timeout.tv_sec = ns / 1000000000LL;
1883 timeout.tv_nsec = ns % 1000000000LL;
1884 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1885 requested = &timeout;
1886 }
1887
1888 while (mRemainingFrames > 0) {
1889
1890 Buffer audioBuffer;
1891 audioBuffer.frameCount = mRemainingFrames;
1892 size_t nonContig;
1893 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1894 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001895 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001896 requested = &ClientProxy::kNonBlocking;
1897 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001898 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001899 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001900 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001901 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1902 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001903 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001904 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001905 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1906 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001907 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001908
Eric Laurent42a6f422013-08-29 14:35:05 -07001909 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001910 mRetryOnPartialBuffer = false;
1911 if (avail < mRemainingFrames) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001912 int64_t myns = ((double)(mRemainingFrames - avail) * 1100000000)
1913 / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001914 if (ns < 0 || myns < ns) {
1915 ns = myns;
1916 }
1917 return ns;
1918 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001919 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001920
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001921 size_t reqSize = audioBuffer.size;
1922 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001923 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001924
1925 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001926 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001927 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1928 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001929 return NS_NEVER;
1930 }
1931
1932 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001933 // The callback is done filling buffers
1934 // Keep this thread going to handle timed events and
1935 // still try to get more data in intervals of WAIT_PERIOD_MS
1936 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001937 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001938 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001939
Glenn Kasten138d6f92015-03-20 10:54:51 -07001940 size_t releasedFrames = writtenSize / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001941 audioBuffer.frameCount = releasedFrames;
1942 mRemainingFrames -= releasedFrames;
1943 if (misalignment >= releasedFrames) {
1944 misalignment -= releasedFrames;
1945 } else {
1946 misalignment = 0;
1947 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001948
1949 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001950
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001951 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1952 // if callback doesn't like to accept the full chunk
1953 if (writtenSize < reqSize) {
1954 continue;
1955 }
1956
1957 // There could be enough non-contiguous frames available to satisfy the remaining request
1958 if (mRemainingFrames <= nonContig) {
1959 continue;
1960 }
1961
1962#if 0
1963 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1964 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1965 // that total to a sum == notificationFrames.
1966 if (0 < misalignment && misalignment <= mRemainingFrames) {
1967 mRemainingFrames = misalignment;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001968 return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001969 }
1970#endif
1971
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001972 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001973 mRemainingFrames = notificationFrames;
1974 mRetryOnPartialBuffer = true;
1975
1976 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1977 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001978}
1979
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001980status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001981{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001982 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001983 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001984 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001985
Glenn Kastena47f3162012-11-07 10:13:08 -08001986 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08001987 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001988 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001989
Eric Laurentab5cdba2014-06-09 17:22:27 -07001990 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001991 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001992 return DEAD_OBJECT;
1993 }
1994
Glenn Kasten200092b2014-08-15 15:13:30 -07001995 // save the old static buffer position
Andy Hung4ede21d2014-12-12 15:37:34 -08001996 size_t bufferPosition = 0;
1997 int loopCount = 0;
1998 if (mStaticProxy != 0) {
1999 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
2000 }
Glenn Kasten200092b2014-08-15 15:13:30 -07002001
2002 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08002003 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07002004 // It will also delete the strong references on previous IAudioTrack and IMemory.
2005 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Glenn Kastenae4b8792015-03-20 09:04:21 -07002006 status_t result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07002007
2008 // take the frames that will be lost by track recreation into account in saved position
Andy Hung9b461582014-12-01 17:56:29 -08002009 // For streaming tracks, this is the amount we obtained from the user/client
2010 // (not the number actually consumed at the server - those are already lost).
Glenn Kasten200092b2014-08-15 15:13:30 -07002011 (void) updateAndGetPosition_l();
Andy Hung7ccdaad2015-03-20 00:38:32 -07002012 if (mStaticProxy == 0) {
Andy Hung9b461582014-12-01 17:56:29 -08002013 mPosition = mReleased;
2014 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002015
Glenn Kastena47f3162012-11-07 10:13:08 -08002016 if (result == NO_ERROR) {
Andy Hung4ede21d2014-12-12 15:37:34 -08002017 // Continue playback from last known position and restore loop.
2018 if (mStaticProxy != 0) {
2019 if (loopCount != 0) {
2020 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
2021 mLoopStart, mLoopEnd, loopCount);
2022 } else {
2023 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002024 if (bufferPosition == mFrameCount) {
2025 ALOGD("restoring track at end of static buffer");
2026 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002027 }
2028 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002029 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08002030 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08002031 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002032 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002033 if (result != NO_ERROR) {
2034 ALOGW("restoreTrack_l() failed status %d", result);
2035 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07002036 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002037 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002038
2039 return result;
2040}
2041
Glenn Kasten200092b2014-08-15 15:13:30 -07002042uint32_t AudioTrack::updateAndGetPosition_l()
2043{
2044 // This is the sole place to read server consumed frames
2045 uint32_t newServer = mProxy->getPosition();
2046 int32_t delta = newServer - mServer;
2047 mServer = newServer;
2048 // TODO There is controversy about whether there can be "negative jitter" in server position.
2049 // This should be investigated further, and if possible, it should be addressed.
2050 // A more definite failure mode is infrequent polling by client.
2051 // One could call (void)getPosition_l() in releaseBuffer(),
2052 // so mReleased and mPosition are always lock-step as best possible.
2053 // That should ensure delta never goes negative for infrequent polling
2054 // unless the server has more than 2^31 frames in its buffer,
2055 // in which case the use of uint32_t for these counters has bigger issues.
2056 if (delta < 0) {
2057 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
2058 delta = 0;
2059 }
2060 return mPosition += (uint32_t) delta;
2061}
2062
Andy Hung8edb8dc2015-03-26 19:13:55 -07002063bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed) const
2064{
2065 // applicable for mixing tracks only (not offloaded or direct)
2066 if (mStaticProxy != 0) {
2067 return true; // static tracks do not have issues with buffer sizing.
2068 }
2069 status_t status;
2070 uint32_t afLatency;
2071 status = AudioSystem::getLatency(mOutput, &afLatency);
2072 if (status != NO_ERROR) {
2073 ALOGE("getLatency(%d) failed status %d", mOutput, status);
2074 return false;
2075 }
2076
2077 size_t afFrameCount;
2078 status = AudioSystem::getFrameCount(mOutput, &afFrameCount);
2079 if (status != NO_ERROR) {
2080 ALOGE("getFrameCount(output=%d) status %d", mOutput, status);
2081 return false;
2082 }
2083
2084 uint32_t afSampleRate;
2085 status = AudioSystem::getSamplingRate(mOutput, &afSampleRate);
2086 if (status != NO_ERROR) {
2087 ALOGE("getSamplingRate(output=%d) status %d", mOutput, status);
2088 return false;
2089 }
2090
2091 const size_t minFrameCount =
2092 calculateMinFrameCount(afLatency, afFrameCount, afSampleRate, sampleRate, speed);
2093 ALOGV("isSampleRateSpeedAllowed_l mFrameCount %zu minFrameCount %zu",
2094 mFrameCount, minFrameCount);
2095 return mFrameCount >= minFrameCount;
2096}
2097
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002098status_t AudioTrack::setParameters(const String8& keyValuePairs)
2099{
2100 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07002101 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002102}
2103
Glenn Kastence703742013-07-19 16:33:58 -07002104status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
2105{
Glenn Kasten53cec222013-08-29 09:01:02 -07002106 AutoMutex lock(mLock);
Phil Burk1b420972015-04-22 10:52:21 -07002107
2108 bool previousTimestampValid = mPreviousTimestampValid;
2109 // Set false here to cover all the error return cases.
2110 mPreviousTimestampValid = false;
2111
Glenn Kastenfe346c72013-08-30 13:28:22 -07002112 // FIXME not implemented for fast tracks; should use proxy and SSQ
2113 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
2114 return INVALID_OPERATION;
2115 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002116
2117 switch (mState) {
2118 case STATE_ACTIVE:
2119 case STATE_PAUSED:
2120 break; // handle below
2121 case STATE_FLUSHED:
2122 case STATE_STOPPED:
2123 return WOULD_BLOCK;
2124 case STATE_STOPPING:
2125 case STATE_PAUSED_STOPPING:
2126 if (!isOffloaded_l()) {
2127 return INVALID_OPERATION;
2128 }
2129 break; // offloaded tracks handled below
2130 default:
2131 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
2132 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07002133 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002134
Eric Laurent275e8e92014-11-30 15:14:47 -08002135 if (mCblk->mFlags & CBLK_INVALID) {
2136 restoreTrack_l("getTimestamp");
2137 }
2138
Glenn Kasten200092b2014-08-15 15:13:30 -07002139 // The presented frame count must always lag behind the consumed frame count.
2140 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002141 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002142 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07002143 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002144 return status;
2145 }
2146 if (isOffloadedOrDirect_l()) {
2147 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
2148 // use cached paused position in case another offloaded track is running.
2149 timestamp.mPosition = mPausedPosition;
2150 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
2151 return NO_ERROR;
2152 }
2153
2154 // Check whether a pending flush or stop has completed, as those commands may
2155 // be asynchronous or return near finish.
2156 if (mStartUs != 0 && mSampleRate != 0) {
2157 static const int kTimeJitterUs = 100000; // 100 ms
2158 static const int k1SecUs = 1000000;
2159
2160 const int64_t timeNow = getNowUs();
2161
2162 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
2163 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
2164 if (timestampTimeUs < mStartUs) {
2165 return WOULD_BLOCK; // stale timestamp time, occurs before start.
2166 }
2167 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002168 const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002169 / ((double)mSampleRate * mPlaybackRate.mSpeed);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002170
2171 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2172 // Verify that the counter can't count faster than the sample rate
2173 // since the start time. If greater, then that means we have failed
2174 // to completely flush or stop the previous playing track.
2175 ALOGW("incomplete flush or stop:"
2176 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2177 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2178 timestamp.mPosition);
2179 return WOULD_BLOCK;
2180 }
2181 }
2182 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
2183 }
2184 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002185 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2186 (void) updateAndGetPosition_l();
2187 // Server consumed (mServer) and presented both use the same server time base,
2188 // and server consumed is always >= presented.
2189 // The delta between these represents the number of frames in the buffer pipeline.
2190 // If this delta between these is greater than the client position, it means that
2191 // actually presented is still stuck at the starting line (figuratively speaking),
2192 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
2193 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2194 return INVALID_OPERATION;
2195 }
2196 // Convert timestamp position from server time base to client time base.
2197 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2198 // But if we change it to 64-bit then this could fail.
2199 // If (mPosition - mServer) can be negative then should use:
2200 // (int32_t)(mPosition - mServer)
2201 timestamp.mPosition += mPosition - mServer;
2202 // Immediately after a call to getPosition_l(), mPosition and
2203 // mServer both represent the same frame position. mPosition is
2204 // in client's point of view, and mServer is in server's point of
2205 // view. So the difference between them is the "fudge factor"
2206 // between client and server views due to stop() and/or new
2207 // IAudioTrack. And timestamp.mPosition is initially in server's
2208 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002209 }
Phil Burk1b420972015-04-22 10:52:21 -07002210
2211 // Prevent retrograde motion in timestamp.
2212 // This is sometimes caused by erratic reports of the available space in the ALSA drivers.
2213 if (status == NO_ERROR) {
2214 if (previousTimestampValid) {
2215#define TIME_TO_NANOS(time) ((uint64_t)time.tv_sec * 1000000000 + time.tv_nsec)
2216 const uint64_t previousTimeNanos = TIME_TO_NANOS(mPreviousTimestamp.mTime);
2217 const uint64_t currentTimeNanos = TIME_TO_NANOS(timestamp.mTime);
2218#undef TIME_TO_NANOS
2219 if (currentTimeNanos < previousTimeNanos) {
2220 ALOGW("retrograde timestamp time");
2221 // FIXME Consider blocking this from propagating upwards.
2222 }
2223
2224 // Looking at signed delta will work even when the timestamps
2225 // are wrapping around.
2226 int32_t deltaPosition = static_cast<int32_t>(timestamp.mPosition
2227 - mPreviousTimestamp.mPosition);
2228 // position can bobble slightly as an artifact; this hides the bobble
2229 static const int32_t MINIMUM_POSITION_DELTA = 8;
2230 ALOGW_IF(deltaPosition < 0,
Phil Burk5aab9252015-04-30 14:55:19 -07002231 "retrograde timestamp position corrected, %d = %u - %u",
Phil Burk1b420972015-04-22 10:52:21 -07002232 deltaPosition,
2233 timestamp.mPosition,
Phil Burk5aab9252015-04-30 14:55:19 -07002234 mPreviousTimestamp.mPosition);
Phil Burk1b420972015-04-22 10:52:21 -07002235 if (deltaPosition < MINIMUM_POSITION_DELTA) {
2236 timestamp = mPreviousTimestamp; // Use last valid timestamp.
2237 }
2238 }
2239 mPreviousTimestamp = timestamp;
2240 mPreviousTimestampValid = true;
2241 }
2242
Glenn Kastenfe346c72013-08-30 13:28:22 -07002243 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002244}
2245
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002246String8 AudioTrack::getParameters(const String8& keys)
2247{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002248 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002249 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002250 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002251 } else {
2252 return String8::empty();
2253 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002254}
2255
Glenn Kasten23a75452014-01-13 10:37:17 -08002256bool AudioTrack::isOffloaded() const
2257{
2258 AutoMutex lock(mLock);
2259 return isOffloaded_l();
2260}
2261
Eric Laurentab5cdba2014-06-09 17:22:27 -07002262bool AudioTrack::isDirect() const
2263{
2264 AutoMutex lock(mLock);
2265 return isDirect_l();
2266}
2267
2268bool AudioTrack::isOffloadedOrDirect() const
2269{
2270 AutoMutex lock(mLock);
2271 return isOffloadedOrDirect_l();
2272}
2273
2274
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002275status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002276{
2277
2278 const size_t SIZE = 256;
2279 char buffer[SIZE];
2280 String8 result;
2281
2282 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002283 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002284 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002285 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002286 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002287 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002288 result.append(buffer);
Andy Hung8edb8dc2015-03-26 19:13:55 -07002289 snprintf(buffer, 255, " sample rate(%u), speed(%f), status(%d)\n",
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002290 mSampleRate, mPlaybackRate.mSpeed, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002291 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002292 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002293 result.append(buffer);
2294 ::write(fd, result.string(), result.size());
2295 return NO_ERROR;
2296}
2297
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002298uint32_t AudioTrack::getUnderrunFrames() const
2299{
2300 AutoMutex lock(mLock);
2301 return mProxy->getUnderrunFrames();
2302}
2303
2304// =========================================================================
2305
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002306void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002307{
2308 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2309 if (audioTrack != 0) {
2310 AutoMutex lock(audioTrack->mLock);
2311 audioTrack->mProxy->binderDied();
2312 }
2313}
2314
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002315// =========================================================================
2316
2317AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002318 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2319 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002320{
2321}
2322
2323AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002324{
2325}
2326
2327bool AudioTrack::AudioTrackThread::threadLoop()
2328{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002329 {
2330 AutoMutex _l(mMyLock);
2331 if (mPaused) {
2332 mMyCond.wait(mMyLock);
2333 // caller will check for exitPending()
2334 return true;
2335 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002336 if (mIgnoreNextPausedInt) {
2337 mIgnoreNextPausedInt = false;
2338 mPausedInt = false;
2339 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002340 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002341 if (mPausedNs > 0) {
2342 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2343 } else {
2344 mMyCond.wait(mMyLock);
2345 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002346 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002347 return true;
2348 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002349 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002350 if (exitPending()) {
2351 return false;
2352 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002353 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002354 switch (ns) {
2355 case 0:
2356 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002357 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002358 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002359 return true;
2360 case NS_NEVER:
2361 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002362 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08002363 // Event driven: call wake() when callback notifications conditions change.
2364 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002365 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002366 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002367 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002368 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002369 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002370 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002371}
2372
Glenn Kasten3acbd052012-02-28 10:39:56 -08002373void AudioTrack::AudioTrackThread::requestExit()
2374{
2375 // must be in this order to avoid a race condition
2376 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002377 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002378}
2379
2380void AudioTrack::AudioTrackThread::pause()
2381{
2382 AutoMutex _l(mMyLock);
2383 mPaused = true;
2384}
2385
2386void AudioTrack::AudioTrackThread::resume()
2387{
2388 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002389 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002390 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002391 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002392 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002393 mMyCond.signal();
2394 }
2395}
2396
Andy Hung3c09c782014-12-29 18:39:32 -08002397void AudioTrack::AudioTrackThread::wake()
2398{
2399 AutoMutex _l(mMyLock);
2400 if (!mPaused && mPausedInt && mPausedNs > 0) {
2401 // audio track is active and internally paused with timeout.
2402 mIgnoreNextPausedInt = true;
2403 mPausedInt = false;
2404 mMyCond.signal();
2405 }
2406}
2407
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002408void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2409{
2410 AutoMutex _l(mMyLock);
2411 mPausedInt = true;
2412 mPausedNs = ns;
2413}
2414
Glenn Kasten40bc9062015-03-20 09:09:33 -07002415} // namespace android