blob: d32db7cca71c8aabf1110cbe7f9e07eaa8c57203 [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) {
Glenn Kasten551b5352015-03-20 11:30:28 -07001341 if (nonContig != NULL) {
1342 *nonContig = 0;
1343 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001344 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001345 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001346 if (mTransfer != TRANSFER_OBTAIN) {
1347 audioBuffer->frameCount = 0;
1348 audioBuffer->size = 0;
1349 audioBuffer->raw = NULL;
Glenn Kasten551b5352015-03-20 11:30:28 -07001350 if (nonContig != NULL) {
1351 *nonContig = 0;
1352 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001353 return INVALID_OPERATION;
1354 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001355
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001356 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001357 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001358 if (waitCount == -1) {
1359 requested = &ClientProxy::kForever;
1360 } else if (waitCount == 0) {
1361 requested = &ClientProxy::kNonBlocking;
1362 } else if (waitCount > 0) {
1363 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001364 timeout.tv_sec = ms / 1000;
1365 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1366 requested = &timeout;
1367 } else {
1368 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1369 requested = NULL;
1370 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001371 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001372}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001373
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001374status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1375 struct timespec *elapsed, size_t *nonContig)
1376{
1377 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1378 uint32_t oldSequence = 0;
1379 uint32_t newSequence;
1380
1381 Proxy::Buffer buffer;
1382 status_t status = NO_ERROR;
1383
1384 static const int32_t kMaxTries = 5;
1385 int32_t tryCounter = kMaxTries;
1386
1387 do {
1388 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1389 // keep them from going away if another thread re-creates the track during obtainBuffer()
1390 sp<AudioTrackClientProxy> proxy;
1391 sp<IMemory> iMem;
1392
1393 { // start of lock scope
1394 AutoMutex lock(mLock);
1395
1396 newSequence = mSequence;
1397 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1398 if (status == DEAD_OBJECT) {
1399 // re-create track, unless someone else has already done so
1400 if (newSequence == oldSequence) {
1401 status = restoreTrack_l("obtainBuffer");
1402 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001403 buffer.mFrameCount = 0;
1404 buffer.mRaw = NULL;
1405 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001406 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001407 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001408 }
1409 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001410 oldSequence = newSequence;
1411
1412 // Keep the extra references
1413 proxy = mProxy;
1414 iMem = mCblkMemory;
1415
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001416 if (mState == STATE_STOPPING) {
1417 status = -EINTR;
1418 buffer.mFrameCount = 0;
1419 buffer.mRaw = NULL;
1420 buffer.mNonContig = 0;
1421 break;
1422 }
1423
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001424 // Non-blocking if track is stopped or paused
1425 if (mState != STATE_ACTIVE) {
1426 requested = &ClientProxy::kNonBlocking;
1427 }
1428
1429 } // end of lock scope
1430
1431 buffer.mFrameCount = audioBuffer->frameCount;
1432 // FIXME starts the requested timeout and elapsed over from scratch
1433 status = proxy->obtainBuffer(&buffer, requested, elapsed);
1434
1435 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1436
1437 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001438 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001439 audioBuffer->raw = buffer.mRaw;
1440 if (nonContig != NULL) {
1441 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001442 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001443 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001444}
1445
Glenn Kasten54a8a452015-03-09 12:03:00 -07001446void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001447{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001448 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001449 if (mTransfer == TRANSFER_SHARED) {
1450 return;
1451 }
1452
Andy Hungabdb9902015-01-12 15:08:22 -08001453 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001454 if (stepCount == 0) {
1455 return;
1456 }
1457
1458 Proxy::Buffer buffer;
1459 buffer.mFrameCount = stepCount;
1460 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001461
Eric Laurent1703cdf2011-03-07 14:52:59 -08001462 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001463 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001464 mInUnderrun = false;
1465 mProxy->releaseBuffer(&buffer);
1466
1467 // restart track if it was disabled by audioflinger due to previous underrun
1468 if (mState == STATE_ACTIVE) {
1469 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001470 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
Glenn Kastenc5a17422014-03-13 14:59:59 -07001471 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001472 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001473 mAudioTrack->start();
1474 }
1475 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001476}
1477
1478// -------------------------------------------------------------------------
1479
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001480ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001481{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001482 if (mTransfer != TRANSFER_SYNC || mIsTimed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001483 return INVALID_OPERATION;
1484 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001485
Eric Laurentab5cdba2014-06-09 17:22:27 -07001486 if (isDirect()) {
1487 AutoMutex lock(mLock);
1488 int32_t flags = android_atomic_and(
1489 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1490 &mCblk->mFlags);
1491 if (flags & CBLK_INVALID) {
1492 return DEAD_OBJECT;
1493 }
1494 }
1495
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001496 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001497 // Sanity-check: user is most-likely passing an error code, and it would
1498 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001499 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001500 return BAD_VALUE;
1501 }
1502
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001503 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001504 Buffer audioBuffer;
1505
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001506 while (userSize >= mFrameSize) {
1507 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001508
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001509 status_t err = obtainBuffer(&audioBuffer,
1510 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001511 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001512 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001513 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001514 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001515 return ssize_t(err);
1516 }
1517
Glenn Kastenae4b8792015-03-20 09:04:21 -07001518 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08001519 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001520 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001521 userSize -= toWrite;
1522 written += toWrite;
1523
1524 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001525 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001526
1527 return written;
1528}
1529
1530// -------------------------------------------------------------------------
1531
John Grossman4ff14ba2012-02-08 16:37:41 -08001532TimedAudioTrack::TimedAudioTrack() {
1533 mIsTimed = true;
1534}
1535
1536status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1537{
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001538 AutoMutex lock(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -08001539 status_t result = UNKNOWN_ERROR;
1540
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001541#if 1
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001542 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1543 // while we are accessing the cblk
1544 sp<IAudioTrack> audioTrack = mAudioTrack;
1545 sp<IMemory> iMem = mCblkMemory;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001546#endif
Glenn Kastend5ed6e82012-11-02 13:05:14 -07001547
John Grossman4ff14ba2012-02-08 16:37:41 -08001548 // If the track is not invalid already, try to allocate a buffer. alloc
1549 // fails indicating that the server is dead, flag the track as invalid so
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001550 // we can attempt to restore in just a bit.
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001551 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001552 if (!(cblk->mFlags & CBLK_INVALID)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001553 result = mAudioTrack->allocateTimedBuffer(size, buffer);
1554 if (result == DEAD_OBJECT) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001555 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001556 }
1557 }
1558
1559 // If the track is invalid at this point, attempt to restore it. and try the
1560 // allocation one more time.
Glenn Kasten96f60d82013-07-12 10:21:18 -07001561 if (cblk->mFlags & CBLK_INVALID) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001562 result = restoreTrack_l("allocateTimedBuffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08001563
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001564 if (result == NO_ERROR) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001565 result = mAudioTrack->allocateTimedBuffer(size, buffer);
Glenn Kastend65d73c2012-06-22 17:21:07 -07001566 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001567 }
1568
1569 return result;
1570}
1571
1572status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1573 int64_t pts)
1574{
Eric Laurentdf839842012-05-31 14:27:14 -07001575 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1576 {
1577 AutoMutex lock(mLock);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001578 audio_track_cblk_t* cblk = mCblk;
Eric Laurentdf839842012-05-31 14:27:14 -07001579 // restart track if it was disabled by audioflinger due to previous underrun
1580 if (buffer->size() != 0 && status == NO_ERROR &&
Glenn Kasten96f60d82013-07-12 10:21:18 -07001581 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1582 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
Eric Laurentdf839842012-05-31 14:27:14 -07001583 ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001584 // FIXME ignoring status
Eric Laurentdf839842012-05-31 14:27:14 -07001585 mAudioTrack->start();
1586 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001587 }
Eric Laurentdf839842012-05-31 14:27:14 -07001588 return status;
John Grossman4ff14ba2012-02-08 16:37:41 -08001589}
1590
1591status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1592 TargetTimeline target)
1593{
1594 return mAudioTrack->setMediaTimeTransform(xform, target);
1595}
1596
1597// -------------------------------------------------------------------------
1598
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001599nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001600{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001601 // Currently the AudioTrack thread is not created if there are no callbacks.
1602 // Would it ever make sense to run the thread, even without callbacks?
1603 // If so, then replace this by checks at each use for mCbf != NULL.
1604 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1605
Eric Laurent1703cdf2011-03-07 14:52:59 -08001606 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001607 if (mAwaitBoost) {
1608 mAwaitBoost = false;
1609 mLock.unlock();
1610 static const int32_t kMaxTries = 5;
1611 int32_t tryCounter = kMaxTries;
1612 uint32_t pollUs = 10000;
1613 do {
1614 int policy = sched_getscheduler(0);
1615 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1616 break;
1617 }
1618 usleep(pollUs);
1619 pollUs <<= 1;
1620 } while (tryCounter-- > 0);
1621 if (tryCounter < 0) {
1622 ALOGE("did not receive expected priority boost on time");
1623 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001624 // Run again immediately
1625 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001626 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001627
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001628 // Can only reference mCblk while locked
1629 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001630 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001631
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001632 // Check for track invalidation
1633 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001634 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1635 // AudioSystem cache. We should not exit here but after calling the callback so
1636 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001637 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001638 status_t status = restoreTrack_l("processAudioBuffer");
Andy Hung53c3b5f2014-12-15 16:42:05 -08001639 // after restoration, continue below to make sure that the loop and buffer events
1640 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001641 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001642 }
1643
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001644 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001645 bool active = mState == STATE_ACTIVE;
1646
1647 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1648 bool newUnderrun = false;
1649 if (flags & CBLK_UNDERRUN) {
1650#if 0
1651 // Currently in shared buffer mode, when the server reaches the end of buffer,
1652 // the track stays active in continuous underrun state. It's up to the application
1653 // to pause or stop the track, or set the position to a new offset within buffer.
1654 // This was some experimental code to auto-pause on underrun. Keeping it here
1655 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1656 if (mTransfer == TRANSFER_SHARED) {
1657 mState = STATE_PAUSED;
1658 active = false;
1659 }
1660#endif
1661 if (!mInUnderrun) {
1662 mInUnderrun = true;
1663 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001664 }
1665 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001666
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001667 // Get current position of server
Glenn Kasten200092b2014-08-15 15:13:30 -07001668 size_t position = updateAndGetPosition_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001669
1670 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001671 bool markerReached = false;
1672 size_t markerPosition = mMarkerPosition;
1673 // FIXME fails for wraparound, need 64 bits
1674 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1675 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001676 }
1677
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001678 // Determine number of new position callback(s) that will be needed, while locked
1679 size_t newPosCount = 0;
1680 size_t newPosition = mNewPosition;
1681 size_t updatePeriod = mUpdatePeriod;
1682 // FIXME fails for wraparound, need 64 bits
1683 if (updatePeriod > 0 && position >= newPosition) {
1684 newPosCount = ((position - newPosition) / updatePeriod) + 1;
1685 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001686 }
1687
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001688 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001689 uint32_t sampleRate = mSampleRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001690 float speed = mSpeed;
Glenn Kasten838b3d82014-02-27 15:30:41 -08001691 uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001692 if (mRefreshRemaining) {
1693 mRefreshRemaining = false;
1694 mRemainingFrames = notificationFrames;
1695 mRetryOnPartialBuffer = false;
1696 }
1697 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001698 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001699 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001700
Andy Hung53c3b5f2014-12-15 16:42:05 -08001701 // Determine the number of new loop callback(s) that will be needed, while locked.
1702 int loopCountNotifications = 0;
1703 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1704
1705 if (mLoopCount > 0) {
1706 int loopCount;
1707 size_t bufferPosition;
1708 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1709 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1710 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1711 mLoopCountNotified = loopCount; // discard any excess notifications
1712 } else if (mLoopCount < 0) {
1713 // FIXME: We're not accurate with notification count and position with infinite looping
1714 // since loopCount from server side will always return -1 (we could decrement it).
1715 size_t bufferPosition = mStaticProxy->getBufferPosition();
1716 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1717 loopPeriod = mLoopEnd - bufferPosition;
1718 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1719 size_t bufferPosition = mStaticProxy->getBufferPosition();
1720 loopPeriod = mFrameCount - bufferPosition;
1721 }
1722
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001723 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08001724 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001725 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1726
1727 mLock.unlock();
1728
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001729 if (waitStreamEnd) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001730 struct timespec timeout;
1731 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1732 timeout.tv_nsec = 0;
1733
Glenn Kasten96f04882013-09-20 09:28:56 -07001734 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001735 switch (status) {
1736 case NO_ERROR:
1737 case DEAD_OBJECT:
1738 case TIMED_OUT:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001739 mCbf(EVENT_STREAM_END, mUserData, NULL);
Glenn Kasten96f04882013-09-20 09:28:56 -07001740 {
1741 AutoMutex lock(mLock);
1742 // The previously assigned value of waitStreamEnd is no longer valid,
1743 // since the mutex has been unlocked and either the callback handler
1744 // or another thread could have re-started the AudioTrack during that time.
1745 waitStreamEnd = mState == STATE_STOPPING;
1746 if (waitStreamEnd) {
1747 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001748 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001749 }
1750 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001751 if (waitStreamEnd && status != DEAD_OBJECT) {
1752 return NS_INACTIVE;
1753 }
1754 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001755 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001756 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001757 }
1758
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001759 // perform callbacks while unlocked
1760 if (newUnderrun) {
1761 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1762 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001763 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001764 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001765 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001766 }
1767 if (flags & CBLK_BUFFER_END) {
1768 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1769 }
1770 if (markerReached) {
1771 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1772 }
1773 while (newPosCount > 0) {
1774 size_t temp = newPosition;
1775 mCbf(EVENT_NEW_POS, mUserData, &temp);
1776 newPosition += updatePeriod;
1777 newPosCount--;
1778 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001779
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001780 if (mObservedSequence != sequence) {
1781 mObservedSequence = sequence;
1782 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001783 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001784 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001785 return NS_INACTIVE;
1786 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001787 }
1788
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001789 // if inactive, then don't run me again until re-started
1790 if (!active) {
1791 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07001792 }
1793
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001794 // Compute the estimated time until the next timed event (position, markers, loops)
1795 // FIXME only for non-compressed audio
1796 uint32_t minFrames = ~0;
1797 if (!markerReached && position < markerPosition) {
1798 minFrames = markerPosition - position;
1799 }
1800 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08001801 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001802 minFrames = loopPeriod;
1803 }
Andy Hung2d85f092015-01-07 12:45:13 -08001804 if (updatePeriod > 0) {
1805 minFrames = min(minFrames, uint32_t(newPosition - position));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001806 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001807
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001808 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
1809 static const uint32_t kPoll = 0;
1810 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1811 minFrames = kPoll * notificationFrames;
1812 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001813
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001814 // Convert frame units to time units
1815 nsecs_t ns = NS_WHENEVER;
1816 if (minFrames != (uint32_t) ~0) {
1817 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1818 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
Andy Hung8edb8dc2015-03-26 19:13:55 -07001819 ns = ((double)minFrames * 1000000000) / ((double)sampleRate * speed) + kFudgeNs;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001820 }
1821
1822 // If not supplying data by EVENT_MORE_DATA, then we're done
1823 if (mTransfer != TRANSFER_CALLBACK) {
1824 return ns;
1825 }
1826
1827 struct timespec timeout;
1828 const struct timespec *requested = &ClientProxy::kForever;
1829 if (ns != NS_WHENEVER) {
1830 timeout.tv_sec = ns / 1000000000LL;
1831 timeout.tv_nsec = ns % 1000000000LL;
1832 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1833 requested = &timeout;
1834 }
1835
1836 while (mRemainingFrames > 0) {
1837
1838 Buffer audioBuffer;
1839 audioBuffer.frameCount = mRemainingFrames;
1840 size_t nonContig;
1841 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1842 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001843 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001844 requested = &ClientProxy::kNonBlocking;
1845 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001846 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001847 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001848 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001849 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1850 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001851 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001852 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001853 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1854 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001855 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001856
Eric Laurent42a6f422013-08-29 14:35:05 -07001857 if (mRetryOnPartialBuffer && !isOffloaded()) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001858 mRetryOnPartialBuffer = false;
1859 if (avail < mRemainingFrames) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001860 int64_t myns = ((double)(mRemainingFrames - avail) * 1100000000)
1861 / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001862 if (ns < 0 || myns < ns) {
1863 ns = myns;
1864 }
1865 return ns;
1866 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001867 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001868
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001869 size_t reqSize = audioBuffer.size;
1870 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001871 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001872
1873 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001874 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07001875 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1876 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001877 return NS_NEVER;
1878 }
1879
1880 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08001881 // The callback is done filling buffers
1882 // Keep this thread going to handle timed events and
1883 // still try to get more data in intervals of WAIT_PERIOD_MS
1884 // but don't just loop and block the CPU, so wait
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001885 return WAIT_PERIOD_MS * 1000000LL;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001886 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001887
Glenn Kasten138d6f92015-03-20 10:54:51 -07001888 size_t releasedFrames = writtenSize / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001889 audioBuffer.frameCount = releasedFrames;
1890 mRemainingFrames -= releasedFrames;
1891 if (misalignment >= releasedFrames) {
1892 misalignment -= releasedFrames;
1893 } else {
1894 misalignment = 0;
1895 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001896
1897 releaseBuffer(&audioBuffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001898
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001899 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1900 // if callback doesn't like to accept the full chunk
1901 if (writtenSize < reqSize) {
1902 continue;
1903 }
1904
1905 // There could be enough non-contiguous frames available to satisfy the remaining request
1906 if (mRemainingFrames <= nonContig) {
1907 continue;
1908 }
1909
1910#if 0
1911 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1912 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
1913 // that total to a sum == notificationFrames.
1914 if (0 < misalignment && misalignment <= mRemainingFrames) {
1915 mRemainingFrames = misalignment;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001916 return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001917 }
1918#endif
1919
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001920 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001921 mRemainingFrames = notificationFrames;
1922 mRetryOnPartialBuffer = true;
1923
1924 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1925 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001926}
1927
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001928status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08001929{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001930 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07001931 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001932 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001933
Glenn Kastena47f3162012-11-07 10:13:08 -08001934 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08001935 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08001936 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07001937
Eric Laurentab5cdba2014-06-09 17:22:27 -07001938 if (isOffloadedOrDirect_l()) {
Glenn Kasten23a75452014-01-13 10:37:17 -08001939 // FIXME re-creation of offloaded tracks is not yet implemented
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001940 return DEAD_OBJECT;
1941 }
1942
Glenn Kasten200092b2014-08-15 15:13:30 -07001943 // save the old static buffer position
Andy Hung4ede21d2014-12-12 15:37:34 -08001944 size_t bufferPosition = 0;
1945 int loopCount = 0;
1946 if (mStaticProxy != 0) {
1947 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1948 }
Glenn Kasten200092b2014-08-15 15:13:30 -07001949
1950 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08001951 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07001952 // It will also delete the strong references on previous IAudioTrack and IMemory.
1953 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Glenn Kastenae4b8792015-03-20 09:04:21 -07001954 status_t result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07001955
1956 // take the frames that will be lost by track recreation into account in saved position
Andy Hung9b461582014-12-01 17:56:29 -08001957 // For streaming tracks, this is the amount we obtained from the user/client
1958 // (not the number actually consumed at the server - those are already lost).
Glenn Kasten200092b2014-08-15 15:13:30 -07001959 (void) updateAndGetPosition_l();
Andy Hung7ccdaad2015-03-20 00:38:32 -07001960 if (mStaticProxy == 0) {
Andy Hung9b461582014-12-01 17:56:29 -08001961 mPosition = mReleased;
1962 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001963
Glenn Kastena47f3162012-11-07 10:13:08 -08001964 if (result == NO_ERROR) {
Andy Hung4ede21d2014-12-12 15:37:34 -08001965 // Continue playback from last known position and restore loop.
1966 if (mStaticProxy != 0) {
1967 if (loopCount != 0) {
1968 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
1969 mLoopStart, mLoopEnd, loopCount);
1970 } else {
1971 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001972 if (bufferPosition == mFrameCount) {
1973 ALOGD("restoring track at end of static buffer");
1974 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001975 }
1976 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001977 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08001978 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08001979 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001980 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001981 if (result != NO_ERROR) {
1982 ALOGW("restoreTrack_l() failed status %d", result);
1983 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001984 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001985 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001986
1987 return result;
1988}
1989
Glenn Kasten200092b2014-08-15 15:13:30 -07001990uint32_t AudioTrack::updateAndGetPosition_l()
1991{
1992 // This is the sole place to read server consumed frames
1993 uint32_t newServer = mProxy->getPosition();
1994 int32_t delta = newServer - mServer;
1995 mServer = newServer;
1996 // TODO There is controversy about whether there can be "negative jitter" in server position.
1997 // This should be investigated further, and if possible, it should be addressed.
1998 // A more definite failure mode is infrequent polling by client.
1999 // One could call (void)getPosition_l() in releaseBuffer(),
2000 // so mReleased and mPosition are always lock-step as best possible.
2001 // That should ensure delta never goes negative for infrequent polling
2002 // unless the server has more than 2^31 frames in its buffer,
2003 // in which case the use of uint32_t for these counters has bigger issues.
2004 if (delta < 0) {
2005 ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
2006 delta = 0;
2007 }
2008 return mPosition += (uint32_t) delta;
2009}
2010
Andy Hung8edb8dc2015-03-26 19:13:55 -07002011bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed) const
2012{
2013 // applicable for mixing tracks only (not offloaded or direct)
2014 if (mStaticProxy != 0) {
2015 return true; // static tracks do not have issues with buffer sizing.
2016 }
2017 status_t status;
2018 uint32_t afLatency;
2019 status = AudioSystem::getLatency(mOutput, &afLatency);
2020 if (status != NO_ERROR) {
2021 ALOGE("getLatency(%d) failed status %d", mOutput, status);
2022 return false;
2023 }
2024
2025 size_t afFrameCount;
2026 status = AudioSystem::getFrameCount(mOutput, &afFrameCount);
2027 if (status != NO_ERROR) {
2028 ALOGE("getFrameCount(output=%d) status %d", mOutput, status);
2029 return false;
2030 }
2031
2032 uint32_t afSampleRate;
2033 status = AudioSystem::getSamplingRate(mOutput, &afSampleRate);
2034 if (status != NO_ERROR) {
2035 ALOGE("getSamplingRate(output=%d) status %d", mOutput, status);
2036 return false;
2037 }
2038
2039 const size_t minFrameCount =
2040 calculateMinFrameCount(afLatency, afFrameCount, afSampleRate, sampleRate, speed);
2041 ALOGV("isSampleRateSpeedAllowed_l mFrameCount %zu minFrameCount %zu",
2042 mFrameCount, minFrameCount);
2043 return mFrameCount >= minFrameCount;
2044}
2045
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002046status_t AudioTrack::setParameters(const String8& keyValuePairs)
2047{
2048 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07002049 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002050}
2051
Glenn Kastence703742013-07-19 16:33:58 -07002052status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
2053{
Glenn Kasten53cec222013-08-29 09:01:02 -07002054 AutoMutex lock(mLock);
Glenn Kastenfe346c72013-08-30 13:28:22 -07002055 // FIXME not implemented for fast tracks; should use proxy and SSQ
2056 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
2057 return INVALID_OPERATION;
2058 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002059
2060 switch (mState) {
2061 case STATE_ACTIVE:
2062 case STATE_PAUSED:
2063 break; // handle below
2064 case STATE_FLUSHED:
2065 case STATE_STOPPED:
2066 return WOULD_BLOCK;
2067 case STATE_STOPPING:
2068 case STATE_PAUSED_STOPPING:
2069 if (!isOffloaded_l()) {
2070 return INVALID_OPERATION;
2071 }
2072 break; // offloaded tracks handled below
2073 default:
2074 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
2075 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07002076 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002077
Eric Laurent275e8e92014-11-30 15:14:47 -08002078 if (mCblk->mFlags & CBLK_INVALID) {
2079 restoreTrack_l("getTimestamp");
2080 }
2081
Glenn Kasten200092b2014-08-15 15:13:30 -07002082 // The presented frame count must always lag behind the consumed frame count.
2083 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002084 status_t status = mAudioTrack->getTimestamp(timestamp);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002085 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07002086 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002087 return status;
2088 }
2089 if (isOffloadedOrDirect_l()) {
2090 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
2091 // use cached paused position in case another offloaded track is running.
2092 timestamp.mPosition = mPausedPosition;
2093 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
2094 return NO_ERROR;
2095 }
2096
2097 // Check whether a pending flush or stop has completed, as those commands may
2098 // be asynchronous or return near finish.
2099 if (mStartUs != 0 && mSampleRate != 0) {
2100 static const int kTimeJitterUs = 100000; // 100 ms
2101 static const int k1SecUs = 1000000;
2102
2103 const int64_t timeNow = getNowUs();
2104
2105 if (timeNow < mStartUs + k1SecUs) { // within first second of starting
2106 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
2107 if (timestampTimeUs < mStartUs) {
2108 return WOULD_BLOCK; // stale timestamp time, occurs before start.
2109 }
2110 const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002111 const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
2112 / ((double)mSampleRate * mSpeed);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002113
2114 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2115 // Verify that the counter can't count faster than the sample rate
2116 // since the start time. If greater, then that means we have failed
2117 // to completely flush or stop the previous playing track.
2118 ALOGW("incomplete flush or stop:"
2119 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2120 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2121 timestamp.mPosition);
2122 return WOULD_BLOCK;
2123 }
2124 }
2125 mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
2126 }
2127 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002128 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2129 (void) updateAndGetPosition_l();
2130 // Server consumed (mServer) and presented both use the same server time base,
2131 // and server consumed is always >= presented.
2132 // The delta between these represents the number of frames in the buffer pipeline.
2133 // If this delta between these is greater than the client position, it means that
2134 // actually presented is still stuck at the starting line (figuratively speaking),
2135 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
2136 if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2137 return INVALID_OPERATION;
2138 }
2139 // Convert timestamp position from server time base to client time base.
2140 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2141 // But if we change it to 64-bit then this could fail.
2142 // If (mPosition - mServer) can be negative then should use:
2143 // (int32_t)(mPosition - mServer)
2144 timestamp.mPosition += mPosition - mServer;
2145 // Immediately after a call to getPosition_l(), mPosition and
2146 // mServer both represent the same frame position. mPosition is
2147 // in client's point of view, and mServer is in server's point of
2148 // view. So the difference between them is the "fudge factor"
2149 // between client and server views due to stop() and/or new
2150 // IAudioTrack. And timestamp.mPosition is initially in server's
2151 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002152 }
2153 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002154}
2155
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002156String8 AudioTrack::getParameters(const String8& keys)
2157{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002158 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002159 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002160 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002161 } else {
2162 return String8::empty();
2163 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002164}
2165
Glenn Kasten23a75452014-01-13 10:37:17 -08002166bool AudioTrack::isOffloaded() const
2167{
2168 AutoMutex lock(mLock);
2169 return isOffloaded_l();
2170}
2171
Eric Laurentab5cdba2014-06-09 17:22:27 -07002172bool AudioTrack::isDirect() const
2173{
2174 AutoMutex lock(mLock);
2175 return isDirect_l();
2176}
2177
2178bool AudioTrack::isOffloadedOrDirect() const
2179{
2180 AutoMutex lock(mLock);
2181 return isOffloadedOrDirect_l();
2182}
2183
2184
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002185status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002186{
2187
2188 const size_t SIZE = 256;
2189 char buffer[SIZE];
2190 String8 result;
2191
2192 result.append(" AudioTrack::dump\n");
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002193 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType,
Glenn Kasten877a0ac2014-04-30 17:04:13 -07002194 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002195 result.append(buffer);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002196 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat,
Glenn Kastenb6037442012-11-14 13:42:25 -08002197 mChannelCount, mFrameCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002198 result.append(buffer);
Andy Hung8edb8dc2015-03-26 19:13:55 -07002199 snprintf(buffer, 255, " sample rate(%u), speed(%f), status(%d)\n",
2200 mSampleRate, mSpeed, mStatus);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002201 result.append(buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002202 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002203 result.append(buffer);
2204 ::write(fd, result.string(), result.size());
2205 return NO_ERROR;
2206}
2207
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002208uint32_t AudioTrack::getUnderrunFrames() const
2209{
2210 AutoMutex lock(mLock);
2211 return mProxy->getUnderrunFrames();
2212}
2213
2214// =========================================================================
2215
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002216void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002217{
2218 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2219 if (audioTrack != 0) {
2220 AutoMutex lock(audioTrack->mLock);
2221 audioTrack->mProxy->binderDied();
2222 }
2223}
2224
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002225// =========================================================================
2226
2227AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07002228 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2229 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08002230{
2231}
2232
2233AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002234{
2235}
2236
2237bool AudioTrack::AudioTrackThread::threadLoop()
2238{
Glenn Kasten3acbd052012-02-28 10:39:56 -08002239 {
2240 AutoMutex _l(mMyLock);
2241 if (mPaused) {
2242 mMyCond.wait(mMyLock);
2243 // caller will check for exitPending()
2244 return true;
2245 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07002246 if (mIgnoreNextPausedInt) {
2247 mIgnoreNextPausedInt = false;
2248 mPausedInt = false;
2249 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002250 if (mPausedInt) {
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002251 if (mPausedNs > 0) {
2252 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2253 } else {
2254 mMyCond.wait(mMyLock);
2255 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002256 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002257 return true;
2258 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002259 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07002260 if (exitPending()) {
2261 return false;
2262 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002263 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002264 switch (ns) {
2265 case 0:
2266 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002267 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002268 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002269 return true;
2270 case NS_NEVER:
2271 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002272 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08002273 // Event driven: call wake() when callback notifications conditions change.
2274 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002275 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002276 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002277 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002278 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002279 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07002280 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002281}
2282
Glenn Kasten3acbd052012-02-28 10:39:56 -08002283void AudioTrack::AudioTrackThread::requestExit()
2284{
2285 // must be in this order to avoid a race condition
2286 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07002287 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08002288}
2289
2290void AudioTrack::AudioTrackThread::pause()
2291{
2292 AutoMutex _l(mMyLock);
2293 mPaused = true;
2294}
2295
2296void AudioTrack::AudioTrackThread::resume()
2297{
2298 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07002299 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002300 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08002301 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07002302 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08002303 mMyCond.signal();
2304 }
2305}
2306
Andy Hung3c09c782014-12-29 18:39:32 -08002307void AudioTrack::AudioTrackThread::wake()
2308{
2309 AutoMutex _l(mMyLock);
2310 if (!mPaused && mPausedInt && mPausedNs > 0) {
2311 // audio track is active and internally paused with timeout.
2312 mIgnoreNextPausedInt = true;
2313 mPausedInt = false;
2314 mMyCond.signal();
2315 }
2316}
2317
Glenn Kasten5a6cd222013-09-20 09:20:45 -07002318void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2319{
2320 AutoMutex _l(mMyLock);
2321 mPausedInt = true;
2322 mPausedNs = ns;
2323}
2324
Glenn Kasten40bc9062015-03-20 09:09:33 -07002325} // namespace android