blob: 89138e29a18683162cdf5df44a4c75f688d51123 [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 Hung8edb8dc2015-03-26 19:13:55 -070059// Must match similar computation in createTrack_l in Threads.cpp.
60// TODO: Move to a common library
61static size_t calculateMinFrameCount(
62 uint32_t afLatencyMs, uint32_t afFrameCount, uint32_t afSampleRate,
63 uint32_t sampleRate, float speed)
64{
65 // Ensure that buffer depth covers at least audio hardware latency
66 uint32_t minBufCount = afLatencyMs / ((1000 * afFrameCount) / afSampleRate);
67 if (minBufCount < 2) {
68 minBufCount = 2;
69 }
70 ALOGV("calculateMinFrameCount afLatency %u afFrameCount %u afSampleRate %u "
71 "sampleRate %u speed %f minBufCount: %u",
72 afLatencyMs, afFrameCount, afSampleRate, sampleRate, speed, minBufCount);
73 return minBufCount * sourceFramesNeededWithTimestretch(
74 sampleRate, afFrameCount, afSampleRate, speed);
75}
76
Chia-chi Yeh33005a92010-06-16 06:33:13 +080077// static
78status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -080079 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -080080 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +080081 uint32_t sampleRate)
82{
Glenn Kastend65d73c2012-06-22 17:21:07 -070083 if (frameCount == NULL) {
84 return BAD_VALUE;
85 }
Glenn Kasten04cd0182012-06-25 11:49:27 -070086
Andy Hung0e48d252015-01-26 11:43:15 -080087 // FIXME handle in server, like createTrack_l(), possible missing info:
Glenn Kastene0fa4672012-04-24 14:35:14 -070088 // audio_io_handle_t output
89 // audio_format_t format
90 // audio_channel_mask_t channelMask
Andy Hung0e48d252015-01-26 11:43:15 -080091 // audio_output_flags_t flags (FAST)
Glenn Kasten3b16c762012-11-14 08:44:39 -080092 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -080093 status_t status;
94 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
95 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -080096 ALOGE("Unable to query output sample rate for stream type %d; status %d",
97 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -080098 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +080099 }
Glenn Kastene33054e2012-11-14 12:54:39 -0800100 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -0800101 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
102 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -0800103 ALOGE("Unable to query output frame count for stream type %d; status %d",
104 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800105 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800106 }
107 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -0800108 status = AudioSystem::getOutputLatency(&afLatency, streamType);
109 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -0800110 ALOGE("Unable to query output latency for stream type %d; status %d",
111 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800112 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800113 }
114
Andy Hung8edb8dc2015-03-26 19:13:55 -0700115 // When called from createTrack, speed is 1.0f (normal speed).
116 // This is rechecked again on setting playback rate (TODO: on setting sample rate, too).
117 *frameCount = calculateMinFrameCount(afLatency, afFrameCount, afSampleRate, sampleRate, 1.0f);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800118
Andy Hung0e48d252015-01-26 11:43:15 -0800119 // The formula above should always produce a non-zero value under normal circumstances:
120 // AudioTrack.SAMPLE_RATE_HZ_MIN <= sampleRate <= AudioTrack.SAMPLE_RATE_HZ_MAX.
121 // 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 -0800122 if (*frameCount == 0) {
Andy Hung0e48d252015-01-26 11:43:15 -0800123 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %u",
Glenn Kasten66a04672014-01-08 08:53:44 -0800124 streamType, sampleRate);
125 return BAD_VALUE;
126 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700127 ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, afSampleRate=%u, afLatency=%u",
128 *frameCount, afFrameCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800129 return NO_ERROR;
130}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800131
132// ---------------------------------------------------------------------------
133
134AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700135 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800136 mIsTimed(false),
137 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800138 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700139 mPausedPosition(0),
140 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800141{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700142 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
143 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
144 mAttributes.flags = 0x0;
145 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800146}
147
148AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800149 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800150 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800151 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700152 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800153 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700154 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800155 callback_t cbf,
156 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800157 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800158 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000159 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800160 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800161 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700162 pid_t pid,
163 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700164 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800165 mIsTimed(false),
166 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800167 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700168 mPausedPosition(0),
169 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800170{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700171 mStatus = set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700172 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800173 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700174 offloadInfo, uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800175}
176
Andreas Huberc8139852012-01-18 10:51:55 -0800177AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800178 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800179 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800180 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700181 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800182 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700183 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800184 callback_t cbf,
185 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800186 uint32_t notificationFrames,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800187 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000188 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800189 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800190 int uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700191 pid_t pid,
192 const audio_attributes_t* pAttributes)
Glenn Kasten87913512011-06-22 16:15:25 -0700193 : mStatus(NO_INIT),
John Grossman4ff14ba2012-02-08 16:37:41 -0800194 mIsTimed(false),
195 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800196 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700197 mPausedPosition(0),
198 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800199{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700200 mStatus = set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800201 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800202 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700203 uid, pid, pAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800204}
205
206AudioTrack::~AudioTrack()
207{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800208 if (mStatus == NO_ERROR) {
209 // Make sure that callback function exits in the case where
210 // it is looping on buffer full condition in obtainBuffer().
211 // Otherwise the callback thread will never exit.
212 stop();
213 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100214 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800215 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800216 mAudioTrackThread->requestExitAndWait();
217 mAudioTrackThread.clear();
218 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800219 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700220 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700221 mCblkMemory.clear();
222 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800223 IPCThreadState::self()->flushCommands();
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700224 ALOGV("~AudioTrack, releasing session id %d from %d on behalf of %d",
225 mSessionId, IPCThreadState::self()->getCallingPid(), mClientPid);
Marco Nelissend457c972014-02-11 08:47:07 -0800226 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800227 }
228}
229
230status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800231 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800232 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800233 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700234 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800235 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700236 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800237 callback_t cbf,
238 void* user,
Glenn Kasten838b3d82014-02-27 15:30:41 -0800239 uint32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800240 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700241 bool threadCanCallJava,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800242 int sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000243 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800244 const audio_offload_info_t *offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -0800245 int uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700246 pid_t pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700247 const audio_attributes_t* pAttributes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800248{
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800249 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700250 "flags #%x, notificationFrames %u, sessionId %d, transferType %d, uid %d, pid %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800251 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700252 sessionId, transferType, uid, pid);
Glenn Kasten86f04662014-02-24 15:13:05 -0800253
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800254 switch (transferType) {
255 case TRANSFER_DEFAULT:
256 if (sharedBuffer != 0) {
257 transferType = TRANSFER_SHARED;
258 } else if (cbf == NULL || threadCanCallJava) {
259 transferType = TRANSFER_SYNC;
260 } else {
261 transferType = TRANSFER_CALLBACK;
262 }
263 break;
264 case TRANSFER_CALLBACK:
265 if (cbf == NULL || sharedBuffer != 0) {
266 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
267 return BAD_VALUE;
268 }
269 break;
270 case TRANSFER_OBTAIN:
271 case TRANSFER_SYNC:
272 if (sharedBuffer != 0) {
273 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
274 return BAD_VALUE;
275 }
276 break;
277 case TRANSFER_SHARED:
278 if (sharedBuffer == 0) {
279 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
280 return BAD_VALUE;
281 }
282 break;
283 default:
284 ALOGE("Invalid transfer type %d", transferType);
285 return BAD_VALUE;
286 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800287 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800288 mTransfer = transferType;
289
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700290 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
291 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800292
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700293 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700294
Glenn Kasten53cec222013-08-29 09:01:02 -0700295 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700296 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000297 ALOGE("Track already in use");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800298 return INVALID_OPERATION;
299 }
300
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800301 // handle default values first.
Eric Laurente83b55d2014-11-14 10:06:21 -0800302 if (streamType == AUDIO_STREAM_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700303 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800304 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700305 if (pAttributes == NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800306 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700307 ALOGE("Invalid stream type %d", streamType);
308 return BAD_VALUE;
309 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700310 mStreamType = streamType;
Eric Laurente83b55d2014-11-14 10:06:21 -0800311
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700312 } else {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700313 // stream type shouldn't be looked at, this track has audio attributes
314 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700315 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
316 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800317 mStreamType = AUDIO_STREAM_DEFAULT;
Eric Laurentc6bd5db2015-03-09 16:29:33 -0700318 if ((mAttributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
319 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
320 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800321 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700322
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800323 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800324 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700325 format = AUDIO_FORMAT_PCM_16_BIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800326 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800327
328 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700329 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800330 ALOGE("Invalid format %#x", format);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800331 return BAD_VALUE;
332 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800333 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700334
Glenn Kasten8ba90322013-10-30 11:29:27 -0700335 if (!audio_is_output_channel(channelMask)) {
336 ALOGE("Invalid channel mask %#x", channelMask);
337 return BAD_VALUE;
338 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800339 mChannelMask = channelMask;
Andy Hunge5412692014-05-16 11:25:07 -0700340 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800341 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700342
Eric Laurentc2f1f072009-07-17 12:17:14 -0700343 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100344 // or offload was requested
345 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
346 || !audio_is_linear_pcm(format)) {
347 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
348 ? "Offload request, forcing to Direct Output"
349 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700350 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800351 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700352 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700353 }
354
Eric Laurentd1f69b02014-12-15 14:33:13 -0800355 // force direct flag if HW A/V sync requested
356 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
357 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
358 }
359
Glenn Kastenb7730382014-04-30 15:50:31 -0700360 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
361 if (audio_is_linear_pcm(format)) {
362 mFrameSize = channelCount * audio_bytes_per_sample(format);
363 } else {
364 mFrameSize = sizeof(uint8_t);
365 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800366 } else {
Glenn Kastenb7730382014-04-30 15:50:31 -0700367 ALOG_ASSERT(audio_is_linear_pcm(format));
368 mFrameSize = channelCount * audio_bytes_per_sample(format);
Glenn Kastenb7730382014-04-30 15:50:31 -0700369 // createTrack will return an error if PCM format is not supported by server,
370 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800371 }
372
Eric Laurent0d6db582014-11-12 18:39:44 -0800373 // sampling rate must be specified for direct outputs
374 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
375 return BAD_VALUE;
376 }
377 mSampleRate = sampleRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700378 mSpeed = AUDIO_TIMESTRETCH_SPEED_NORMAL;
379 mPitch = AUDIO_TIMESTRETCH_PITCH_NORMAL;
Eric Laurent0d6db582014-11-12 18:39:44 -0800380
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800381 // Make copy of input parameter offloadInfo so that in the future:
382 // (a) createTrack_l doesn't need it as an input parameter
383 // (b) we can support re-creation of offloaded tracks
384 if (offloadInfo != NULL) {
385 mOffloadInfoCopy = *offloadInfo;
386 mOffloadInfo = &mOffloadInfoCopy;
387 } else {
388 mOffloadInfo = NULL;
389 }
390
Glenn Kasten66e46352014-01-16 17:44:23 -0800391 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
392 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800393 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800394 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800395 mReqFrameCount = frameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -0700396 mNotificationFramesReq = notificationFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800397 mNotificationFramesAct = 0;
Eric Laurentcaf7f482014-11-25 17:50:47 -0800398 if (sessionId == AUDIO_SESSION_ALLOCATE) {
399 mSessionId = AudioSystem::newAudioUniqueId();
400 } else {
401 mSessionId = sessionId;
402 }
Marco Nelissend457c972014-02-11 08:47:07 -0800403 int callingpid = IPCThreadState::self()->getCallingPid();
404 int mypid = getpid();
405 if (uid == -1 || (callingpid != mypid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800406 mClientUid = IPCThreadState::self()->getCallingUid();
407 } else {
408 mClientUid = uid;
409 }
Marco Nelissend457c972014-02-11 08:47:07 -0800410 if (pid == -1 || (callingpid != mypid)) {
411 mClientPid = callingpid;
412 } else {
413 mClientPid = pid;
414 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700415 mAuxEffectId = 0;
Glenn Kasten093000f2012-05-03 09:35:36 -0700416 mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700417 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700418
Glenn Kastena997e7a2012-08-07 09:44:19 -0700419 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700420 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700421 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
Glenn Kastenbfd31842015-03-20 09:01:44 -0700422 // thread begins in paused state, and will not reference us until start()
Glenn Kastena997e7a2012-08-07 09:44:19 -0700423 }
424
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800425 // create the IAudioTrack
Eric Laurent0d6db582014-11-12 18:39:44 -0800426 status_t status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800427
Glenn Kastena997e7a2012-08-07 09:44:19 -0700428 if (status != NO_ERROR) {
429 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100430 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
431 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700432 mAudioTrackThread.clear();
433 }
434 return status;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700435 }
436
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800437 mStatus = NO_ERROR;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800438 mState = STATE_STOPPED;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800439 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800440 mLoopCount = 0;
441 mLoopStart = 0;
442 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800443 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800444 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700445 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800446 mNewPosition = 0;
447 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700448 mServer = 0;
449 mPosition = 0;
450 mReleased = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700451 mStartUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800452 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800453 mSequence = 1;
454 mObservedSequence = mSequence;
455 mInUnderrun = false;
456
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800457 return NO_ERROR;
458}
459
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800460// -------------------------------------------------------------------------
461
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100462status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800463{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800464 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100465
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800466 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100467 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800468 }
469
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800470 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800471
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800472 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100473 if (previousState == STATE_PAUSED_STOPPING) {
474 mState = STATE_STOPPING;
475 } else {
476 mState = STATE_ACTIVE;
477 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700478 (void) updateAndGetPosition_l();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800479 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
480 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700481 mPosition = 0;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700482 // For offloaded tracks, we don't know if the hardware counters are really zero here,
483 // since the flush is asynchronous and stop may not fully drain.
484 // We save the time when the track is started to later verify whether
485 // the counters are realistic (i.e. start from zero after this time).
486 mStartUs = getNowUs();
487
Eric Laurentec9a0322013-08-28 10:23:01 -0700488 // force refresh of remaining frames by processAudioBuffer() as last
489 // write before stop could be partial.
490 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800491 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700492 mNewPosition = mPosition + mUpdatePeriod;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700493 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800494
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800495 sp<AudioTrackThread> t = mAudioTrackThread;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800496 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100497 if (previousState == STATE_STOPPING) {
498 mProxy->interrupt();
499 } else {
500 t->resume();
501 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800502 } else {
503 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
504 get_sched_policy(0, &mPreviousSchedulingGroup);
505 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
506 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800507
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800508 status_t status = NO_ERROR;
509 if (!(flags & CBLK_INVALID)) {
510 status = mAudioTrack->start();
511 if (status == DEAD_OBJECT) {
512 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800513 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800514 }
515 if (flags & CBLK_INVALID) {
516 status = restoreTrack_l("start");
517 }
518
519 if (status != NO_ERROR) {
520 ALOGE("start() status %d", status);
521 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800522 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100523 if (previousState != STATE_STOPPING) {
524 t->pause();
525 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800526 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700527 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700528 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800529 }
530 }
531
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100532 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800533}
534
535void AudioTrack::stop()
536{
537 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700538 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800539 return;
540 }
541
Glenn Kasten23a75452014-01-13 10:37:17 -0800542 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100543 mState = STATE_STOPPING;
544 } else {
545 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -0700546 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100547 }
548
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800549 mProxy->interrupt();
550 mAudioTrack->stop();
551 // the playback head position will reset to 0, so if a marker is set, we need
552 // to activate it again
553 mMarkerReached = false;
Andy Hung9b461582014-12-01 17:56:29 -0800554
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800555 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800556 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800557 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
558 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800559 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100560
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800561 sp<AudioTrackThread> t = mAudioTrackThread;
562 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800563 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100564 t->pause();
565 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800566 } else {
567 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
568 set_sched_policy(0, mPreviousSchedulingGroup);
569 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800570}
571
572bool AudioTrack::stopped() const
573{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800574 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800575 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800576}
577
578void AudioTrack::flush()
579{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800580 if (mSharedBuffer != 0) {
581 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800582 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800583 AutoMutex lock(mLock);
584 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
585 return;
586 }
587 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800588}
589
Eric Laurent1703cdf2011-03-07 14:52:59 -0800590void AudioTrack::flush_l()
591{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800592 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700593
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700594 // clear playback marker and periodic update counter
595 mMarkerPosition = 0;
596 mMarkerReached = false;
597 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100598 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700599
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800600 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700601 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800602 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100603 mProxy->interrupt();
604 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800605 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800606 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800607}
608
609void AudioTrack::pause()
610{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800611 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100612 if (mState == STATE_ACTIVE) {
613 mState = STATE_PAUSED;
614 } else if (mState == STATE_STOPPING) {
615 mState = STATE_PAUSED_STOPPING;
616 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800617 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800618 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800619 mProxy->interrupt();
620 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800621
Marco Nelissen3a90f282014-03-10 11:21:43 -0700622 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700623 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700624 // An offload output can be re-used between two audio tracks having
625 // the same configuration. A timestamp query for a paused track
626 // while the other is running would return an incorrect time.
627 // To fix this, cache the playback position on a pause() and return
628 // this time when requested until the track is resumed.
629
630 // OffloadThread sends HAL pause in its threadLoop. Time saved
631 // here can be slightly off.
632
633 // TODO: check return code for getRenderPosition.
634
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800635 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800636 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
637 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
638 }
639 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800640}
641
Eric Laurentbe916aa2010-06-01 23:49:17 -0700642status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800643{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700644 // This duplicates a test by AudioTrack JNI, but that is not the only caller
645 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
646 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700647 return BAD_VALUE;
648 }
649
Eric Laurent1703cdf2011-03-07 14:52:59 -0800650 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800651 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
652 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800653
Glenn Kastenc56f3422014-03-21 17:53:17 -0700654 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700655
Glenn Kasten23a75452014-01-13 10:37:17 -0800656 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700657 mAudioTrack->signal();
658 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700659 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800660}
661
Glenn Kastenb1c09932012-02-27 16:21:04 -0800662status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800663{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800664 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700665}
666
Eric Laurent2beeb502010-07-16 07:43:46 -0700667status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700668{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700669 // This duplicates a test by AudioTrack JNI, but that is not the only caller
670 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700671 return BAD_VALUE;
672 }
673
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800674 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700675 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800676 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700677
678 return NO_ERROR;
679}
680
Glenn Kastena5224f32012-01-04 12:41:44 -0800681void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700682{
683 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800684 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700685 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800686}
687
Glenn Kasten3b16c762012-11-14 08:44:39 -0800688status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800689{
Andy Hung5cbb5782015-03-27 18:39:59 -0700690 AutoMutex lock(mLock);
691 if (rate == mSampleRate) {
692 return NO_ERROR;
693 }
694 if (mIsTimed || isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800695 return INVALID_OPERATION;
696 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800697 if (mOutput == AUDIO_IO_HANDLE_NONE) {
698 return NO_INIT;
699 }
Andy Hung5cbb5782015-03-27 18:39:59 -0700700 // NOTE: it is theoretically possible, but highly unlikely, that a device change
701 // could mean a previously allowed sampling rate is no longer allowed.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800702 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800703 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700704 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800705 }
Andy Hungcd044842014-08-07 11:04:34 -0700706 if (rate == 0 || rate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700707 return BAD_VALUE;
708 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700709 // TODO: Should we also check if the buffer size is compatible?
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800710
Glenn Kastene3aa6592012-12-04 12:22:46 -0800711 mSampleRate = rate;
712 mProxy->setSampleRate(rate);
713
Eric Laurent57326622009-07-07 07:10:45 -0700714 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800715}
716
Glenn Kastena5224f32012-01-04 12:41:44 -0800717uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800718{
John Grossman4ff14ba2012-02-08 16:37:41 -0800719 if (mIsTimed) {
Glenn Kasten3b16c762012-11-14 08:44:39 -0800720 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800721 }
722
Eric Laurent1703cdf2011-03-07 14:52:59 -0800723 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700724
725 // sample rate can be updated during playback by the offloaded decoder so we need to
726 // query the HAL and update if needed.
727// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700728 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700729 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700730 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700731 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700732 if (status == NO_ERROR) {
733 mSampleRate = sampleRate;
734 }
735 }
736 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800737 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800738}
739
Andy Hung8edb8dc2015-03-26 19:13:55 -0700740status_t AudioTrack::setPlaybackRate(float speed, float pitch)
741{
742 if (speed < AUDIO_TIMESTRETCH_SPEED_MIN
743 || speed > AUDIO_TIMESTRETCH_SPEED_MAX
744 || pitch < AUDIO_TIMESTRETCH_PITCH_MIN
745 || pitch > AUDIO_TIMESTRETCH_PITCH_MAX) {
746 return BAD_VALUE;
747 }
748 AutoMutex lock(mLock);
749 if (speed == mSpeed && pitch == mPitch) {
750 return NO_ERROR;
751 }
752 if (mIsTimed || isOffloadedOrDirect_l()) {
753 return INVALID_OPERATION;
754 }
755 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
756 return INVALID_OPERATION;
757 }
758 // Check if the buffer size is compatible.
759 if (!isSampleRateSpeedAllowed_l(mSampleRate, speed)) {
760 ALOGV("setPlaybackRate(%f, %f) failed", speed, pitch);
761 return BAD_VALUE;
762 }
763 mSpeed = speed;
764 mPitch = pitch;
765 mProxy->setPlaybackRate(speed, pitch);
766 return NO_ERROR;
767}
768
769void AudioTrack::getPlaybackRate(float *speed, float *pitch) const
770{
771 AutoMutex lock(mLock);
772 *speed = mSpeed;
773 *pitch = mPitch;
774}
775
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800776status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
777{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700778 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800779 return INVALID_OPERATION;
780 }
781
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800782 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800783 ;
784 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
785 loopEnd - loopStart >= MIN_LOOP) {
786 ;
787 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800788 return BAD_VALUE;
789 }
790
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800791 AutoMutex lock(mLock);
792 // See setPosition() regarding setting parameters such as loop points or position while active
793 if (mState == STATE_ACTIVE) {
794 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700795 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800796 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800797 return NO_ERROR;
798}
799
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800800void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
801{
Andy Hung4ede21d2014-12-12 15:37:34 -0800802 // We do not update the periodic notification point.
803 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
804 mLoopCount = loopCount;
805 mLoopEnd = loopEnd;
806 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800807 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800808 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -0800809
810 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800811}
812
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800813status_t AudioTrack::setMarkerPosition(uint32_t marker)
814{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700815 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700816 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700817 return INVALID_OPERATION;
818 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800819
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800820 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800821 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700822 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800823
Andy Hung3c09c782014-12-29 18:39:32 -0800824 sp<AudioTrackThread> t = mAudioTrackThread;
825 if (t != 0) {
826 t->wake();
827 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800828 return NO_ERROR;
829}
830
Glenn Kastena5224f32012-01-04 12:41:44 -0800831status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800832{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700833 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100834 return INVALID_OPERATION;
835 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700836 if (marker == NULL) {
837 return BAD_VALUE;
838 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800839
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800840 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800841 *marker = mMarkerPosition;
842
843 return NO_ERROR;
844}
845
846status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
847{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700848 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -0700849 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700850 return INVALID_OPERATION;
851 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800852
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800853 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -0700854 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800855 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -0800856
Andy Hung3c09c782014-12-29 18:39:32 -0800857 sp<AudioTrackThread> t = mAudioTrackThread;
858 if (t != 0) {
859 t->wake();
860 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800861 return NO_ERROR;
862}
863
Glenn Kastena5224f32012-01-04 12:41:44 -0800864status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800865{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700866 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100867 return INVALID_OPERATION;
868 }
Glenn Kastend65d73c2012-06-22 17:21:07 -0700869 if (updatePeriod == NULL) {
870 return BAD_VALUE;
871 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800872
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800873 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800874 *updatePeriod = mUpdatePeriod;
875
876 return NO_ERROR;
877}
878
879status_t AudioTrack::setPosition(uint32_t position)
880{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700881 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700882 return INVALID_OPERATION;
883 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800884 if (position > mFrameCount) {
885 return BAD_VALUE;
886 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800887
Eric Laurent1703cdf2011-03-07 14:52:59 -0800888 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800889 // Currently we require that the player is inactive before setting parameters such as position
890 // or loop points. Otherwise, there could be a race condition: the application could read the
891 // current position, compute a new position or loop parameters, and then set that position or
892 // loop parameters but it would do the "wrong" thing since the position has continued to advance
893 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
894 // to specify how it wants to handle such scenarios.
895 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700896 return INVALID_OPERATION;
897 }
Andy Hung9b461582014-12-01 17:56:29 -0800898 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -0700899 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800900 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -0800901
902 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800903 return NO_ERROR;
904}
905
Glenn Kasten200092b2014-08-15 15:13:30 -0700906status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800907{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700908 if (position == NULL) {
909 return BAD_VALUE;
910 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800911
Eric Laurent1703cdf2011-03-07 14:52:59 -0800912 AutoMutex lock(mLock);
Eric Laurentab5cdba2014-06-09 17:22:27 -0700913 if (isOffloadedOrDirect_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100914 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800915
Eric Laurentab5cdba2014-06-09 17:22:27 -0700916 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800917 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
918 *position = mPausedPosition;
919 return NO_ERROR;
920 }
921
Glenn Kasten142f5192014-03-25 17:44:59 -0700922 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100923 uint32_t halFrames;
924 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
925 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700926 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
927 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100928 *position = dspFrames;
929 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -0800930 if (mCblk->mFlags & CBLK_INVALID) {
931 restoreTrack_l("getPosition");
932 }
933
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100934 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -0700935 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
936 0 : updateAndGetPosition_l();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100937 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800938 return NO_ERROR;
939}
940
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000941status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800942{
943 if (mSharedBuffer == 0 || mIsTimed) {
944 return INVALID_OPERATION;
945 }
946 if (position == NULL) {
947 return BAD_VALUE;
948 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800949
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800950 AutoMutex lock(mLock);
951 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800952 return NO_ERROR;
953}
Glenn Kasten9c6745f2012-11-30 13:35:29 -0800954
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800955status_t AudioTrack::reload()
956{
Eric Laurentab5cdba2014-06-09 17:22:27 -0700957 if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -0800958 return INVALID_OPERATION;
959 }
960
Eric Laurent1703cdf2011-03-07 14:52:59 -0800961 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800962 // See setPosition() regarding setting parameters such as loop points or position while active
963 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700964 return INVALID_OPERATION;
965 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800966 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -0800967 (void) updateAndGetPosition_l();
968 mPosition = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800969#if 0
Andy Hung9b461582014-12-01 17:56:29 -0800970 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -0800971 // of loop count. Historically we have not restored loop count, start, end,
972 // but it makes sense if one desires to repeat playing a particular sound.
973 if (mLoopCount != 0) {
974 mLoopCountNotified = mLoopCount;
975 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
976 }
977#endif
Andy Hung9b461582014-12-01 17:56:29 -0800978 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800979 return NO_ERROR;
980}
981
Glenn Kasten38e905b2014-01-13 10:21:48 -0800982audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -0700983{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800984 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100985 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -0800986}
987
Paul McLeanaa981192015-03-21 09:55:15 -0700988status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
989 AutoMutex lock(mLock);
990 if (mSelectedDeviceId != deviceId) {
991 mSelectedDeviceId = deviceId;
992 return restoreTrack_l("setOutputDevice() restart");
993 } else {
994 return NO_ERROR;
995 }
996}
997
998audio_port_handle_t AudioTrack::getOutputDevice() {
999 AutoMutex lock(mLock);
1000 return mSelectedDeviceId;
1001}
1002
Eric Laurentbe916aa2010-06-01 23:49:17 -07001003status_t AudioTrack::attachAuxEffect(int effectId)
1004{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001005 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001006 status_t status = mAudioTrack->attachAuxEffect(effectId);
1007 if (status == NO_ERROR) {
1008 mAuxEffectId = effectId;
1009 }
1010 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -07001011}
1012
Eric Laurente83b55d2014-11-14 10:06:21 -08001013audio_stream_type_t AudioTrack::streamType() const
1014{
1015 if (mStreamType == AUDIO_STREAM_DEFAULT) {
1016 return audio_attributes_to_stream_type(&mAttributes);
1017 }
1018 return mStreamType;
1019}
1020
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001021// -------------------------------------------------------------------------
1022
Eric Laurent1703cdf2011-03-07 14:52:59 -08001023// must be called with mLock held
Glenn Kasten200092b2014-08-15 15:13:30 -07001024status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001025{
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001026 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
1027 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001028 ALOGE("Could not get audioflinger");
1029 return NO_INIT;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001030 }
1031
Eric Laurente83b55d2014-11-14 10:06:21 -08001032 audio_io_handle_t output;
1033 audio_stream_type_t streamType = mStreamType;
1034 audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
Eric Laurente83b55d2014-11-14 10:06:21 -08001035
Paul McLeanaa981192015-03-21 09:55:15 -07001036 status_t status;
1037 status = AudioSystem::getOutputForAttr(attr, &output,
1038 (audio_session_t)mSessionId, &streamType,
1039 mSampleRate, mFormat, mChannelMask,
1040 mFlags, mSelectedDeviceId, mOffloadInfo);
Eric Laurente83b55d2014-11-14 10:06:21 -08001041
1042 if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001043 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 -07001044 " channel mask %#x, flags %#x",
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001045 mSessionId, streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001046 return BAD_VALUE;
1047 }
1048 {
1049 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
1050 // we must release it ourselves if anything goes wrong.
1051
Glenn Kastence8828a2013-09-16 18:07:38 -07001052 // Not all of these values are needed under all conditions, but it is easier to get them all
1053
Eric Laurentd1b449a2010-05-14 03:26:45 -07001054 uint32_t afLatency;
Glenn Kasten241618f2014-03-25 17:48:57 -07001055 status = AudioSystem::getLatency(output, &afLatency);
Glenn Kastence8828a2013-09-16 18:07:38 -07001056 if (status != NO_ERROR) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001057 ALOGE("getLatency(%d) failed status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001058 goto release;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001059 }
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001060 ALOGV("createTrack_l() output %d afLatency %u", output, afLatency);
Eric Laurentd1b449a2010-05-14 03:26:45 -07001061
Glenn Kastence8828a2013-09-16 18:07:38 -07001062 size_t afFrameCount;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001063 status = AudioSystem::getFrameCount(output, &afFrameCount);
Glenn Kastence8828a2013-09-16 18:07:38 -07001064 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001065 ALOGE("getFrameCount(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001066 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001067 }
1068
1069 uint32_t afSampleRate;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001070 status = AudioSystem::getSamplingRate(output, &afSampleRate);
Glenn Kastence8828a2013-09-16 18:07:38 -07001071 if (status != NO_ERROR) {
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001072 ALOGE("getSamplingRate(output=%d) status %d", output, status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001073 goto release;
Glenn Kastence8828a2013-09-16 18:07:38 -07001074 }
Eric Laurent0d6db582014-11-12 18:39:44 -08001075 if (mSampleRate == 0) {
1076 mSampleRate = afSampleRate;
1077 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001078 // Client decides whether the track is TIMED (see below), but can only express a preference
1079 // for FAST. Server will perform additional tests.
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001080 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001081 // either of these use cases:
1082 // use case 1: shared buffer
Glenn Kasten363fb752014-01-15 12:27:31 -08001083 (mSharedBuffer != 0) ||
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001084 // use case 2: callback transfer mode
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001085 (mTransfer == TRANSFER_CALLBACK) ||
1086 // use case 3: obtain/release mode
1087 (mTransfer == TRANSFER_OBTAIN)) &&
Glenn Kasten43bdc1d2014-02-10 09:53:55 -08001088 // matching sample rate
1089 (mSampleRate == afSampleRate))) {
Glenn Kasten4c36d6f2015-03-20 09:05:01 -07001090 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client; transfer %d, track %u Hz, output %u Hz",
1091 mTransfer, mSampleRate, afSampleRate);
Glenn Kasten093000f2012-05-03 09:35:36 -07001092 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001093 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001094 }
1095
Glenn Kastence8828a2013-09-16 18:07:38 -07001096 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
Glenn Kastenb5fed682013-12-03 09:06:43 -08001097 // n = 1 fast track with single buffering; nBuffering is ignored
1098 // n = 2 fast track with double buffering
Andy Hung0e48d252015-01-26 11:43:15 -08001099 // n = 2 normal track, (including those with sample rate conversion)
1100 // n >= 3 very high latency or very small notification interval (unused).
1101 const uint32_t nBuffering = 2;
Glenn Kastence8828a2013-09-16 18:07:38 -07001102
Eric Laurentd1b449a2010-05-14 03:26:45 -07001103 mNotificationFramesAct = mNotificationFramesReq;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001104
Glenn Kasten363fb752014-01-15 12:27:31 -08001105 size_t frameCount = mReqFrameCount;
1106 if (!audio_is_linear_pcm(mFormat)) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001107
Glenn Kasten363fb752014-01-15 12:27:31 -08001108 if (mSharedBuffer != 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001109 // Same comment as below about ignoring frameCount parameter for set()
Glenn Kasten363fb752014-01-15 12:27:31 -08001110 frameCount = mSharedBuffer->size();
Glenn Kastene0fa4672012-04-24 14:35:14 -07001111 } else if (frameCount == 0) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001112 frameCount = afFrameCount;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001113 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001114 if (mNotificationFramesAct != frameCount) {
1115 mNotificationFramesAct = frameCount;
1116 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001117 } else if (mSharedBuffer != 0) {
Andy Hungabdb9902015-01-12 15:08:22 -08001118 // FIXME: Ensure client side memory buffers need
1119 // not have additional alignment beyond sample
1120 // (e.g. 16 bit stereo accessed as 32 bit frame).
1121 size_t alignment = audio_bytes_per_sample(mFormat);
Glenn Kastenb7730382014-04-30 15:50:31 -07001122 if (alignment & 1) {
Andy Hungabdb9902015-01-12 15:08:22 -08001123 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
Glenn Kastenb7730382014-04-30 15:50:31 -07001124 alignment = 1;
1125 }
Glenn Kastena42ff002012-11-14 12:47:55 -08001126 if (mChannelCount > 1) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001127 // More than 2 channels does not require stronger alignment than stereo
1128 alignment <<= 1;
1129 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001130 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
Glenn Kastena42ff002012-11-14 12:47:55 -08001131 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Glenn Kasten363fb752014-01-15 12:27:31 -08001132 mSharedBuffer->pointer(), mChannelCount);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001133 status = BAD_VALUE;
1134 goto release;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001135 }
1136
1137 // When initializing a shared buffer AudioTrack via constructors,
1138 // there's no frameCount parameter.
1139 // But when initializing a shared buffer AudioTrack via set(),
1140 // there _is_ a frameCount parameter. We silently ignore it.
Andy Hungabdb9902015-01-12 15:08:22 -08001141 frameCount = mSharedBuffer->size() / mFrameSize;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001142 } else {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001143 // For fast tracks the frame count calculations and checks are done by server
1144
1145 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1146 // for normal tracks precompute the frame count based on speed.
1147 const size_t minFrameCount = calculateMinFrameCount(
1148 afLatency, afFrameCount, afSampleRate, mSampleRate, mSpeed);
1149 if (frameCount < minFrameCount) {
1150 frameCount = minFrameCount;
1151 }
1152 }
Eric Laurentd1b449a2010-05-14 03:26:45 -07001153 }
1154
Glenn Kastena075db42012-03-06 11:22:44 -08001155 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1156 if (mIsTimed) {
1157 trackFlags |= IAudioFlinger::TRACK_TIMED;
1158 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001159
1160 pid_t tid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001161 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001162 trackFlags |= IAudioFlinger::TRACK_FAST;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001163 if (mAudioTrackThread != 0) {
1164 tid = mAudioTrackThread->getTid();
1165 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001166 }
1167
Glenn Kasten363fb752014-01-15 12:27:31 -08001168 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001169 trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1170 }
1171
Eric Laurentab5cdba2014-06-09 17:22:27 -07001172 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1173 trackFlags |= IAudioFlinger::TRACK_DIRECT;
1174 }
1175
Glenn Kasten74935e42013-12-19 08:56:45 -08001176 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount,
1177 // but we will still need the original value also
Glenn Kasten138d6f92015-03-20 10:54:51 -07001178 int originalSessionId = mSessionId;
Eric Laurente83b55d2014-11-14 10:06:21 -08001179 sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
Glenn Kasten363fb752014-01-15 12:27:31 -08001180 mSampleRate,
Andy Hungabdb9902015-01-12 15:08:22 -08001181 mFormat,
Glenn Kastena42ff002012-11-14 12:47:55 -08001182 mChannelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001183 &temp,
Glenn Kastene0b07172012-11-06 15:03:34 -08001184 &trackFlags,
Glenn Kasten363fb752014-01-15 12:27:31 -08001185 mSharedBuffer,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001186 output,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001187 tid,
Eric Laurentbe916aa2010-06-01 23:49:17 -07001188 &mSessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001189 mClientUid,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001190 &status);
Glenn Kasten138d6f92015-03-20 10:54:51 -07001191 ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
1192 "session ID changed from %d to %d", originalSessionId, mSessionId);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001193
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001194 if (status != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001195 ALOGE("AudioFlinger could not create track, status: %d", status);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001196 goto release;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001197 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001198 ALOG_ASSERT(track != 0);
1199
Glenn Kasten38e905b2014-01-13 10:21:48 -08001200 // AudioFlinger now owns the reference to the I/O handle,
1201 // so we are no longer responsible for releasing it.
1202
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001203 sp<IMemory> iMem = track->getCblk();
1204 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001205 ALOGE("Could not get control block");
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001206 return NO_INIT;
1207 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001208 void *iMemPointer = iMem->pointer();
1209 if (iMemPointer == NULL) {
1210 ALOGE("Could not get control block pointer");
1211 return NO_INIT;
1212 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001213 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001214 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001215 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001216 mDeathNotifier.clear();
1217 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001218 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001219 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001220 IPCThreadState::self()->flushCommands();
1221
Glenn Kasten0cde0762014-01-16 15:06:36 -08001222 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001223 mCblk = cblk;
Glenn Kasten74935e42013-12-19 08:56:45 -08001224 // note that temp is the (possibly revised) value of frameCount
Glenn Kastenb6037442012-11-14 13:42:25 -08001225 if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1226 // In current design, AudioTrack client checks and ensures frame count validity before
1227 // passing it to AudioFlinger so AudioFlinger should not return a different value except
1228 // for fast track as it uses a special method of assigning frame count.
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001229 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
Glenn Kastenb6037442012-11-14 13:42:25 -08001230 }
1231 frameCount = temp;
Glenn Kasten5f631512014-02-24 15:16:07 -08001232
Glenn Kastena07f17c2013-04-23 12:39:37 -07001233 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001234 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kastene0b07172012-11-06 15:03:34 -08001235 if (trackFlags & IAudioFlinger::TRACK_FAST) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001236 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
Glenn Kastena07f17c2013-04-23 12:39:37 -07001237 mAwaitBoost = true;
Glenn Kasten3acbd052012-02-28 10:39:56 -08001238 } else {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001239 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
Glenn Kasten093000f2012-05-03 09:35:36 -07001240 // once denied, do not request again if IAudioTrack is re-created
Glenn Kasten363fb752014-01-15 12:27:31 -08001241 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001242 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001243 }
Glenn Kasten363fb752014-01-15 12:27:31 -08001244 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001245 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1246 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1247 } else {
1248 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
Glenn Kasten363fb752014-01-15 12:27:31 -08001249 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001250 // FIXME This is a warning, not an error, so don't return error status
1251 //return NO_INIT;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001252 }
1253 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07001254 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1255 if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1256 ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1257 } else {
1258 ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1259 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1260 // FIXME This is a warning, not an error, so don't return error status
1261 //return NO_INIT;
1262 }
1263 }
Andy Hung0e48d252015-01-26 11:43:15 -08001264 // Make sure that application is notified with sufficient margin before underrun
1265 if (mSharedBuffer == 0 && audio_is_linear_pcm(mFormat)) {
1266 // Theoretically double-buffering is not required for fast tracks,
1267 // due to tighter scheduling. But in practice, to accommodate kernels with
1268 // scheduling jitter, and apps with computation jitter, we use double-buffering
1269 // for fast tracks just like normal streaming tracks.
1270 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount / nBuffering) {
1271 mNotificationFramesAct = frameCount / nBuffering;
1272 }
1273 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001274
Glenn Kasten38e905b2014-01-13 10:21:48 -08001275 // We retain a copy of the I/O handle, but don't own the reference
1276 mOutput = output;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001277 mRefreshRemaining = true;
1278
1279 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1280 // is the value of pointer() for the shared buffer, otherwise buffers points
1281 // immediately after the control block. This address is for the mapping within client
1282 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1283 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001284 if (mSharedBuffer == 0) {
Glenn Kasten138d6f92015-03-20 10:54:51 -07001285 buffers = cblk + 1;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001286 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001287 buffers = mSharedBuffer->pointer();
Glenn Kasten138d6f92015-03-20 10:54:51 -07001288 if (buffers == NULL) {
1289 ALOGE("Could not get buffer pointer");
1290 return NO_INIT;
1291 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001292 }
1293
Eric Laurent2beeb502010-07-16 07:43:46 -07001294 mAudioTrack->attachAuxEffect(mAuxEffectId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07001295 // FIXME doesn't take into account speed or future sample rate changes (until restoreTrack)
Glenn Kastene0fa4672012-04-24 14:35:14 -07001296 // FIXME don't believe this lie
Glenn Kasten363fb752014-01-15 12:27:31 -08001297 mLatency = afLatency + (1000*frameCount) / mSampleRate;
Glenn Kasten5f631512014-02-24 15:16:07 -08001298
Glenn Kastenb6037442012-11-14 13:42:25 -08001299 mFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001300 // If IAudioTrack is re-created, don't let the requested frameCount
1301 // decrease. This can confuse clients that cache frameCount().
Glenn Kastenb6037442012-11-14 13:42:25 -08001302 if (frameCount > mReqFrameCount) {
1303 mReqFrameCount = frameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001304 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001305
1306 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001307 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001308 mStaticProxy.clear();
Andy Hungabdb9902015-01-12 15:08:22 -08001309 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001310 } else {
Andy Hungabdb9902015-01-12 15:08:22 -08001311 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001312 mProxy = mStaticProxy;
1313 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001314
1315 mProxy->setVolumeLR(gain_minifloat_pack(
1316 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1317 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1318
Glenn Kastene3aa6592012-12-04 12:22:46 -08001319 mProxy->setSendLevel(mSendLevel);
1320 mProxy->setSampleRate(mSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07001321 mProxy->setPlaybackRate(mSpeed, mPitch);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001322 mProxy->setMinimum(mNotificationFramesAct);
1323
1324 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001325 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001326
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001327 return NO_ERROR;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001328 }
1329
1330release:
Eric Laurente83b55d2014-11-14 10:06:21 -08001331 AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
Glenn Kasten38e905b2014-01-13 10:21:48 -08001332 if (status == NO_ERROR) {
1333 status = NO_INIT;
1334 }
1335 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001336}
1337
Glenn Kastenb46f3942015-03-09 12:00:30 -07001338status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001339{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001340 if (audioBuffer == NULL) {
1341 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001342 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001343 if (mTransfer != TRANSFER_OBTAIN) {
1344 audioBuffer->frameCount = 0;
1345 audioBuffer->size = 0;
1346 audioBuffer->raw = NULL;
1347 return INVALID_OPERATION;
1348 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001349
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001350 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001351 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001352 if (waitCount == -1) {
1353 requested = &ClientProxy::kForever;
1354 } else if (waitCount == 0) {
1355 requested = &ClientProxy::kNonBlocking;
1356 } else if (waitCount > 0) {
1357 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001358 timeout.tv_sec = ms / 1000;
1359 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1360 requested = &timeout;
1361 } else {
1362 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1363 requested = NULL;
1364 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001365 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001366}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001367
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001368status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1369 struct timespec *elapsed, size_t *nonContig)
1370{
1371 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1372 uint32_t oldSequence = 0;
1373 uint32_t newSequence;
1374
1375 Proxy::Buffer buffer;
1376 status_t status = NO_ERROR;
1377
1378 static const int32_t kMaxTries = 5;
1379 int32_t tryCounter = kMaxTries;
1380
1381 do {
1382 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1383 // keep them from going away if another thread re-creates the track during obtainBuffer()
1384 sp<AudioTrackClientProxy> proxy;
1385 sp<IMemory> iMem;
1386
1387 { // start of lock scope
1388 AutoMutex lock(mLock);
1389
1390 newSequence = mSequence;
1391 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1392 if (status == DEAD_OBJECT) {
1393 // re-create track, unless someone else has already done so
1394 if (newSequence == oldSequence) {
1395 status = restoreTrack_l("obtainBuffer");
1396 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001397 buffer.mFrameCount = 0;
1398 buffer.mRaw = NULL;
1399 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001400 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001401 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001402 }
1403 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001404 oldSequence = newSequence;
1405
1406 // Keep the extra references
1407 proxy = mProxy;
1408 iMem = mCblkMemory;
1409
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001410 if (mState == STATE_STOPPING) {
1411 status = -EINTR;
1412 buffer.mFrameCount = 0;
1413 buffer.mRaw = NULL;
1414 buffer.mNonContig = 0;
1415 break;
1416 }
1417
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001418 // Non-blocking if track is stopped or paused
1419 if (mState != STATE_ACTIVE) {
1420 requested = &ClientProxy::kNonBlocking;
1421 }
1422
1423 } // end of lock scope
1424
1425 buffer.mFrameCount = audioBuffer->frameCount;
1426 // FIXME starts the requested timeout and elapsed over from scratch
1427 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1428
1429 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1430
1431 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001432 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001433 audioBuffer->raw = buffer.mRaw;
1434 if (nonContig != NULL) {
1435 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001436 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001437 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001438}
1439
Glenn Kasten54a8a452015-03-09 12:03:00 -07001440void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001441{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001442 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001443 if (mTransfer == TRANSFER_SHARED) {
1444 return;
1445 }
1446
Andy Hungabdb9902015-01-12 15:08:22 -08001447 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001448 if (stepCount == 0) {
1449 return;
1450 }
1451
1452 Proxy::Buffer buffer;
1453 buffer.mFrameCount = stepCount;
1454 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001455
Eric Laurent1703cdf2011-03-07 14:52:59 -08001456 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001457 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001458 mInUnderrun = false;
1459 mProxy->releaseBuffer(&buffer);
1460
1461 // restart track if it was disabled by audioflinger due to previous underrun
1462 if (mState == STATE_ACTIVE) {
1463 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001464 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001465 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001466 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001467 mAudioTrack->start();
1468 }
1469 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001470}
1471
1472// -------------------------------------------------------------------------
1473
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001474ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001475{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001476 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001477 return INVALID_OPERATION;
1478 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001479
Eric Laurentab5cdba2014-06-09 17:22:27 -07001480 if (isDirect()) {
1481 AutoMutex lock(mLock);
1482 int32_t flags = android_atomic_and(
1483 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1484 &mCblk->mFlags);
1485 if (flags & CBLK_INVALID) {
1486 return DEAD_OBJECT;
1487 }
1488 }
1489
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001490 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001491 // Sanity-check: user is most-likely passing an error code, and it would
1492 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001493 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001494 return BAD_VALUE;
1495 }
1496
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001497 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001498 Buffer audioBuffer;
1499
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001500 while (userSize >= mFrameSize) {
1501 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001502
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001503 status_t err = obtainBuffer(&audioBuffer,
1504 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001505 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001506 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001507 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001508 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001509 return ssize_t(err);
1510 }
1511
Glenn Kastenae4b8792015-03-20 09:04:21 -07001512 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08001513 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001514 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001515 userSize -= toWrite;
1516 written += toWrite;
1517
1518 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001519 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001520
1521 return written;
1522}
1523
1524// -------------------------------------------------------------------------
1525
John Grossman4ff14ba2012-02-08 16:37:41 -08001526TimedAudioTrack::TimedAudioTrack() {
1527 mIsTimed = true;
1528}
1529
1530status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1531{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001532 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001533 status_t result = UNKNOWN_ERROR;
1534
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001535#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001536 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1537 // while we are accessing the cblk
1538 sp<IAudioTrack> audioTrack = mAudioTrack;
1539 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001540#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001541
John Grossman4ff14ba2012-02-08 16:37:41 -08001542 // If the track is not invalid already, try to allocate a buffer. alloc
1543 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001544 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001545 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001546 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001547 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1548 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001549 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001550 }
1551 }
1552
1553 // If the track is invalid at this point, attempt to restore it. and try the
1554 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001555 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001556 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001557
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001558 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001559 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001560 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001561 }
1562
1563 return result;
1564}
1565
1566status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1567 int64_t pts)
1568{
Eric Laurentdf839842012-05-31 14:27:14 -07001569 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1570 {
1571 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001572 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001573 // restart track if it was disabled by audioflinger due to previous underrun
1574 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001575 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1576 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001577 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001578 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001579 mAudioTrack->start();
1580 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001581 }
Eric Laurentdf839842012-05-31 14:27:14 -07001582 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001583}
1584
1585status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1586 TargetTimeline target)
1587{
1588 return mAudioTrack->setMediaTimeTransform(xform, target);
1589}
1590
1591// -------------------------------------------------------------------------
1592
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001593nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001594{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001595 // Currently the AudioTrack thread is not created if there are no callbacks.
1596 // Would it ever make sense to run the thread, even without callbacks?
1597 // If so, then replace this by checks at each use for mCbf != NULL.
1598 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1599
Eric Laurent1703cdf2011-03-07 14:52:59 -08001600 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001601 if (mAwaitBoost) {
1602 mAwaitBoost = false;
1603 mLock.unlock();
1604 static const int32_t kMaxTries = 5;
1605 int32_t tryCounter = kMaxTries;
1606 uint32_t pollUs = 10000;
1607 do {
1608 int policy = sched_getscheduler(0);
1609 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1610 break;
1611 }
1612 usleep(pollUs);
1613 pollUs <<= 1;
1614 } while (tryCounter-- > 0);
1615 if (tryCounter < 0) {
1616 ALOGE("did not receive expected priority boost on time");
1617 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001618 // Run again immediately
1619 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001620 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001621
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001622 // Can only reference mCblk while locked
1623 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001624 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001625
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001626 // Check for track invalidation
1627 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001628 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1629 // AudioSystem cache. We should not exit here but after calling the callback so
1630 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001631 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001632 status_t status = restoreTrack_l("processAudioBuffer");
Andy Hung53c3b5f2014-12-15 16:42:05 -08001633 // after restoration, continue below to make sure that the loop and buffer events
1634 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001635 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001636 }
1637
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001638 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001639 bool active = mState == STATE_ACTIVE;
1640
1641 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1642 bool newUnderrun = false;
1643 if (flags & CBLK_UNDERRUN) {
1644#if 0
1645 // Currently in shared buffer mode, when the server reaches the end of buffer,
1646 // the track stays active in continuous underrun state. It's up to the application
1647 // to pause or stop the track, or set the position to a new offset within buffer.
1648 // This was some experimental code to auto-pause on underrun. Keeping it here
1649 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1650 if (mTransfer == TRANSFER_SHARED) {
1651 mState = STATE_PAUSED;
1652 active = false;
1653 }
1654#endif
1655 if (!mInUnderrun) {
1656 mInUnderrun = true;
1657 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001658 }
1659 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001660
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001661 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001662 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001663
1664 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001665 bool markerReached = false;
1666 size_t markerPosition = mMarkerPosition;
1667 // FIXME fails for wraparound, need 64 bits
1668 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1669 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001670 }
1671
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001672 // Determine number of new position callback(s) that will be needed, while locked
1673 size_t newPosCount = 0;
1674 size_t newPosition = mNewPosition;
1675 size_t updatePeriod = mUpdatePeriod;
1676 // FIXME fails for wraparound, need 64 bits
1677 if (updatePeriod > 0 && position >= newPosition) {
1678 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1679 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001680 }
1681
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001682 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001683 uint32_t sampleRate = mSampleRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001684 float speed = mSpeed;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001685 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001686 if (mRefreshRemaining) {
1687 mRefreshRemaining = false;
1688 mRemainingFrames = notificationFrames;
1689 mRetryOnPartialBuffer = false;
1690 }
1691 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001692 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001693 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001694
Andy Hung53c3b5f2014-12-15 16:42:05 -08001695 // Determine the number of new loop callback(s) that will be needed, while locked.
1696 int loopCountNotifications = 0;
1697 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1698
1699 if (mLoopCount > 0) {
1700 int loopCount;
1701 size_t bufferPosition;
1702 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1703 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1704 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1705 mLoopCountNotified = loopCount; // discard any excess notifications
1706 } else if (mLoopCount < 0) {
1707 // FIXME: We're not accurate with notification count and position with infinite looping
1708 // since loopCount from server side will always return -1 (we could decrement it).
1709 size_t bufferPosition = mStaticProxy->getBufferPosition();
1710 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1711 loopPeriod = mLoopEnd - bufferPosition;
1712 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1713 size_t bufferPosition = mStaticProxy->getBufferPosition();
1714 loopPeriod = mFrameCount - bufferPosition;
1715 }
1716
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001717 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08001718 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001719 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1720
1721 mLock.unlock();
1722
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001723 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001724 struct timespec timeout;
1725 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1726 timeout.tv_nsec = 0;
1727
Glenn Kasten96f04882013-09-20 09:28:56 -07001728 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001729 switch (status) {
1730 case NO_ERROR:
1731 case DEAD_OBJECT:
1732 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001733 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001734 {
1735 AutoMutex lock(mLock);
1736 // The previously assigned value of waitStreamEnd is no longer valid,
1737 // since the mutex has been unlocked and either the callback handler
1738 // or another thread could have re-started the AudioTrack during that time.
1739 waitStreamEnd = mState == STATE_STOPPING;
1740 if (waitStreamEnd) {
1741 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001742 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001743 }
1744 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001745 if (waitStreamEnd && status != DEAD_OBJECT) {
1746 return NS_INACTIVE;
1747 }
1748 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001749 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001750 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001751 }
1752
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001753 // perform callbacks while unlocked
1754 if (newUnderrun) {
1755 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1756 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001757 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001758 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001759 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001760 }
1761 if (flags & CBLK_BUFFER_END) {
1762 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1763 }
1764 if (markerReached) {
1765 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1766 }
1767 while (newPosCount > 0) {
1768 size_t temp = newPosition;
1769 mCbf(EVENT_NEW_POS, mUserData, &temp);
1770 newPosition += updatePeriod;
1771 newPosCount--;
1772 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001773
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001774 if (mObservedSequence != sequence) {
1775 mObservedSequence = sequence;
1776 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001777 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001778 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001779 return NS_INACTIVE;
1780 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001781 }
1782
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001783 // if inactive, then don't run me again until re-started
1784 if (!active) {
1785 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001786 }
1787
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001788 // Compute the estimated time until the next timed event (position, markers, loops)
1789 // FIXME only for non-compressed audio
1790 uint32_t minFrames = ~0;
1791 if (!markerReached && position < markerPosition) {
1792 minFrames = markerPosition - position;
1793 }
1794 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08001795 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001796 minFrames = loopPeriod;
1797 }
Andy Hung2d85f092015-01-07 12:45:13 -08001798 if (updatePeriod > 0) {
1799 minFrames = min(minFrames, uint32_t(newPosition - position));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001800 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001801
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001802 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1803 static const uint32_t kPoll = 0;
1804 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1805 minFrames = kPoll * notificationFrames;
1806 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001807
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001808 // Convert frame units to time units
1809 nsecs_t ns = NS_WHENEVER;
1810 if (minFrames != (uint32_t) ~0) {
1811 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1812 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
Andy Hung8edb8dc2015-03-26 19:13:55 -07001813 ns = ((double)minFrames * 1000000000) / ((double)sampleRate * speed) + kFudgeNs;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001814 }
1815
1816 // If not supplying data by EVENT_MORE_DATA, then we're done
1817 if (mTransfer != TRANSFER_CALLBACK) {
1818 return ns;
1819 }
1820
1821 struct timespec timeout;
1822 const struct timespec *requested = &ClientProxy::kForever;
1823 if (ns != NS_WHENEVER) {
1824 timeout.tv_sec = ns / 1000000000LL;
1825 timeout.tv_nsec = ns % 1000000000LL;
1826 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1827 requested = &timeout;
1828 }
1829
1830 while (mRemainingFrames > 0) {
1831
1832 Buffer audioBuffer;
1833 audioBuffer.frameCount = mRemainingFrames;
1834 size_t nonContig;
1835 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1836 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001837 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001838 requested = &ClientProxy::kNonBlocking;
1839 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001840 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001841 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001842 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001843 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1844 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001845 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001846 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001847 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1848 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001849 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001850
Eric Laurent42a6f422013-08-29 14:35:05 -07001851 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001852 mRetryOnPartialBuffer = false;
1853 if (avail < mRemainingFrames) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001854 int64_t myns = ((double)(mRemainingFrames - avail) * 1100000000)
1855 / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001856 if (ns < 0 || myns < ns) {
1857 ns = myns;
1858 }
1859 return ns;
1860 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001861 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001862
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001863 size_t reqSize = audioBuffer.size;
1864 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001865 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001866
1867 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001868 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001869 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1870 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001871 return NS_NEVER;
1872 }
1873
1874 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001875 // The callback is done filling buffers
1876 // Keep this thread going to handle timed events and
1877 // still try to get more data in intervals of WAIT_PERIOD_MS
1878 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001879 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001880 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001881
Glenn Kasten138d6f92015-03-20 10:54:51 -07001882 size_t releasedFrames = writtenSize / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001883 audioBuffer.frameCount = releasedFrames;
1884 mRemainingFrames -= releasedFrames;
1885 if (misalignment >= releasedFrames) {
1886 misalignment -= releasedFrames;
1887 } else {
1888 misalignment = 0;
1889 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001890
1891 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001892
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001893 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1894 // if callback doesn't like to accept the full chunk
1895 if (writtenSize < reqSize) {
1896 continue;
1897 }
1898
1899 // There could be enough non-contiguous frames available to satisfy the remaining request
1900 if (mRemainingFrames <= nonContig) {
1901 continue;
1902 }
1903
1904#if 0
1905 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1906 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1907 // that total to a sum == notificationFrames.
1908 if (0 < misalignment && misalignment <= mRemainingFrames) {
1909 mRemainingFrames = misalignment;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001910 return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001911 }
1912#endif
1913
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001914 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001915 mRemainingFrames = notificationFrames;
1916 mRetryOnPartialBuffer = true;
1917
1918 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1919 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001920}
1921
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001922status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001923{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001924 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001925 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001926 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001927
Glenn Kastena47f3162012-11-07 10:13:08 -08001928 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08001929 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001930 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001931
Eric Laurentab5cdba2014-06-09 17:22:27 -07001932 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001933 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001934 return DEAD_OBJECT;
1935 }
1936
Glenn Kasten200092b2014-08-15 15:13:30 -07001937 // save the old static buffer position
Andy Hung4ede21d2014-12-12 15:37:34 -08001938 size_t bufferPosition = 0;
1939 int loopCount = 0;
1940 if (mStaticProxy != 0) {
1941 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1942 }
Glenn Kasten200092b2014-08-15 15:13:30 -07001943
1944 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001945 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001946 // It will also delete the strong references on previous IAudioTrack and IMemory.
1947 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Glenn Kastenae4b8792015-03-20 09:04:21 -07001948 status_t result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001949
1950 // take the frames that will be lost by track recreation into account in saved position
Andy Hung9b461582014-12-01 17:56:29 -08001951 // For streaming tracks, this is the amount we obtained from the user/client
1952 // (not the number actually consumed at the server - those are already lost).
Glenn Kasten200092b2014-08-15 15:13:30 -07001953 (void) updateAndGetPosition_l();
Andy Hung7ccdaad2015-03-20 00:38:32 -07001954 if (mStaticProxy == 0) {
Andy Hung9b461582014-12-01 17:56:29 -08001955 mPosition = mReleased;
1956 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001957
Glenn Kastena47f3162012-11-07 10:13:08 -08001958 if (result == NO_ERROR) {
Andy Hung4ede21d2014-12-12 15:37:34 -08001959 // Continue playback from last known position and restore loop.
1960 if (mStaticProxy != 0) {
1961 if (loopCount != 0) {
1962 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
1963 mLoopStart, mLoopEnd, loopCount);
1964 } else {
1965 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001966 if (bufferPosition == mFrameCount) {
1967 ALOGD("restoring track at end of static buffer");
1968 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001969 }
1970 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001971 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001972 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001973 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001974 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001975 if (result != NO_ERROR) {
1976 ALOGW("restoreTrack_l() failed status %d", result);
1977 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001978 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001979 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001980
1981 return result;
1982}
1983
Glenn Kasten200092b2014-08-15 15:13:30 -07001984uint32_t AudioTrack::updateAndGetPosition_l()
1985{
1986 // This is the sole place to read server consumed frames
1987 uint32_t newServer = mProxy->getPosition();
1988 int32_t delta = newServer - mServer;
1989 mServer = newServer;
1990 // TODO There is controversy about whether there can be "negative jitter" in server position.
1991 // This should be investigated further, and if possible, it should be addressed.
1992 // A more definite failure mode is infrequent polling by client.
1993 // One could call (void)getPosition_l() in releaseBuffer(),
1994 // so mReleased and mPosition are always lock-step as best possible.
1995 // That should ensure delta never goes negative for infrequent polling
1996 // unless the server has more than 2^31 frames in its buffer,
1997 // in which case the use of uint32_t for these counters has bigger issues.
1998 if (delta < 0) {
1999 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
2000 delta = 0;
2001 }
2002 return mPosition += (uint32_t) delta;
2003}
2004
Andy Hung8edb8dc2015-03-26 19:13:55 -07002005bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed) const
2006{
2007 // applicable for mixing tracks only (not offloaded or direct)
2008 if (mStaticProxy != 0) {
2009 return true; // static tracks do not have issues with buffer sizing.
2010 }
2011 status_t status;
2012 uint32_t afLatency;
2013 status = AudioSystem::getLatency(mOutput, &afLatency);
2014 if (status != NO_ERROR) {
2015 ALOGE("getLatency(%d) failed status %d", mOutput, status);
2016 return false;
2017 }
2018
2019 size_t afFrameCount;
2020 status = AudioSystem::getFrameCount(mOutput, &afFrameCount);
2021 if (status != NO_ERROR) {
2022 ALOGE("getFrameCount(output=%d) status %d", mOutput, status);
2023 return false;
2024 }
2025
2026 uint32_t afSampleRate;
2027 status = AudioSystem::getSamplingRate(mOutput, &afSampleRate);
2028 if (status != NO_ERROR) {
2029 ALOGE("getSamplingRate(output=%d) status %d", mOutput, status);
2030 return false;
2031 }
2032
2033 const size_t minFrameCount =
2034 calculateMinFrameCount(afLatency, afFrameCount, afSampleRate, sampleRate, speed);
2035 ALOGV("isSampleRateSpeedAllowed_l mFrameCount %zu minFrameCount %zu",
2036 mFrameCount, minFrameCount);
2037 return mFrameCount >= minFrameCount;
2038}
2039
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002040status_t AudioTrack::setParameters(const String8& keyValuePairs)
2041{
2042 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07002043 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002044}
2045
Glenn Kastence703742013-07-19 16:33:58 -07002046status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
2047{
Glenn Kasten53cec222013-08-29 09:01:02 -07002048 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07002049 // FIXME not implemented for fast tracks; should use proxy and SSQ
2050 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
2051 return INVALID_OPERATION;
2052 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002053
2054 switch (mState) {
2055 case STATE_ACTIVE:
2056 case STATE_PAUSED:
2057 break; // handle below
2058 case STATE_FLUSHED:
2059 case STATE_STOPPED:
2060 return WOULD_BLOCK;
2061 case STATE_STOPPING:
2062 case STATE_PAUSED_STOPPING:
2063 if (!isOffloaded_l()) {
2064 return INVALID_OPERATION;
2065 }
2066 break; // offloaded tracks handled below
2067 default:
2068 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
2069 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07002070 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002071
Eric Laurent275e8e92014-11-30 15:14:47 -08002072 if (mCblk->mFlags & CBLK_INVALID) {
2073 restoreTrack_l("getTimestamp");
2074 }
2075
Glenn Kasten200092b2014-08-15 15:13:30 -07002076 // The presented frame count must always lag behind the consumed frame count.
2077 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002078 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002079 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07002080 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002081 return status;
2082 }
2083 if (isOffloadedOrDirect_l()) {
2084 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
2085 // use cached paused position in case another offloaded track is running.
2086 timestamp.mPosition = mPausedPosition;
2087 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
2088 return NO_ERROR;
2089 }
2090
2091 // Check whether a pending flush or stop has completed, as those commands may
2092 // be asynchronous or return near finish.
2093 if (mStartUs != 0 && mSampleRate != 0) {
2094 static const int kTimeJitterUs = 100000; // 100 ms
2095 static const int k1SecUs = 1000000;
2096
2097 const int64_t timeNow = getNowUs();
2098
2099 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
2100 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
2101 if (timestampTimeUs < mStartUs) {
2102 return WOULD_BLOCK; // stale timestamp time, occurs before start.
2103 }
2104 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002105 const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
2106 / ((double)mSampleRate * mSpeed);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002107
2108 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2109 // Verify that the counter can't count faster than the sample rate
2110 // since the start time. If greater, then that means we have failed
2111 // to completely flush or stop the previous playing track.
2112 ALOGW("incomplete flush or stop:"
2113 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2114 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2115 timestamp.mPosition);
2116 return WOULD_BLOCK;
2117 }
2118 }
2119 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
2120 }
2121 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002122 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2123 (void) updateAndGetPosition_l();
2124 // Server consumed (mServer) and presented both use the same server time base,
2125 // and server consumed is always >= presented.
2126 // The delta between these represents the number of frames in the buffer pipeline.
2127 // If this delta between these is greater than the client position, it means that
2128 // actually presented is still stuck at the starting line (figuratively speaking),
2129 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
2130 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2131 return INVALID_OPERATION;
2132 }
2133 // Convert timestamp position from server time base to client time base.
2134 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2135 // But if we change it to 64-bit then this could fail.
2136 // If (mPosition - mServer) can be negative then should use:
2137 // (int32_t)(mPosition - mServer)
2138 timestamp.mPosition += mPosition - mServer;
2139 // Immediately after a call to getPosition_l(), mPosition and
2140 // mServer both represent the same frame position. mPosition is
2141 // in client's point of view, and mServer is in server's point of
2142 // view. So the difference between them is the "fudge factor"
2143 // between client and server views due to stop() and/or new
2144 // IAudioTrack. And timestamp.mPosition is initially in server's
2145 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002146 }
2147 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002148}
2149
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002150String8 AudioTrack::getParameters(const String8& keys)
2151{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002152 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002153 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002154 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002155 } else {
2156 return String8::empty();
2157 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002158}
2159
Glenn Kasten23a75452014-01-13 10:37:17 -08002160bool AudioTrack::isOffloaded() const
2161{
2162 AutoMutex lock(mLock);
2163 return isOffloaded_l();
2164}
2165
Eric Laurentab5cdba2014-06-09 17:22:27 -07002166bool AudioTrack::isDirect() const
2167{
2168 AutoMutex lock(mLock);
2169 return isDirect_l();
2170}
2171
2172bool AudioTrack::isOffloadedOrDirect() const
2173{
2174 AutoMutex lock(mLock);
2175 return isOffloadedOrDirect_l();
2176}
2177
2178
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002179status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002180{
2181
2182 const size_t SIZE = 256;
2183 char buffer[SIZE];
2184 String8 result;
2185
2186 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002187 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002188 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002189 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002190 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002191 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002192 result.append(buffer);
Andy Hung8edb8dc2015-03-26 19:13:55 -07002193 snprintf(buffer, 255, " sample rate(%u), speed(%f), status(%d)\n",
2194 mSampleRate, mSpeed, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002195 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002196 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002197 result.append(buffer);
2198 ::write(fd, result.string(), result.size());
2199 return NO_ERROR;
2200}
2201
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002202uint32_t AudioTrack::getUnderrunFrames() const
2203{
2204 AutoMutex lock(mLock);
2205 return mProxy->getUnderrunFrames();
2206}
2207
2208// =========================================================================
2209
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002210void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002211{
2212 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2213 if (audioTrack != 0) {
2214 AutoMutex lock(audioTrack->mLock);
2215 audioTrack->mProxy->binderDied();
2216 }
2217}
2218
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002219// =========================================================================
2220
2221AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002222 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2223 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002224{
2225}
2226
2227AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002228{
2229}
2230
2231bool AudioTrack::AudioTrackThread::threadLoop()
2232{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002233 {
2234 AutoMutex _l(mMyLock);
2235 if (mPaused) {
2236 mMyCond.wait(mMyLock);
2237 // caller will check for exitPending()
2238 return true;
2239 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002240 if (mIgnoreNextPausedInt) {
2241 mIgnoreNextPausedInt = false;
2242 mPausedInt = false;
2243 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002244 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002245 if (mPausedNs > 0) {
2246 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2247 } else {
2248 mMyCond.wait(mMyLock);
2249 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002250 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002251 return true;
2252 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002253 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002254 if (exitPending()) {
2255 return false;
2256 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002257 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002258 switch (ns) {
2259 case 0:
2260 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002261 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002262 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002263 return true;
2264 case NS_NEVER:
2265 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002266 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08002267 // Event driven: call wake() when callback notifications conditions change.
2268 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002269 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002270 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002271 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002272 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002273 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002274 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002275}
2276
Glenn Kasten3acbd052012-02-28 10:39:56 -08002277void AudioTrack::AudioTrackThread::requestExit()
2278{
2279 // must be in this order to avoid a race condition
2280 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002281 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002282}
2283
2284void AudioTrack::AudioTrackThread::pause()
2285{
2286 AutoMutex _l(mMyLock);
2287 mPaused = true;
2288}
2289
2290void AudioTrack::AudioTrackThread::resume()
2291{
2292 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002293 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002294 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002295 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002296 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002297 mMyCond.signal();
2298 }
2299}
2300
Andy Hung3c09c782014-12-29 18:39:32 -08002301void AudioTrack::AudioTrackThread::wake()
2302{
2303 AutoMutex _l(mMyLock);
2304 if (!mPaused && mPausedInt && mPausedNs > 0) {
2305 // audio track is active and internally paused with timeout.
2306 mIgnoreNextPausedInt = true;
2307 mPausedInt = false;
2308 mMyCond.signal();
2309 }
2310}
2311
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002312void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2313{
2314 AutoMutex _l(mMyLock);
2315 mPausedInt = true;
2316 mPausedNs = ns;
2317}
2318
Glenn Kasten40bc9062015-03-20 09:09:33 -07002319} // namespace android