blob: b51b94f6b9236f908de4d37eed353686b593f8c0 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080018//#define LOG_NDEBUG 0
19#define LOG_TAG "AudioTrack"
20
Mark Salyzyn34fb2962014-06-18 16:30:56 -070021#include <inttypes.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070022#include <math.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080023#include <sys/resource.h>
Mark Salyzyn34fb2962014-06-18 16:30:56 -070024
Glenn Kasten9f80dd22012-12-18 15:57:32 -080025#include <audio_utils/primitives.h>
26#include <binder/IPCThreadState.h>
27#include <media/AudioTrack.h>
28#include <utils/Log.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080029#include <private/media/AudioTrackShared.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/IAudioFlinger.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080031#include <media/AudioPolicyHelper.h>
Andy Hungcd044842014-08-07 11:04:34 -070032#include <media/AudioResamplerPublic.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080033
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010034#define WAIT_PERIOD_MS 10
35#define WAIT_STREAM_END_TIMEOUT_SEC 120
Andy Hung53c3b5f2014-12-15 16:42:05 -080036static const int kMaxLoopCountNotifications = 32;
Glenn Kasten511754b2012-01-11 09:52:19 -080037
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080038namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080039// ---------------------------------------------------------------------------
40
Andy Hung4ede21d2014-12-12 15:37:34 -080041template <typename T>
42const T &min(const T &x, const T &y) {
43 return x < y ? x : y;
44}
45
Andy Hung7f1bc8a2014-09-12 14:43:11 -070046static int64_t convertTimespecToUs(const struct timespec &tv)
47{
48 return tv.tv_sec * 1000000ll + tv.tv_nsec / 1000;
49}
50
51// current monotonic time in microseconds.
52static int64_t getNowUs()
53{
54 struct timespec tv;
55 (void) clock_gettime(CLOCK_MONOTONIC, &tv);
56 return convertTimespecToUs(tv);
57}
58
Andy Hung26145642015-04-15 21:56:53 -070059// FIXME: we don't use the pitch setting in the time stretcher (not working);
60// instead we emulate it using our sample rate converter.
61static const bool kFixPitch = true; // enable pitch fix
62static inline uint32_t adjustSampleRate(uint32_t sampleRate, float pitch)
63{
64 return kFixPitch ? (sampleRate * pitch + 0.5) : sampleRate;
65}
66
67static inline float adjustSpeed(float speed, float pitch)
68{
69 return kFixPitch ? (speed / pitch) : speed;
70}
71
72static inline float adjustPitch(float pitch)
73{
74 return kFixPitch ? AUDIO_TIMESTRETCH_PITCH_NORMAL : pitch;
75}
76
Andy Hung8edb8dc2015-03-26 19:13:55 -070077// Must match similar computation in createTrack_l in Threads.cpp.
78// TODO: Move to a common library
79static size_t calculateMinFrameCount(
80 uint32_t afLatencyMs, uint32_t afFrameCount, uint32_t afSampleRate,
81 uint32_t sampleRate, float speed)
82{
83 // Ensure that buffer depth covers at least audio hardware latency
84 uint32_t minBufCount = afLatencyMs / ((1000 * afFrameCount) / afSampleRate);
85 if (minBufCount < 2) {
86 minBufCount = 2;
87 }
88 ALOGV("calculateMinFrameCount afLatency %u afFrameCount %u afSampleRate %u "
89 "sampleRate %u speed %f minBufCount: %u",
90 afLatencyMs, afFrameCount, afSampleRate, sampleRate, speed, minBufCount);
91 return minBufCount * sourceFramesNeededWithTimestretch(
92 sampleRate, afFrameCount, afSampleRate, speed);
93}
94
Chia-chi Yeh33005a92010-06-16 06:33:13 +080095// static
96status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080097 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080098 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080099 uint32_t sampleRate)
100{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700101 if (frameCount == NULL) {
102 return BAD_VALUE;
103 }
Glenn Kasten04cd0182012-06-25 11:49:27 -0700104
Andy Hung0e48d252015-01-26 11:43:15 -0800105 // FIXME handle in server, like createTrack_l(), possible missing info:
Glenn Kastene0fa4672012-04-24 14:35:14 -0700106 // audio_io_handle_t output
107 // audio_format_t format
108 // audio_channel_mask_t channelMask
Andy Hung0e48d252015-01-26 11:43:15 -0800109 // audio_output_flags_t flags (FAST)
Glenn Kasten3b16c762012-11-14 08:44:39 -0800110 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -0800111 status_t status;
112 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
113 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -0800114 ALOGE("Unable to query output sample rate for stream type %d; status %d",
115 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800116 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800117 }
Glenn Kastene33054e2012-11-14 12:54:39 -0800118 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -0800119 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
120 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -0800121 ALOGE("Unable to query output frame count for stream type %d; status %d",
122 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800123 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800124 }
125 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -0800126 status = AudioSystem::getOutputLatency(&afLatency, streamType);
127 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -0800128 ALOGE("Unable to query output latency for stream type %d; status %d",
129 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800130 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800131 }
132
Andy Hung8edb8dc2015-03-26 19:13:55 -0700133 // When called from createTrack, speed is 1.0f (normal speed).
134 // This is rechecked again on setting playback rate (TODO: on setting sample rate, too).
135 *frameCount = calculateMinFrameCount(afLatency, afFrameCount, afSampleRate, sampleRate, 1.0f);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800136
Andy Hung0e48d252015-01-26 11:43:15 -0800137 // The formula above should always produce a non-zero value under normal circumstances:
138 // AudioTrack.SAMPLE_RATE_HZ_MIN <= sampleRate <= AudioTrack.SAMPLE_RATE_HZ_MAX.
139 // Return error in the unlikely event that it does not, as that's part of the API contract.
Glenn Kasten66a04672014-01-08 08:53:44 -0800140 if (*frameCount == 0) {
Andy Hung0e48d252015-01-26 11:43:15 -0800141 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %u",
Glenn Kasten66a04672014-01-08 08:53:44 -0800142 streamType, sampleRate);
143 return BAD_VALUE;
144 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700145 ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, afSampleRate=%u, afLatency=%u",
146 *frameCount, afFrameCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800147 return NO_ERROR;
148}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800149
150// ---------------------------------------------------------------------------
151
152AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700153 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800154 mIsTimed(false),
155 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800156 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700157 mPausedPosition(0),
158 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800159{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700160 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
161 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
162 mAttributes.flags = 0x0;
163 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800164}
165
166AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800167 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800168 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800169 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700170 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800171 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700172 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800173 callback_t cbf,
174 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800175 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800176 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000177 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800178 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800179 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700180 pid_t pid,
181 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700182 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800183 mIsTimed(false),
184 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800185 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700186 mPausedPosition(0),
187 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800188{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700189 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700190 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800191 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700192 offloadInfo, uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800193}
194
Andreas Huberc8139852012-01-18 10:51:55 -0800195AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800196 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800197 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800198 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700199 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800200 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700201 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800202 callback_t cbf,
203 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800204 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800205 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000206 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800207 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800208 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700209 pid_t pid,
210 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700211 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800212 mIsTimed(false),
213 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800214 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700215 mPausedPosition(0),
216 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800217{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700218 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800219 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800220 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700221 uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800222}
223
224AudioTrack::~AudioTrack()
225{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800226 if (mStatus == NO_ERROR) {
227 // Make sure that callback function exits in the case where
228 // it is looping on buffer full condition in obtainBuffer().
229 // Otherwise the callback thread will never exit.
230 stop();
231 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100232 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800233 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800234 mAudioTrackThread->requestExitAndWait();
235 mAudioTrackThread.clear();
236 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800237 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700238 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700239 mCblkMemory.clear();
240 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800241 IPCThreadState::self()->flushCommands();
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700242 ALOGV("~AudioTrack, releasing session id %d from %d on behalf of %d",
243 mSessionId, IPCThreadState::self()->getCallingPid(), mClientPid);
Marco Nelissend457c972014-02-11 08:47:07 -0800244 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800245 }
246}
247
248status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800249 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800250 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800251 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700252 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800253 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700254 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800255 callback_t cbf,
256 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800257 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800258 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700259 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800260 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000261 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800262 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800263 int uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700264 pid_t pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700265 const audio_attributes_t* pAttributes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800266{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800267 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700268 "flags #%x, notificationFrames %u, sessionId %d, transferType %d, uid %d, pid %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800269 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700270 sessionId, transferType, uid, pid);
Glenn Kasten86f04662014-02-24 15:13:05 -0800271
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800272 switch (transferType) {
273 case TRANSFER_DEFAULT:
274 if (sharedBuffer != 0) {
275 transferType = TRANSFER_SHARED;
276 } else if (cbf == NULL || threadCanCallJava) {
277 transferType = TRANSFER_SYNC;
278 } else {
279 transferType = TRANSFER_CALLBACK;
280 }
281 break;
282 case TRANSFER_CALLBACK:
283 if (cbf == NULL || sharedBuffer != 0) {
284 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
285 return BAD_VALUE;
286 }
287 break;
288 case TRANSFER_OBTAIN:
289 case TRANSFER_SYNC:
290 if (sharedBuffer != 0) {
291 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
292 return BAD_VALUE;
293 }
294 break;
295 case TRANSFER_SHARED:
296 if (sharedBuffer == 0) {
297 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
298 return BAD_VALUE;
299 }
300 break;
301 default:
302 ALOGE("Invalid transfer type %d", transferType);
303 return BAD_VALUE;
304 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800305 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800306 mTransfer = transferType;
307
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700308 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
309 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800310
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700311 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700312
Glenn Kasten53cec222013-08-29 09:01:02 -0700313 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700314 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000315 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800316 return INVALID_OPERATION;
317 }
318
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800319 // handle default values first.
Eric Laurente83b55d2014-11-14 10:06:21 -0800320 if (streamType == AUDIO_STREAM_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700321 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800322 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700323 if (pAttributes == NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800324 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700325 ALOGE("Invalid stream type %d", streamType);
326 return BAD_VALUE;
327 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700328 mStreamType = streamType;
Eric Laurente83b55d2014-11-14 10:06:21 -0800329
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700330 } else {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700331 // stream type shouldn't be looked at, this track has audio attributes
332 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700333 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
334 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800335 mStreamType = AUDIO_STREAM_DEFAULT;
Eric Laurentc6bd5db2015-03-09 16:29:33 -0700336 if ((mAttributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
337 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
338 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800339 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700340
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800341 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800342 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700343 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800344 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800345
346 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700347 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800348 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800349 return BAD_VALUE;
350 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800351 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700352
Glenn Kasten8ba90322013-10-30 11:29:27 -0700353 if (!audio_is_output_channel(channelMask)) {
354 ALOGE("Invalid channel mask %#x", channelMask);
355 return BAD_VALUE;
356 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800357 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700358 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800359 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700360
Eric Laurentc2f1f072009-07-17 12:17:14 -0700361 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100362 // or offload was requested
363 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
364 || !audio_is_linear_pcm(format)) {
365 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
366 ? "Offload request, forcing to Direct Output"
367 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700368 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800369 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700370 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700371 }
372
Eric Laurentd1f69b02014-12-15 14:33:13 -0800373 // force direct flag if HW A/V sync requested
374 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
375 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
376 }
377
Glenn Kastenb7730382014-04-30 15:50:31 -0700378 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
379 if (audio_is_linear_pcm(format)) {
380 mFrameSize = channelCount * audio_bytes_per_sample(format);
381 } else {
382 mFrameSize = sizeof(uint8_t);
383 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800384 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700385 ALOG_ASSERT(audio_is_linear_pcm(format));
386 mFrameSize = channelCount * audio_bytes_per_sample(format);
Glenn Kastenb7730382014-04-30 15:50:31 -0700387 // createTrack will return an error if PCM format is not supported by server,
388 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800389 }
390
Eric Laurent0d6db582014-11-12 18:39:44 -0800391 // sampling rate must be specified for direct outputs
392 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
393 return BAD_VALUE;
394 }
395 mSampleRate = sampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700396 mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT;
Eric Laurent0d6db582014-11-12 18:39:44 -0800397
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800398 // Make copy of input parameter offloadInfo so that in the future:
399 // (a) createTrack_l doesn't need it as an input parameter
400 // (b) we can support re-creation of offloaded tracks
401 if (offloadInfo != NULL) {
402 mOffloadInfoCopy = *offloadInfo;
403 mOffloadInfo = &mOffloadInfoCopy;
404 } else {
405 mOffloadInfo = NULL;
406 }
407
Glenn Kasten66e46352014-01-16 17:44:23 -0800408 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
409 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800410 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800411 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800412 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700413 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800414 mNotificationFramesAct = 0;
Eric Laurentcaf7f482014-11-25 17:50:47 -0800415 if (sessionId == AUDIO_SESSION_ALLOCATE) {
416 mSessionId = AudioSystem::newAudioUniqueId();
417 } else {
418 mSessionId = sessionId;
419 }
Marco Nelissend457c972014-02-11 08:47:07 -0800420 int callingpid = IPCThreadState::self()->getCallingPid();
421 int mypid = getpid();
422 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800423 mClientUid = IPCThreadState::self()->getCallingUid();
424 } else {
425 mClientUid = uid;
426 }
Marco Nelissend457c972014-02-11 08:47:07 -0800427 if (pid == -1 || (callingpid != mypid)) {
428 mClientPid = callingpid;
429 } else {
430 mClientPid = pid;
431 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700432 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700433 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700434 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700435
Glenn Kastena997e7a2012-08-07 09:44:19 -0700436 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700437 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700438 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
Glenn Kastenbfd31842015-03-20 09:01:44 -0700439 // thread begins in paused state, and will not reference us until start()
Glenn Kastena997e7a2012-08-07 09:44:19 -0700440 }
441
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800442 // create the IAudioTrack
Eric Laurent0d6db582014-11-12 18:39:44 -0800443 status_t status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800444
Glenn Kastena997e7a2012-08-07 09:44:19 -0700445 if (status != NO_ERROR) {
446 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100447 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
448 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700449 mAudioTrackThread.clear();
450 }
451 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700452 }
453
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800454 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800455 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800456 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800457 mLoopCount = 0;
458 mLoopStart = 0;
459 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800460 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800461 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700462 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800463 mNewPosition = 0;
464 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700465 mServer = 0;
466 mPosition = 0;
467 mReleased = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700468 mStartUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800469 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800470 mSequence = 1;
471 mObservedSequence = mSequence;
472 mInUnderrun = false;
473
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800474 return NO_ERROR;
475}
476
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800477// -------------------------------------------------------------------------
478
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100479status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800480{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800481 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100482
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800483 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100484 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800485 }
486
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800487 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800488
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800489 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100490 if (previousState == STATE_PAUSED_STOPPING) {
491 mState = STATE_STOPPING;
492 } else {
493 mState = STATE_ACTIVE;
494 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700495 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800496 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
497 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700498 mPosition = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700499 // For offloaded tracks, we don't know if the hardware counters are really zero here,
500 // since the flush is asynchronous and stop may not fully drain.
501 // We save the time when the track is started to later verify whether
502 // the counters are realistic (i.e. start from zero after this time).
503 mStartUs = getNowUs();
504
Eric Laurentec9a0322013-08-28 10:23:01 -0700505 // force refresh of remaining frames by processAudioBuffer() as last
506 // write before stop could be partial.
507 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800508 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700509 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700510 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800511
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800512 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800513 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100514 if (previousState == STATE_STOPPING) {
515 mProxy->interrupt();
516 } else {
517 t->resume();
518 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800519 } else {
520 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
521 get_sched_policy(0, &mPreviousSchedulingGroup);
522 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
523 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800524
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800525 status_t status = NO_ERROR;
526 if (!(flags & CBLK_INVALID)) {
527 status = mAudioTrack->start();
528 if (status == DEAD_OBJECT) {
529 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800530 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800531 }
532 if (flags & CBLK_INVALID) {
533 status = restoreTrack_l("start");
534 }
535
536 if (status != NO_ERROR) {
537 ALOGE("start() status %d", status);
538 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800539 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100540 if (previousState != STATE_STOPPING) {
541 t->pause();
542 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800543 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700544 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700545 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800546 }
547 }
548
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100549 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800550}
551
552void AudioTrack::stop()
553{
554 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700555 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800556 return;
557 }
558
Glenn Kasten23a75452014-01-13 10:37:17 -0800559 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100560 mState = STATE_STOPPING;
561 } else {
562 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -0700563 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100564 }
565
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800566 mProxy->interrupt();
567 mAudioTrack->stop();
568 // the playback head position will reset to 0, so if a marker is set, we need
569 // to activate it again
570 mMarkerReached = false;
Andy Hung9b461582014-12-01 17:56:29 -0800571
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800572 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800573 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800574 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
575 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800576 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100577
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800578 sp<AudioTrackThread> t = mAudioTrackThread;
579 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800580 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100581 t->pause();
582 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800583 } else {
584 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
585 set_sched_policy(0, mPreviousSchedulingGroup);
586 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800587}
588
589bool AudioTrack::stopped() const
590{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800591 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800592 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800593}
594
595void AudioTrack::flush()
596{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800597 if (mSharedBuffer != 0) {
598 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800599 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800600 AutoMutex lock(mLock);
601 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
602 return;
603 }
604 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800605}
606
Eric Laurent1703cdf2011-03-07 14:52:59 -0800607void AudioTrack::flush_l()
608{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800609 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700610
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700611 // clear playback marker and periodic update counter
612 mMarkerPosition = 0;
613 mMarkerReached = false;
614 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100615 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700616
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800617 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700618 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800619 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100620 mProxy->interrupt();
621 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800622 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800623 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800624}
625
626void AudioTrack::pause()
627{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800628 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100629 if (mState == STATE_ACTIVE) {
630 mState = STATE_PAUSED;
631 } else if (mState == STATE_STOPPING) {
632 mState = STATE_PAUSED_STOPPING;
633 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800634 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800635 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800636 mProxy->interrupt();
637 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800638
Marco Nelissen3a90f282014-03-10 11:21:43 -0700639 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700640 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700641 // An offload output can be re-used between two audio tracks having
642 // the same configuration. A timestamp query for a paused track
643 // while the other is running would return an incorrect time.
644 // To fix this, cache the playback position on a pause() and return
645 // this time when requested until the track is resumed.
646
647 // OffloadThread sends HAL pause in its threadLoop. Time saved
648 // here can be slightly off.
649
650 // TODO: check return code for getRenderPosition.
651
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800652 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800653 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
654 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
655 }
656 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800657}
658
Eric Laurentbe916aa2010-06-01 23:49:17 -0700659status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800660{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700661 // This duplicates a test by AudioTrack JNI, but that is not the only caller
662 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
663 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700664 return BAD_VALUE;
665 }
666
Eric Laurent1703cdf2011-03-07 14:52:59 -0800667 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800668 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
669 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800670
Glenn Kastenc56f3422014-03-21 17:53:17 -0700671 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700672
Glenn Kasten23a75452014-01-13 10:37:17 -0800673 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700674 mAudioTrack->signal();
675 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700676 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800677}
678
Glenn Kastenb1c09932012-02-27 16:21:04 -0800679status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800680{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800681 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700682}
683
Eric Laurent2beeb502010-07-16 07:43:46 -0700684status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700685{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700686 // This duplicates a test by AudioTrack JNI, but that is not the only caller
687 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700688 return BAD_VALUE;
689 }
690
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800691 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700692 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800693 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700694
695 return NO_ERROR;
696}
697
Glenn Kastena5224f32012-01-04 12:41:44 -0800698void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700699{
700 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800701 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700702 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800703}
704
Glenn Kasten3b16c762012-11-14 08:44:39 -0800705status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800706{
Andy Hung5cbb5782015-03-27 18:39:59 -0700707 AutoMutex lock(mLock);
708 if (rate == mSampleRate) {
709 return NO_ERROR;
710 }
711 if (mIsTimed || isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800712 return INVALID_OPERATION;
713 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800714 if (mOutput == AUDIO_IO_HANDLE_NONE) {
715 return NO_INIT;
716 }
Andy Hung5cbb5782015-03-27 18:39:59 -0700717 // NOTE: it is theoretically possible, but highly unlikely, that a device change
718 // could mean a previously allowed sampling rate is no longer allowed.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800719 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800720 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700721 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800722 }
Andy Hung26145642015-04-15 21:56:53 -0700723 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700724 const uint32_t effectiveSampleRate = adjustSampleRate(rate, mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -0700725 if (rate == 0 || effectiveSampleRate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700726 return BAD_VALUE;
727 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700728 // TODO: Should we also check if the buffer size is compatible?
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800729
Glenn Kastene3aa6592012-12-04 12:22:46 -0800730 mSampleRate = rate;
Andy Hung26145642015-04-15 21:56:53 -0700731 mProxy->setSampleRate(effectiveSampleRate);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800732
Eric Laurent57326622009-07-07 07:10:45 -0700733 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800734}
735
Glenn Kastena5224f32012-01-04 12:41:44 -0800736uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800737{
John Grossman4ff14ba2012-02-08 16:37:41 -0800738 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800739 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800740 }
741
Eric Laurent1703cdf2011-03-07 14:52:59 -0800742 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700743
744 // sample rate can be updated during playback by the offloaded decoder so we need to
745 // query the HAL and update if needed.
746// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700747 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700748 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700749 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700750 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700751 if (status == NO_ERROR) {
752 mSampleRate = sampleRate;
753 }
754 }
755 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800756 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800757}
758
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700759status_t AudioTrack::setPlaybackRate(const AudioPlaybackRate &playbackRate)
Andy Hung8edb8dc2015-03-26 19:13:55 -0700760{
Andy Hung8edb8dc2015-03-26 19:13:55 -0700761 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700762 if (isAudioPlaybackRateEqual(playbackRate, mPlaybackRate)) {
Andy Hung8edb8dc2015-03-26 19:13:55 -0700763 return NO_ERROR;
764 }
765 if (mIsTimed || isOffloadedOrDirect_l()) {
766 return INVALID_OPERATION;
767 }
768 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
769 return INVALID_OPERATION;
770 }
Andy Hung26145642015-04-15 21:56:53 -0700771 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700772 const uint32_t effectiveRate = adjustSampleRate(mSampleRate, playbackRate.mPitch);
773 const float effectiveSpeed = adjustSpeed(playbackRate.mSpeed, playbackRate.mPitch);
774 const float effectivePitch = adjustPitch(playbackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -0700775 if (effectiveSpeed < AUDIO_TIMESTRETCH_SPEED_MIN
776 || effectiveSpeed > AUDIO_TIMESTRETCH_SPEED_MAX
777 || effectivePitch < AUDIO_TIMESTRETCH_PITCH_MIN
778 || effectivePitch > AUDIO_TIMESTRETCH_PITCH_MAX) {
779 return BAD_VALUE;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700780 //TODO: add function in AudioResamplerPublic.h to check for validity.
Andy Hung26145642015-04-15 21:56:53 -0700781 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700782 // Check if the buffer size is compatible.
Andy Hung26145642015-04-15 21:56:53 -0700783 if (!isSampleRateSpeedAllowed_l(effectiveRate, effectiveSpeed)) {
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700784 ALOGV("setPlaybackRate(%f, %f) failed", playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung8edb8dc2015-03-26 19:13:55 -0700785 return BAD_VALUE;
786 }
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700787 mPlaybackRate = playbackRate;
788 mProxy->setPlaybackRate(playbackRate);
789
790 //modify this
791 AudioPlaybackRate playbackRateTemp = playbackRate;
792 playbackRateTemp.mSpeed = effectiveSpeed;
793 playbackRateTemp.mPitch = effectivePitch;
794 mProxy->setPlaybackRate(playbackRateTemp);
Andy Hung26145642015-04-15 21:56:53 -0700795 mProxy->setSampleRate(effectiveRate); // FIXME: not quite "atomic" with setPlaybackRate
Andy Hung8edb8dc2015-03-26 19:13:55 -0700796 return NO_ERROR;
797}
798
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700799const AudioPlaybackRate& AudioTrack::getPlaybackRate() const
Andy Hung8edb8dc2015-03-26 19:13:55 -0700800{
801 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700802 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700803}
804
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800805status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
806{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700807 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800808 return INVALID_OPERATION;
809 }
810
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800811 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800812 ;
813 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
814 loopEnd - loopStart >= MIN_LOOP) {
815 ;
816 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800817 return BAD_VALUE;
818 }
819
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800820 AutoMutex lock(mLock);
821 // See setPosition() regarding setting parameters such as loop points or position while active
822 if (mState == STATE_ACTIVE) {
823 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700824 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800825 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800826 return NO_ERROR;
827}
828
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800829void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
830{
Andy Hung4ede21d2014-12-12 15:37:34 -0800831 // We do not update the periodic notification point.
832 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
833 mLoopCount = loopCount;
834 mLoopEnd = loopEnd;
835 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800836 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800837 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -0800838
839 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800840}
841
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800842status_t AudioTrack::setMarkerPosition(uint32_t marker)
843{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700844 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700845 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700846 return INVALID_OPERATION;
847 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800848
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800849 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800850 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700851 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800852
Andy Hung3c09c782014-12-29 18:39:32 -0800853 sp<AudioTrackThread> t = mAudioTrackThread;
854 if (t != 0) {
855 t->wake();
856 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800857 return NO_ERROR;
858}
859
Glenn Kastena5224f32012-01-04 12:41:44 -0800860status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800861{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700862 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100863 return INVALID_OPERATION;
864 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700865 if (marker == NULL) {
866 return BAD_VALUE;
867 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800868
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800869 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800870 *marker = mMarkerPosition;
871
872 return NO_ERROR;
873}
874
875status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
876{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700877 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700878 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700879 return INVALID_OPERATION;
880 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800881
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800882 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700883 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800884 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800885
Andy Hung3c09c782014-12-29 18:39:32 -0800886 sp<AudioTrackThread> t = mAudioTrackThread;
887 if (t != 0) {
888 t->wake();
889 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800890 return NO_ERROR;
891}
892
Glenn Kastena5224f32012-01-04 12:41:44 -0800893status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800894{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700895 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100896 return INVALID_OPERATION;
897 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700898 if (updatePeriod == NULL) {
899 return BAD_VALUE;
900 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800901
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800902 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800903 *updatePeriod = mUpdatePeriod;
904
905 return NO_ERROR;
906}
907
908status_t AudioTrack::setPosition(uint32_t position)
909{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700910 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700911 return INVALID_OPERATION;
912 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800913 if (position > mFrameCount) {
914 return BAD_VALUE;
915 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800916
Eric Laurent1703cdf2011-03-07 14:52:59 -0800917 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800918 // Currently we require that the player is inactive before setting parameters such as position
919 // or loop points. Otherwise, there could be a race condition: the application could read the
920 // current position, compute a new position or loop parameters, and then set that position or
921 // loop parameters but it would do the "wrong" thing since the position has continued to advance
922 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
923 // to specify how it wants to handle such scenarios.
924 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700925 return INVALID_OPERATION;
926 }
Andy Hung9b461582014-12-01 17:56:29 -0800927 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -0700928 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800929 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -0800930
931 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800932 return NO_ERROR;
933}
934
Glenn Kasten200092b2014-08-15 15:13:30 -0700935status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800936{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700937 if (position == NULL) {
938 return BAD_VALUE;
939 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800940
Eric Laurent1703cdf2011-03-07 14:52:59 -0800941 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700942 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100943 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800944
Eric Laurentab5cdba2014-06-09 17:22:27 -0700945 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800946 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
947 *position = mPausedPosition;
948 return NO_ERROR;
949 }
950
Glenn Kasten142f5192014-03-25 17:44:59 -0700951 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100952 uint32_t halFrames;
953 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
954 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700955 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
956 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100957 *position = dspFrames;
958 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -0800959 if (mCblk->mFlags & CBLK_INVALID) {
960 restoreTrack_l("getPosition");
961 }
962
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100963 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700964 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
965 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100966 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800967 return NO_ERROR;
968}
969
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000970status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800971{
972 if (mSharedBuffer == 0 || mIsTimed) {
973 return INVALID_OPERATION;
974 }
975 if (position == NULL) {
976 return BAD_VALUE;
977 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800978
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800979 AutoMutex lock(mLock);
980 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800981 return NO_ERROR;
982}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800983
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800984status_t AudioTrack::reload()
985{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700986 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800987 return INVALID_OPERATION;
988 }
989
Eric Laurent1703cdf2011-03-07 14:52:59 -0800990 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800991 // See setPosition() regarding setting parameters such as loop points or position while active
992 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700993 return INVALID_OPERATION;
994 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800995 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800996 (void) updateAndGetPosition_l();
997 mPosition = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800998#if 0
Andy Hung9b461582014-12-01 17:56:29 -0800999 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -08001000 // of loop count. Historically we have not restored loop count, start, end,
1001 // but it makes sense if one desires to repeat playing a particular sound.
1002 if (mLoopCount != 0) {
1003 mLoopCountNotified = mLoopCount;
1004 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
1005 }
1006#endif
Andy Hung9b461582014-12-01 17:56:29 -08001007 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001008 return NO_ERROR;
1009}
1010
Glenn Kasten38e905b2014-01-13 10:21:48 -08001011audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -07001012{
Eric Laurent1703cdf2011-03-07 14:52:59 -08001013 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001014 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001015}
1016
Paul McLeanaa981192015-03-21 09:55:15 -07001017status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
1018 AutoMutex lock(mLock);
1019 if (mSelectedDeviceId != deviceId) {
1020 mSelectedDeviceId = deviceId;
1021 return restoreTrack_l("setOutputDevice() restart");
1022 } else {
1023 return NO_ERROR;
1024 }
1025}
1026
1027audio_port_handle_t AudioTrack::getOutputDevice() {
1028 AutoMutex lock(mLock);
1029 return mSelectedDeviceId;
1030}
1031
Eric Laurentbe916aa2010-06-01 23:49:17 -07001032status_t AudioTrack::attachAuxEffect(int effectId)
1033{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001034 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001035 status_t status = mAudioTrack->attachAuxEffect(effectId);
1036 if (status == NO_ERROR) {
1037 mAuxEffectId = effectId;
1038 }
1039 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -07001040}
1041
Eric Laurente83b55d2014-11-14 10:06:21 -08001042audio_stream_type_t AudioTrack::streamType() const
1043{
1044 if (mStreamType == AUDIO_STREAM_DEFAULT) {
1045 return audio_attributes_to_stream_type(&mAttributes);
1046 }
1047 return mStreamType;
1048}
1049
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001050// -------------------------------------------------------------------------
1051
Eric Laurent1703cdf2011-03-07 14:52:59 -08001052// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -07001053status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001054{
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001055 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
1056 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001057 ALOGE("Could not get audioflinger");
1058 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001059 }
1060
Eric Laurente83b55d2014-11-14 10:06:21 -08001061 audio_io_handle_t output;
1062 audio_stream_type_t streamType = mStreamType;
1063 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
Eric Laurente83b55d2014-11-14 10:06:21 -08001064
Paul McLeanaa981192015-03-21 09:55:15 -07001065 status_t status;
1066 status = AudioSystem::getOutputForAttr(attr, &output,
1067 (audio_session_t)mSessionId, &streamType,
1068 mSampleRate, mFormat, mChannelMask,
1069 mFlags, mSelectedDeviceId, mOffloadInfo);
Eric Laurente83b55d2014-11-14 10:06:21 -08001070
1071 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001072 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 -07001073 " channel mask %#x, flags %#x",
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001074 mSessionId, streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001075 return BAD_VALUE;
1076 }
1077 {
1078 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
1079 // we must release it ourselves if anything goes wrong.
1080
Glenn Kastence8828a2013-09-16 18:07:38 -07001081 // Not all of these values are needed under all conditions, but it is easier to get them all
1082
Eric Laurentd1b449a2010-05-14 03:26:45 -07001083 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -07001084 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001085 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001086 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001087 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001088 }
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001089 ALOGV("createTrack_l() output %d afLatency %u", output, afLatency);
Eric Laurentd1b449a2010-05-14 03:26:45 -07001090
Glenn Kastence8828a2013-09-16 18:07:38 -07001091 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001092 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -07001093 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001094 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001095 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001096 }
1097
1098 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001099 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -07001100 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001101 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001102 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001103 }
Eric Laurent0d6db582014-11-12 18:39:44 -08001104 if (mSampleRate == 0) {
1105 mSampleRate = afSampleRate;
1106 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001107 // Client decides whether the track is TIMED (see below), but can only express a preference
1108 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001109 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001110 // either of these use cases:
1111 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -08001112 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001113 // use case 2: callback transfer mode
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001114 (mTransfer == TRANSFER_CALLBACK) ||
1115 // use case 3: obtain/release mode
1116 (mTransfer == TRANSFER_OBTAIN)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001117 // matching sample rate
1118 (mSampleRate == afSampleRate))) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001119 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client; transfer %d, track %u Hz, output %u Hz",
1120 mTransfer, mSampleRate, afSampleRate);
Glenn Kasten093000f2012-05-03 09:35:36 -07001121 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001122 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001123 }
1124
Glenn Kastence8828a2013-09-16 18:07:38 -07001125 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -08001126 // n = 1 fast track with single buffering; nBuffering is ignored
1127 // n = 2 fast track with double buffering
Andy Hung0e48d252015-01-26 11:43:15 -08001128 // n = 2 normal track, (including those with sample rate conversion)
1129 // n >= 3 very high latency or very small notification interval (unused).
1130 const uint32_t nBuffering = 2;
Glenn Kastence8828a2013-09-16 18:07:38 -07001131
Eric Laurentd1b449a2010-05-14 03:26:45 -07001132 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001133
Glenn Kasten363fb752014-01-15 12:27:31 -08001134 size_t frameCount = mReqFrameCount;
1135 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001136
Glenn Kasten363fb752014-01-15 12:27:31 -08001137 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001138 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001139 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001140 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001141 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001142 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001143 if (mNotificationFramesAct != frameCount) {
1144 mNotificationFramesAct = frameCount;
1145 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001146 } else if (mSharedBuffer != 0) {
Andy Hungabdb9902015-01-12 15:08:22 -08001147 // FIXME: Ensure client side memory buffers need
1148 // not have additional alignment beyond sample
1149 // (e.g. 16 bit stereo accessed as 32 bit frame).
1150 size_t alignment = audio_bytes_per_sample(mFormat);
Glenn Kastenb7730382014-04-30 15:50:31 -07001151 if (alignment & 1) {
Andy Hungabdb9902015-01-12 15:08:22 -08001152 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
Glenn Kastenb7730382014-04-30 15:50:31 -07001153 alignment = 1;
1154 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001155 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001156 // More than 2 channels does not require stronger alignment than stereo
1157 alignment <<= 1;
1158 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001159 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001160 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001161 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001162 status = BAD_VALUE;
1163 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001164 }
1165
1166 // When initializing a shared buffer AudioTrack via constructors,
1167 // there's no frameCount parameter.
1168 // But when initializing a shared buffer AudioTrack via set(),
1169 // there _is_ a frameCount parameter. We silently ignore it.
Andy Hungabdb9902015-01-12 15:08:22 -08001170 frameCount = mSharedBuffer->size() / mFrameSize;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001171 } else {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001172 // For fast tracks the frame count calculations and checks are done by server
1173
1174 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1175 // for normal tracks precompute the frame count based on speed.
1176 const size_t minFrameCount = calculateMinFrameCount(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001177 afLatency, afFrameCount, afSampleRate, mSampleRate,
1178 mPlaybackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07001179 if (frameCount < minFrameCount) {
1180 frameCount = minFrameCount;
1181 }
1182 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001183 }
1184
Glenn Kastena075db42012-03-06 11:22:44 -08001185 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1186 if (mIsTimed) {
1187 trackFlags |= IAudioFlinger::TRACK_TIMED;
1188 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001189
1190 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001191 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001192 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001193 if (mAudioTrackThread != 0) {
1194 tid = mAudioTrackThread->getTid();
1195 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001196 }
1197
Glenn Kasten363fb752014-01-15 12:27:31 -08001198 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001199 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1200 }
1201
Eric Laurentab5cdba2014-06-09 17:22:27 -07001202 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1203 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1204 }
1205
Glenn Kasten74935e42013-12-19 08:56:45 -08001206 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1207 // but we will still need the original value also
Glenn Kasten138d6f92015-03-20 10:54:51 -07001208 int originalSessionId = mSessionId;
Eric Laurente83b55d2014-11-14 10:06:21 -08001209 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001210 mSampleRate,
Andy Hungabdb9902015-01-12 15:08:22 -08001211 mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001212 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001213 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001214 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001215 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001216 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001217 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001218 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001219 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001220 &status);
Glenn Kasten138d6f92015-03-20 10:54:51 -07001221 ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
1222 "session ID changed from %d to %d", originalSessionId, mSessionId);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001223
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001224 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001225 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001226 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001227 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001228 ALOG_ASSERT(track != 0);
1229
Glenn Kasten38e905b2014-01-13 10:21:48 -08001230 // AudioFlinger now owns the reference to the I/O handle,
1231 // so we are no longer responsible for releasing it.
1232
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001233 sp<IMemory> iMem = track->getCblk();
1234 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001235 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001236 return NO_INIT;
1237 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001238 void *iMemPointer = iMem->pointer();
1239 if (iMemPointer == NULL) {
1240 ALOGE("Could not get control block pointer");
1241 return NO_INIT;
1242 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001243 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001244 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001245 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001246 mDeathNotifier.clear();
1247 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001248 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001249 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001250 IPCThreadState::self()->flushCommands();
1251
Glenn Kasten0cde0762014-01-16 15:06:36 -08001252 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001253 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001254 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001255 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1256 // In current design, AudioTrack client checks and ensures frame count validity before
1257 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1258 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001259 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001260 }
1261 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001262
Glenn Kastena07f17c2013-04-23 12:39:37 -07001263 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001264 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001265 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001266 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001267 mAwaitBoost = true;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001268 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001269 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001270 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001271 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001272 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001273 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001274 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001275 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1276 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1277 } else {
1278 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001279 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001280 // FIXME This is a warning, not an error, so don't return error status
1281 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001282 }
1283 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001284 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1285 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1286 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1287 } else {
1288 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1289 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1290 // FIXME This is a warning, not an error, so don't return error status
1291 //return NO_INIT;
1292 }
1293 }
Andy Hung0e48d252015-01-26 11:43:15 -08001294 // Make sure that application is notified with sufficient margin before underrun
1295 if (mSharedBuffer == 0 && audio_is_linear_pcm(mFormat)) {
1296 // Theoretically double-buffering is not required for fast tracks,
1297 // due to tighter scheduling. But in practice, to accommodate kernels with
1298 // scheduling jitter, and apps with computation jitter, we use double-buffering
1299 // for fast tracks just like normal streaming tracks.
1300 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount / nBuffering) {
1301 mNotificationFramesAct = frameCount / nBuffering;
1302 }
1303 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001304
Glenn Kasten38e905b2014-01-13 10:21:48 -08001305 // We retain a copy of the I/O handle, but don't own the reference
1306 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001307 mRefreshRemaining = true;
1308
1309 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1310 // is the value of pointer() for the shared buffer, otherwise buffers points
1311 // immediately after the control block. This address is for the mapping within client
1312 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1313 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001314 if (mSharedBuffer == 0) {
Glenn Kasten138d6f92015-03-20 10:54:51 -07001315 buffers = cblk + 1;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001316 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001317 buffers = mSharedBuffer->pointer();
Glenn Kasten138d6f92015-03-20 10:54:51 -07001318 if (buffers == NULL) {
1319 ALOGE("Could not get buffer pointer");
1320 return NO_INIT;
1321 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001322 }
1323
Eric Laurent2beeb502010-07-16 07:43:46 -07001324 mAudioTrack->attachAuxEffect(mAuxEffectId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07001325 // FIXME doesn't take into account speed or future sample rate changes (until restoreTrack)
Glenn Kastene0fa4672012-04-24 14:35:14 -07001326 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001327 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001328
Glenn Kastenb6037442012-11-14 13:42:25 -08001329 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001330 // If IAudioTrack is re-created, don't let the requested frameCount
1331 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001332 if (frameCount > mReqFrameCount) {
1333 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001334 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001335
1336 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001337 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001338 mStaticProxy.clear();
Andy Hungabdb9902015-01-12 15:08:22 -08001339 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001340 } else {
Andy Hungabdb9902015-01-12 15:08:22 -08001341 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001342 mProxy = mStaticProxy;
1343 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001344
1345 mProxy->setVolumeLR(gain_minifloat_pack(
1346 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1347 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1348
Glenn Kastene3aa6592012-12-04 12:22:46 -08001349 mProxy->setSendLevel(mSendLevel);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001350 const uint32_t effectiveSampleRate = adjustSampleRate(mSampleRate, mPlaybackRate.mPitch);
1351 const float effectiveSpeed = adjustSpeed(mPlaybackRate.mSpeed, mPlaybackRate.mPitch);
1352 const float effectivePitch = adjustPitch(mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001353 mProxy->setSampleRate(effectiveSampleRate);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001354
1355 AudioPlaybackRate playbackRateTemp = mPlaybackRate;
1356 playbackRateTemp.mSpeed = effectiveSpeed;
1357 playbackRateTemp.mPitch = effectivePitch;
1358 mProxy->setPlaybackRate(playbackRateTemp);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001359 mProxy->setMinimum(mNotificationFramesAct);
1360
1361 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001362 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001363
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001364 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001365 }
1366
1367release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001368 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001369 if (status == NO_ERROR) {
1370 status = NO_INIT;
1371 }
1372 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001373}
1374
Glenn Kastenb46f3942015-03-09 12:00:30 -07001375status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001376{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001377 if (audioBuffer == NULL) {
Glenn Kasten551b5352015-03-20 11:30:28 -07001378 if (nonContig != NULL) {
1379 *nonContig = 0;
1380 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001381 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001382 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001383 if (mTransfer != TRANSFER_OBTAIN) {
1384 audioBuffer->frameCount = 0;
1385 audioBuffer->size = 0;
1386 audioBuffer->raw = NULL;
Glenn Kasten551b5352015-03-20 11:30:28 -07001387 if (nonContig != NULL) {
1388 *nonContig = 0;
1389 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001390 return INVALID_OPERATION;
1391 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001392
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001393 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001394 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001395 if (waitCount == -1) {
1396 requested = &ClientProxy::kForever;
1397 } else if (waitCount == 0) {
1398 requested = &ClientProxy::kNonBlocking;
1399 } else if (waitCount > 0) {
1400 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001401 timeout.tv_sec = ms / 1000;
1402 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1403 requested = &timeout;
1404 } else {
1405 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1406 requested = NULL;
1407 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001408 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001409}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001410
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001411status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1412 struct timespec *elapsed, size_t *nonContig)
1413{
1414 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1415 uint32_t oldSequence = 0;
1416 uint32_t newSequence;
1417
1418 Proxy::Buffer buffer;
1419 status_t status = NO_ERROR;
1420
1421 static const int32_t kMaxTries = 5;
1422 int32_t tryCounter = kMaxTries;
1423
1424 do {
1425 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1426 // keep them from going away if another thread re-creates the track during obtainBuffer()
1427 sp<AudioTrackClientProxy> proxy;
1428 sp<IMemory> iMem;
1429
1430 { // start of lock scope
1431 AutoMutex lock(mLock);
1432
1433 newSequence = mSequence;
1434 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1435 if (status == DEAD_OBJECT) {
1436 // re-create track, unless someone else has already done so
1437 if (newSequence == oldSequence) {
1438 status = restoreTrack_l("obtainBuffer");
1439 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001440 buffer.mFrameCount = 0;
1441 buffer.mRaw = NULL;
1442 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001443 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001444 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001445 }
1446 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001447 oldSequence = newSequence;
1448
1449 // Keep the extra references
1450 proxy = mProxy;
1451 iMem = mCblkMemory;
1452
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001453 if (mState == STATE_STOPPING) {
1454 status = -EINTR;
1455 buffer.mFrameCount = 0;
1456 buffer.mRaw = NULL;
1457 buffer.mNonContig = 0;
1458 break;
1459 }
1460
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001461 // Non-blocking if track is stopped or paused
1462 if (mState != STATE_ACTIVE) {
1463 requested = &ClientProxy::kNonBlocking;
1464 }
1465
1466 } // end of lock scope
1467
1468 buffer.mFrameCount = audioBuffer->frameCount;
1469 // FIXME starts the requested timeout and elapsed over from scratch
1470 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1471
1472 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1473
1474 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001475 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001476 audioBuffer->raw = buffer.mRaw;
1477 if (nonContig != NULL) {
1478 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001479 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001480 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001481}
1482
Glenn Kasten54a8a452015-03-09 12:03:00 -07001483void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001484{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001485 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001486 if (mTransfer == TRANSFER_SHARED) {
1487 return;
1488 }
1489
Andy Hungabdb9902015-01-12 15:08:22 -08001490 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001491 if (stepCount == 0) {
1492 return;
1493 }
1494
1495 Proxy::Buffer buffer;
1496 buffer.mFrameCount = stepCount;
1497 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001498
Eric Laurent1703cdf2011-03-07 14:52:59 -08001499 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001500 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001501 mInUnderrun = false;
1502 mProxy->releaseBuffer(&buffer);
1503
1504 // restart track if it was disabled by audioflinger due to previous underrun
1505 if (mState == STATE_ACTIVE) {
1506 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001507 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001508 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001509 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001510 mAudioTrack->start();
1511 }
1512 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001513}
1514
1515// -------------------------------------------------------------------------
1516
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001517ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001518{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001519 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001520 return INVALID_OPERATION;
1521 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001522
Eric Laurentab5cdba2014-06-09 17:22:27 -07001523 if (isDirect()) {
1524 AutoMutex lock(mLock);
1525 int32_t flags = android_atomic_and(
1526 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1527 &mCblk->mFlags);
1528 if (flags & CBLK_INVALID) {
1529 return DEAD_OBJECT;
1530 }
1531 }
1532
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001533 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001534 // Sanity-check: user is most-likely passing an error code, and it would
1535 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001536 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001537 return BAD_VALUE;
1538 }
1539
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001540 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001541 Buffer audioBuffer;
1542
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001543 while (userSize >= mFrameSize) {
1544 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001545
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001546 status_t err = obtainBuffer(&audioBuffer,
1547 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001548 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001549 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001550 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001551 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001552 return ssize_t(err);
1553 }
1554
Glenn Kastenae4b8792015-03-20 09:04:21 -07001555 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08001556 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001557 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001558 userSize -= toWrite;
1559 written += toWrite;
1560
1561 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001562 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001563
1564 return written;
1565}
1566
1567// -------------------------------------------------------------------------
1568
John Grossman4ff14ba2012-02-08 16:37:41 -08001569TimedAudioTrack::TimedAudioTrack() {
1570 mIsTimed = true;
1571}
1572
1573status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1574{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001575 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001576 status_t result = UNKNOWN_ERROR;
1577
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001578#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001579 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1580 // while we are accessing the cblk
1581 sp<IAudioTrack> audioTrack = mAudioTrack;
1582 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001583#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001584
John Grossman4ff14ba2012-02-08 16:37:41 -08001585 // If the track is not invalid already, try to allocate a buffer. alloc
1586 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001587 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001588 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001589 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001590 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1591 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001592 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001593 }
1594 }
1595
1596 // If the track is invalid at this point, attempt to restore it. and try the
1597 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001598 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001599 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001600
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001601 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001602 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001603 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001604 }
1605
1606 return result;
1607}
1608
1609status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1610 int64_t pts)
1611{
Eric Laurentdf839842012-05-31 14:27:14 -07001612 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1613 {
1614 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001615 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001616 // restart track if it was disabled by audioflinger due to previous underrun
1617 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001618 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1619 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001620 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001621 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001622 mAudioTrack->start();
1623 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001624 }
Eric Laurentdf839842012-05-31 14:27:14 -07001625 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001626}
1627
1628status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1629 TargetTimeline target)
1630{
1631 return mAudioTrack->setMediaTimeTransform(xform, target);
1632}
1633
1634// -------------------------------------------------------------------------
1635
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001636nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001637{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001638 // Currently the AudioTrack thread is not created if there are no callbacks.
1639 // Would it ever make sense to run the thread, even without callbacks?
1640 // If so, then replace this by checks at each use for mCbf != NULL.
1641 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1642
Eric Laurent1703cdf2011-03-07 14:52:59 -08001643 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001644 if (mAwaitBoost) {
1645 mAwaitBoost = false;
1646 mLock.unlock();
1647 static const int32_t kMaxTries = 5;
1648 int32_t tryCounter = kMaxTries;
1649 uint32_t pollUs = 10000;
1650 do {
1651 int policy = sched_getscheduler(0);
1652 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1653 break;
1654 }
1655 usleep(pollUs);
1656 pollUs <<= 1;
1657 } while (tryCounter-- > 0);
1658 if (tryCounter < 0) {
1659 ALOGE("did not receive expected priority boost on time");
1660 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001661 // Run again immediately
1662 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001663 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001664
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001665 // Can only reference mCblk while locked
1666 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001667 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001668
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001669 // Check for track invalidation
1670 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001671 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1672 // AudioSystem cache. We should not exit here but after calling the callback so
1673 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001674 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Lajos Molnarf1063e22015-04-17 15:19:42 -07001675 status_t status __unused = restoreTrack_l("processAudioBuffer");
1676 // FIXME unused status
Andy Hung53c3b5f2014-12-15 16:42:05 -08001677 // after restoration, continue below to make sure that the loop and buffer events
1678 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001679 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001680 }
1681
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001682 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001683 bool active = mState == STATE_ACTIVE;
1684
1685 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1686 bool newUnderrun = false;
1687 if (flags & CBLK_UNDERRUN) {
1688#if 0
1689 // Currently in shared buffer mode, when the server reaches the end of buffer,
1690 // the track stays active in continuous underrun state. It's up to the application
1691 // to pause or stop the track, or set the position to a new offset within buffer.
1692 // This was some experimental code to auto-pause on underrun. Keeping it here
1693 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1694 if (mTransfer == TRANSFER_SHARED) {
1695 mState = STATE_PAUSED;
1696 active = false;
1697 }
1698#endif
1699 if (!mInUnderrun) {
1700 mInUnderrun = true;
1701 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001702 }
1703 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001704
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001705 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001706 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001707
1708 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001709 bool markerReached = false;
1710 size_t markerPosition = mMarkerPosition;
1711 // FIXME fails for wraparound, need 64 bits
1712 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1713 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001714 }
1715
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001716 // Determine number of new position callback(s) that will be needed, while locked
1717 size_t newPosCount = 0;
1718 size_t newPosition = mNewPosition;
1719 size_t updatePeriod = mUpdatePeriod;
1720 // FIXME fails for wraparound, need 64 bits
1721 if (updatePeriod > 0 && position >= newPosition) {
1722 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1723 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001724 }
1725
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001726 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001727 uint32_t sampleRate = mSampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001728 float speed = mPlaybackRate.mSpeed;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001729 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001730 if (mRefreshRemaining) {
1731 mRefreshRemaining = false;
1732 mRemainingFrames = notificationFrames;
1733 mRetryOnPartialBuffer = false;
1734 }
1735 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001736 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001737 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001738
Andy Hung53c3b5f2014-12-15 16:42:05 -08001739 // Determine the number of new loop callback(s) that will be needed, while locked.
1740 int loopCountNotifications = 0;
1741 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1742
1743 if (mLoopCount > 0) {
1744 int loopCount;
1745 size_t bufferPosition;
1746 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1747 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1748 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1749 mLoopCountNotified = loopCount; // discard any excess notifications
1750 } else if (mLoopCount < 0) {
1751 // FIXME: We're not accurate with notification count and position with infinite looping
1752 // since loopCount from server side will always return -1 (we could decrement it).
1753 size_t bufferPosition = mStaticProxy->getBufferPosition();
1754 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1755 loopPeriod = mLoopEnd - bufferPosition;
1756 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1757 size_t bufferPosition = mStaticProxy->getBufferPosition();
1758 loopPeriod = mFrameCount - bufferPosition;
1759 }
1760
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001761 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08001762 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001763 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1764
1765 mLock.unlock();
1766
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001767 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001768 struct timespec timeout;
1769 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1770 timeout.tv_nsec = 0;
1771
Glenn Kasten96f04882013-09-20 09:28:56 -07001772 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001773 switch (status) {
1774 case NO_ERROR:
1775 case DEAD_OBJECT:
1776 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001777 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001778 {
1779 AutoMutex lock(mLock);
1780 // The previously assigned value of waitStreamEnd is no longer valid,
1781 // since the mutex has been unlocked and either the callback handler
1782 // or another thread could have re-started the AudioTrack during that time.
1783 waitStreamEnd = mState == STATE_STOPPING;
1784 if (waitStreamEnd) {
1785 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001786 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001787 }
1788 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001789 if (waitStreamEnd && status != DEAD_OBJECT) {
1790 return NS_INACTIVE;
1791 }
1792 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001793 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001794 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001795 }
1796
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001797 // perform callbacks while unlocked
1798 if (newUnderrun) {
1799 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1800 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001801 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001802 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001803 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001804 }
1805 if (flags & CBLK_BUFFER_END) {
1806 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1807 }
1808 if (markerReached) {
1809 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1810 }
1811 while (newPosCount > 0) {
1812 size_t temp = newPosition;
1813 mCbf(EVENT_NEW_POS, mUserData, &temp);
1814 newPosition += updatePeriod;
1815 newPosCount--;
1816 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001817
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001818 if (mObservedSequence != sequence) {
1819 mObservedSequence = sequence;
1820 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001821 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001822 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001823 return NS_INACTIVE;
1824 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001825 }
1826
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001827 // if inactive, then don't run me again until re-started
1828 if (!active) {
1829 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001830 }
1831
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001832 // Compute the estimated time until the next timed event (position, markers, loops)
1833 // FIXME only for non-compressed audio
1834 uint32_t minFrames = ~0;
1835 if (!markerReached && position < markerPosition) {
1836 minFrames = markerPosition - position;
1837 }
1838 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08001839 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001840 minFrames = loopPeriod;
1841 }
Andy Hung2d85f092015-01-07 12:45:13 -08001842 if (updatePeriod > 0) {
1843 minFrames = min(minFrames, uint32_t(newPosition - position));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001844 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001845
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001846 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1847 static const uint32_t kPoll = 0;
1848 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1849 minFrames = kPoll * notificationFrames;
1850 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001851
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001852 // Convert frame units to time units
1853 nsecs_t ns = NS_WHENEVER;
1854 if (minFrames != (uint32_t) ~0) {
1855 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1856 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
Andy Hung8edb8dc2015-03-26 19:13:55 -07001857 ns = ((double)minFrames * 1000000000) / ((double)sampleRate * speed) + kFudgeNs;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001858 }
1859
1860 // If not supplying data by EVENT_MORE_DATA, then we're done
1861 if (mTransfer != TRANSFER_CALLBACK) {
1862 return ns;
1863 }
1864
1865 struct timespec timeout;
1866 const struct timespec *requested = &ClientProxy::kForever;
1867 if (ns != NS_WHENEVER) {
1868 timeout.tv_sec = ns / 1000000000LL;
1869 timeout.tv_nsec = ns % 1000000000LL;
1870 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1871 requested = &timeout;
1872 }
1873
1874 while (mRemainingFrames > 0) {
1875
1876 Buffer audioBuffer;
1877 audioBuffer.frameCount = mRemainingFrames;
1878 size_t nonContig;
1879 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1880 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001881 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001882 requested = &ClientProxy::kNonBlocking;
1883 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001884 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001885 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001886 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001887 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1888 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001889 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001890 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001891 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1892 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001893 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001894
Eric Laurent42a6f422013-08-29 14:35:05 -07001895 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001896 mRetryOnPartialBuffer = false;
1897 if (avail < mRemainingFrames) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001898 int64_t myns = ((double)(mRemainingFrames - avail) * 1100000000)
1899 / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001900 if (ns < 0 || myns < ns) {
1901 ns = myns;
1902 }
1903 return ns;
1904 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001905 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001906
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001907 size_t reqSize = audioBuffer.size;
1908 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001909 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001910
1911 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001912 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001913 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1914 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001915 return NS_NEVER;
1916 }
1917
1918 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001919 // The callback is done filling buffers
1920 // Keep this thread going to handle timed events and
1921 // still try to get more data in intervals of WAIT_PERIOD_MS
1922 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001923 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001924 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001925
Glenn Kasten138d6f92015-03-20 10:54:51 -07001926 size_t releasedFrames = writtenSize / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001927 audioBuffer.frameCount = releasedFrames;
1928 mRemainingFrames -= releasedFrames;
1929 if (misalignment >= releasedFrames) {
1930 misalignment -= releasedFrames;
1931 } else {
1932 misalignment = 0;
1933 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001934
1935 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001936
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001937 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1938 // if callback doesn't like to accept the full chunk
1939 if (writtenSize < reqSize) {
1940 continue;
1941 }
1942
1943 // There could be enough non-contiguous frames available to satisfy the remaining request
1944 if (mRemainingFrames <= nonContig) {
1945 continue;
1946 }
1947
1948#if 0
1949 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1950 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1951 // that total to a sum == notificationFrames.
1952 if (0 < misalignment && misalignment <= mRemainingFrames) {
1953 mRemainingFrames = misalignment;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001954 return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001955 }
1956#endif
1957
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001958 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001959 mRemainingFrames = notificationFrames;
1960 mRetryOnPartialBuffer = true;
1961
1962 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1963 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001964}
1965
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001966status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001967{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001968 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001969 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001970 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001971
Glenn Kastena47f3162012-11-07 10:13:08 -08001972 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08001973 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001974 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001975
Eric Laurentab5cdba2014-06-09 17:22:27 -07001976 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001977 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001978 return DEAD_OBJECT;
1979 }
1980
Glenn Kasten200092b2014-08-15 15:13:30 -07001981 // save the old static buffer position
Andy Hung4ede21d2014-12-12 15:37:34 -08001982 size_t bufferPosition = 0;
1983 int loopCount = 0;
1984 if (mStaticProxy != 0) {
1985 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1986 }
Glenn Kasten200092b2014-08-15 15:13:30 -07001987
1988 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001989 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001990 // It will also delete the strong references on previous IAudioTrack and IMemory.
1991 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Glenn Kastenae4b8792015-03-20 09:04:21 -07001992 status_t result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001993
1994 // take the frames that will be lost by track recreation into account in saved position
Andy Hung9b461582014-12-01 17:56:29 -08001995 // For streaming tracks, this is the amount we obtained from the user/client
1996 // (not the number actually consumed at the server - those are already lost).
Glenn Kasten200092b2014-08-15 15:13:30 -07001997 (void) updateAndGetPosition_l();
Andy Hung7ccdaad2015-03-20 00:38:32 -07001998 if (mStaticProxy == 0) {
Andy Hung9b461582014-12-01 17:56:29 -08001999 mPosition = mReleased;
2000 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002001
Glenn Kastena47f3162012-11-07 10:13:08 -08002002 if (result == NO_ERROR) {
Andy Hung4ede21d2014-12-12 15:37:34 -08002003 // Continue playback from last known position and restore loop.
2004 if (mStaticProxy != 0) {
2005 if (loopCount != 0) {
2006 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
2007 mLoopStart, mLoopEnd, loopCount);
2008 } else {
2009 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002010 if (bufferPosition == mFrameCount) {
2011 ALOGD("restoring track at end of static buffer");
2012 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002013 }
2014 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002015 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08002016 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08002017 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002018 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002019 if (result != NO_ERROR) {
2020 ALOGW("restoreTrack_l() failed status %d", result);
2021 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07002022 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002023 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002024
2025 return result;
2026}
2027
Glenn Kasten200092b2014-08-15 15:13:30 -07002028uint32_t AudioTrack::updateAndGetPosition_l()
2029{
2030 // This is the sole place to read server consumed frames
2031 uint32_t newServer = mProxy->getPosition();
2032 int32_t delta = newServer - mServer;
2033 mServer = newServer;
2034 // TODO There is controversy about whether there can be "negative jitter" in server position.
2035 // This should be investigated further, and if possible, it should be addressed.
2036 // A more definite failure mode is infrequent polling by client.
2037 // One could call (void)getPosition_l() in releaseBuffer(),
2038 // so mReleased and mPosition are always lock-step as best possible.
2039 // That should ensure delta never goes negative for infrequent polling
2040 // unless the server has more than 2^31 frames in its buffer,
2041 // in which case the use of uint32_t for these counters has bigger issues.
2042 if (delta < 0) {
2043 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
2044 delta = 0;
2045 }
2046 return mPosition += (uint32_t) delta;
2047}
2048
Andy Hung8edb8dc2015-03-26 19:13:55 -07002049bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed) const
2050{
2051 // applicable for mixing tracks only (not offloaded or direct)
2052 if (mStaticProxy != 0) {
2053 return true; // static tracks do not have issues with buffer sizing.
2054 }
2055 status_t status;
2056 uint32_t afLatency;
2057 status = AudioSystem::getLatency(mOutput, &afLatency);
2058 if (status != NO_ERROR) {
2059 ALOGE("getLatency(%d) failed status %d", mOutput, status);
2060 return false;
2061 }
2062
2063 size_t afFrameCount;
2064 status = AudioSystem::getFrameCount(mOutput, &afFrameCount);
2065 if (status != NO_ERROR) {
2066 ALOGE("getFrameCount(output=%d) status %d", mOutput, status);
2067 return false;
2068 }
2069
2070 uint32_t afSampleRate;
2071 status = AudioSystem::getSamplingRate(mOutput, &afSampleRate);
2072 if (status != NO_ERROR) {
2073 ALOGE("getSamplingRate(output=%d) status %d", mOutput, status);
2074 return false;
2075 }
2076
2077 const size_t minFrameCount =
2078 calculateMinFrameCount(afLatency, afFrameCount, afSampleRate, sampleRate, speed);
2079 ALOGV("isSampleRateSpeedAllowed_l mFrameCount %zu minFrameCount %zu",
2080 mFrameCount, minFrameCount);
2081 return mFrameCount >= minFrameCount;
2082}
2083
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002084status_t AudioTrack::setParameters(const String8& keyValuePairs)
2085{
2086 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07002087 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002088}
2089
Glenn Kastence703742013-07-19 16:33:58 -07002090status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
2091{
Glenn Kasten53cec222013-08-29 09:01:02 -07002092 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07002093 // FIXME not implemented for fast tracks; should use proxy and SSQ
2094 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
2095 return INVALID_OPERATION;
2096 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002097
2098 switch (mState) {
2099 case STATE_ACTIVE:
2100 case STATE_PAUSED:
2101 break; // handle below
2102 case STATE_FLUSHED:
2103 case STATE_STOPPED:
2104 return WOULD_BLOCK;
2105 case STATE_STOPPING:
2106 case STATE_PAUSED_STOPPING:
2107 if (!isOffloaded_l()) {
2108 return INVALID_OPERATION;
2109 }
2110 break; // offloaded tracks handled below
2111 default:
2112 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
2113 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07002114 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002115
Eric Laurent275e8e92014-11-30 15:14:47 -08002116 if (mCblk->mFlags & CBLK_INVALID) {
2117 restoreTrack_l("getTimestamp");
2118 }
2119
Glenn Kasten200092b2014-08-15 15:13:30 -07002120 // The presented frame count must always lag behind the consumed frame count.
2121 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002122 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002123 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07002124 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002125 return status;
2126 }
2127 if (isOffloadedOrDirect_l()) {
2128 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
2129 // use cached paused position in case another offloaded track is running.
2130 timestamp.mPosition = mPausedPosition;
2131 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
2132 return NO_ERROR;
2133 }
2134
2135 // Check whether a pending flush or stop has completed, as those commands may
2136 // be asynchronous or return near finish.
2137 if (mStartUs != 0 && mSampleRate != 0) {
2138 static const int kTimeJitterUs = 100000; // 100 ms
2139 static const int k1SecUs = 1000000;
2140
2141 const int64_t timeNow = getNowUs();
2142
2143 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
2144 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
2145 if (timestampTimeUs < mStartUs) {
2146 return WOULD_BLOCK; // stale timestamp time, occurs before start.
2147 }
2148 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002149 const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002150 / ((double)mSampleRate * mPlaybackRate.mSpeed);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002151
2152 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2153 // Verify that the counter can't count faster than the sample rate
2154 // since the start time. If greater, then that means we have failed
2155 // to completely flush or stop the previous playing track.
2156 ALOGW("incomplete flush or stop:"
2157 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2158 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2159 timestamp.mPosition);
2160 return WOULD_BLOCK;
2161 }
2162 }
2163 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
2164 }
2165 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002166 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2167 (void) updateAndGetPosition_l();
2168 // Server consumed (mServer) and presented both use the same server time base,
2169 // and server consumed is always >= presented.
2170 // The delta between these represents the number of frames in the buffer pipeline.
2171 // If this delta between these is greater than the client position, it means that
2172 // actually presented is still stuck at the starting line (figuratively speaking),
2173 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
2174 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2175 return INVALID_OPERATION;
2176 }
2177 // Convert timestamp position from server time base to client time base.
2178 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2179 // But if we change it to 64-bit then this could fail.
2180 // If (mPosition - mServer) can be negative then should use:
2181 // (int32_t)(mPosition - mServer)
2182 timestamp.mPosition += mPosition - mServer;
2183 // Immediately after a call to getPosition_l(), mPosition and
2184 // mServer both represent the same frame position. mPosition is
2185 // in client's point of view, and mServer is in server's point of
2186 // view. So the difference between them is the "fudge factor"
2187 // between client and server views due to stop() and/or new
2188 // IAudioTrack. And timestamp.mPosition is initially in server's
2189 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002190 }
2191 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002192}
2193
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002194String8 AudioTrack::getParameters(const String8& keys)
2195{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002196 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002197 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002198 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002199 } else {
2200 return String8::empty();
2201 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002202}
2203
Glenn Kasten23a75452014-01-13 10:37:17 -08002204bool AudioTrack::isOffloaded() const
2205{
2206 AutoMutex lock(mLock);
2207 return isOffloaded_l();
2208}
2209
Eric Laurentab5cdba2014-06-09 17:22:27 -07002210bool AudioTrack::isDirect() const
2211{
2212 AutoMutex lock(mLock);
2213 return isDirect_l();
2214}
2215
2216bool AudioTrack::isOffloadedOrDirect() const
2217{
2218 AutoMutex lock(mLock);
2219 return isOffloadedOrDirect_l();
2220}
2221
2222
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002223status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002224{
2225
2226 const size_t SIZE = 256;
2227 char buffer[SIZE];
2228 String8 result;
2229
2230 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002231 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002232 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002233 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002234 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002235 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002236 result.append(buffer);
Andy Hung8edb8dc2015-03-26 19:13:55 -07002237 snprintf(buffer, 255, " sample rate(%u), speed(%f), status(%d)\n",
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002238 mSampleRate, mPlaybackRate.mSpeed, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002239 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002240 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002241 result.append(buffer);
2242 ::write(fd, result.string(), result.size());
2243 return NO_ERROR;
2244}
2245
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002246uint32_t AudioTrack::getUnderrunFrames() const
2247{
2248 AutoMutex lock(mLock);
2249 return mProxy->getUnderrunFrames();
2250}
2251
2252// =========================================================================
2253
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002254void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002255{
2256 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2257 if (audioTrack != 0) {
2258 AutoMutex lock(audioTrack->mLock);
2259 audioTrack->mProxy->binderDied();
2260 }
2261}
2262
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002263// =========================================================================
2264
2265AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002266 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2267 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002268{
2269}
2270
2271AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002272{
2273}
2274
2275bool AudioTrack::AudioTrackThread::threadLoop()
2276{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002277 {
2278 AutoMutex _l(mMyLock);
2279 if (mPaused) {
2280 mMyCond.wait(mMyLock);
2281 // caller will check for exitPending()
2282 return true;
2283 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002284 if (mIgnoreNextPausedInt) {
2285 mIgnoreNextPausedInt = false;
2286 mPausedInt = false;
2287 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002288 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002289 if (mPausedNs > 0) {
2290 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2291 } else {
2292 mMyCond.wait(mMyLock);
2293 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002294 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002295 return true;
2296 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002297 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002298 if (exitPending()) {
2299 return false;
2300 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002301 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002302 switch (ns) {
2303 case 0:
2304 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002305 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002306 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002307 return true;
2308 case NS_NEVER:
2309 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002310 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08002311 // Event driven: call wake() when callback notifications conditions change.
2312 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002313 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002314 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002315 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002316 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002317 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002318 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002319}
2320
Glenn Kasten3acbd052012-02-28 10:39:56 -08002321void AudioTrack::AudioTrackThread::requestExit()
2322{
2323 // must be in this order to avoid a race condition
2324 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002325 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002326}
2327
2328void AudioTrack::AudioTrackThread::pause()
2329{
2330 AutoMutex _l(mMyLock);
2331 mPaused = true;
2332}
2333
2334void AudioTrack::AudioTrackThread::resume()
2335{
2336 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002337 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002338 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002339 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002340 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002341 mMyCond.signal();
2342 }
2343}
2344
Andy Hung3c09c782014-12-29 18:39:32 -08002345void AudioTrack::AudioTrackThread::wake()
2346{
2347 AutoMutex _l(mMyLock);
2348 if (!mPaused && mPausedInt && mPausedNs > 0) {
2349 // audio track is active and internally paused with timeout.
2350 mIgnoreNextPausedInt = true;
2351 mPausedInt = false;
2352 mMyCond.signal();
2353 }
2354}
2355
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002356void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2357{
2358 AutoMutex _l(mMyLock);
2359 mPausedInt = true;
2360 mPausedNs = ns;
2361}
2362
Glenn Kasten40bc9062015-03-20 09:09:33 -07002363} // namespace android