blob: 7869a84c51ca943370c9e01f5bf5bbc00b5982f3 [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;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700396 mSpeed = AUDIO_TIMESTRETCH_SPEED_NORMAL;
397 mPitch = AUDIO_TIMESTRETCH_PITCH_NORMAL;
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;
474
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800475 return NO_ERROR;
476}
477
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800478// -------------------------------------------------------------------------
479
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100480status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800481{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800482 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100483
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800484 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100485 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800486 }
487
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800488 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800489
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800490 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100491 if (previousState == STATE_PAUSED_STOPPING) {
492 mState = STATE_STOPPING;
493 } else {
494 mState = STATE_ACTIVE;
495 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700496 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800497 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
498 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700499 mPosition = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700500 // For offloaded tracks, we don't know if the hardware counters are really zero here,
501 // since the flush is asynchronous and stop may not fully drain.
502 // We save the time when the track is started to later verify whether
503 // the counters are realistic (i.e. start from zero after this time).
504 mStartUs = getNowUs();
505
Eric Laurentec9a0322013-08-28 10:23:01 -0700506 // force refresh of remaining frames by processAudioBuffer() as last
507 // write before stop could be partial.
508 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800509 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700510 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700511 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800512
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800513 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800514 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100515 if (previousState == STATE_STOPPING) {
516 mProxy->interrupt();
517 } else {
518 t->resume();
519 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800520 } else {
521 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
522 get_sched_policy(0, &mPreviousSchedulingGroup);
523 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
524 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800525
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800526 status_t status = NO_ERROR;
527 if (!(flags & CBLK_INVALID)) {
528 status = mAudioTrack->start();
529 if (status == DEAD_OBJECT) {
530 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800531 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800532 }
533 if (flags & CBLK_INVALID) {
534 status = restoreTrack_l("start");
535 }
536
537 if (status != NO_ERROR) {
538 ALOGE("start() status %d", status);
539 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800540 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100541 if (previousState != STATE_STOPPING) {
542 t->pause();
543 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800544 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700545 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700546 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800547 }
548 }
549
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100550 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800551}
552
553void AudioTrack::stop()
554{
555 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700556 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800557 return;
558 }
559
Glenn Kasten23a75452014-01-13 10:37:17 -0800560 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100561 mState = STATE_STOPPING;
562 } else {
563 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -0700564 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100565 }
566
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800567 mProxy->interrupt();
568 mAudioTrack->stop();
569 // the playback head position will reset to 0, so if a marker is set, we need
570 // to activate it again
571 mMarkerReached = false;
Andy Hung9b461582014-12-01 17:56:29 -0800572
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800573 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800574 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800575 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
576 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800577 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100578
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800579 sp<AudioTrackThread> t = mAudioTrackThread;
580 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800581 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100582 t->pause();
583 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800584 } else {
585 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
586 set_sched_policy(0, mPreviousSchedulingGroup);
587 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800588}
589
590bool AudioTrack::stopped() const
591{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800592 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800593 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800594}
595
596void AudioTrack::flush()
597{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800598 if (mSharedBuffer != 0) {
599 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800600 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800601 AutoMutex lock(mLock);
602 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
603 return;
604 }
605 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800606}
607
Eric Laurent1703cdf2011-03-07 14:52:59 -0800608void AudioTrack::flush_l()
609{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800610 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700611
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700612 // clear playback marker and periodic update counter
613 mMarkerPosition = 0;
614 mMarkerReached = false;
615 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100616 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700617
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800618 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700619 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800620 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100621 mProxy->interrupt();
622 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800623 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800624 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800625}
626
627void AudioTrack::pause()
628{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800629 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100630 if (mState == STATE_ACTIVE) {
631 mState = STATE_PAUSED;
632 } else if (mState == STATE_STOPPING) {
633 mState = STATE_PAUSED_STOPPING;
634 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800635 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800636 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800637 mProxy->interrupt();
638 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800639
Marco Nelissen3a90f282014-03-10 11:21:43 -0700640 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700641 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700642 // An offload output can be re-used between two audio tracks having
643 // the same configuration. A timestamp query for a paused track
644 // while the other is running would return an incorrect time.
645 // To fix this, cache the playback position on a pause() and return
646 // this time when requested until the track is resumed.
647
648 // OffloadThread sends HAL pause in its threadLoop. Time saved
649 // here can be slightly off.
650
651 // TODO: check return code for getRenderPosition.
652
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800653 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800654 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
655 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
656 }
657 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800658}
659
Eric Laurentbe916aa2010-06-01 23:49:17 -0700660status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800661{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700662 // This duplicates a test by AudioTrack JNI, but that is not the only caller
663 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
664 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700665 return BAD_VALUE;
666 }
667
Eric Laurent1703cdf2011-03-07 14:52:59 -0800668 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800669 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
670 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800671
Glenn Kastenc56f3422014-03-21 17:53:17 -0700672 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700673
Glenn Kasten23a75452014-01-13 10:37:17 -0800674 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700675 mAudioTrack->signal();
676 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700677 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800678}
679
Glenn Kastenb1c09932012-02-27 16:21:04 -0800680status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800681{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800682 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700683}
684
Eric Laurent2beeb502010-07-16 07:43:46 -0700685status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700686{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700687 // This duplicates a test by AudioTrack JNI, but that is not the only caller
688 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700689 return BAD_VALUE;
690 }
691
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800692 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700693 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800694 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700695
696 return NO_ERROR;
697}
698
Glenn Kastena5224f32012-01-04 12:41:44 -0800699void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700700{
701 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800702 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700703 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800704}
705
Glenn Kasten3b16c762012-11-14 08:44:39 -0800706status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800707{
Andy Hung5cbb5782015-03-27 18:39:59 -0700708 AutoMutex lock(mLock);
709 if (rate == mSampleRate) {
710 return NO_ERROR;
711 }
712 if (mIsTimed || isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800713 return INVALID_OPERATION;
714 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800715 if (mOutput == AUDIO_IO_HANDLE_NONE) {
716 return NO_INIT;
717 }
Andy Hung5cbb5782015-03-27 18:39:59 -0700718 // NOTE: it is theoretically possible, but highly unlikely, that a device change
719 // could mean a previously allowed sampling rate is no longer allowed.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800720 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800721 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700722 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800723 }
Andy Hung26145642015-04-15 21:56:53 -0700724 // pitch is emulated by adjusting speed and sampleRate
725 const uint32_t effectiveSampleRate = adjustSampleRate(rate, mPitch);
726 if (rate == 0 || effectiveSampleRate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700727 return BAD_VALUE;
728 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700729 // TODO: Should we also check if the buffer size is compatible?
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800730
Glenn Kastene3aa6592012-12-04 12:22:46 -0800731 mSampleRate = rate;
Andy Hung26145642015-04-15 21:56:53 -0700732 mProxy->setSampleRate(effectiveSampleRate);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800733
Eric Laurent57326622009-07-07 07:10:45 -0700734 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800735}
736
Glenn Kastena5224f32012-01-04 12:41:44 -0800737uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800738{
John Grossman4ff14ba2012-02-08 16:37:41 -0800739 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800740 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800741 }
742
Eric Laurent1703cdf2011-03-07 14:52:59 -0800743 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700744
745 // sample rate can be updated during playback by the offloaded decoder so we need to
746 // query the HAL and update if needed.
747// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700748 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700749 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700750 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700751 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700752 if (status == NO_ERROR) {
753 mSampleRate = sampleRate;
754 }
755 }
756 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800757 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800758}
759
Andy Hung8edb8dc2015-03-26 19:13:55 -0700760status_t AudioTrack::setPlaybackRate(float speed, float pitch)
761{
Andy Hung8edb8dc2015-03-26 19:13:55 -0700762 AutoMutex lock(mLock);
763 if (speed == mSpeed && pitch == mPitch) {
764 return NO_ERROR;
765 }
766 if (mIsTimed || isOffloadedOrDirect_l()) {
767 return INVALID_OPERATION;
768 }
769 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
770 return INVALID_OPERATION;
771 }
Andy Hung26145642015-04-15 21:56:53 -0700772 // pitch is emulated by adjusting speed and sampleRate
773 const uint32_t effectiveRate = adjustSampleRate(mSampleRate, pitch);
774 const float effectiveSpeed = adjustSpeed(speed, pitch);
775 const float effectivePitch = adjustPitch(pitch);
776 if (effectiveSpeed < AUDIO_TIMESTRETCH_SPEED_MIN
777 || effectiveSpeed > AUDIO_TIMESTRETCH_SPEED_MAX
778 || effectivePitch < AUDIO_TIMESTRETCH_PITCH_MIN
779 || effectivePitch > AUDIO_TIMESTRETCH_PITCH_MAX) {
780 return BAD_VALUE;
781 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700782 // Check if the buffer size is compatible.
Andy Hung26145642015-04-15 21:56:53 -0700783 if (!isSampleRateSpeedAllowed_l(effectiveRate, effectiveSpeed)) {
Andy Hung8edb8dc2015-03-26 19:13:55 -0700784 ALOGV("setPlaybackRate(%f, %f) failed", speed, pitch);
785 return BAD_VALUE;
786 }
787 mSpeed = speed;
788 mPitch = pitch;
Andy Hung26145642015-04-15 21:56:53 -0700789 mProxy->setPlaybackRate(effectiveSpeed, effectivePitch);
790 mProxy->setSampleRate(effectiveRate); // FIXME: not quite "atomic" with setPlaybackRate
Andy Hung8edb8dc2015-03-26 19:13:55 -0700791 return NO_ERROR;
792}
793
794void AudioTrack::getPlaybackRate(float *speed, float *pitch) const
795{
796 AutoMutex lock(mLock);
797 *speed = mSpeed;
798 *pitch = mPitch;
799}
800
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800801status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
802{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700803 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800804 return INVALID_OPERATION;
805 }
806
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800807 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800808 ;
809 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
810 loopEnd - loopStart >= MIN_LOOP) {
811 ;
812 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800813 return BAD_VALUE;
814 }
815
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800816 AutoMutex lock(mLock);
817 // See setPosition() regarding setting parameters such as loop points or position while active
818 if (mState == STATE_ACTIVE) {
819 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700820 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800821 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800822 return NO_ERROR;
823}
824
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800825void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
826{
Andy Hung4ede21d2014-12-12 15:37:34 -0800827 // We do not update the periodic notification point.
828 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
829 mLoopCount = loopCount;
830 mLoopEnd = loopEnd;
831 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800832 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800833 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -0800834
835 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800836}
837
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800838status_t AudioTrack::setMarkerPosition(uint32_t marker)
839{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700840 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700841 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700842 return INVALID_OPERATION;
843 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800844
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800845 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800846 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700847 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800848
Andy Hung3c09c782014-12-29 18:39:32 -0800849 sp<AudioTrackThread> t = mAudioTrackThread;
850 if (t != 0) {
851 t->wake();
852 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800853 return NO_ERROR;
854}
855
Glenn Kastena5224f32012-01-04 12:41:44 -0800856status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800857{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700858 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100859 return INVALID_OPERATION;
860 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700861 if (marker == NULL) {
862 return BAD_VALUE;
863 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800864
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800865 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800866 *marker = mMarkerPosition;
867
868 return NO_ERROR;
869}
870
871status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
872{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700873 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700874 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700875 return INVALID_OPERATION;
876 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800877
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800878 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700879 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800880 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800881
Andy Hung3c09c782014-12-29 18:39:32 -0800882 sp<AudioTrackThread> t = mAudioTrackThread;
883 if (t != 0) {
884 t->wake();
885 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800886 return NO_ERROR;
887}
888
Glenn Kastena5224f32012-01-04 12:41:44 -0800889status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800890{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700891 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100892 return INVALID_OPERATION;
893 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700894 if (updatePeriod == NULL) {
895 return BAD_VALUE;
896 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800897
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800898 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800899 *updatePeriod = mUpdatePeriod;
900
901 return NO_ERROR;
902}
903
904status_t AudioTrack::setPosition(uint32_t position)
905{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700906 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700907 return INVALID_OPERATION;
908 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800909 if (position > mFrameCount) {
910 return BAD_VALUE;
911 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800912
Eric Laurent1703cdf2011-03-07 14:52:59 -0800913 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800914 // Currently we require that the player is inactive before setting parameters such as position
915 // or loop points. Otherwise, there could be a race condition: the application could read the
916 // current position, compute a new position or loop parameters, and then set that position or
917 // loop parameters but it would do the "wrong" thing since the position has continued to advance
918 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
919 // to specify how it wants to handle such scenarios.
920 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700921 return INVALID_OPERATION;
922 }
Andy Hung9b461582014-12-01 17:56:29 -0800923 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -0700924 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800925 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -0800926
927 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800928 return NO_ERROR;
929}
930
Glenn Kasten200092b2014-08-15 15:13:30 -0700931status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800932{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700933 if (position == NULL) {
934 return BAD_VALUE;
935 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800936
Eric Laurent1703cdf2011-03-07 14:52:59 -0800937 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700938 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100939 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800940
Eric Laurentab5cdba2014-06-09 17:22:27 -0700941 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800942 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
943 *position = mPausedPosition;
944 return NO_ERROR;
945 }
946
Glenn Kasten142f5192014-03-25 17:44:59 -0700947 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100948 uint32_t halFrames;
949 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
950 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700951 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
952 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100953 *position = dspFrames;
954 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -0800955 if (mCblk->mFlags & CBLK_INVALID) {
956 restoreTrack_l("getPosition");
957 }
958
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100959 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700960 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
961 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100962 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800963 return NO_ERROR;
964}
965
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000966status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800967{
968 if (mSharedBuffer == 0 || mIsTimed) {
969 return INVALID_OPERATION;
970 }
971 if (position == NULL) {
972 return BAD_VALUE;
973 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800974
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800975 AutoMutex lock(mLock);
976 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800977 return NO_ERROR;
978}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800979
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800980status_t AudioTrack::reload()
981{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700982 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800983 return INVALID_OPERATION;
984 }
985
Eric Laurent1703cdf2011-03-07 14:52:59 -0800986 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800987 // See setPosition() regarding setting parameters such as loop points or position while active
988 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700989 return INVALID_OPERATION;
990 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800991 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800992 (void) updateAndGetPosition_l();
993 mPosition = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800994#if 0
Andy Hung9b461582014-12-01 17:56:29 -0800995 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -0800996 // of loop count. Historically we have not restored loop count, start, end,
997 // but it makes sense if one desires to repeat playing a particular sound.
998 if (mLoopCount != 0) {
999 mLoopCountNotified = mLoopCount;
1000 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
1001 }
1002#endif
Andy Hung9b461582014-12-01 17:56:29 -08001003 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001004 return NO_ERROR;
1005}
1006
Glenn Kasten38e905b2014-01-13 10:21:48 -08001007audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -07001008{
Eric Laurent1703cdf2011-03-07 14:52:59 -08001009 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001010 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001011}
1012
Paul McLeanaa981192015-03-21 09:55:15 -07001013status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
1014 AutoMutex lock(mLock);
1015 if (mSelectedDeviceId != deviceId) {
1016 mSelectedDeviceId = deviceId;
Eric Laurent493404d2015-04-21 15:07:36 -07001017 android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
Paul McLeanaa981192015-03-21 09:55:15 -07001018 }
Eric Laurent493404d2015-04-21 15:07:36 -07001019 return NO_ERROR;
Paul McLeanaa981192015-03-21 09:55:15 -07001020}
1021
1022audio_port_handle_t AudioTrack::getOutputDevice() {
1023 AutoMutex lock(mLock);
1024 return mSelectedDeviceId;
1025}
1026
Eric Laurentbe916aa2010-06-01 23:49:17 -07001027status_t AudioTrack::attachAuxEffect(int effectId)
1028{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001029 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001030 status_t status = mAudioTrack->attachAuxEffect(effectId);
1031 if (status == NO_ERROR) {
1032 mAuxEffectId = effectId;
1033 }
1034 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -07001035}
1036
Eric Laurente83b55d2014-11-14 10:06:21 -08001037audio_stream_type_t AudioTrack::streamType() const
1038{
1039 if (mStreamType == AUDIO_STREAM_DEFAULT) {
1040 return audio_attributes_to_stream_type(&mAttributes);
1041 }
1042 return mStreamType;
1043}
1044
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001045// -------------------------------------------------------------------------
1046
Eric Laurent1703cdf2011-03-07 14:52:59 -08001047// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -07001048status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001049{
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001050 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
1051 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001052 ALOGE("Could not get audioflinger");
1053 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001054 }
1055
Eric Laurente83b55d2014-11-14 10:06:21 -08001056 audio_io_handle_t output;
1057 audio_stream_type_t streamType = mStreamType;
1058 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
Eric Laurente83b55d2014-11-14 10:06:21 -08001059
Paul McLeanaa981192015-03-21 09:55:15 -07001060 status_t status;
1061 status = AudioSystem::getOutputForAttr(attr, &output,
1062 (audio_session_t)mSessionId, &streamType,
1063 mSampleRate, mFormat, mChannelMask,
1064 mFlags, mSelectedDeviceId, mOffloadInfo);
Eric Laurente83b55d2014-11-14 10:06:21 -08001065
1066 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001067 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 -07001068 " channel mask %#x, flags %#x",
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001069 mSessionId, streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001070 return BAD_VALUE;
1071 }
1072 {
1073 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
1074 // we must release it ourselves if anything goes wrong.
1075
Glenn Kastence8828a2013-09-16 18:07:38 -07001076 // Not all of these values are needed under all conditions, but it is easier to get them all
1077
Eric Laurentd1b449a2010-05-14 03:26:45 -07001078 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -07001079 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001080 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001081 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001082 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001083 }
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001084 ALOGV("createTrack_l() output %d afLatency %u", output, afLatency);
Eric Laurentd1b449a2010-05-14 03:26:45 -07001085
Glenn Kastence8828a2013-09-16 18:07:38 -07001086 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001087 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -07001088 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001089 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001090 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001091 }
1092
1093 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001094 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -07001095 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001096 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001097 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001098 }
Eric Laurent0d6db582014-11-12 18:39:44 -08001099 if (mSampleRate == 0) {
1100 mSampleRate = afSampleRate;
1101 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001102 // Client decides whether the track is TIMED (see below), but can only express a preference
1103 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001104 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001105 // either of these use cases:
1106 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -08001107 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001108 // use case 2: callback transfer mode
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001109 (mTransfer == TRANSFER_CALLBACK) ||
1110 // use case 3: obtain/release mode
1111 (mTransfer == TRANSFER_OBTAIN)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001112 // matching sample rate
1113 (mSampleRate == afSampleRate))) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001114 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client; transfer %d, track %u Hz, output %u Hz",
1115 mTransfer, mSampleRate, afSampleRate);
Glenn Kasten093000f2012-05-03 09:35:36 -07001116 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001117 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001118 }
1119
Glenn Kastence8828a2013-09-16 18:07:38 -07001120 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -08001121 // n = 1 fast track with single buffering; nBuffering is ignored
1122 // n = 2 fast track with double buffering
Andy Hung0e48d252015-01-26 11:43:15 -08001123 // n = 2 normal track, (including those with sample rate conversion)
1124 // n >= 3 very high latency or very small notification interval (unused).
1125 const uint32_t nBuffering = 2;
Glenn Kastence8828a2013-09-16 18:07:38 -07001126
Eric Laurentd1b449a2010-05-14 03:26:45 -07001127 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001128
Glenn Kasten363fb752014-01-15 12:27:31 -08001129 size_t frameCount = mReqFrameCount;
1130 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001131
Glenn Kasten363fb752014-01-15 12:27:31 -08001132 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001133 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001134 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001135 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001136 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001137 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001138 if (mNotificationFramesAct != frameCount) {
1139 mNotificationFramesAct = frameCount;
1140 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001141 } else if (mSharedBuffer != 0) {
Andy Hungabdb9902015-01-12 15:08:22 -08001142 // FIXME: Ensure client side memory buffers need
1143 // not have additional alignment beyond sample
1144 // (e.g. 16 bit stereo accessed as 32 bit frame).
1145 size_t alignment = audio_bytes_per_sample(mFormat);
Glenn Kastenb7730382014-04-30 15:50:31 -07001146 if (alignment & 1) {
Andy Hungabdb9902015-01-12 15:08:22 -08001147 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
Glenn Kastenb7730382014-04-30 15:50:31 -07001148 alignment = 1;
1149 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001150 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001151 // More than 2 channels does not require stronger alignment than stereo
1152 alignment <<= 1;
1153 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001154 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001155 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001156 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001157 status = BAD_VALUE;
1158 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001159 }
1160
1161 // When initializing a shared buffer AudioTrack via constructors,
1162 // there's no frameCount parameter.
1163 // But when initializing a shared buffer AudioTrack via set(),
1164 // there _is_ a frameCount parameter. We silently ignore it.
Andy Hungabdb9902015-01-12 15:08:22 -08001165 frameCount = mSharedBuffer->size() / mFrameSize;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001166 } else {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001167 // For fast tracks the frame count calculations and checks are done by server
1168
1169 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1170 // for normal tracks precompute the frame count based on speed.
1171 const size_t minFrameCount = calculateMinFrameCount(
1172 afLatency, afFrameCount, afSampleRate, mSampleRate, mSpeed);
1173 if (frameCount < minFrameCount) {
1174 frameCount = minFrameCount;
1175 }
1176 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001177 }
1178
Glenn Kastena075db42012-03-06 11:22:44 -08001179 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1180 if (mIsTimed) {
1181 trackFlags |= IAudioFlinger::TRACK_TIMED;
1182 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001183
1184 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001185 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001186 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001187 if (mAudioTrackThread != 0) {
1188 tid = mAudioTrackThread->getTid();
1189 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001190 }
1191
Glenn Kasten363fb752014-01-15 12:27:31 -08001192 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001193 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1194 }
1195
Eric Laurentab5cdba2014-06-09 17:22:27 -07001196 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1197 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1198 }
1199
Glenn Kasten74935e42013-12-19 08:56:45 -08001200 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1201 // but we will still need the original value also
Glenn Kasten138d6f92015-03-20 10:54:51 -07001202 int originalSessionId = mSessionId;
Eric Laurente83b55d2014-11-14 10:06:21 -08001203 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001204 mSampleRate,
Andy Hungabdb9902015-01-12 15:08:22 -08001205 mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001206 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001207 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001208 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001209 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001210 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001211 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001212 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001213 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001214 &status);
Glenn Kasten138d6f92015-03-20 10:54:51 -07001215 ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
1216 "session ID changed from %d to %d", originalSessionId, mSessionId);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001217
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001218 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001219 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001220 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001221 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001222 ALOG_ASSERT(track != 0);
1223
Glenn Kasten38e905b2014-01-13 10:21:48 -08001224 // AudioFlinger now owns the reference to the I/O handle,
1225 // so we are no longer responsible for releasing it.
1226
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001227 sp<IMemory> iMem = track->getCblk();
1228 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001229 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001230 return NO_INIT;
1231 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001232 void *iMemPointer = iMem->pointer();
1233 if (iMemPointer == NULL) {
1234 ALOGE("Could not get control block pointer");
1235 return NO_INIT;
1236 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001237 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001238 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001239 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001240 mDeathNotifier.clear();
1241 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001242 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001243 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001244 IPCThreadState::self()->flushCommands();
1245
Glenn Kasten0cde0762014-01-16 15:06:36 -08001246 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001247 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001248 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001249 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1250 // In current design, AudioTrack client checks and ensures frame count validity before
1251 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1252 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001253 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001254 }
1255 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001256
Glenn Kastena07f17c2013-04-23 12:39:37 -07001257 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001258 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001259 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001260 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001261 mAwaitBoost = true;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001262 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001263 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001264 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001265 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001266 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001267 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001268 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001269 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1270 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1271 } else {
1272 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001273 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001274 // FIXME This is a warning, not an error, so don't return error status
1275 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001276 }
1277 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001278 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1279 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1280 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1281 } else {
1282 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1283 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1284 // FIXME This is a warning, not an error, so don't return error status
1285 //return NO_INIT;
1286 }
1287 }
Andy Hung0e48d252015-01-26 11:43:15 -08001288 // Make sure that application is notified with sufficient margin before underrun
1289 if (mSharedBuffer == 0 && audio_is_linear_pcm(mFormat)) {
1290 // Theoretically double-buffering is not required for fast tracks,
1291 // due to tighter scheduling. But in practice, to accommodate kernels with
1292 // scheduling jitter, and apps with computation jitter, we use double-buffering
1293 // for fast tracks just like normal streaming tracks.
1294 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount / nBuffering) {
1295 mNotificationFramesAct = frameCount / nBuffering;
1296 }
1297 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001298
Glenn Kasten38e905b2014-01-13 10:21:48 -08001299 // We retain a copy of the I/O handle, but don't own the reference
1300 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001301 mRefreshRemaining = true;
1302
1303 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1304 // is the value of pointer() for the shared buffer, otherwise buffers points
1305 // immediately after the control block. This address is for the mapping within client
1306 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1307 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001308 if (mSharedBuffer == 0) {
Glenn Kasten138d6f92015-03-20 10:54:51 -07001309 buffers = cblk + 1;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001310 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001311 buffers = mSharedBuffer->pointer();
Glenn Kasten138d6f92015-03-20 10:54:51 -07001312 if (buffers == NULL) {
1313 ALOGE("Could not get buffer pointer");
1314 return NO_INIT;
1315 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001316 }
1317
Eric Laurent2beeb502010-07-16 07:43:46 -07001318 mAudioTrack->attachAuxEffect(mAuxEffectId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07001319 // FIXME doesn't take into account speed or future sample rate changes (until restoreTrack)
Glenn Kastene0fa4672012-04-24 14:35:14 -07001320 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001321 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001322
Glenn Kastenb6037442012-11-14 13:42:25 -08001323 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001324 // If IAudioTrack is re-created, don't let the requested frameCount
1325 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001326 if (frameCount > mReqFrameCount) {
1327 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001328 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001329
1330 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001331 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001332 mStaticProxy.clear();
Andy Hungabdb9902015-01-12 15:08:22 -08001333 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001334 } else {
Andy Hungabdb9902015-01-12 15:08:22 -08001335 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001336 mProxy = mStaticProxy;
1337 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001338
1339 mProxy->setVolumeLR(gain_minifloat_pack(
1340 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1341 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1342
Glenn Kastene3aa6592012-12-04 12:22:46 -08001343 mProxy->setSendLevel(mSendLevel);
Andy Hung26145642015-04-15 21:56:53 -07001344 const uint32_t effectiveSampleRate = adjustSampleRate(mSampleRate, mPitch);
1345 const float effectiveSpeed = adjustSpeed(mSpeed, mPitch);
1346 const float effectivePitch = adjustPitch(mPitch);
1347 mProxy->setSampleRate(effectiveSampleRate);
1348 mProxy->setPlaybackRate(effectiveSpeed, effectivePitch);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001349 mProxy->setMinimum(mNotificationFramesAct);
1350
1351 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001352 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001353
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001354 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001355 }
1356
1357release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001358 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001359 if (status == NO_ERROR) {
1360 status = NO_INIT;
1361 }
1362 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001363}
1364
Glenn Kastenb46f3942015-03-09 12:00:30 -07001365status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001366{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001367 if (audioBuffer == NULL) {
Glenn Kasten551b5352015-03-20 11:30:28 -07001368 if (nonContig != NULL) {
1369 *nonContig = 0;
1370 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001371 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001372 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001373 if (mTransfer != TRANSFER_OBTAIN) {
1374 audioBuffer->frameCount = 0;
1375 audioBuffer->size = 0;
1376 audioBuffer->raw = NULL;
Glenn Kasten551b5352015-03-20 11:30:28 -07001377 if (nonContig != NULL) {
1378 *nonContig = 0;
1379 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001380 return INVALID_OPERATION;
1381 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001382
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001383 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001384 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001385 if (waitCount == -1) {
1386 requested = &ClientProxy::kForever;
1387 } else if (waitCount == 0) {
1388 requested = &ClientProxy::kNonBlocking;
1389 } else if (waitCount > 0) {
1390 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001391 timeout.tv_sec = ms / 1000;
1392 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1393 requested = &timeout;
1394 } else {
1395 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1396 requested = NULL;
1397 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001398 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001399}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001400
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001401status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1402 struct timespec *elapsed, size_t *nonContig)
1403{
1404 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1405 uint32_t oldSequence = 0;
1406 uint32_t newSequence;
1407
1408 Proxy::Buffer buffer;
1409 status_t status = NO_ERROR;
1410
1411 static const int32_t kMaxTries = 5;
1412 int32_t tryCounter = kMaxTries;
1413
1414 do {
1415 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1416 // keep them from going away if another thread re-creates the track during obtainBuffer()
1417 sp<AudioTrackClientProxy> proxy;
1418 sp<IMemory> iMem;
1419
1420 { // start of lock scope
1421 AutoMutex lock(mLock);
1422
1423 newSequence = mSequence;
1424 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1425 if (status == DEAD_OBJECT) {
1426 // re-create track, unless someone else has already done so
1427 if (newSequence == oldSequence) {
1428 status = restoreTrack_l("obtainBuffer");
1429 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001430 buffer.mFrameCount = 0;
1431 buffer.mRaw = NULL;
1432 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001433 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001434 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001435 }
1436 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001437 oldSequence = newSequence;
1438
1439 // Keep the extra references
1440 proxy = mProxy;
1441 iMem = mCblkMemory;
1442
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001443 if (mState == STATE_STOPPING) {
1444 status = -EINTR;
1445 buffer.mFrameCount = 0;
1446 buffer.mRaw = NULL;
1447 buffer.mNonContig = 0;
1448 break;
1449 }
1450
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001451 // Non-blocking if track is stopped or paused
1452 if (mState != STATE_ACTIVE) {
1453 requested = &ClientProxy::kNonBlocking;
1454 }
1455
1456 } // end of lock scope
1457
1458 buffer.mFrameCount = audioBuffer->frameCount;
1459 // FIXME starts the requested timeout and elapsed over from scratch
1460 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1461
1462 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1463
1464 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001465 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001466 audioBuffer->raw = buffer.mRaw;
1467 if (nonContig != NULL) {
1468 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001469 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001470 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001471}
1472
Glenn Kasten54a8a452015-03-09 12:03:00 -07001473void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001474{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001475 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001476 if (mTransfer == TRANSFER_SHARED) {
1477 return;
1478 }
1479
Andy Hungabdb9902015-01-12 15:08:22 -08001480 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001481 if (stepCount == 0) {
1482 return;
1483 }
1484
1485 Proxy::Buffer buffer;
1486 buffer.mFrameCount = stepCount;
1487 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001488
Eric Laurent1703cdf2011-03-07 14:52:59 -08001489 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001490 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001491 mInUnderrun = false;
1492 mProxy->releaseBuffer(&buffer);
1493
1494 // restart track if it was disabled by audioflinger due to previous underrun
1495 if (mState == STATE_ACTIVE) {
1496 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001497 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001498 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001499 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001500 mAudioTrack->start();
1501 }
1502 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001503}
1504
1505// -------------------------------------------------------------------------
1506
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001507ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001508{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001509 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001510 return INVALID_OPERATION;
1511 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001512
Eric Laurentab5cdba2014-06-09 17:22:27 -07001513 if (isDirect()) {
1514 AutoMutex lock(mLock);
1515 int32_t flags = android_atomic_and(
1516 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1517 &mCblk->mFlags);
1518 if (flags & CBLK_INVALID) {
1519 return DEAD_OBJECT;
1520 }
1521 }
1522
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001523 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001524 // Sanity-check: user is most-likely passing an error code, and it would
1525 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001526 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001527 return BAD_VALUE;
1528 }
1529
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001530 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001531 Buffer audioBuffer;
1532
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001533 while (userSize >= mFrameSize) {
1534 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001535
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001536 status_t err = obtainBuffer(&audioBuffer,
1537 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001538 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001539 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001540 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001541 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001542 return ssize_t(err);
1543 }
1544
Glenn Kastenae4b8792015-03-20 09:04:21 -07001545 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08001546 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001547 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001548 userSize -= toWrite;
1549 written += toWrite;
1550
1551 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001552 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001553
1554 return written;
1555}
1556
1557// -------------------------------------------------------------------------
1558
John Grossman4ff14ba2012-02-08 16:37:41 -08001559TimedAudioTrack::TimedAudioTrack() {
1560 mIsTimed = true;
1561}
1562
1563status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1564{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001565 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001566 status_t result = UNKNOWN_ERROR;
1567
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001568#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001569 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1570 // while we are accessing the cblk
1571 sp<IAudioTrack> audioTrack = mAudioTrack;
1572 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001573#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001574
John Grossman4ff14ba2012-02-08 16:37:41 -08001575 // If the track is not invalid already, try to allocate a buffer. alloc
1576 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001577 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001578 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001579 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001580 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1581 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001582 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001583 }
1584 }
1585
1586 // If the track is invalid at this point, attempt to restore it. and try the
1587 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001588 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001589 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001590
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001591 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001592 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001593 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001594 }
1595
1596 return result;
1597}
1598
1599status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1600 int64_t pts)
1601{
Eric Laurentdf839842012-05-31 14:27:14 -07001602 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1603 {
1604 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001605 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001606 // restart track if it was disabled by audioflinger due to previous underrun
1607 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001608 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1609 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001610 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001611 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001612 mAudioTrack->start();
1613 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001614 }
Eric Laurentdf839842012-05-31 14:27:14 -07001615 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001616}
1617
1618status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1619 TargetTimeline target)
1620{
1621 return mAudioTrack->setMediaTimeTransform(xform, target);
1622}
1623
1624// -------------------------------------------------------------------------
1625
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001626nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001627{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001628 // Currently the AudioTrack thread is not created if there are no callbacks.
1629 // Would it ever make sense to run the thread, even without callbacks?
1630 // If so, then replace this by checks at each use for mCbf != NULL.
1631 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1632
Eric Laurent1703cdf2011-03-07 14:52:59 -08001633 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001634 if (mAwaitBoost) {
1635 mAwaitBoost = false;
1636 mLock.unlock();
1637 static const int32_t kMaxTries = 5;
1638 int32_t tryCounter = kMaxTries;
1639 uint32_t pollUs = 10000;
1640 do {
1641 int policy = sched_getscheduler(0);
1642 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1643 break;
1644 }
1645 usleep(pollUs);
1646 pollUs <<= 1;
1647 } while (tryCounter-- > 0);
1648 if (tryCounter < 0) {
1649 ALOGE("did not receive expected priority boost on time");
1650 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001651 // Run again immediately
1652 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001653 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001654
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001655 // Can only reference mCblk while locked
1656 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001657 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001658
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001659 // Check for track invalidation
1660 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001661 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1662 // AudioSystem cache. We should not exit here but after calling the callback so
1663 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001664 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Lajos Molnarf1063e22015-04-17 15:19:42 -07001665 status_t status __unused = restoreTrack_l("processAudioBuffer");
1666 // FIXME unused status
Andy Hung53c3b5f2014-12-15 16:42:05 -08001667 // after restoration, continue below to make sure that the loop and buffer events
1668 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001669 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001670 }
1671
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001672 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001673 bool active = mState == STATE_ACTIVE;
1674
1675 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1676 bool newUnderrun = false;
1677 if (flags & CBLK_UNDERRUN) {
1678#if 0
1679 // Currently in shared buffer mode, when the server reaches the end of buffer,
1680 // the track stays active in continuous underrun state. It's up to the application
1681 // to pause or stop the track, or set the position to a new offset within buffer.
1682 // This was some experimental code to auto-pause on underrun. Keeping it here
1683 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1684 if (mTransfer == TRANSFER_SHARED) {
1685 mState = STATE_PAUSED;
1686 active = false;
1687 }
1688#endif
1689 if (!mInUnderrun) {
1690 mInUnderrun = true;
1691 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001692 }
1693 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001694
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001695 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001696 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001697
1698 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001699 bool markerReached = false;
1700 size_t markerPosition = mMarkerPosition;
1701 // FIXME fails for wraparound, need 64 bits
1702 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1703 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001704 }
1705
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001706 // Determine number of new position callback(s) that will be needed, while locked
1707 size_t newPosCount = 0;
1708 size_t newPosition = mNewPosition;
1709 size_t updatePeriod = mUpdatePeriod;
1710 // FIXME fails for wraparound, need 64 bits
1711 if (updatePeriod > 0 && position >= newPosition) {
1712 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1713 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001714 }
1715
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001716 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001717 uint32_t sampleRate = mSampleRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001718 float speed = mSpeed;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001719 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001720 if (mRefreshRemaining) {
1721 mRefreshRemaining = false;
1722 mRemainingFrames = notificationFrames;
1723 mRetryOnPartialBuffer = false;
1724 }
1725 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001726 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001727 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001728
Andy Hung53c3b5f2014-12-15 16:42:05 -08001729 // Determine the number of new loop callback(s) that will be needed, while locked.
1730 int loopCountNotifications = 0;
1731 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1732
1733 if (mLoopCount > 0) {
1734 int loopCount;
1735 size_t bufferPosition;
1736 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1737 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1738 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1739 mLoopCountNotified = loopCount; // discard any excess notifications
1740 } else if (mLoopCount < 0) {
1741 // FIXME: We're not accurate with notification count and position with infinite looping
1742 // since loopCount from server side will always return -1 (we could decrement it).
1743 size_t bufferPosition = mStaticProxy->getBufferPosition();
1744 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1745 loopPeriod = mLoopEnd - bufferPosition;
1746 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1747 size_t bufferPosition = mStaticProxy->getBufferPosition();
1748 loopPeriod = mFrameCount - bufferPosition;
1749 }
1750
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001751 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08001752 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001753 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1754
1755 mLock.unlock();
1756
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001757 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001758 struct timespec timeout;
1759 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1760 timeout.tv_nsec = 0;
1761
Glenn Kasten96f04882013-09-20 09:28:56 -07001762 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001763 switch (status) {
1764 case NO_ERROR:
1765 case DEAD_OBJECT:
1766 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001767 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001768 {
1769 AutoMutex lock(mLock);
1770 // The previously assigned value of waitStreamEnd is no longer valid,
1771 // since the mutex has been unlocked and either the callback handler
1772 // or another thread could have re-started the AudioTrack during that time.
1773 waitStreamEnd = mState == STATE_STOPPING;
1774 if (waitStreamEnd) {
1775 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001776 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001777 }
1778 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001779 if (waitStreamEnd && status != DEAD_OBJECT) {
1780 return NS_INACTIVE;
1781 }
1782 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001783 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001784 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001785 }
1786
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001787 // perform callbacks while unlocked
1788 if (newUnderrun) {
1789 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1790 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001791 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001792 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001793 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001794 }
1795 if (flags & CBLK_BUFFER_END) {
1796 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1797 }
1798 if (markerReached) {
1799 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1800 }
1801 while (newPosCount > 0) {
1802 size_t temp = newPosition;
1803 mCbf(EVENT_NEW_POS, mUserData, &temp);
1804 newPosition += updatePeriod;
1805 newPosCount--;
1806 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001807
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001808 if (mObservedSequence != sequence) {
1809 mObservedSequence = sequence;
1810 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001811 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001812 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001813 return NS_INACTIVE;
1814 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001815 }
1816
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001817 // if inactive, then don't run me again until re-started
1818 if (!active) {
1819 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001820 }
1821
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001822 // Compute the estimated time until the next timed event (position, markers, loops)
1823 // FIXME only for non-compressed audio
1824 uint32_t minFrames = ~0;
1825 if (!markerReached && position < markerPosition) {
1826 minFrames = markerPosition - position;
1827 }
1828 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08001829 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001830 minFrames = loopPeriod;
1831 }
Andy Hung2d85f092015-01-07 12:45:13 -08001832 if (updatePeriod > 0) {
1833 minFrames = min(minFrames, uint32_t(newPosition - position));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001834 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001835
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001836 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1837 static const uint32_t kPoll = 0;
1838 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1839 minFrames = kPoll * notificationFrames;
1840 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001841
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001842 // Convert frame units to time units
1843 nsecs_t ns = NS_WHENEVER;
1844 if (minFrames != (uint32_t) ~0) {
1845 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1846 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
Andy Hung8edb8dc2015-03-26 19:13:55 -07001847 ns = ((double)minFrames * 1000000000) / ((double)sampleRate * speed) + kFudgeNs;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001848 }
1849
1850 // If not supplying data by EVENT_MORE_DATA, then we're done
1851 if (mTransfer != TRANSFER_CALLBACK) {
1852 return ns;
1853 }
1854
1855 struct timespec timeout;
1856 const struct timespec *requested = &ClientProxy::kForever;
1857 if (ns != NS_WHENEVER) {
1858 timeout.tv_sec = ns / 1000000000LL;
1859 timeout.tv_nsec = ns % 1000000000LL;
1860 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1861 requested = &timeout;
1862 }
1863
1864 while (mRemainingFrames > 0) {
1865
1866 Buffer audioBuffer;
1867 audioBuffer.frameCount = mRemainingFrames;
1868 size_t nonContig;
1869 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1870 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001871 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001872 requested = &ClientProxy::kNonBlocking;
1873 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001874 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001875 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001876 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001877 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1878 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001879 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001880 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001881 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1882 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001883 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001884
Eric Laurent42a6f422013-08-29 14:35:05 -07001885 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001886 mRetryOnPartialBuffer = false;
1887 if (avail < mRemainingFrames) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001888 int64_t myns = ((double)(mRemainingFrames - avail) * 1100000000)
1889 / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001890 if (ns < 0 || myns < ns) {
1891 ns = myns;
1892 }
1893 return ns;
1894 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001895 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001896
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001897 size_t reqSize = audioBuffer.size;
1898 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001899 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001900
1901 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001902 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001903 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1904 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001905 return NS_NEVER;
1906 }
1907
1908 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001909 // The callback is done filling buffers
1910 // Keep this thread going to handle timed events and
1911 // still try to get more data in intervals of WAIT_PERIOD_MS
1912 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001913 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001914 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001915
Glenn Kasten138d6f92015-03-20 10:54:51 -07001916 size_t releasedFrames = writtenSize / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001917 audioBuffer.frameCount = releasedFrames;
1918 mRemainingFrames -= releasedFrames;
1919 if (misalignment >= releasedFrames) {
1920 misalignment -= releasedFrames;
1921 } else {
1922 misalignment = 0;
1923 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001924
1925 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001926
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001927 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1928 // if callback doesn't like to accept the full chunk
1929 if (writtenSize < reqSize) {
1930 continue;
1931 }
1932
1933 // There could be enough non-contiguous frames available to satisfy the remaining request
1934 if (mRemainingFrames <= nonContig) {
1935 continue;
1936 }
1937
1938#if 0
1939 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1940 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1941 // that total to a sum == notificationFrames.
1942 if (0 < misalignment && misalignment <= mRemainingFrames) {
1943 mRemainingFrames = misalignment;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001944 return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001945 }
1946#endif
1947
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001948 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001949 mRemainingFrames = notificationFrames;
1950 mRetryOnPartialBuffer = true;
1951
1952 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1953 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001954}
1955
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001956status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001957{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001958 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001959 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001960 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001961
Glenn Kastena47f3162012-11-07 10:13:08 -08001962 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08001963 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001964 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001965
Eric Laurentab5cdba2014-06-09 17:22:27 -07001966 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001967 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001968 return DEAD_OBJECT;
1969 }
1970
Glenn Kasten200092b2014-08-15 15:13:30 -07001971 // save the old static buffer position
Andy Hung4ede21d2014-12-12 15:37:34 -08001972 size_t bufferPosition = 0;
1973 int loopCount = 0;
1974 if (mStaticProxy != 0) {
1975 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1976 }
Glenn Kasten200092b2014-08-15 15:13:30 -07001977
1978 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001979 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001980 // It will also delete the strong references on previous IAudioTrack and IMemory.
1981 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Glenn Kastenae4b8792015-03-20 09:04:21 -07001982 status_t result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001983
1984 // take the frames that will be lost by track recreation into account in saved position
Andy Hung9b461582014-12-01 17:56:29 -08001985 // For streaming tracks, this is the amount we obtained from the user/client
1986 // (not the number actually consumed at the server - those are already lost).
Glenn Kasten200092b2014-08-15 15:13:30 -07001987 (void) updateAndGetPosition_l();
Andy Hung7ccdaad2015-03-20 00:38:32 -07001988 if (mStaticProxy == 0) {
Andy Hung9b461582014-12-01 17:56:29 -08001989 mPosition = mReleased;
1990 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001991
Glenn Kastena47f3162012-11-07 10:13:08 -08001992 if (result == NO_ERROR) {
Andy Hung4ede21d2014-12-12 15:37:34 -08001993 // Continue playback from last known position and restore loop.
1994 if (mStaticProxy != 0) {
1995 if (loopCount != 0) {
1996 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
1997 mLoopStart, mLoopEnd, loopCount);
1998 } else {
1999 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002000 if (bufferPosition == mFrameCount) {
2001 ALOGD("restoring track at end of static buffer");
2002 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002003 }
2004 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002005 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08002006 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08002007 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002008 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002009 if (result != NO_ERROR) {
2010 ALOGW("restoreTrack_l() failed status %d", result);
2011 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07002012 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002013 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002014
2015 return result;
2016}
2017
Glenn Kasten200092b2014-08-15 15:13:30 -07002018uint32_t AudioTrack::updateAndGetPosition_l()
2019{
2020 // This is the sole place to read server consumed frames
2021 uint32_t newServer = mProxy->getPosition();
2022 int32_t delta = newServer - mServer;
2023 mServer = newServer;
2024 // TODO There is controversy about whether there can be "negative jitter" in server position.
2025 // This should be investigated further, and if possible, it should be addressed.
2026 // A more definite failure mode is infrequent polling by client.
2027 // One could call (void)getPosition_l() in releaseBuffer(),
2028 // so mReleased and mPosition are always lock-step as best possible.
2029 // That should ensure delta never goes negative for infrequent polling
2030 // unless the server has more than 2^31 frames in its buffer,
2031 // in which case the use of uint32_t for these counters has bigger issues.
2032 if (delta < 0) {
2033 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
2034 delta = 0;
2035 }
2036 return mPosition += (uint32_t) delta;
2037}
2038
Andy Hung8edb8dc2015-03-26 19:13:55 -07002039bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed) const
2040{
2041 // applicable for mixing tracks only (not offloaded or direct)
2042 if (mStaticProxy != 0) {
2043 return true; // static tracks do not have issues with buffer sizing.
2044 }
2045 status_t status;
2046 uint32_t afLatency;
2047 status = AudioSystem::getLatency(mOutput, &afLatency);
2048 if (status != NO_ERROR) {
2049 ALOGE("getLatency(%d) failed status %d", mOutput, status);
2050 return false;
2051 }
2052
2053 size_t afFrameCount;
2054 status = AudioSystem::getFrameCount(mOutput, &afFrameCount);
2055 if (status != NO_ERROR) {
2056 ALOGE("getFrameCount(output=%d) status %d", mOutput, status);
2057 return false;
2058 }
2059
2060 uint32_t afSampleRate;
2061 status = AudioSystem::getSamplingRate(mOutput, &afSampleRate);
2062 if (status != NO_ERROR) {
2063 ALOGE("getSamplingRate(output=%d) status %d", mOutput, status);
2064 return false;
2065 }
2066
2067 const size_t minFrameCount =
2068 calculateMinFrameCount(afLatency, afFrameCount, afSampleRate, sampleRate, speed);
2069 ALOGV("isSampleRateSpeedAllowed_l mFrameCount %zu minFrameCount %zu",
2070 mFrameCount, minFrameCount);
2071 return mFrameCount >= minFrameCount;
2072}
2073
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002074status_t AudioTrack::setParameters(const String8& keyValuePairs)
2075{
2076 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07002077 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002078}
2079
Glenn Kastence703742013-07-19 16:33:58 -07002080status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
2081{
Glenn Kasten53cec222013-08-29 09:01:02 -07002082 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07002083 // FIXME not implemented for fast tracks; should use proxy and SSQ
2084 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
2085 return INVALID_OPERATION;
2086 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002087
2088 switch (mState) {
2089 case STATE_ACTIVE:
2090 case STATE_PAUSED:
2091 break; // handle below
2092 case STATE_FLUSHED:
2093 case STATE_STOPPED:
2094 return WOULD_BLOCK;
2095 case STATE_STOPPING:
2096 case STATE_PAUSED_STOPPING:
2097 if (!isOffloaded_l()) {
2098 return INVALID_OPERATION;
2099 }
2100 break; // offloaded tracks handled below
2101 default:
2102 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
2103 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07002104 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002105
Eric Laurent275e8e92014-11-30 15:14:47 -08002106 if (mCblk->mFlags & CBLK_INVALID) {
2107 restoreTrack_l("getTimestamp");
2108 }
2109
Glenn Kasten200092b2014-08-15 15:13:30 -07002110 // The presented frame count must always lag behind the consumed frame count.
2111 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002112 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002113 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07002114 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002115 return status;
2116 }
2117 if (isOffloadedOrDirect_l()) {
2118 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
2119 // use cached paused position in case another offloaded track is running.
2120 timestamp.mPosition = mPausedPosition;
2121 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
2122 return NO_ERROR;
2123 }
2124
2125 // Check whether a pending flush or stop has completed, as those commands may
2126 // be asynchronous or return near finish.
2127 if (mStartUs != 0 && mSampleRate != 0) {
2128 static const int kTimeJitterUs = 100000; // 100 ms
2129 static const int k1SecUs = 1000000;
2130
2131 const int64_t timeNow = getNowUs();
2132
2133 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
2134 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
2135 if (timestampTimeUs < mStartUs) {
2136 return WOULD_BLOCK; // stale timestamp time, occurs before start.
2137 }
2138 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002139 const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
2140 / ((double)mSampleRate * mSpeed);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002141
2142 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2143 // Verify that the counter can't count faster than the sample rate
2144 // since the start time. If greater, then that means we have failed
2145 // to completely flush or stop the previous playing track.
2146 ALOGW("incomplete flush or stop:"
2147 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2148 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2149 timestamp.mPosition);
2150 return WOULD_BLOCK;
2151 }
2152 }
2153 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
2154 }
2155 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002156 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2157 (void) updateAndGetPosition_l();
2158 // Server consumed (mServer) and presented both use the same server time base,
2159 // and server consumed is always >= presented.
2160 // The delta between these represents the number of frames in the buffer pipeline.
2161 // If this delta between these is greater than the client position, it means that
2162 // actually presented is still stuck at the starting line (figuratively speaking),
2163 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
2164 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2165 return INVALID_OPERATION;
2166 }
2167 // Convert timestamp position from server time base to client time base.
2168 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2169 // But if we change it to 64-bit then this could fail.
2170 // If (mPosition - mServer) can be negative then should use:
2171 // (int32_t)(mPosition - mServer)
2172 timestamp.mPosition += mPosition - mServer;
2173 // Immediately after a call to getPosition_l(), mPosition and
2174 // mServer both represent the same frame position. mPosition is
2175 // in client's point of view, and mServer is in server's point of
2176 // view. So the difference between them is the "fudge factor"
2177 // between client and server views due to stop() and/or new
2178 // IAudioTrack. And timestamp.mPosition is initially in server's
2179 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002180 }
2181 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002182}
2183
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002184String8 AudioTrack::getParameters(const String8& keys)
2185{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002186 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002187 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002188 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002189 } else {
2190 return String8::empty();
2191 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002192}
2193
Glenn Kasten23a75452014-01-13 10:37:17 -08002194bool AudioTrack::isOffloaded() const
2195{
2196 AutoMutex lock(mLock);
2197 return isOffloaded_l();
2198}
2199
Eric Laurentab5cdba2014-06-09 17:22:27 -07002200bool AudioTrack::isDirect() const
2201{
2202 AutoMutex lock(mLock);
2203 return isDirect_l();
2204}
2205
2206bool AudioTrack::isOffloadedOrDirect() const
2207{
2208 AutoMutex lock(mLock);
2209 return isOffloadedOrDirect_l();
2210}
2211
2212
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002213status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002214{
2215
2216 const size_t SIZE = 256;
2217 char buffer[SIZE];
2218 String8 result;
2219
2220 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002221 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002222 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002223 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002224 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002225 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002226 result.append(buffer);
Andy Hung8edb8dc2015-03-26 19:13:55 -07002227 snprintf(buffer, 255, " sample rate(%u), speed(%f), status(%d)\n",
2228 mSampleRate, mSpeed, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002229 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002230 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002231 result.append(buffer);
2232 ::write(fd, result.string(), result.size());
2233 return NO_ERROR;
2234}
2235
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002236uint32_t AudioTrack::getUnderrunFrames() const
2237{
2238 AutoMutex lock(mLock);
2239 return mProxy->getUnderrunFrames();
2240}
2241
2242// =========================================================================
2243
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002244void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002245{
2246 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2247 if (audioTrack != 0) {
2248 AutoMutex lock(audioTrack->mLock);
2249 audioTrack->mProxy->binderDied();
2250 }
2251}
2252
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002253// =========================================================================
2254
2255AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002256 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2257 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002258{
2259}
2260
2261AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002262{
2263}
2264
2265bool AudioTrack::AudioTrackThread::threadLoop()
2266{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002267 {
2268 AutoMutex _l(mMyLock);
2269 if (mPaused) {
2270 mMyCond.wait(mMyLock);
2271 // caller will check for exitPending()
2272 return true;
2273 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002274 if (mIgnoreNextPausedInt) {
2275 mIgnoreNextPausedInt = false;
2276 mPausedInt = false;
2277 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002278 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002279 if (mPausedNs > 0) {
2280 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2281 } else {
2282 mMyCond.wait(mMyLock);
2283 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002284 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002285 return true;
2286 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002287 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002288 if (exitPending()) {
2289 return false;
2290 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002291 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002292 switch (ns) {
2293 case 0:
2294 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002295 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002296 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002297 return true;
2298 case NS_NEVER:
2299 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002300 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08002301 // Event driven: call wake() when callback notifications conditions change.
2302 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002303 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002304 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002305 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002306 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002307 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002308 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002309}
2310
Glenn Kasten3acbd052012-02-28 10:39:56 -08002311void AudioTrack::AudioTrackThread::requestExit()
2312{
2313 // must be in this order to avoid a race condition
2314 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002315 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002316}
2317
2318void AudioTrack::AudioTrackThread::pause()
2319{
2320 AutoMutex _l(mMyLock);
2321 mPaused = true;
2322}
2323
2324void AudioTrack::AudioTrackThread::resume()
2325{
2326 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002327 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002328 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002329 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002330 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002331 mMyCond.signal();
2332 }
2333}
2334
Andy Hung3c09c782014-12-29 18:39:32 -08002335void AudioTrack::AudioTrackThread::wake()
2336{
2337 AutoMutex _l(mMyLock);
2338 if (!mPaused && mPausedInt && mPausedNs > 0) {
2339 // audio track is active and internally paused with timeout.
2340 mIgnoreNextPausedInt = true;
2341 mPausedInt = false;
2342 mMyCond.signal();
2343 }
2344}
2345
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002346void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2347{
2348 AutoMutex _l(mMyLock);
2349 mPausedInt = true;
2350 mPausedNs = ns;
2351}
2352
Glenn Kasten40bc9062015-03-20 09:09:33 -07002353} // namespace android