blob: 55954f244e38767eec4f7a76035e6234da809ff0 [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
Andy Hung2b01f002017-07-05 12:01:36 -070025#include <audio_utils/clock.h>
Glenn Kasten9f80dd22012-12-18 15:57:32 -080026#include <audio_utils/primitives.h>
27#include <binder/IPCThreadState.h>
28#include <media/AudioTrack.h>
29#include <utils/Log.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080030#include <private/media/AudioTrackShared.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070031#include <media/IAudioFlinger.h>
Dean Wheatleya70eef72018-01-04 14:23:50 +110032#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080033#include <media/AudioPolicyHelper.h>
Andy Hungcd044842014-08-07 11:04:34 -070034#include <media/AudioResamplerPublic.h>
Ray Essicked304702017-12-12 14:00:57 -080035#include <media/MediaAnalyticsItem.h>
36#include <media/TypeConverter.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080037
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010038#define WAIT_PERIOD_MS 10
39#define WAIT_STREAM_END_TIMEOUT_SEC 120
Andy Hung53c3b5f2014-12-15 16:42:05 -080040static const int kMaxLoopCountNotifications = 32;
Glenn Kasten511754b2012-01-11 09:52:19 -080041
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080042namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080043// ---------------------------------------------------------------------------
44
Ivan Lozano8cf3a072017-08-09 09:01:33 -070045using media::VolumeShaper;
46
Andy Hunga7f03352015-05-31 21:54:49 -070047// TODO: Move to a separate .h
48
Andy Hung4ede21d2014-12-12 15:37:34 -080049template <typename T>
Andy Hunga7f03352015-05-31 21:54:49 -070050static inline const T &min(const T &x, const T &y) {
Andy Hung4ede21d2014-12-12 15:37:34 -080051 return x < y ? x : y;
52}
53
Andy Hunga7f03352015-05-31 21:54:49 -070054template <typename T>
55static inline const T &max(const T &x, const T &y) {
56 return x > y ? x : y;
57}
58
Andy Hung5d313802016-10-10 15:09:39 -070059static const int32_t NANOS_PER_SECOND = 1000000000;
60
Andy Hunga7f03352015-05-31 21:54:49 -070061static inline nsecs_t framesToNanoseconds(ssize_t frames, uint32_t sampleRate, float speed)
62{
63 return ((double)frames * 1000000000) / ((double)sampleRate * speed);
64}
65
Andy Hung7f1bc8a2014-09-12 14:43:11 -070066static int64_t convertTimespecToUs(const struct timespec &tv)
67{
68 return tv.tv_sec * 1000000ll + tv.tv_nsec / 1000;
69}
70
Andy Hungffa36952017-08-17 10:41:51 -070071// TODO move to audio_utils.
72static inline struct timespec convertNsToTimespec(int64_t ns) {
73 struct timespec tv;
74 tv.tv_sec = static_cast<time_t>(ns / NANOS_PER_SECOND);
75 tv.tv_nsec = static_cast<long>(ns % NANOS_PER_SECOND);
76 return tv;
77}
78
Andy Hung7f1bc8a2014-09-12 14:43:11 -070079// current monotonic time in microseconds.
80static int64_t getNowUs()
81{
82 struct timespec tv;
83 (void) clock_gettime(CLOCK_MONOTONIC, &tv);
84 return convertTimespecToUs(tv);
85}
86
Andy Hung26145642015-04-15 21:56:53 -070087// FIXME: we don't use the pitch setting in the time stretcher (not working);
88// instead we emulate it using our sample rate converter.
89static const bool kFixPitch = true; // enable pitch fix
90static inline uint32_t adjustSampleRate(uint32_t sampleRate, float pitch)
91{
92 return kFixPitch ? (sampleRate * pitch + 0.5) : sampleRate;
93}
94
95static inline float adjustSpeed(float speed, float pitch)
96{
Ricardo Garcia6c7f0622015-04-30 18:39:16 -070097 return kFixPitch ? speed / max(pitch, AUDIO_TIMESTRETCH_PITCH_MIN_DELTA) : speed;
Andy Hung26145642015-04-15 21:56:53 -070098}
99
100static inline float adjustPitch(float pitch)
101{
102 return kFixPitch ? AUDIO_TIMESTRETCH_PITCH_NORMAL : pitch;
103}
104
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800105// static
106status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -0800107 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800108 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800109 uint32_t sampleRate)
110{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700111 if (frameCount == NULL) {
112 return BAD_VALUE;
113 }
Glenn Kasten04cd0182012-06-25 11:49:27 -0700114
Andy Hung0e48d252015-01-26 11:43:15 -0800115 // FIXME handle in server, like createTrack_l(), possible missing info:
Glenn Kastene0fa4672012-04-24 14:35:14 -0700116 // audio_io_handle_t output
117 // audio_format_t format
118 // audio_channel_mask_t channelMask
Andy Hung0e48d252015-01-26 11:43:15 -0800119 // audio_output_flags_t flags (FAST)
Glenn Kasten3b16c762012-11-14 08:44:39 -0800120 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -0800121 status_t status;
122 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
123 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -0800124 ALOGE("Unable to query output sample rate for stream type %d; status %d",
125 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800126 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800127 }
Glenn Kastene33054e2012-11-14 12:54:39 -0800128 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -0800129 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
130 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -0800131 ALOGE("Unable to query output frame count for stream type %d; status %d",
132 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800133 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800134 }
135 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -0800136 status = AudioSystem::getOutputLatency(&afLatency, streamType);
137 if (status != NO_ERROR) {
Glenn Kasten70c0bfb2014-01-14 15:47:01 -0800138 ALOGE("Unable to query output latency for stream type %d; status %d",
139 streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800140 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800141 }
142
Andy Hung8edb8dc2015-03-26 19:13:55 -0700143 // When called from createTrack, speed is 1.0f (normal speed).
144 // This is rechecked again on setting playback rate (TODO: on setting sample rate, too).
Eric Laurent21da6472017-11-09 16:29:26 -0800145 *frameCount = AudioSystem::calculateMinFrameCount(afLatency, afFrameCount, afSampleRate,
146 sampleRate, 1.0f /*, 0 notificationsPerBufferReq*/);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800147
Andy Hung0e48d252015-01-26 11:43:15 -0800148 // The formula above should always produce a non-zero value under normal circumstances:
149 // AudioTrack.SAMPLE_RATE_HZ_MIN <= sampleRate <= AudioTrack.SAMPLE_RATE_HZ_MAX.
150 // 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 -0800151 if (*frameCount == 0) {
Andy Hung0e48d252015-01-26 11:43:15 -0800152 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %u",
Glenn Kasten66a04672014-01-08 08:53:44 -0800153 streamType, sampleRate);
154 return BAD_VALUE;
155 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700156 ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, afSampleRate=%u, afLatency=%u",
157 *frameCount, afFrameCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800158 return NO_ERROR;
159}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800160
161// ---------------------------------------------------------------------------
162
Ray Essicked304702017-12-12 14:00:57 -0800163static std::string audioContentTypeString(audio_content_type_t value) {
164 std::string contentType;
165 if (AudioContentTypeConverter::toString(value, contentType)) {
166 return contentType;
167 }
168 char rawbuffer[16]; // room for "%d"
169 snprintf(rawbuffer, sizeof(rawbuffer), "%d", value);
170 return rawbuffer;
171}
172
173static std::string audioUsageString(audio_usage_t value) {
174 std::string usage;
175 if (UsageTypeConverter::toString(value, usage)) {
176 return usage;
177 }
178 char rawbuffer[16]; // room for "%d"
179 snprintf(rawbuffer, sizeof(rawbuffer), "%d", value);
180 return rawbuffer;
181}
182
183void AudioTrack::MediaMetrics::gather(const AudioTrack *track)
184{
185
186 // key for media statistics is defined in the header
187 // attrs for media statistics
188 static constexpr char kAudioTrackStreamType[] = "android.media.audiotrack.streamtype";
189 static constexpr char kAudioTrackContentType[] = "android.media.audiotrack.type";
190 static constexpr char kAudioTrackUsage[] = "android.media.audiotrack.usage";
191 static constexpr char kAudioTrackSampleRate[] = "android.media.audiotrack.samplerate";
192 static constexpr char kAudioTrackChannelMask[] = "android.media.audiotrack.channelmask";
193 static constexpr char kAudioTrackUnderrunFrames[] = "android.media.audiotrack.underrunframes";
194 static constexpr char kAudioTrackStartupGlitch[] = "android.media.audiotrack.glitch.startup";
195
Ray Essick88394302018-01-24 14:52:05 -0800196 // only if we're in a good state...
197 // XXX: shall we gather alternative info if failing?
198 const status_t lstatus = track->initCheck();
199 if (lstatus != NO_ERROR) {
200 ALOGD("no metrics gathered, track status=%d", (int) lstatus);
201 return;
202 }
203
Ray Essicked304702017-12-12 14:00:57 -0800204 // constructor guarantees mAnalyticsItem is valid
205
Ray Essicked304702017-12-12 14:00:57 -0800206 const int32_t underrunFrames = track->getUnderrunFrames();
207 if (underrunFrames != 0) {
208 mAnalyticsItem->setInt32(kAudioTrackUnderrunFrames, underrunFrames);
209 }
210
211 if (track->mTimestampStartupGlitchReported) {
212 mAnalyticsItem->setInt32(kAudioTrackStartupGlitch, 1);
213 }
214
215 if (track->mStreamType != -1) {
216 // deprecated, but this will tell us who still uses it.
217 mAnalyticsItem->setInt32(kAudioTrackStreamType, track->mStreamType);
218 }
219 // XXX: consider including from mAttributes: source type
220 mAnalyticsItem->setCString(kAudioTrackContentType,
221 audioContentTypeString(track->mAttributes.content_type).c_str());
222 mAnalyticsItem->setCString(kAudioTrackUsage,
223 audioUsageString(track->mAttributes.usage).c_str());
224 mAnalyticsItem->setInt32(kAudioTrackSampleRate, track->mSampleRate);
225 mAnalyticsItem->setInt64(kAudioTrackChannelMask, track->mChannelMask);
226}
227
Ray Essick88394302018-01-24 14:52:05 -0800228// hand the user a snapshot of the metrics.
229status_t AudioTrack::getMetrics(MediaAnalyticsItem * &item)
230{
231 mMediaMetrics.gather(this);
232 MediaAnalyticsItem *tmp = mMediaMetrics.dup();
233 if (tmp == nullptr) {
234 return BAD_VALUE;
235 }
236 item = tmp;
237 return NO_ERROR;
238}
Ray Essicked304702017-12-12 14:00:57 -0800239
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800240AudioTrack::AudioTrack()
Glenn Kasten87913512011-06-22 16:15:25 -0700241 : mStatus(NO_INIT),
Haynes Mathew George9b3359f2016-03-23 19:09:10 -0700242 mState(STATE_STOPPED),
John Grossman4ff14ba2012-02-08 16:37:41 -0800243 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800244 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700245 mPausedPosition(0),
Eric Laurent20b9ef02016-12-05 11:03:16 -0800246 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
Eric Laurent21da6472017-11-09 16:29:26 -0800247 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800248{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700249 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
250 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
251 mAttributes.flags = 0x0;
252 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800253}
254
255AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800256 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800257 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800258 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700259 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800260 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700261 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800262 callback_t cbf,
263 void* user,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700264 int32_t notificationFrames,
Glenn Kastend848eb42016-03-08 13:42:11 -0800265 audio_session_t sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000266 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800267 const audio_offload_info_t *offloadInfo,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800268 uid_t uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700269 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700270 const audio_attributes_t* pAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -0700271 bool doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -0700272 float maxRequiredSpeed,
273 audio_port_handle_t selectedDeviceId)
Glenn Kasten87913512011-06-22 16:15:25 -0700274 : mStatus(NO_INIT),
Haynes Mathew George9b3359f2016-03-23 19:09:10 -0700275 mState(STATE_STOPPED),
John Grossman4ff14ba2012-02-08 16:37:41 -0800276 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800277 mPreviousSchedulingGroup(SP_DEFAULT),
Eric Laurent21da6472017-11-09 16:29:26 -0800278 mPausedPosition(0)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800279{
Eric Laurentf32d7812017-11-30 14:44:07 -0800280 (void)set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700281 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800282 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
jiabin156c6872017-10-06 09:47:15 -0700283 offloadInfo, uid, pid, pAttributes, doNotReconnect, maxRequiredSpeed, selectedDeviceId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800284}
285
Andreas Huberc8139852012-01-18 10:51:55 -0800286AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800287 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800288 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800289 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700290 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800291 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700292 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800293 callback_t cbf,
294 void* user,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700295 int32_t notificationFrames,
Glenn Kastend848eb42016-03-08 13:42:11 -0800296 audio_session_t sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000297 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800298 const audio_offload_info_t *offloadInfo,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800299 uid_t uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700300 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700301 const audio_attributes_t* pAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -0700302 bool doNotReconnect,
303 float maxRequiredSpeed)
Glenn Kasten87913512011-06-22 16:15:25 -0700304 : mStatus(NO_INIT),
Haynes Mathew George9b3359f2016-03-23 19:09:10 -0700305 mState(STATE_STOPPED),
John Grossman4ff14ba2012-02-08 16:37:41 -0800306 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800307 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700308 mPausedPosition(0),
Eric Laurent21da6472017-11-09 16:29:26 -0800309 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800310{
Eric Laurentf32d7812017-11-30 14:44:07 -0800311 (void)set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800312 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800313 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Andy Hungff874dc2016-04-11 16:49:09 -0700314 uid, pid, pAttributes, doNotReconnect, maxRequiredSpeed);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800315}
316
317AudioTrack::~AudioTrack()
318{
Ray Essicked304702017-12-12 14:00:57 -0800319 // pull together the numbers, before we clean up our structures
320 mMediaMetrics.gather(this);
321
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800322 if (mStatus == NO_ERROR) {
323 // Make sure that callback function exits in the case where
324 // it is looping on buffer full condition in obtainBuffer().
325 // Otherwise the callback thread will never exit.
326 stop();
327 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100328 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800329 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800330 mAudioTrackThread->requestExitAndWait();
331 mAudioTrackThread.clear();
332 }
Eric Laurent296fb132015-05-01 11:38:42 -0700333 // No lock here: worst case we remove a NULL callback which will be a nop
334 if (mDeviceCallback != 0 && mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700335 AudioSystem::removeAudioDeviceCallback(this, mOutput);
Eric Laurent296fb132015-05-01 11:38:42 -0700336 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800337 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700338 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700339 mCblkMemory.clear();
340 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800341 IPCThreadState::self()->flushCommands();
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700342 ALOGV("~AudioTrack, releasing session id %d from %d on behalf of %d",
343 mSessionId, IPCThreadState::self()->getCallingPid(), mClientPid);
Marco Nelissend457c972014-02-11 08:47:07 -0800344 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800345 }
346}
347
348status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800349 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800350 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800351 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700352 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800353 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700354 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800355 callback_t cbf,
356 void* user,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700357 int32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800358 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700359 bool threadCanCallJava,
Glenn Kastend848eb42016-03-08 13:42:11 -0800360 audio_session_t sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000361 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800362 const audio_offload_info_t *offloadInfo,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800363 uid_t uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700364 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700365 const audio_attributes_t* pAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -0700366 bool doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -0700367 float maxRequiredSpeed,
368 audio_port_handle_t selectedDeviceId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800369{
Eric Laurentf32d7812017-11-30 14:44:07 -0800370 status_t status;
371 uint32_t channelCount;
372 pid_t callingPid;
373 pid_t myPid;
374
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800375 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kastenea38ee72016-04-18 11:08:01 -0700376 "flags #%x, notificationFrames %d, sessionId %d, transferType %d, uid %d, pid %d",
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800377 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700378 sessionId, transferType, uid, pid);
Glenn Kasten86f04662014-02-24 15:13:05 -0800379
Phil Burk33ff89b2015-11-30 11:16:01 -0800380 mThreadCanCallJava = threadCanCallJava;
jiabin156c6872017-10-06 09:47:15 -0700381 mSelectedDeviceId = selectedDeviceId;
Eric Laurent21da6472017-11-09 16:29:26 -0800382 mSessionId = sessionId;
Phil Burk33ff89b2015-11-30 11:16:01 -0800383
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800384 switch (transferType) {
385 case TRANSFER_DEFAULT:
386 if (sharedBuffer != 0) {
387 transferType = TRANSFER_SHARED;
388 } else if (cbf == NULL || threadCanCallJava) {
389 transferType = TRANSFER_SYNC;
390 } else {
391 transferType = TRANSFER_CALLBACK;
392 }
393 break;
394 case TRANSFER_CALLBACK:
395 if (cbf == NULL || sharedBuffer != 0) {
396 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
Eric Laurentf32d7812017-11-30 14:44:07 -0800397 status = BAD_VALUE;
398 goto exit;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800399 }
400 break;
401 case TRANSFER_OBTAIN:
402 case TRANSFER_SYNC:
403 if (sharedBuffer != 0) {
404 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
Eric Laurentf32d7812017-11-30 14:44:07 -0800405 status = BAD_VALUE;
406 goto exit;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800407 }
408 break;
409 case TRANSFER_SHARED:
410 if (sharedBuffer == 0) {
411 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
Eric Laurentf32d7812017-11-30 14:44:07 -0800412 status = BAD_VALUE;
413 goto exit;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800414 }
415 break;
416 default:
417 ALOGE("Invalid transfer type %d", transferType);
Eric Laurentf32d7812017-11-30 14:44:07 -0800418 status = BAD_VALUE;
419 goto exit;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800420 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800421 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800422 mTransfer = transferType;
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700423 mDoNotReconnect = doNotReconnect;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800424
Eric Laurent97c9f4f2015-08-11 18:04:14 -0700425 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %zu", sharedBuffer->pointer(),
Glenn Kasten85ab62c2012-11-01 11:11:38 -0700426 sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800427
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700428 ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700429
Glenn Kasten53cec222013-08-29 09:01:02 -0700430 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700431 if (mAudioTrack != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000432 ALOGE("Track already in use");
Eric Laurentf32d7812017-11-30 14:44:07 -0800433 status = INVALID_OPERATION;
434 goto exit;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800435 }
436
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800437 // handle default values first.
Eric Laurente83b55d2014-11-14 10:06:21 -0800438 if (streamType == AUDIO_STREAM_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700439 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800440 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700441 if (pAttributes == NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800442 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700443 ALOGE("Invalid stream type %d", streamType);
Eric Laurentf32d7812017-11-30 14:44:07 -0800444 status = BAD_VALUE;
445 goto exit;
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700446 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700447 mStreamType = streamType;
Eric Laurente83b55d2014-11-14 10:06:21 -0800448
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700449 } else {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700450 // stream type shouldn't be looked at, this track has audio attributes
451 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700452 ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
453 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800454 mStreamType = AUDIO_STREAM_DEFAULT;
Eric Laurentc6bd5db2015-03-09 16:29:33 -0700455 if ((mAttributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
456 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
457 }
Phil Burk33ff89b2015-11-30 11:16:01 -0800458 if ((mAttributes.flags & AUDIO_FLAG_LOW_LATENCY) != 0) {
459 flags = (audio_output_flags_t) (flags | AUDIO_OUTPUT_FLAG_FAST);
460 }
Andy Hungfff204c2017-01-12 19:09:55 -0800461 // check deep buffer after flags have been modified above
462 if (flags == AUDIO_OUTPUT_FLAG_NONE && (mAttributes.flags & AUDIO_FLAG_DEEP_BUFFER) != 0) {
463 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
464 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800465 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700466
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800467 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800468 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700469 format = AUDIO_FORMAT_PCM_16_BIT;
Phil Burkfdb3c072016-02-09 10:47:02 -0800470 } else if (format == AUDIO_FORMAT_IEC61937) { // HDMI pass-through?
471 mAttributes.flags |= AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800472 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800473
474 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700475 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800476 ALOGE("Invalid format %#x", format);
Eric Laurentf32d7812017-11-30 14:44:07 -0800477 status = BAD_VALUE;
478 goto exit;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800479 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800480 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700481
Glenn Kasten8ba90322013-10-30 11:29:27 -0700482 if (!audio_is_output_channel(channelMask)) {
483 ALOGE("Invalid channel mask %#x", channelMask);
Eric Laurentf32d7812017-11-30 14:44:07 -0800484 status = BAD_VALUE;
485 goto exit;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700486 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800487 mChannelMask = channelMask;
Eric Laurentf32d7812017-11-30 14:44:07 -0800488 channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800489 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700490
Eric Laurentc2f1f072009-07-17 12:17:14 -0700491 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100492 // or offload was requested
493 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
494 || !audio_is_linear_pcm(format)) {
495 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
496 ? "Offload request, forcing to Direct Output"
497 : "Not linear PCM, forcing to Direct Output");
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700498 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800499 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700500 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700501 }
502
Eric Laurentd1f69b02014-12-15 14:33:13 -0800503 // force direct flag if HW A/V sync requested
504 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
505 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
506 }
507
Glenn Kastenb7730382014-04-30 15:50:31 -0700508 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Phil Burkfdb3c072016-02-09 10:47:02 -0800509 if (audio_has_proportional_frames(format)) {
Glenn Kastenb7730382014-04-30 15:50:31 -0700510 mFrameSize = channelCount * audio_bytes_per_sample(format);
511 } else {
512 mFrameSize = sizeof(uint8_t);
513 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800514 } else {
Phil Burkfdb3c072016-02-09 10:47:02 -0800515 ALOG_ASSERT(audio_has_proportional_frames(format));
Glenn Kastenb7730382014-04-30 15:50:31 -0700516 mFrameSize = channelCount * audio_bytes_per_sample(format);
Glenn Kastenb7730382014-04-30 15:50:31 -0700517 // createTrack will return an error if PCM format is not supported by server,
518 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800519 }
520
Eric Laurent0d6db582014-11-12 18:39:44 -0800521 // sampling rate must be specified for direct outputs
522 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentf32d7812017-11-30 14:44:07 -0800523 status = BAD_VALUE;
524 goto exit;
Eric Laurent0d6db582014-11-12 18:39:44 -0800525 }
526 mSampleRate = sampleRate;
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700527 mOriginalSampleRate = sampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700528 mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT;
Andy Hungff874dc2016-04-11 16:49:09 -0700529 // 1.0 <= mMaxRequiredSpeed <= AUDIO_TIMESTRETCH_SPEED_MAX
530 mMaxRequiredSpeed = min(max(maxRequiredSpeed, 1.0f), AUDIO_TIMESTRETCH_SPEED_MAX);
Eric Laurent0d6db582014-11-12 18:39:44 -0800531
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800532 // Make copy of input parameter offloadInfo so that in the future:
533 // (a) createTrack_l doesn't need it as an input parameter
534 // (b) we can support re-creation of offloaded tracks
535 if (offloadInfo != NULL) {
536 mOffloadInfoCopy = *offloadInfo;
537 mOffloadInfo = &mOffloadInfoCopy;
538 } else {
539 mOffloadInfo = NULL;
Eric Laurent20b9ef02016-12-05 11:03:16 -0800540 memset(&mOffloadInfoCopy, 0, sizeof(audio_offload_info_t));
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800541 }
542
Glenn Kasten66e46352014-01-16 17:44:23 -0800543 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
544 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800545 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800546 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800547 mReqFrameCount = frameCount;
Glenn Kastenea38ee72016-04-18 11:08:01 -0700548 if (notificationFrames >= 0) {
549 mNotificationFramesReq = notificationFrames;
550 mNotificationsPerBufferReq = 0;
551 } else {
552 if (!(flags & AUDIO_OUTPUT_FLAG_FAST)) {
553 ALOGE("notificationFrames=%d not permitted for non-fast track",
554 notificationFrames);
Eric Laurentf32d7812017-11-30 14:44:07 -0800555 status = BAD_VALUE;
556 goto exit;
Glenn Kastenea38ee72016-04-18 11:08:01 -0700557 }
558 if (frameCount > 0) {
559 ALOGE("notificationFrames=%d not permitted with non-zero frameCount=%zu",
560 notificationFrames, frameCount);
Eric Laurentf32d7812017-11-30 14:44:07 -0800561 status = BAD_VALUE;
562 goto exit;
Glenn Kastenea38ee72016-04-18 11:08:01 -0700563 }
564 mNotificationFramesReq = 0;
565 const uint32_t minNotificationsPerBuffer = 1;
566 const uint32_t maxNotificationsPerBuffer = 8;
567 mNotificationsPerBufferReq = min(maxNotificationsPerBuffer,
568 max((uint32_t) -notificationFrames, minNotificationsPerBuffer));
569 ALOGW_IF(mNotificationsPerBufferReq != (uint32_t) -notificationFrames,
570 "notificationFrames=%d clamped to the range -%u to -%u",
571 notificationFrames, minNotificationsPerBuffer, maxNotificationsPerBuffer);
572 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800573 mNotificationFramesAct = 0;
Eric Laurentf32d7812017-11-30 14:44:07 -0800574 callingPid = IPCThreadState::self()->getCallingPid();
575 myPid = getpid();
576 if (uid == AUDIO_UID_INVALID || (callingPid != myPid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800577 mClientUid = IPCThreadState::self()->getCallingUid();
578 } else {
579 mClientUid = uid;
580 }
Eric Laurentf32d7812017-11-30 14:44:07 -0800581 if (pid == -1 || (callingPid != myPid)) {
582 mClientPid = callingPid;
Marco Nelissend457c972014-02-11 08:47:07 -0800583 } else {
584 mClientPid = pid;
585 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700586 mAuxEffectId = 0;
Haynes Mathew Georgeae34ed22016-01-28 11:58:39 -0800587 mOrigFlags = mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700588 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700589
Glenn Kastena997e7a2012-08-07 09:44:19 -0700590 if (cbf != NULL) {
Eric Laurent896adcd2012-09-13 11:18:23 -0700591 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700592 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
Glenn Kastenbfd31842015-03-20 09:01:44 -0700593 // thread begins in paused state, and will not reference us until start()
Glenn Kastena997e7a2012-08-07 09:44:19 -0700594 }
595
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800596 // create the IAudioTrack
Eric Laurentf32d7812017-11-30 14:44:07 -0800597 status = createTrack_l();
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800598
Glenn Kastena997e7a2012-08-07 09:44:19 -0700599 if (status != NO_ERROR) {
600 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100601 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
602 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700603 mAudioTrackThread.clear();
604 }
Eric Laurentf32d7812017-11-30 14:44:07 -0800605 goto exit;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700606 }
607
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800608 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800609 mLoopCount = 0;
610 mLoopStart = 0;
611 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800612 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800613 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700614 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800615 mNewPosition = 0;
616 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700617 mPosition = 0;
618 mReleased = 0;
Andy Hungffa36952017-08-17 10:41:51 -0700619 mStartNs = 0;
620 mStartFromZeroUs = 0;
Marco Nelissend457c972014-02-11 08:47:07 -0800621 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800622 mSequence = 1;
623 mObservedSequence = mSequence;
624 mInUnderrun = false;
Phil Burk1b420972015-04-22 10:52:21 -0700625 mPreviousTimestampValid = false;
Andy Hungc8e09c62015-06-03 23:43:36 -0700626 mTimestampStartupGlitchReported = false;
627 mRetrogradeMotionReported = false;
Andy Hungb01faa32016-04-27 12:51:32 -0700628 mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
Andy Hung65ffdfc2016-10-10 15:52:11 -0700629 mStartTs.mPosition = 0;
Phil Burk2812d9e2016-01-04 10:34:30 -0800630 mUnderrunCountOffset = 0;
Andy Hungea2b9c02016-02-12 17:06:53 -0800631 mFramesWritten = 0;
632 mFramesWrittenServerOffset = 0;
Andy Hungf20a4e92016-08-15 19:10:34 -0700633 mFramesWrittenAtRestore = -1; // -1 is a unique initializer.
Ivan Lozano8cf3a072017-08-09 09:01:33 -0700634 mVolumeHandler = new media::VolumeHandler();
Eric Laurentf32d7812017-11-30 14:44:07 -0800635
636exit:
637 mStatus = status;
638 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800639}
640
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800641// -------------------------------------------------------------------------
642
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100643status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800644{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800645 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100646
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800647 if (mState == STATE_ACTIVE) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100648 return INVALID_OPERATION;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800649 }
650
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800651 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800652
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800653 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100654 if (previousState == STATE_PAUSED_STOPPING) {
655 mState = STATE_STOPPING;
656 } else {
657 mState = STATE_ACTIVE;
658 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700659 (void) updateAndGetPosition_l();
Andy Hung65ffdfc2016-10-10 15:52:11 -0700660
661 // save start timestamp
662 if (isOffloadedOrDirect_l()) {
663 if (getTimestamp_l(mStartTs) != OK) {
664 mStartTs.mPosition = 0;
665 }
666 } else {
667 if (getTimestamp_l(&mStartEts) != OK) {
668 mStartEts.clear();
669 }
670 }
Andy Hungffa36952017-08-17 10:41:51 -0700671 mStartNs = systemTime(); // save this for timestamp adjustment after starting.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800672 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
673 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700674 mPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -0700675 mPreviousTimestampValid = false;
Andy Hungc8e09c62015-06-03 23:43:36 -0700676 mTimestampStartupGlitchReported = false;
677 mRetrogradeMotionReported = false;
Andy Hungb01faa32016-04-27 12:51:32 -0700678 mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
Phil Burk1b420972015-04-22 10:52:21 -0700679
Andy Hung65ffdfc2016-10-10 15:52:11 -0700680 if (!isOffloadedOrDirect_l()
681 && mStartEts.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] > 0) {
Andy Hunge1e98462016-04-12 10:18:51 -0700682 // Server side has consumed something, but is it finished consuming?
683 // It is possible since flush and stop are asynchronous that the server
684 // is still active at this point.
685 ALOGV("start: server read:%lld cumulative flushed:%lld client written:%lld",
686 (long long)(mFramesWrittenServerOffset
Andy Hung65ffdfc2016-10-10 15:52:11 -0700687 + mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER]),
688 (long long)mStartEts.mFlushed,
Andy Hunge1e98462016-04-12 10:18:51 -0700689 (long long)mFramesWritten);
Andy Hungc4e60eb2017-09-06 11:14:57 -0700690 // mStartEts is already adjusted by mFramesWrittenServerOffset, so we delta adjust.
691 mFramesWrittenServerOffset -= mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung61be8412015-10-06 10:51:09 -0700692 }
Andy Hunge1e98462016-04-12 10:18:51 -0700693 mFramesWritten = 0;
694 mProxy->clearTimestamp(); // need new server push for valid timestamp
695 mMarkerReached = false;
Andy Hung61be8412015-10-06 10:51:09 -0700696
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700697 // For offloaded tracks, we don't know if the hardware counters are really zero here,
698 // since the flush is asynchronous and stop may not fully drain.
699 // We save the time when the track is started to later verify whether
700 // the counters are realistic (i.e. start from zero after this time).
Andy Hungffa36952017-08-17 10:41:51 -0700701 mStartFromZeroUs = mStartNs / 1000;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700702
Eric Laurentec9a0322013-08-28 10:23:01 -0700703 // force refresh of remaining frames by processAudioBuffer() as last
704 // write before stop could be partial.
705 mRefreshRemaining = true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800706 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700707 mNewPosition = mPosition + mUpdatePeriod;
Andy Hung4be3b832016-10-13 17:51:43 -0700708 int32_t flags = android_atomic_and(~(CBLK_STREAM_END_DONE | CBLK_DISABLED), &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800709
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800710 status_t status = NO_ERROR;
711 if (!(flags & CBLK_INVALID)) {
712 status = mAudioTrack->start();
713 if (status == DEAD_OBJECT) {
714 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800715 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800716 }
717 if (flags & CBLK_INVALID) {
718 status = restoreTrack_l("start");
719 }
720
Andy Hung79629f02016-03-24 13:57:40 -0700721 // resume or pause the callback thread as needed.
722 sp<AudioTrackThread> t = mAudioTrackThread;
723 if (status == NO_ERROR) {
724 if (t != 0) {
725 if (previousState == STATE_STOPPING) {
726 mProxy->interrupt();
727 } else {
728 t->resume();
729 }
730 } else {
731 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
732 get_sched_policy(0, &mPreviousSchedulingGroup);
733 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
734 }
Andy Hung39399b62017-04-21 15:07:45 -0700735
736 // Start our local VolumeHandler for restoration purposes.
737 mVolumeHandler->setStarted();
Andy Hung79629f02016-03-24 13:57:40 -0700738 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800739 ALOGE("start() status %d", status);
740 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800741 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100742 if (previousState != STATE_STOPPING) {
743 t->pause();
744 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800745 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700746 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700747 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800748 }
749 }
750
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100751 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800752}
753
754void AudioTrack::stop()
755{
756 AutoMutex lock(mLock);
Glenn Kasten397edb32013-08-30 15:10:13 -0700757 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800758 return;
759 }
760
Glenn Kasten23a75452014-01-13 10:37:17 -0800761 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100762 mState = STATE_STOPPING;
763 } else {
764 mState = STATE_STOPPED;
Andy Hung2148bf02016-11-28 19:01:02 -0800765 ALOGD_IF(mSharedBuffer == nullptr,
766 "stop() called with %u frames delivered", mReleased.value());
Andy Hungc2813e52014-10-16 17:54:34 -0700767 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100768 }
769
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800770 mProxy->interrupt();
771 mAudioTrack->stop();
Andy Hung61be8412015-10-06 10:51:09 -0700772
773 // Note: legacy handling - stop does not clear playback marker
774 // and periodic update counter, but flush does for streaming tracks.
Andy Hung9b461582014-12-01 17:56:29 -0800775
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800776 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800777 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800778 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
779 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800780 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100781
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800782 sp<AudioTrackThread> t = mAudioTrackThread;
783 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800784 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100785 t->pause();
786 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800787 } else {
788 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
789 set_sched_policy(0, mPreviousSchedulingGroup);
790 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800791}
792
793bool AudioTrack::stopped() const
794{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800795 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800796 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800797}
798
799void AudioTrack::flush()
800{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800801 if (mSharedBuffer != 0) {
802 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800803 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800804 AutoMutex lock(mLock);
805 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
806 return;
807 }
808 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800809}
810
Eric Laurent1703cdf2011-03-07 14:52:59 -0800811void AudioTrack::flush_l()
812{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800813 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700814
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700815 // clear playback marker and periodic update counter
816 mMarkerPosition = 0;
817 mMarkerReached = false;
818 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100819 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700820
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800821 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700822 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800823 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100824 mProxy->interrupt();
825 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800826 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800827 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800828}
829
830void AudioTrack::pause()
831{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800832 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100833 if (mState == STATE_ACTIVE) {
834 mState = STATE_PAUSED;
835 } else if (mState == STATE_STOPPING) {
836 mState = STATE_PAUSED_STOPPING;
837 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800838 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800839 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800840 mProxy->interrupt();
841 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800842
Marco Nelissen3a90f282014-03-10 11:21:43 -0700843 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700844 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700845 // An offload output can be re-used between two audio tracks having
846 // the same configuration. A timestamp query for a paused track
847 // while the other is running would return an incorrect time.
848 // To fix this, cache the playback position on a pause() and return
849 // this time when requested until the track is resumed.
850
851 // OffloadThread sends HAL pause in its threadLoop. Time saved
852 // here can be slightly off.
853
854 // TODO: check return code for getRenderPosition.
855
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800856 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800857 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
858 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
859 }
860 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800861}
862
Eric Laurentbe916aa2010-06-01 23:49:17 -0700863status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800864{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700865 // This duplicates a test by AudioTrack JNI, but that is not the only caller
866 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
867 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700868 return BAD_VALUE;
869 }
870
Eric Laurent1703cdf2011-03-07 14:52:59 -0800871 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800872 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
873 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800874
Glenn Kastenc56f3422014-03-21 17:53:17 -0700875 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700876
Glenn Kasten23a75452014-01-13 10:37:17 -0800877 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700878 mAudioTrack->signal();
879 }
Eric Laurentbe916aa2010-06-01 23:49:17 -0700880 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800881}
882
Glenn Kastenb1c09932012-02-27 16:21:04 -0800883status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800884{
Glenn Kastenb1c09932012-02-27 16:21:04 -0800885 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700886}
887
Eric Laurent2beeb502010-07-16 07:43:46 -0700888status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -0700889{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700890 // This duplicates a test by AudioTrack JNI, but that is not the only caller
891 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700892 return BAD_VALUE;
893 }
894
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800895 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700896 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800897 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -0700898
899 return NO_ERROR;
900}
901
Glenn Kastena5224f32012-01-04 12:41:44 -0800902void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -0700903{
904 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800905 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700906 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800907}
908
Glenn Kasten3b16c762012-11-14 08:44:39 -0800909status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800910{
Andy Hung5cbb5782015-03-27 18:39:59 -0700911 AutoMutex lock(mLock);
912 if (rate == mSampleRate) {
913 return NO_ERROR;
914 }
Glenn Kastend79072e2016-01-06 08:41:20 -0800915 if (isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
John Grossman4ff14ba2012-02-08 16:37:41 -0800916 return INVALID_OPERATION;
917 }
Eric Laurent0d6db582014-11-12 18:39:44 -0800918 if (mOutput == AUDIO_IO_HANDLE_NONE) {
919 return NO_INIT;
920 }
Andy Hung5cbb5782015-03-27 18:39:59 -0700921 // NOTE: it is theoretically possible, but highly unlikely, that a device change
922 // could mean a previously allowed sampling rate is no longer allowed.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800923 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -0800924 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -0700925 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800926 }
Andy Hung26145642015-04-15 21:56:53 -0700927 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700928 const uint32_t effectiveSampleRate = adjustSampleRate(rate, mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -0700929 if (rate == 0 || effectiveSampleRate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -0700930 return BAD_VALUE;
931 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700932 // TODO: Should we also check if the buffer size is compatible?
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800933
Glenn Kastene3aa6592012-12-04 12:22:46 -0800934 mSampleRate = rate;
Andy Hung26145642015-04-15 21:56:53 -0700935 mProxy->setSampleRate(effectiveSampleRate);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800936
Eric Laurent57326622009-07-07 07:10:45 -0700937 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800938}
939
Glenn Kastena5224f32012-01-04 12:41:44 -0800940uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800941{
Eric Laurent1703cdf2011-03-07 14:52:59 -0800942 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -0700943
944 // sample rate can be updated during playback by the offloaded decoder so we need to
945 // query the HAL and update if needed.
946// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -0700947 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700948 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -0700949 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -0700950 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -0700951 if (status == NO_ERROR) {
952 mSampleRate = sampleRate;
953 }
954 }
955 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800956 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800957}
958
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700959uint32_t AudioTrack::getOriginalSampleRate() const
960{
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700961 return mOriginalSampleRate;
962}
963
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700964status_t AudioTrack::setPlaybackRate(const AudioPlaybackRate &playbackRate)
Andy Hung8edb8dc2015-03-26 19:13:55 -0700965{
Andy Hung8edb8dc2015-03-26 19:13:55 -0700966 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700967 if (isAudioPlaybackRateEqual(playbackRate, mPlaybackRate)) {
Andy Hung8edb8dc2015-03-26 19:13:55 -0700968 return NO_ERROR;
969 }
Glenn Kastend79072e2016-01-06 08:41:20 -0800970 if (isOffloadedOrDirect_l()) {
Andy Hung8edb8dc2015-03-26 19:13:55 -0700971 return INVALID_OPERATION;
972 }
973 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
974 return INVALID_OPERATION;
975 }
Andy Hungff874dc2016-04-11 16:49:09 -0700976
977 ALOGV("setPlaybackRate (input): mSampleRate:%u mSpeed:%f mPitch:%f",
978 mSampleRate, playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -0700979 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700980 const uint32_t effectiveRate = adjustSampleRate(mSampleRate, playbackRate.mPitch);
981 const float effectiveSpeed = adjustSpeed(playbackRate.mSpeed, playbackRate.mPitch);
982 const float effectivePitch = adjustPitch(playbackRate.mPitch);
Ricardo Garcia6c7f0622015-04-30 18:39:16 -0700983 AudioPlaybackRate playbackRateTemp = playbackRate;
984 playbackRateTemp.mSpeed = effectiveSpeed;
985 playbackRateTemp.mPitch = effectivePitch;
986
Andy Hungff874dc2016-04-11 16:49:09 -0700987 ALOGV("setPlaybackRate (effective): mSampleRate:%u mSpeed:%f mPitch:%f",
988 effectiveRate, effectiveSpeed, effectivePitch);
989
Ricardo Garcia6c7f0622015-04-30 18:39:16 -0700990 if (!isAudioPlaybackRateValid(playbackRateTemp)) {
Kevin Rocard4e728d42017-04-06 18:00:40 -0700991 ALOGW("setPlaybackRate(%f, %f) failed (effective rate out of bounds)",
Andy Hungff874dc2016-04-11 16:49:09 -0700992 playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -0700993 return BAD_VALUE;
994 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700995 // Check if the buffer size is compatible.
Andy Hung26145642015-04-15 21:56:53 -0700996 if (!isSampleRateSpeedAllowed_l(effectiveRate, effectiveSpeed)) {
Kevin Rocard4e728d42017-04-06 18:00:40 -0700997 ALOGW("setPlaybackRate(%f, %f) failed (buffer size)",
Andy Hungff874dc2016-04-11 16:49:09 -0700998 playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung8edb8dc2015-03-26 19:13:55 -0700999 return BAD_VALUE;
1000 }
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001001
Ricardo Garcia6c7f0622015-04-30 18:39:16 -07001002 // Check resampler ratios are within bounds
Glenn Kastend3bb6452016-12-05 18:14:37 -08001003 if ((uint64_t)effectiveRate > (uint64_t)mSampleRate *
1004 (uint64_t)AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Kevin Rocard4e728d42017-04-06 18:00:40 -07001005 ALOGW("setPlaybackRate(%f, %f) failed. Resample rate exceeds max accepted value",
Ricardo Garcia6c7f0622015-04-30 18:39:16 -07001006 playbackRate.mSpeed, playbackRate.mPitch);
1007 return BAD_VALUE;
1008 }
1009
Dan Austine34eae22015-10-27 16:14:52 -07001010 if ((uint64_t)effectiveRate * (uint64_t)AUDIO_RESAMPLER_UP_RATIO_MAX < (uint64_t)mSampleRate) {
Kevin Rocard4e728d42017-04-06 18:00:40 -07001011 ALOGW("setPlaybackRate(%f, %f) failed. Resample rate below min accepted value",
Ricardo Garcia6c7f0622015-04-30 18:39:16 -07001012 playbackRate.mSpeed, playbackRate.mPitch);
1013 return BAD_VALUE;
1014 }
1015 mPlaybackRate = playbackRate;
1016 //set effective rates
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001017 mProxy->setPlaybackRate(playbackRateTemp);
Andy Hung26145642015-04-15 21:56:53 -07001018 mProxy->setSampleRate(effectiveRate); // FIXME: not quite "atomic" with setPlaybackRate
Andy Hung8edb8dc2015-03-26 19:13:55 -07001019 return NO_ERROR;
1020}
1021
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001022const AudioPlaybackRate& AudioTrack::getPlaybackRate() const
Andy Hung8edb8dc2015-03-26 19:13:55 -07001023{
1024 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001025 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001026}
1027
Phil Burkc0adecb2016-01-08 12:44:11 -08001028ssize_t AudioTrack::getBufferSizeInFrames()
1029{
1030 AutoMutex lock(mLock);
1031 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1032 return NO_INIT;
1033 }
Phil Burke8972b02016-03-04 11:29:57 -08001034 return (ssize_t) mProxy->getBufferSizeInFrames();
Phil Burkc0adecb2016-01-08 12:44:11 -08001035}
1036
Andy Hungf2c87b32016-04-07 19:49:29 -07001037status_t AudioTrack::getBufferDurationInUs(int64_t *duration)
1038{
1039 if (duration == nullptr) {
1040 return BAD_VALUE;
1041 }
1042 AutoMutex lock(mLock);
1043 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1044 return NO_INIT;
1045 }
1046 ssize_t bufferSizeInFrames = (ssize_t) mProxy->getBufferSizeInFrames();
1047 if (bufferSizeInFrames < 0) {
1048 return (status_t)bufferSizeInFrames;
1049 }
1050 *duration = (int64_t)((double)bufferSizeInFrames * 1000000
1051 / ((double)mSampleRate * mPlaybackRate.mSpeed));
1052 return NO_ERROR;
1053}
1054
Phil Burkc0adecb2016-01-08 12:44:11 -08001055ssize_t AudioTrack::setBufferSizeInFrames(size_t bufferSizeInFrames)
1056{
1057 AutoMutex lock(mLock);
1058 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1059 return NO_INIT;
1060 }
1061 // Reject if timed track or compressed audio.
Glenn Kastend79072e2016-01-06 08:41:20 -08001062 if (!audio_is_linear_pcm(mFormat)) {
Phil Burkc0adecb2016-01-08 12:44:11 -08001063 return INVALID_OPERATION;
1064 }
Phil Burke8972b02016-03-04 11:29:57 -08001065 return (ssize_t) mProxy->setBufferSizeInFrames((uint32_t) bufferSizeInFrames);
Phil Burkc0adecb2016-01-08 12:44:11 -08001066}
1067
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001068status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
1069{
Glenn Kastend79072e2016-01-06 08:41:20 -08001070 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -08001071 return INVALID_OPERATION;
1072 }
1073
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001074 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001075 ;
1076 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
1077 loopEnd - loopStart >= MIN_LOOP) {
1078 ;
1079 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001080 return BAD_VALUE;
1081 }
1082
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001083 AutoMutex lock(mLock);
1084 // See setPosition() regarding setting parameters such as loop points or position while active
1085 if (mState == STATE_ACTIVE) {
1086 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001087 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001088 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001089 return NO_ERROR;
1090}
1091
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001092void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
1093{
Andy Hung4ede21d2014-12-12 15:37:34 -08001094 // We do not update the periodic notification point.
1095 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
1096 mLoopCount = loopCount;
1097 mLoopEnd = loopEnd;
1098 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -08001099 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001100 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -08001101
1102 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001103}
1104
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001105status_t AudioTrack::setMarkerPosition(uint32_t marker)
1106{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001107 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -07001108 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001109 return INVALID_OPERATION;
1110 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001111
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001112 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001113 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -07001114 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001115
Andy Hung3c09c782014-12-29 18:39:32 -08001116 sp<AudioTrackThread> t = mAudioTrackThread;
1117 if (t != 0) {
1118 t->wake();
1119 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001120 return NO_ERROR;
1121}
1122
Glenn Kastena5224f32012-01-04 12:41:44 -08001123status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001124{
Eric Laurentab5cdba2014-06-09 17:22:27 -07001125 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001126 return INVALID_OPERATION;
1127 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001128 if (marker == NULL) {
1129 return BAD_VALUE;
1130 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001131
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001132 AutoMutex lock(mLock);
Andy Hung90e8a972015-11-09 16:42:40 -08001133 mMarkerPosition.getValue(marker);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001134
1135 return NO_ERROR;
1136}
1137
1138status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
1139{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001140 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -07001141 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001142 return INVALID_OPERATION;
1143 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001144
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001145 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001146 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001147 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -08001148
Andy Hung3c09c782014-12-29 18:39:32 -08001149 sp<AudioTrackThread> t = mAudioTrackThread;
1150 if (t != 0) {
1151 t->wake();
1152 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001153 return NO_ERROR;
1154}
1155
Glenn Kastena5224f32012-01-04 12:41:44 -08001156status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001157{
Eric Laurentab5cdba2014-06-09 17:22:27 -07001158 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001159 return INVALID_OPERATION;
1160 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001161 if (updatePeriod == NULL) {
1162 return BAD_VALUE;
1163 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001164
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001165 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001166 *updatePeriod = mUpdatePeriod;
1167
1168 return NO_ERROR;
1169}
1170
1171status_t AudioTrack::setPosition(uint32_t position)
1172{
Glenn Kastend79072e2016-01-06 08:41:20 -08001173 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001174 return INVALID_OPERATION;
1175 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001176 if (position > mFrameCount) {
1177 return BAD_VALUE;
1178 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001179
Eric Laurent1703cdf2011-03-07 14:52:59 -08001180 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001181 // Currently we require that the player is inactive before setting parameters such as position
1182 // or loop points. Otherwise, there could be a race condition: the application could read the
1183 // current position, compute a new position or loop parameters, and then set that position or
1184 // loop parameters but it would do the "wrong" thing since the position has continued to advance
1185 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
1186 // to specify how it wants to handle such scenarios.
1187 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001188 return INVALID_OPERATION;
1189 }
Andy Hung9b461582014-12-01 17:56:29 -08001190 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -07001191 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -08001192 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -08001193
1194 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001195 return NO_ERROR;
1196}
1197
Glenn Kasten200092b2014-08-15 15:13:30 -07001198status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001199{
Glenn Kastend65d73c2012-06-22 17:21:07 -07001200 if (position == NULL) {
1201 return BAD_VALUE;
1202 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001203
Eric Laurent1703cdf2011-03-07 14:52:59 -08001204 AutoMutex lock(mLock);
Andy Hung7a490e72016-03-23 15:58:10 -07001205 // FIXME: offloaded and direct tracks call into the HAL for render positions
1206 // for compressed/synced data; however, we use proxy position for pure linear pcm data
1207 // as we do not know the capability of the HAL for pcm position support and standby.
1208 // There may be some latency differences between the HAL position and the proxy position.
1209 if (isOffloadedOrDirect_l() && !isPurePcmData_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001210 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001211
Eric Laurentab5cdba2014-06-09 17:22:27 -07001212 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Haynes Mathew George7064fd22014-01-08 13:59:53 -08001213 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
1214 *position = mPausedPosition;
1215 return NO_ERROR;
1216 }
1217
Glenn Kasten142f5192014-03-25 17:44:59 -07001218 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung1f1db832015-06-08 13:26:10 -07001219 uint32_t halFrames; // actually unused
1220 (void) AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
1221 // FIXME: on getRenderPosition() error, we return OK with frame position 0.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001222 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001223 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
1224 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001225 *position = dspFrames;
1226 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -08001227 if (mCblk->mFlags & CBLK_INVALID) {
Andy Hung1f1db832015-06-08 13:26:10 -07001228 (void) restoreTrack_l("getPosition");
1229 // FIXME: for compatibility with the Java API we ignore the restoreTrack_l()
1230 // error here (e.g. DEAD_OBJECT) and return OK with the last recorded server position.
Eric Laurent275e8e92014-11-30 15:14:47 -08001231 }
1232
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001233 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -07001234 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
Andy Hung90e8a972015-11-09 16:42:40 -08001235 0 : updateAndGetPosition_l().value();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001236 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001237 return NO_ERROR;
1238}
1239
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001240status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001241{
Glenn Kastend79072e2016-01-06 08:41:20 -08001242 if (mSharedBuffer == 0) {
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001243 return INVALID_OPERATION;
1244 }
1245 if (position == NULL) {
1246 return BAD_VALUE;
1247 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001248
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001249 AutoMutex lock(mLock);
1250 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001251 return NO_ERROR;
1252}
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001253
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001254status_t AudioTrack::reload()
1255{
Glenn Kastend79072e2016-01-06 08:41:20 -08001256 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -08001257 return INVALID_OPERATION;
1258 }
1259
Eric Laurent1703cdf2011-03-07 14:52:59 -08001260 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001261 // See setPosition() regarding setting parameters such as loop points or position while active
1262 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001263 return INVALID_OPERATION;
1264 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001265 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -08001266 (void) updateAndGetPosition_l();
1267 mPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -07001268 mPreviousTimestampValid = false;
Andy Hung53c3b5f2014-12-15 16:42:05 -08001269#if 0
Andy Hung9b461582014-12-01 17:56:29 -08001270 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -08001271 // of loop count. Historically we have not restored loop count, start, end,
1272 // but it makes sense if one desires to repeat playing a particular sound.
1273 if (mLoopCount != 0) {
1274 mLoopCountNotified = mLoopCount;
1275 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
1276 }
1277#endif
Andy Hung9b461582014-12-01 17:56:29 -08001278 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001279 return NO_ERROR;
1280}
1281
Glenn Kasten38e905b2014-01-13 10:21:48 -08001282audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -07001283{
Eric Laurent1703cdf2011-03-07 14:52:59 -08001284 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001285 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001286}
1287
Paul McLeanaa981192015-03-21 09:55:15 -07001288status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
1289 AutoMutex lock(mLock);
1290 if (mSelectedDeviceId != deviceId) {
1291 mSelectedDeviceId = deviceId;
Eric Laurentfb00fc72017-05-25 18:17:12 -07001292 if (mStatus == NO_ERROR) {
1293 android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
jiabin156c6872017-10-06 09:47:15 -07001294 mProxy->interrupt();
Eric Laurentfb00fc72017-05-25 18:17:12 -07001295 }
Paul McLeanaa981192015-03-21 09:55:15 -07001296 }
Eric Laurent493404d2015-04-21 15:07:36 -07001297 return NO_ERROR;
Paul McLeanaa981192015-03-21 09:55:15 -07001298}
1299
1300audio_port_handle_t AudioTrack::getOutputDevice() {
1301 AutoMutex lock(mLock);
1302 return mSelectedDeviceId;
1303}
1304
Eric Laurentad2e7b92017-09-14 20:06:42 -07001305// must be called with mLock held
1306void AudioTrack::updateRoutedDeviceId_l()
1307{
1308 // if the track is inactive, do not update actual device as the output stream maybe routed
1309 // to a device not relevant to this client because of other active use cases.
1310 if (mState != STATE_ACTIVE) {
1311 return;
1312 }
1313 if (mOutput != AUDIO_IO_HANDLE_NONE) {
1314 audio_port_handle_t deviceId = AudioSystem::getDeviceIdForIo(mOutput);
1315 if (deviceId != AUDIO_PORT_HANDLE_NONE) {
1316 mRoutedDeviceId = deviceId;
1317 }
1318 }
1319}
1320
Eric Laurent296fb132015-05-01 11:38:42 -07001321audio_port_handle_t AudioTrack::getRoutedDeviceId() {
1322 AutoMutex lock(mLock);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001323 updateRoutedDeviceId_l();
1324 return mRoutedDeviceId;
Eric Laurent296fb132015-05-01 11:38:42 -07001325}
1326
Eric Laurentbe916aa2010-06-01 23:49:17 -07001327status_t AudioTrack::attachAuxEffect(int effectId)
1328{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001329 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001330 status_t status = mAudioTrack->attachAuxEffect(effectId);
1331 if (status == NO_ERROR) {
1332 mAuxEffectId = effectId;
1333 }
1334 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -07001335}
1336
Eric Laurente83b55d2014-11-14 10:06:21 -08001337audio_stream_type_t AudioTrack::streamType() const
1338{
1339 if (mStreamType == AUDIO_STREAM_DEFAULT) {
1340 return audio_attributes_to_stream_type(&mAttributes);
1341 }
1342 return mStreamType;
1343}
1344
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001345uint32_t AudioTrack::latency()
1346{
1347 AutoMutex lock(mLock);
1348 updateLatency_l();
1349 return mLatency;
1350}
1351
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001352// -------------------------------------------------------------------------
1353
Eric Laurent1703cdf2011-03-07 14:52:59 -08001354// must be called with mLock held
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001355void AudioTrack::updateLatency_l()
1356{
1357 status_t status = AudioSystem::getLatency(mOutput, &mAfLatency);
1358 if (status != NO_ERROR) {
1359 ALOGW("getLatency(%d) failed status %d", mOutput, status);
1360 } else {
1361 // FIXME don't believe this lie
Andy Hung13969262017-09-11 17:24:21 -07001362 mLatency = mAfLatency + (1000LL * mFrameCount) / mSampleRate;
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001363 }
1364}
1365
Phil Burkadbb75a2017-06-16 12:19:42 -07001366// TODO Move this macro to a common header file for enum to string conversion in audio framework.
1367#define MEDIA_CASE_ENUM(name) case name: return #name
1368const char * AudioTrack::convertTransferToText(transfer_type transferType) {
1369 switch (transferType) {
1370 MEDIA_CASE_ENUM(TRANSFER_DEFAULT);
1371 MEDIA_CASE_ENUM(TRANSFER_CALLBACK);
1372 MEDIA_CASE_ENUM(TRANSFER_OBTAIN);
1373 MEDIA_CASE_ENUM(TRANSFER_SYNC);
1374 MEDIA_CASE_ENUM(TRANSFER_SHARED);
1375 default:
1376 return "UNRECOGNIZED";
1377 }
1378}
1379
Glenn Kasten200092b2014-08-15 15:13:30 -07001380status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001381{
Eric Laurentf32d7812017-11-30 14:44:07 -08001382 status_t status;
1383 bool callbackAdded = false;
1384
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001385 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
1386 if (audioFlinger == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001387 ALOGE("Could not get audioflinger");
Eric Laurentf32d7812017-11-30 14:44:07 -08001388 status = NO_INIT;
1389 goto exit;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001390 }
1391
Eric Laurent21da6472017-11-09 16:29:26 -08001392 {
Haynes Mathew Georgeae34ed22016-01-28 11:58:39 -08001393 // mFlags (not mOrigFlags) is modified depending on whether fast request is accepted.
1394 // After fast request is denied, we will request again if IAudioTrack is re-created.
Glenn Kastend79072e2016-01-06 08:41:20 -08001395 // Client can only express a preference for FAST. Server will perform additional tests.
Phil Burk33ff89b2015-11-30 11:16:01 -08001396 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Phil Burkadbb75a2017-06-16 12:19:42 -07001397 // either of these use cases:
1398 // use case 1: shared buffer
1399 bool sharedBuffer = mSharedBuffer != 0;
1400 bool transferAllowed =
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001401 // use case 2: callback transfer mode
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001402 (mTransfer == TRANSFER_CALLBACK) ||
1403 // use case 3: obtain/release mode
Phil Burk33ff89b2015-11-30 11:16:01 -08001404 (mTransfer == TRANSFER_OBTAIN) ||
1405 // use case 4: synchronous write
1406 ((mTransfer == TRANSFER_SYNC) && mThreadCanCallJava);
Phil Burkadbb75a2017-06-16 12:19:42 -07001407
Eric Laurent21da6472017-11-09 16:29:26 -08001408 bool fastAllowed = sharedBuffer || transferAllowed;
1409 if (!fastAllowed) {
Glenn Kasten9bf34d52017-10-24 14:26:23 -07001410 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client, not shared buffer and transfer = %s",
Phil Burkadbb75a2017-06-16 12:19:42 -07001411 convertTransferToText(mTransfer));
Phil Burk33ff89b2015-11-30 11:16:01 -08001412 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1413 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001414 }
1415
Eric Laurent21da6472017-11-09 16:29:26 -08001416 IAudioFlinger::CreateTrackInput input;
1417 if (mStreamType != AUDIO_STREAM_DEFAULT) {
1418 stream_type_to_audio_attributes(mStreamType, &input.attr);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001419 } else {
Eric Laurent21da6472017-11-09 16:29:26 -08001420 input.attr = mAttributes;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001421 }
Eric Laurent21da6472017-11-09 16:29:26 -08001422 input.config = AUDIO_CONFIG_INITIALIZER;
1423 input.config.sample_rate = mSampleRate;
1424 input.config.channel_mask = mChannelMask;
1425 input.config.format = mFormat;
1426 input.config.offload_info = mOffloadInfoCopy;
1427 input.clientInfo.clientUid = mClientUid;
1428 input.clientInfo.clientPid = mClientPid;
1429 input.clientInfo.clientTid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001430 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten47d55172017-05-23 11:19:30 -07001431 // It is currently meaningless to request SCHED_FIFO for a Java thread. Even if the
1432 // application-level code follows all non-blocking design rules, the language runtime
1433 // doesn't also follow those rules, so the thread will not benefit overall.
Phil Burk33ff89b2015-11-30 11:16:01 -08001434 if (mAudioTrackThread != 0 && !mThreadCanCallJava) {
Eric Laurent21da6472017-11-09 16:29:26 -08001435 input.clientInfo.clientTid = mAudioTrackThread->getTid();
Glenn Kasten3acbd052012-02-28 10:39:56 -08001436 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001437 }
Eric Laurent21da6472017-11-09 16:29:26 -08001438 input.sharedBuffer = mSharedBuffer;
1439 input.notificationsPerBuffer = mNotificationsPerBufferReq;
1440 input.speed = 1.0;
1441 if (audio_has_proportional_frames(mFormat) && mSharedBuffer == 0 &&
1442 (mFlags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1443 input.speed = !isPurePcmData_l() || isOffloadedOrDirect_l() ? 1.0f :
1444 max(mMaxRequiredSpeed, mPlaybackRate.mSpeed);
1445 }
1446 input.flags = mFlags;
1447 input.frameCount = mReqFrameCount;
1448 input.notificationFrameCount = mNotificationFramesReq;
1449 input.selectedDeviceId = mSelectedDeviceId;
1450 input.sessionId = mSessionId;
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001451
Eric Laurent21da6472017-11-09 16:29:26 -08001452 IAudioFlinger::CreateTrackOutput output;
1453
1454 sp<IAudioTrack> track = audioFlinger->createTrack(input,
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001455 output,
Eric Laurent21da6472017-11-09 16:29:26 -08001456 &status);
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001457
Eric Laurent21da6472017-11-09 16:29:26 -08001458 if (status != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
1459 ALOGE("AudioFlinger could not create track, status: %d output %d", status, output.outputId);
Eric Laurentf32d7812017-11-30 14:44:07 -08001460 if (status == NO_ERROR) {
1461 status = NO_INIT;
1462 }
1463 goto exit;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001464 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001465 ALOG_ASSERT(track != 0);
1466
Eric Laurent21da6472017-11-09 16:29:26 -08001467 mFrameCount = output.frameCount;
1468 mNotificationFramesAct = (uint32_t)output.notificationFrameCount;
1469 mRoutedDeviceId = output.selectedDeviceId;
1470 mSessionId = output.sessionId;
1471
1472 mSampleRate = output.sampleRate;
1473 if (mOriginalSampleRate == 0) {
1474 mOriginalSampleRate = mSampleRate;
1475 }
1476
1477 mAfFrameCount = output.afFrameCount;
1478 mAfSampleRate = output.afSampleRate;
1479 mAfLatency = output.afLatencyMs;
1480
1481 mLatency = mAfLatency + (1000LL * mFrameCount) / mSampleRate;
1482
Glenn Kasten38e905b2014-01-13 10:21:48 -08001483 // AudioFlinger now owns the reference to the I/O handle,
1484 // so we are no longer responsible for releasing it.
1485
Glenn Kasten7fd04222016-02-02 12:38:16 -08001486 // FIXME compare to AudioRecord
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001487 sp<IMemory> iMem = track->getCblk();
1488 if (iMem == 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001489 ALOGE("Could not get control block");
Eric Laurentad2e7b92017-09-14 20:06:42 -07001490 status = NO_INIT;
Eric Laurentf32d7812017-11-30 14:44:07 -08001491 goto exit;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001492 }
Glenn Kasten0cde0762014-01-16 15:06:36 -08001493 void *iMemPointer = iMem->pointer();
1494 if (iMemPointer == NULL) {
1495 ALOGE("Could not get control block pointer");
Eric Laurentad2e7b92017-09-14 20:06:42 -07001496 status = NO_INIT;
Eric Laurentf32d7812017-11-30 14:44:07 -08001497 goto exit;
Glenn Kasten0cde0762014-01-16 15:06:36 -08001498 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001499 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001500 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001501 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001502 mDeathNotifier.clear();
1503 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001504 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001505 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001506 IPCThreadState::self()->flushCommands();
1507
Glenn Kasten0cde0762014-01-16 15:06:36 -08001508 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001509 mCblk = cblk;
Glenn Kasten5f631512014-02-24 15:16:07 -08001510
Glenn Kastena07f17c2013-04-23 12:39:37 -07001511 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001512 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent21da6472017-11-09 16:29:26 -08001513 if (output.flags & AUDIO_OUTPUT_FLAG_FAST) {
1514 ALOGI("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu -> %zu",
1515 mReqFrameCount, mFrameCount);
Phil Burk33ff89b2015-11-30 11:16:01 -08001516 if (!mThreadCanCallJava) {
1517 mAwaitBoost = true;
1518 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001519 } else {
Eric Laurent21da6472017-11-09 16:29:26 -08001520 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu -> %zu", mReqFrameCount,
1521 mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001522 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001523 }
Eric Laurent21da6472017-11-09 16:29:26 -08001524 mFlags = output.flags;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001525
Eric Laurentad2e7b92017-09-14 20:06:42 -07001526 //mOutput != output includes the case where mOutput == AUDIO_IO_HANDLE_NONE for first creation
Eric Laurent21da6472017-11-09 16:29:26 -08001527 if (mDeviceCallback != 0 && mOutput != output.outputId) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001528 if (mOutput != AUDIO_IO_HANDLE_NONE) {
1529 AudioSystem::removeAudioDeviceCallback(this, mOutput);
1530 }
Eric Laurent21da6472017-11-09 16:29:26 -08001531 AudioSystem::addAudioDeviceCallback(this, output.outputId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001532 callbackAdded = true;
1533 }
1534
Glenn Kasten38e905b2014-01-13 10:21:48 -08001535 // We retain a copy of the I/O handle, but don't own the reference
Eric Laurent21da6472017-11-09 16:29:26 -08001536 mOutput = output.outputId;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001537 mRefreshRemaining = true;
1538
1539 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1540 // is the value of pointer() for the shared buffer, otherwise buffers points
1541 // immediately after the control block. This address is for the mapping within client
1542 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1543 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001544 if (mSharedBuffer == 0) {
Glenn Kasten138d6f92015-03-20 10:54:51 -07001545 buffers = cblk + 1;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001546 } else {
Glenn Kasten363fb752014-01-15 12:27:31 -08001547 buffers = mSharedBuffer->pointer();
Glenn Kasten138d6f92015-03-20 10:54:51 -07001548 if (buffers == NULL) {
1549 ALOGE("Could not get buffer pointer");
Eric Laurentad2e7b92017-09-14 20:06:42 -07001550 status = NO_INIT;
Eric Laurentf32d7812017-11-30 14:44:07 -08001551 goto exit;
Glenn Kasten138d6f92015-03-20 10:54:51 -07001552 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001553 }
1554
Eric Laurent2beeb502010-07-16 07:43:46 -07001555 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kasten5f631512014-02-24 15:16:07 -08001556
Glenn Kasten093000f2012-05-03 09:35:36 -07001557 // If IAudioTrack is re-created, don't let the requested frameCount
1558 // decrease. This can confuse clients that cache frameCount().
Eric Laurent21da6472017-11-09 16:29:26 -08001559 if (mFrameCount > mReqFrameCount) {
1560 mReqFrameCount = mFrameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001561 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001562
Andy Hungd7bd69e2015-07-24 07:52:41 -07001563 // reset server position to 0 as we have new cblk.
1564 mServer = 0;
1565
Glenn Kastene3aa6592012-12-04 12:22:46 -08001566 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001567 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001568 mStaticProxy.clear();
Eric Laurent21da6472017-11-09 16:29:26 -08001569 mProxy = new AudioTrackClientProxy(cblk, buffers, mFrameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001570 } else {
Eric Laurent21da6472017-11-09 16:29:26 -08001571 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, mFrameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001572 mProxy = mStaticProxy;
1573 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001574
1575 mProxy->setVolumeLR(gain_minifloat_pack(
1576 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1577 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1578
Glenn Kastene3aa6592012-12-04 12:22:46 -08001579 mProxy->setSendLevel(mSendLevel);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001580 const uint32_t effectiveSampleRate = adjustSampleRate(mSampleRate, mPlaybackRate.mPitch);
1581 const float effectiveSpeed = adjustSpeed(mPlaybackRate.mSpeed, mPlaybackRate.mPitch);
1582 const float effectivePitch = adjustPitch(mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001583 mProxy->setSampleRate(effectiveSampleRate);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001584
1585 AudioPlaybackRate playbackRateTemp = mPlaybackRate;
1586 playbackRateTemp.mSpeed = effectiveSpeed;
1587 playbackRateTemp.mPitch = effectivePitch;
1588 mProxy->setPlaybackRate(playbackRateTemp);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001589 mProxy->setMinimum(mNotificationFramesAct);
1590
1591 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001592 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001593
Glenn Kasten38e905b2014-01-13 10:21:48 -08001594 }
1595
Eric Laurentf32d7812017-11-30 14:44:07 -08001596exit:
1597 if (status != NO_ERROR && callbackAdded) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001598 // note: mOutput is always valid is callbackAdded is true
1599 AudioSystem::removeAudioDeviceCallback(this, mOutput);
1600 }
Eric Laurentf32d7812017-11-30 14:44:07 -08001601
1602 mStatus = status;
Eric Laurent21da6472017-11-09 16:29:26 -08001603
1604 // sp<IAudioTrack> track destructor will cause releaseOutput() to be called by AudioFlinger
Glenn Kasten38e905b2014-01-13 10:21:48 -08001605 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001606}
1607
Glenn Kastenb46f3942015-03-09 12:00:30 -07001608status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001609{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001610 if (audioBuffer == NULL) {
Glenn Kasten551b5352015-03-20 11:30:28 -07001611 if (nonContig != NULL) {
1612 *nonContig = 0;
1613 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001614 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001615 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001616 if (mTransfer != TRANSFER_OBTAIN) {
1617 audioBuffer->frameCount = 0;
1618 audioBuffer->size = 0;
1619 audioBuffer->raw = NULL;
Glenn Kasten551b5352015-03-20 11:30:28 -07001620 if (nonContig != NULL) {
1621 *nonContig = 0;
1622 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001623 return INVALID_OPERATION;
1624 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001625
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001626 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001627 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001628 if (waitCount == -1) {
1629 requested = &ClientProxy::kForever;
1630 } else if (waitCount == 0) {
1631 requested = &ClientProxy::kNonBlocking;
1632 } else if (waitCount > 0) {
1633 long long ms = WAIT_PERIOD_MS * (long long) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001634 timeout.tv_sec = ms / 1000;
1635 timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1636 requested = &timeout;
1637 } else {
1638 ALOGE("%s invalid waitCount %d", __func__, waitCount);
1639 requested = NULL;
1640 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001641 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001642}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001643
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001644status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1645 struct timespec *elapsed, size_t *nonContig)
1646{
1647 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1648 uint32_t oldSequence = 0;
1649 uint32_t newSequence;
1650
1651 Proxy::Buffer buffer;
1652 status_t status = NO_ERROR;
1653
1654 static const int32_t kMaxTries = 5;
1655 int32_t tryCounter = kMaxTries;
1656
1657 do {
1658 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1659 // keep them from going away if another thread re-creates the track during obtainBuffer()
1660 sp<AudioTrackClientProxy> proxy;
1661 sp<IMemory> iMem;
1662
1663 { // start of lock scope
1664 AutoMutex lock(mLock);
1665
1666 newSequence = mSequence;
1667 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1668 if (status == DEAD_OBJECT) {
1669 // re-create track, unless someone else has already done so
1670 if (newSequence == oldSequence) {
1671 status = restoreTrack_l("obtainBuffer");
1672 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001673 buffer.mFrameCount = 0;
1674 buffer.mRaw = NULL;
1675 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001676 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001677 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001678 }
1679 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001680 oldSequence = newSequence;
1681
Eric Laurent4d231dc2016-03-11 18:38:23 -08001682 if (status == NOT_ENOUGH_DATA) {
1683 restartIfDisabled();
1684 }
1685
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001686 // Keep the extra references
1687 proxy = mProxy;
1688 iMem = mCblkMemory;
1689
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001690 if (mState == STATE_STOPPING) {
1691 status = -EINTR;
1692 buffer.mFrameCount = 0;
1693 buffer.mRaw = NULL;
1694 buffer.mNonContig = 0;
1695 break;
1696 }
1697
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001698 // Non-blocking if track is stopped or paused
1699 if (mState != STATE_ACTIVE) {
1700 requested = &ClientProxy::kNonBlocking;
1701 }
1702
1703 } // end of lock scope
1704
1705 buffer.mFrameCount = audioBuffer->frameCount;
1706 // FIXME starts the requested timeout and elapsed over from scratch
1707 status = proxy->obtainBuffer(&buffer, requested, elapsed);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001708 } while (((status == DEAD_OBJECT) || (status == NOT_ENOUGH_DATA)) && (tryCounter-- > 0));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001709
1710 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001711 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001712 audioBuffer->raw = buffer.mRaw;
1713 if (nonContig != NULL) {
1714 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001715 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001716 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001717}
1718
Glenn Kasten54a8a452015-03-09 12:03:00 -07001719void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001720{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001721 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001722 if (mTransfer == TRANSFER_SHARED) {
1723 return;
1724 }
1725
Andy Hungabdb9902015-01-12 15:08:22 -08001726 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001727 if (stepCount == 0) {
1728 return;
1729 }
1730
1731 Proxy::Buffer buffer;
1732 buffer.mFrameCount = stepCount;
1733 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001734
Eric Laurent1703cdf2011-03-07 14:52:59 -08001735 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001736 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001737 mInUnderrun = false;
1738 mProxy->releaseBuffer(&buffer);
1739
1740 // restart track if it was disabled by audioflinger due to previous underrun
Eric Laurent4d231dc2016-03-11 18:38:23 -08001741 restartIfDisabled();
1742}
1743
1744void AudioTrack::restartIfDisabled()
1745{
1746 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1747 if ((mState == STATE_ACTIVE) && (flags & CBLK_DISABLED)) {
1748 ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
1749 // FIXME ignoring status
1750 mAudioTrack->start();
Eric Laurentdf839842012-05-31 14:27:14 -07001751 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001752}
1753
1754// -------------------------------------------------------------------------
1755
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001756ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001757{
Glenn Kastend79072e2016-01-06 08:41:20 -08001758 if (mTransfer != TRANSFER_SYNC) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001759 return INVALID_OPERATION;
1760 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001761
Eric Laurentab5cdba2014-06-09 17:22:27 -07001762 if (isDirect()) {
1763 AutoMutex lock(mLock);
1764 int32_t flags = android_atomic_and(
1765 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1766 &mCblk->mFlags);
1767 if (flags & CBLK_INVALID) {
1768 return DEAD_OBJECT;
1769 }
1770 }
1771
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001772 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Glenn Kasten99e53b82012-01-19 08:59:58 -08001773 // Sanity-check: user is most-likely passing an error code, and it would
1774 // make the return value ambiguous (actualSize vs error).
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001775 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001776 return BAD_VALUE;
1777 }
1778
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001779 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001780 Buffer audioBuffer;
1781
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001782 while (userSize >= mFrameSize) {
1783 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001784
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001785 status_t err = obtainBuffer(&audioBuffer,
1786 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001787 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001788 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001789 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07001790 }
Glenn Kasten0a2f1512016-07-22 08:06:37 -07001791 if (err == TIMED_OUT || err == -EINTR) {
1792 err = WOULD_BLOCK;
1793 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001794 return ssize_t(err);
1795 }
1796
Glenn Kastenae4b8792015-03-20 09:04:21 -07001797 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08001798 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001799 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001800 userSize -= toWrite;
1801 written += toWrite;
1802
1803 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001804 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001805
Andy Hungea2b9c02016-02-12 17:06:53 -08001806 if (written > 0) {
1807 mFramesWritten += written / mFrameSize;
1808 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001809 return written;
1810}
1811
1812// -------------------------------------------------------------------------
1813
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001814nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001815{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001816 // Currently the AudioTrack thread is not created if there are no callbacks.
1817 // Would it ever make sense to run the thread, even without callbacks?
1818 // If so, then replace this by checks at each use for mCbf != NULL.
1819 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1820
Eric Laurent1703cdf2011-03-07 14:52:59 -08001821 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07001822 if (mAwaitBoost) {
1823 mAwaitBoost = false;
1824 mLock.unlock();
1825 static const int32_t kMaxTries = 5;
1826 int32_t tryCounter = kMaxTries;
1827 uint32_t pollUs = 10000;
1828 do {
Glenn Kasten8255ba72016-08-23 13:54:23 -07001829 int policy = sched_getscheduler(0) & ~SCHED_RESET_ON_FORK;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001830 if (policy == SCHED_FIFO || policy == SCHED_RR) {
1831 break;
1832 }
1833 usleep(pollUs);
1834 pollUs <<= 1;
1835 } while (tryCounter-- > 0);
1836 if (tryCounter < 0) {
1837 ALOGE("did not receive expected priority boost on time");
1838 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07001839 // Run again immediately
1840 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07001841 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08001842
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001843 // Can only reference mCblk while locked
1844 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07001845 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08001846
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001847 // Check for track invalidation
1848 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001849 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1850 // AudioSystem cache. We should not exit here but after calling the callback so
1851 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07001852 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Lajos Molnarf1063e22015-04-17 15:19:42 -07001853 status_t status __unused = restoreTrack_l("processAudioBuffer");
1854 // FIXME unused status
Andy Hung53c3b5f2014-12-15 16:42:05 -08001855 // after restoration, continue below to make sure that the loop and buffer events
1856 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001857 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001858 }
1859
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001860 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001861 bool active = mState == STATE_ACTIVE;
1862
1863 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1864 bool newUnderrun = false;
1865 if (flags & CBLK_UNDERRUN) {
1866#if 0
1867 // Currently in shared buffer mode, when the server reaches the end of buffer,
1868 // the track stays active in continuous underrun state. It's up to the application
1869 // to pause or stop the track, or set the position to a new offset within buffer.
1870 // This was some experimental code to auto-pause on underrun. Keeping it here
1871 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1872 if (mTransfer == TRANSFER_SHARED) {
1873 mState = STATE_PAUSED;
1874 active = false;
1875 }
1876#endif
1877 if (!mInUnderrun) {
1878 mInUnderrun = true;
1879 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001880 }
1881 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07001882
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001883 // Get current position of server
Andy Hung90e8a972015-11-09 16:42:40 -08001884 Modulo<uint32_t> position(updateAndGetPosition_l());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001885
1886 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001887 bool markerReached = false;
Andy Hung90e8a972015-11-09 16:42:40 -08001888 Modulo<uint32_t> markerPosition(mMarkerPosition);
1889 // uses 32 bit wraparound for comparison with position.
1890 if (!mMarkerReached && markerPosition.value() > 0 && position >= markerPosition) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001891 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001892 }
1893
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001894 // Determine number of new position callback(s) that will be needed, while locked
1895 size_t newPosCount = 0;
Andy Hung90e8a972015-11-09 16:42:40 -08001896 Modulo<uint32_t> newPosition(mNewPosition);
1897 uint32_t updatePeriod = mUpdatePeriod;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001898 // FIXME fails for wraparound, need 64 bits
1899 if (updatePeriod > 0 && position >= newPosition) {
Andy Hung90e8a972015-11-09 16:42:40 -08001900 newPosCount = ((position - newPosition).value() / updatePeriod) + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001901 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001902 }
1903
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001904 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001905 uint32_t sampleRate = mSampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001906 float speed = mPlaybackRate.mSpeed;
Andy Hunga7f03352015-05-31 21:54:49 -07001907 const uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001908 if (mRefreshRemaining) {
1909 mRefreshRemaining = false;
1910 mRemainingFrames = notificationFrames;
1911 mRetryOnPartialBuffer = false;
1912 }
1913 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001914 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07001915 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001916
Andy Hung53c3b5f2014-12-15 16:42:05 -08001917 // Determine the number of new loop callback(s) that will be needed, while locked.
1918 int loopCountNotifications = 0;
1919 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1920
1921 if (mLoopCount > 0) {
1922 int loopCount;
1923 size_t bufferPosition;
1924 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1925 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1926 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1927 mLoopCountNotified = loopCount; // discard any excess notifications
1928 } else if (mLoopCount < 0) {
1929 // FIXME: We're not accurate with notification count and position with infinite looping
1930 // since loopCount from server side will always return -1 (we could decrement it).
1931 size_t bufferPosition = mStaticProxy->getBufferPosition();
1932 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1933 loopPeriod = mLoopEnd - bufferPosition;
1934 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1935 size_t bufferPosition = mStaticProxy->getBufferPosition();
1936 loopPeriod = mFrameCount - bufferPosition;
1937 }
1938
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001939 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08001940 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001941 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1942
1943 mLock.unlock();
1944
Andy Hunga7f03352015-05-31 21:54:49 -07001945 // get anchor time to account for callbacks.
1946 const nsecs_t timeBeforeCallbacks = systemTime();
1947
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001948 if (waitStreamEnd) {
Andy Hunga7f03352015-05-31 21:54:49 -07001949 // FIXME: Instead of blocking in proxy->waitStreamEndDone(), Callback thread
1950 // should wait on proxy futex and handle CBLK_STREAM_END_DONE within this function
1951 // (and make sure we don't callback for more data while we're stopping).
1952 // This helps with position, marker notifications, and track invalidation.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001953 struct timespec timeout;
1954 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1955 timeout.tv_nsec = 0;
1956
Glenn Kasten96f04882013-09-20 09:28:56 -07001957 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001958 switch (status) {
1959 case NO_ERROR:
1960 case DEAD_OBJECT:
1961 case TIMED_OUT:
Andy Hung39609a02015-09-03 16:38:38 -07001962 if (status != DEAD_OBJECT) {
1963 // for DEAD_OBJECT, we do not send a EVENT_STREAM_END after stop();
1964 // instead, the application should handle the EVENT_NEW_IAUDIOTRACK.
1965 mCbf(EVENT_STREAM_END, mUserData, NULL);
1966 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001967 {
1968 AutoMutex lock(mLock);
1969 // The previously assigned value of waitStreamEnd is no longer valid,
1970 // since the mutex has been unlocked and either the callback handler
1971 // or another thread could have re-started the AudioTrack during that time.
1972 waitStreamEnd = mState == STATE_STOPPING;
1973 if (waitStreamEnd) {
1974 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07001975 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001976 }
1977 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001978 if (waitStreamEnd && status != DEAD_OBJECT) {
1979 return NS_INACTIVE;
1980 }
1981 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001982 }
Glenn Kasten96f04882013-09-20 09:28:56 -07001983 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001984 }
1985
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001986 // perform callbacks while unlocked
1987 if (newUnderrun) {
1988 mCbf(EVENT_UNDERRUN, mUserData, NULL);
1989 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08001990 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001991 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08001992 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001993 }
1994 if (flags & CBLK_BUFFER_END) {
1995 mCbf(EVENT_BUFFER_END, mUserData, NULL);
1996 }
1997 if (markerReached) {
1998 mCbf(EVENT_MARKER, mUserData, &markerPosition);
1999 }
2000 while (newPosCount > 0) {
Andy Hung90e8a972015-11-09 16:42:40 -08002001 size_t temp = newPosition.value(); // FIXME size_t != uint32_t
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002002 mCbf(EVENT_NEW_POS, mUserData, &temp);
2003 newPosition += updatePeriod;
2004 newPosCount--;
2005 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002006
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002007 if (mObservedSequence != sequence) {
2008 mObservedSequence = sequence;
2009 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002010 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07002011 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002012 return NS_INACTIVE;
2013 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002014 }
2015
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002016 // if inactive, then don't run me again until re-started
2017 if (!active) {
2018 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07002019 }
2020
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002021 // Compute the estimated time until the next timed event (position, markers, loops)
2022 // FIXME only for non-compressed audio
2023 uint32_t minFrames = ~0;
2024 if (!markerReached && position < markerPosition) {
Andy Hung90e8a972015-11-09 16:42:40 -08002025 minFrames = (markerPosition - position).value();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002026 }
2027 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08002028 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002029 minFrames = loopPeriod;
2030 }
Andy Hung2d85f092015-01-07 12:45:13 -08002031 if (updatePeriod > 0) {
Andy Hung90e8a972015-11-09 16:42:40 -08002032 minFrames = min(minFrames, (newPosition - position).value());
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002033 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002034
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002035 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
2036 static const uint32_t kPoll = 0;
2037 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
2038 minFrames = kPoll * notificationFrames;
2039 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07002040
Andy Hunga7f03352015-05-31 21:54:49 -07002041 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
2042 static const nsecs_t kWaitPeriodNs = WAIT_PERIOD_MS * 1000000LL;
2043 const nsecs_t timeAfterCallbacks = systemTime();
2044
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002045 // Convert frame units to time units
2046 nsecs_t ns = NS_WHENEVER;
2047 if (minFrames != (uint32_t) ~0) {
jiabinc7bb8322017-09-06 18:20:11 -07002048 // AudioFlinger consumption of client data may be irregular when coming out of device
2049 // standby since the kernel buffers require filling. This is throttled to no more than 2x
2050 // the expected rate in the MixerThread. Hence, we reduce the estimated time to wait by one
2051 // half (but no more than half a second) to improve callback accuracy during these temporary
2052 // data surges.
2053 const nsecs_t estimatedNs = framesToNanoseconds(minFrames, sampleRate, speed);
2054 constexpr nsecs_t maxThrottleCompensationNs = 500000000LL;
2055 ns = estimatedNs - min(estimatedNs / 2, maxThrottleCompensationNs) + kWaitPeriodNs;
Andy Hunga7f03352015-05-31 21:54:49 -07002056 ns -= (timeAfterCallbacks - timeBeforeCallbacks); // account for callback time
2057 // TODO: Should we warn if the callback time is too long?
2058 if (ns < 0) ns = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002059 }
2060
2061 // If not supplying data by EVENT_MORE_DATA, then we're done
2062 if (mTransfer != TRANSFER_CALLBACK) {
2063 return ns;
2064 }
2065
Andy Hunga7f03352015-05-31 21:54:49 -07002066 // EVENT_MORE_DATA callback handling.
2067 // Timing for linear pcm audio data formats can be derived directly from the
2068 // buffer fill level.
2069 // Timing for compressed data is not directly available from the buffer fill level,
2070 // rather indirectly from waiting for blocking mode callbacks or waiting for obtain()
2071 // to return a certain fill level.
2072
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002073 struct timespec timeout;
2074 const struct timespec *requested = &ClientProxy::kForever;
2075 if (ns != NS_WHENEVER) {
2076 timeout.tv_sec = ns / 1000000000LL;
2077 timeout.tv_nsec = ns % 1000000000LL;
2078 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
2079 requested = &timeout;
2080 }
2081
Andy Hungea2b9c02016-02-12 17:06:53 -08002082 size_t writtenFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002083 while (mRemainingFrames > 0) {
2084
2085 Buffer audioBuffer;
2086 audioBuffer.frameCount = mRemainingFrames;
2087 size_t nonContig;
2088 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
2089 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002090 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002091 requested = &ClientProxy::kNonBlocking;
2092 size_t avail = audioBuffer.frameCount + nonContig;
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002093 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002094 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002095 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002096 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
2097 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten606fbc12015-10-22 15:28:15 -07002098 // FIXME bug 25195759
2099 return 1000000;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002100 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002101 ALOGE("Error %d obtaining an audio buffer, giving up.", err);
2102 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002103 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002104
Phil Burkfdb3c072016-02-09 10:47:02 -08002105 if (mRetryOnPartialBuffer && audio_has_proportional_frames(mFormat)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002106 mRetryOnPartialBuffer = false;
2107 if (avail < mRemainingFrames) {
Andy Hunga7f03352015-05-31 21:54:49 -07002108 if (ns > 0) { // account for obtain time
2109 const nsecs_t timeNow = systemTime();
2110 ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2111 }
2112 nsecs_t myns = framesToNanoseconds(mRemainingFrames - avail, sampleRate, speed);
2113 if (ns < 0 /* NS_WHENEVER */ || myns < ns) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002114 ns = myns;
2115 }
2116 return ns;
2117 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07002118 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002119
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002120 size_t reqSize = audioBuffer.size;
2121 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002122 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002123
2124 // Sanity check on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002125 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -07002126 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
2127 reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002128 return NS_NEVER;
2129 }
2130
2131 if (writtenSize == 0) {
The Android Open Source Project8555d082009-03-05 14:34:35 -08002132 // The callback is done filling buffers
2133 // Keep this thread going to handle timed events and
2134 // still try to get more data in intervals of WAIT_PERIOD_MS
2135 // but don't just loop and block the CPU, so wait
Andy Hunga7f03352015-05-31 21:54:49 -07002136
2137 // mCbf(EVENT_MORE_DATA, ...) might either
2138 // (1) Block until it can fill the buffer, returning 0 size on EOS.
2139 // (2) Block until it can fill the buffer, returning 0 data (silence) on EOS.
2140 // (3) Return 0 size when no data is available, does not wait for more data.
2141 //
2142 // (1) and (2) occurs with AudioPlayer/AwesomePlayer; (3) occurs with NuPlayer.
2143 // We try to compute the wait time to avoid a tight sleep-wait cycle,
2144 // especially for case (3).
2145 //
2146 // The decision to support (1) and (2) affect the sizing of mRemainingFrames
2147 // and this loop; whereas for case (3) we could simply check once with the full
2148 // buffer size and skip the loop entirely.
2149
2150 nsecs_t myns;
Phil Burkfdb3c072016-02-09 10:47:02 -08002151 if (audio_has_proportional_frames(mFormat)) {
Andy Hunga7f03352015-05-31 21:54:49 -07002152 // time to wait based on buffer occupancy
2153 const nsecs_t datans = mRemainingFrames <= avail ? 0 :
2154 framesToNanoseconds(mRemainingFrames - avail, sampleRate, speed);
2155 // audio flinger thread buffer size (TODO: adjust for fast tracks)
Glenn Kastenea38ee72016-04-18 11:08:01 -07002156 // FIXME: use mAfFrameCountHAL instead of mAfFrameCount below for fast tracks.
Andy Hunga7f03352015-05-31 21:54:49 -07002157 const nsecs_t afns = framesToNanoseconds(mAfFrameCount, mAfSampleRate, speed);
2158 // add a half the AudioFlinger buffer time to avoid soaking CPU if datans is 0.
2159 myns = datans + (afns / 2);
2160 } else {
2161 // FIXME: This could ping quite a bit if the buffer isn't full.
2162 // Note that when mState is stopping we waitStreamEnd, so it never gets here.
2163 myns = kWaitPeriodNs;
2164 }
2165 if (ns > 0) { // account for obtain and callback time
2166 const nsecs_t timeNow = systemTime();
2167 ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2168 }
2169 if (ns < 0 /* NS_WHENEVER */ || myns < ns) {
2170 ns = myns;
2171 }
2172 return ns;
Glenn Kastend65d73c2012-06-22 17:21:07 -07002173 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002174
Glenn Kasten138d6f92015-03-20 10:54:51 -07002175 size_t releasedFrames = writtenSize / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002176 audioBuffer.frameCount = releasedFrames;
2177 mRemainingFrames -= releasedFrames;
2178 if (misalignment >= releasedFrames) {
2179 misalignment -= releasedFrames;
2180 } else {
2181 misalignment = 0;
2182 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002183
2184 releaseBuffer(&audioBuffer);
Andy Hungea2b9c02016-02-12 17:06:53 -08002185 writtenFrames += releasedFrames;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002186
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002187 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
2188 // if callback doesn't like to accept the full chunk
2189 if (writtenSize < reqSize) {
2190 continue;
2191 }
2192
2193 // There could be enough non-contiguous frames available to satisfy the remaining request
2194 if (mRemainingFrames <= nonContig) {
2195 continue;
2196 }
2197
2198#if 0
2199 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
2200 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
2201 // that total to a sum == notificationFrames.
2202 if (0 < misalignment && misalignment <= mRemainingFrames) {
2203 mRemainingFrames = misalignment;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002204 return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002205 }
2206#endif
2207
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002208 }
Andy Hungea2b9c02016-02-12 17:06:53 -08002209 if (writtenFrames > 0) {
2210 AutoMutex lock(mLock);
2211 mFramesWritten += writtenFrames;
2212 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002213 mRemainingFrames = notificationFrames;
2214 mRetryOnPartialBuffer = true;
2215
2216 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
2217 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002218}
2219
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002220status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08002221{
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002222 ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurentab5cdba2014-06-09 17:22:27 -07002223 isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002224 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002225
Glenn Kastena47f3162012-11-07 10:13:08 -08002226 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08002227 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08002228 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07002229
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002230 if (isOffloadedOrDirect_l() || mDoNotReconnect) {
Andy Hung1f1db832015-06-08 13:26:10 -07002231 // FIXME re-creation of offloaded and direct tracks is not yet implemented;
2232 // reconsider enabling for linear PCM encodings when position can be preserved.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002233 return DEAD_OBJECT;
2234 }
2235
Phil Burk2812d9e2016-01-04 10:34:30 -08002236 // Save so we can return count since creation.
2237 mUnderrunCountOffset = getUnderrunCount_l();
2238
Glenn Kasten200092b2014-08-15 15:13:30 -07002239 // save the old static buffer position
Andy Hungf20a4e92016-08-15 19:10:34 -07002240 uint32_t staticPosition = 0;
Andy Hung4ede21d2014-12-12 15:37:34 -08002241 size_t bufferPosition = 0;
2242 int loopCount = 0;
2243 if (mStaticProxy != 0) {
2244 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
Andy Hungf20a4e92016-08-15 19:10:34 -07002245 staticPosition = mStaticProxy->getPosition().unsignedValue();
Andy Hung4ede21d2014-12-12 15:37:34 -08002246 }
Glenn Kasten200092b2014-08-15 15:13:30 -07002247
Haynes Mathew Georgeae34ed22016-01-28 11:58:39 -08002248 mFlags = mOrigFlags;
2249
Glenn Kasten200092b2014-08-15 15:13:30 -07002250 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08002251 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07002252 // It will also delete the strong references on previous IAudioTrack and IMemory.
2253 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Glenn Kastenae4b8792015-03-20 09:04:21 -07002254 status_t result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07002255
Glenn Kastena47f3162012-11-07 10:13:08 -08002256 if (result == NO_ERROR) {
Andy Hungd7bd69e2015-07-24 07:52:41 -07002257 // take the frames that will be lost by track recreation into account in saved position
2258 // For streaming tracks, this is the amount we obtained from the user/client
2259 // (not the number actually consumed at the server - those are already lost).
2260 if (mStaticProxy == 0) {
2261 mPosition = mReleased;
2262 }
Andy Hung4ede21d2014-12-12 15:37:34 -08002263 // Continue playback from last known position and restore loop.
2264 if (mStaticProxy != 0) {
2265 if (loopCount != 0) {
2266 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
2267 mLoopStart, mLoopEnd, loopCount);
2268 } else {
2269 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002270 if (bufferPosition == mFrameCount) {
2271 ALOGD("restoring track at end of static buffer");
2272 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002273 }
2274 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002275 // restore volume handler
Andy Hung39399b62017-04-21 15:07:45 -07002276 mVolumeHandler->forall([this](const VolumeShaper &shaper) -> VolumeShaper::Status {
2277 sp<VolumeShaper::Operation> operationToEnd =
2278 new VolumeShaper::Operation(shaper.mOperation);
Andy Hung4ef88d72017-02-21 19:47:53 -08002279 // TODO: Ideally we would restore to the exact xOffset position
2280 // as returned by getVolumeShaperState(), but we don't have that
2281 // information when restoring at the client unless we periodically poll
2282 // the server or create shared memory state.
2283 //
Andy Hung39399b62017-04-21 15:07:45 -07002284 // For now, we simply advance to the end of the VolumeShaper effect
2285 // if it has been started.
2286 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002287 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002288 }
2289 return mAudioTrack->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002290 });
2291
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002292 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08002293 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08002294 }
Andy Hungf20a4e92016-08-15 19:10:34 -07002295 // server resets to zero so we offset
2296 mFramesWrittenServerOffset =
2297 mStaticProxy.get() != nullptr ? staticPosition : mFramesWritten;
2298 mFramesWrittenAtRestore = mFramesWrittenServerOffset;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002299 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002300 if (result != NO_ERROR) {
2301 ALOGW("restoreTrack_l() failed status %d", result);
2302 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07002303 mReleased = 0;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002304 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002305
2306 return result;
2307}
2308
Andy Hung90e8a972015-11-09 16:42:40 -08002309Modulo<uint32_t> AudioTrack::updateAndGetPosition_l()
Glenn Kasten200092b2014-08-15 15:13:30 -07002310{
2311 // This is the sole place to read server consumed frames
Andy Hung90e8a972015-11-09 16:42:40 -08002312 Modulo<uint32_t> newServer(mProxy->getPosition());
2313 const int32_t delta = (newServer - mServer).signedValue();
Glenn Kasten200092b2014-08-15 15:13:30 -07002314 // TODO There is controversy about whether there can be "negative jitter" in server position.
2315 // This should be investigated further, and if possible, it should be addressed.
2316 // A more definite failure mode is infrequent polling by client.
2317 // One could call (void)getPosition_l() in releaseBuffer(),
2318 // so mReleased and mPosition are always lock-step as best possible.
2319 // That should ensure delta never goes negative for infrequent polling
2320 // unless the server has more than 2^31 frames in its buffer,
2321 // in which case the use of uint32_t for these counters has bigger issues.
Andy Hung90e8a972015-11-09 16:42:40 -08002322 ALOGE_IF(delta < 0,
2323 "detected illegal retrograde motion by the server: mServer advanced by %d",
2324 delta);
Chad Brubaker039c27a2015-09-23 15:17:29 -07002325 mServer = newServer;
Andy Hung90e8a972015-11-09 16:42:40 -08002326 if (delta > 0) { // avoid retrograde
2327 mPosition += delta;
2328 }
2329 return mPosition;
Glenn Kasten200092b2014-08-15 15:13:30 -07002330}
2331
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002332bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed)
Andy Hung8edb8dc2015-03-26 19:13:55 -07002333{
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002334 updateLatency_l();
Andy Hung8edb8dc2015-03-26 19:13:55 -07002335 // applicable for mixing tracks only (not offloaded or direct)
2336 if (mStaticProxy != 0) {
2337 return true; // static tracks do not have issues with buffer sizing.
2338 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07002339 const size_t minFrameCount =
Eric Laurent21da6472017-11-09 16:29:26 -08002340 AudioSystem::calculateMinFrameCount(mAfLatency, mAfFrameCount, mAfSampleRate,
2341 sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002342 const bool allowed = mFrameCount >= minFrameCount;
2343 ALOGD_IF(!allowed,
2344 "isSampleRateSpeedAllowed_l denied "
2345 "mAfLatency:%u mAfFrameCount:%zu mAfSampleRate:%u sampleRate:%u speed:%f "
2346 "mFrameCount:%zu < minFrameCount:%zu",
2347 mAfLatency, mAfFrameCount, mAfSampleRate, sampleRate, speed,
Andy Hung8edb8dc2015-03-26 19:13:55 -07002348 mFrameCount, minFrameCount);
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002349 return allowed;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002350}
2351
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002352status_t AudioTrack::setParameters(const String8& keyValuePairs)
2353{
2354 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07002355 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002356}
2357
Dean Wheatleya70eef72018-01-04 14:23:50 +11002358status_t AudioTrack::selectPresentation(int presentationId, int programId)
2359{
2360 AutoMutex lock(mLock);
2361 AudioParameter param = AudioParameter();
2362 param.addInt(String8(AudioParameter::keyPresentationId), presentationId);
2363 param.addInt(String8(AudioParameter::keyProgramId), programId);
2364 ALOGV("PresentationId/ProgramId[%s]",param.toString().string());
2365
2366 return mAudioTrack->setParameters(param.toString());
2367}
2368
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002369VolumeShaper::Status AudioTrack::applyVolumeShaper(
2370 const sp<VolumeShaper::Configuration>& configuration,
2371 const sp<VolumeShaper::Operation>& operation)
2372{
2373 AutoMutex lock(mLock);
Andy Hung4ef88d72017-02-21 19:47:53 -08002374 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002375 VolumeShaper::Status status = mAudioTrack->applyVolumeShaper(configuration, operation);
Andy Hung39399b62017-04-21 15:07:45 -07002376
2377 if (status == DEAD_OBJECT) {
2378 if (restoreTrack_l("applyVolumeShaper") == OK) {
2379 status = mAudioTrack->applyVolumeShaper(configuration, operation);
2380 }
2381 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002382 if (status >= 0) {
2383 // save VolumeShaper for restore
2384 mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung39399b62017-04-21 15:07:45 -07002385 if (mState == STATE_ACTIVE || mState == STATE_STOPPING) {
2386 mVolumeHandler->setStarted();
2387 }
2388 } else {
2389 // warn only if not an expected restore failure.
2390 ALOGW_IF(!((isOffloadedOrDirect_l() || mDoNotReconnect) && status == DEAD_OBJECT),
2391 "applyVolumeShaper failed: %d", status);
Andy Hung4ef88d72017-02-21 19:47:53 -08002392 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002393 return status;
2394}
2395
2396sp<VolumeShaper::State> AudioTrack::getVolumeShaperState(int id)
2397{
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002398 AutoMutex lock(mLock);
Andy Hung39399b62017-04-21 15:07:45 -07002399 sp<VolumeShaper::State> state = mAudioTrack->getVolumeShaperState(id);
2400 if (state.get() == nullptr && (mCblk->mFlags & CBLK_INVALID) != 0) {
2401 if (restoreTrack_l("getVolumeShaperState") == OK) {
2402 state = mAudioTrack->getVolumeShaperState(id);
2403 }
2404 }
2405 return state;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002406}
2407
Andy Hungea2b9c02016-02-12 17:06:53 -08002408status_t AudioTrack::getTimestamp(ExtendedTimestamp *timestamp)
2409{
2410 if (timestamp == nullptr) {
2411 return BAD_VALUE;
2412 }
2413 AutoMutex lock(mLock);
Andy Hunge13f8a62016-03-30 14:20:42 -07002414 return getTimestamp_l(timestamp);
2415}
2416
2417status_t AudioTrack::getTimestamp_l(ExtendedTimestamp *timestamp)
2418{
Andy Hungea2b9c02016-02-12 17:06:53 -08002419 if (mCblk->mFlags & CBLK_INVALID) {
2420 const status_t status = restoreTrack_l("getTimestampExtended");
2421 if (status != OK) {
2422 // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
2423 // recommending that the track be recreated.
2424 return DEAD_OBJECT;
2425 }
2426 }
2427 // check for offloaded/direct here in case restoring somehow changed those flags.
2428 if (isOffloadedOrDirect_l()) {
2429 return INVALID_OPERATION; // not supported
2430 }
2431 status_t status = mProxy->getTimestamp(timestamp);
Andy Hunge1e98462016-04-12 10:18:51 -07002432 LOG_ALWAYS_FATAL_IF(status != OK, "status %d not allowed from proxy getTimestamp", status);
Andy Hungea2b9c02016-02-12 17:06:53 -08002433 bool found = false;
Andy Hunge1e98462016-04-12 10:18:51 -07002434 timestamp->mPosition[ExtendedTimestamp::LOCATION_CLIENT] = mFramesWritten;
2435 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_CLIENT] = 0;
2436 // server side frame offset in case AudioTrack has been restored.
2437 for (int i = ExtendedTimestamp::LOCATION_SERVER;
2438 i < ExtendedTimestamp::LOCATION_MAX; ++i) {
2439 if (timestamp->mTimeNs[i] >= 0) {
2440 // apply server offset (frames flushed is ignored
2441 // so we don't report the jump when the flush occurs).
2442 timestamp->mPosition[i] += mFramesWrittenServerOffset;
2443 found = true;
Andy Hungea2b9c02016-02-12 17:06:53 -08002444 }
2445 }
2446 return found ? OK : WOULD_BLOCK;
2447}
2448
Glenn Kastence703742013-07-19 16:33:58 -07002449status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
2450{
Glenn Kasten53cec222013-08-29 09:01:02 -07002451 AutoMutex lock(mLock);
Andy Hung65ffdfc2016-10-10 15:52:11 -07002452 return getTimestamp_l(timestamp);
2453}
Phil Burk1b420972015-04-22 10:52:21 -07002454
Andy Hung65ffdfc2016-10-10 15:52:11 -07002455status_t AudioTrack::getTimestamp_l(AudioTimestamp& timestamp)
2456{
Phil Burk1b420972015-04-22 10:52:21 -07002457 bool previousTimestampValid = mPreviousTimestampValid;
2458 // Set false here to cover all the error return cases.
2459 mPreviousTimestampValid = false;
2460
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002461 switch (mState) {
2462 case STATE_ACTIVE:
2463 case STATE_PAUSED:
2464 break; // handle below
2465 case STATE_FLUSHED:
2466 case STATE_STOPPED:
2467 return WOULD_BLOCK;
2468 case STATE_STOPPING:
2469 case STATE_PAUSED_STOPPING:
2470 if (!isOffloaded_l()) {
2471 return INVALID_OPERATION;
2472 }
2473 break; // offloaded tracks handled below
2474 default:
2475 LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
2476 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07002477 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002478
Eric Laurent275e8e92014-11-30 15:14:47 -08002479 if (mCblk->mFlags & CBLK_INVALID) {
Andy Hung6653c932015-06-08 13:27:48 -07002480 const status_t status = restoreTrack_l("getTimestamp");
2481 if (status != OK) {
2482 // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
2483 // recommending that the track be recreated.
2484 return DEAD_OBJECT;
2485 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002486 }
2487
Glenn Kasten200092b2014-08-15 15:13:30 -07002488 // The presented frame count must always lag behind the consumed frame count.
2489 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Andy Hung6ae58432016-02-16 18:32:24 -08002490
2491 status_t status;
Andy Hung818e7a32016-02-16 18:08:07 -08002492 if (isOffloadedOrDirect_l()) {
Andy Hung6ae58432016-02-16 18:32:24 -08002493 // use Binder to get timestamp
2494 status = mAudioTrack->getTimestamp(timestamp);
2495 } else {
2496 // read timestamp from shared memory
2497 ExtendedTimestamp ets;
2498 status = mProxy->getTimestamp(&ets);
2499 if (status == OK) {
Andy Hungb01faa32016-04-27 12:51:32 -07002500 ExtendedTimestamp::Location location;
2501 status = ets.getBestTimestamp(&timestamp, &location);
2502
2503 if (status == OK) {
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002504 updateLatency_l();
Andy Hungb01faa32016-04-27 12:51:32 -07002505 // It is possible that the best location has moved from the kernel to the server.
2506 // In this case we adjust the position from the previous computed latency.
2507 if (location == ExtendedTimestamp::LOCATION_SERVER) {
2508 ALOGW_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_KERNEL,
2509 "getTimestamp() location moved from kernel to server");
Andy Hung07eee802016-06-21 16:47:16 -07002510 // check that the last kernel OK time info exists and the positions
2511 // are valid (if they predate the current track, the positions may
2512 // be zero or negative).
Andy Hungb01faa32016-04-27 12:51:32 -07002513 const int64_t frames =
Andy Hung6d7b1192016-05-07 22:59:48 -07002514 (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
Andy Hung07eee802016-06-21 16:47:16 -07002515 ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0 ||
2516 ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] <= 0 ||
2517 ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] <= 0)
Andy Hung6d7b1192016-05-07 22:59:48 -07002518 ?
2519 int64_t((double)mAfLatency * mSampleRate * mPlaybackRate.mSpeed
2520 / 1000)
2521 :
2522 (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
2523 - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK]);
2524 ALOGV("frame adjustment:%lld timestamp:%s",
2525 (long long)frames, ets.toString().c_str());
Andy Hungb01faa32016-04-27 12:51:32 -07002526 if (frames >= ets.mPosition[location]) {
2527 timestamp.mPosition = 0;
2528 } else {
2529 timestamp.mPosition = (uint32_t)(ets.mPosition[location] - frames);
2530 }
Andy Hung69488c42016-05-16 18:43:33 -07002531 } else if (location == ExtendedTimestamp::LOCATION_KERNEL) {
2532 ALOGV_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_SERVER,
2533 "getTimestamp() location moved from server to kernel");
Andy Hungb01faa32016-04-27 12:51:32 -07002534 }
Andy Hung5d313802016-10-10 15:09:39 -07002535
2536 // We update the timestamp time even when paused.
2537 if (mState == STATE_PAUSED /* not needed: STATE_PAUSED_STOPPING */) {
2538 const int64_t now = systemTime();
Andy Hung2b01f002017-07-05 12:01:36 -07002539 const int64_t at = audio_utils_ns_from_timespec(&timestamp.mTime);
Andy Hung5d313802016-10-10 15:09:39 -07002540 const int64_t lag =
2541 (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
2542 ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0)
2543 ? int64_t(mAfLatency * 1000000LL)
2544 : (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
2545 - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK])
2546 * NANOS_PER_SECOND / mSampleRate;
2547 const int64_t limit = now - lag; // no earlier than this limit
2548 if (at < limit) {
2549 ALOGV("timestamp pause lag:%lld adjusting from %lld to %lld",
2550 (long long)lag, (long long)at, (long long)limit);
Andy Hungffa36952017-08-17 10:41:51 -07002551 timestamp.mTime = convertNsToTimespec(limit);
Andy Hung5d313802016-10-10 15:09:39 -07002552 }
2553 }
Andy Hungb01faa32016-04-27 12:51:32 -07002554 mPreviousLocation = location;
2555 } else {
2556 // right after AudioTrack is started, one may not find a timestamp
2557 ALOGV("getBestTimestamp did not find timestamp");
2558 }
Andy Hung6ae58432016-02-16 18:32:24 -08002559 }
2560 if (status == INVALID_OPERATION) {
Andy Hungf20a4e92016-08-15 19:10:34 -07002561 // INVALID_OPERATION occurs when no timestamp has been issued by the server;
2562 // other failures are signaled by a negative time.
2563 // If we come out of FLUSHED or STOPPED where the position is known
2564 // to be zero we convert this to WOULD_BLOCK (with the implicit meaning of
2565 // "zero" for NuPlayer). We don't convert for track restoration as position
2566 // does not reset.
2567 ALOGV("timestamp server offset:%lld restore frames:%lld",
2568 (long long)mFramesWrittenServerOffset, (long long)mFramesWrittenAtRestore);
2569 if (mFramesWrittenServerOffset != mFramesWrittenAtRestore) {
2570 status = WOULD_BLOCK;
2571 }
Andy Hung6ae58432016-02-16 18:32:24 -08002572 }
2573 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002574 if (status != NO_ERROR) {
Glenn Kastendfc34da2014-09-19 09:05:05 -07002575 ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002576 return status;
2577 }
2578 if (isOffloadedOrDirect_l()) {
2579 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
2580 // use cached paused position in case another offloaded track is running.
2581 timestamp.mPosition = mPausedPosition;
2582 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
Andy Hung5d313802016-10-10 15:09:39 -07002583 // TODO: adjust for delay
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002584 return NO_ERROR;
2585 }
2586
2587 // Check whether a pending flush or stop has completed, as those commands may
Andy Hungc8e09c62015-06-03 23:43:36 -07002588 // be asynchronous or return near finish or exhibit glitchy behavior.
2589 //
2590 // Originally this showed up as the first timestamp being a continuation of
2591 // the previous song under gapless playback.
2592 // However, we sometimes see zero timestamps, then a glitch of
2593 // the previous song's position, and then correct timestamps afterwards.
Andy Hungffa36952017-08-17 10:41:51 -07002594 if (mStartFromZeroUs != 0 && mSampleRate != 0) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002595 static const int kTimeJitterUs = 100000; // 100 ms
2596 static const int k1SecUs = 1000000;
2597
2598 const int64_t timeNow = getNowUs();
2599
Andy Hungffa36952017-08-17 10:41:51 -07002600 if (timeNow < mStartFromZeroUs + k1SecUs) { // within first second of starting
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002601 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
Andy Hungffa36952017-08-17 10:41:51 -07002602 if (timestampTimeUs < mStartFromZeroUs) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002603 return WOULD_BLOCK; // stale timestamp time, occurs before start.
2604 }
Andy Hungffa36952017-08-17 10:41:51 -07002605 const int64_t deltaTimeUs = timestampTimeUs - mStartFromZeroUs;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002606 const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002607 / ((double)mSampleRate * mPlaybackRate.mSpeed);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002608
2609 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2610 // Verify that the counter can't count faster than the sample rate
Andy Hungc8e09c62015-06-03 23:43:36 -07002611 // since the start time. If greater, then that means we may have failed
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002612 // to completely flush or stop the previous playing track.
Andy Hungc8e09c62015-06-03 23:43:36 -07002613 ALOGW_IF(!mTimestampStartupGlitchReported,
2614 "getTimestamp startup glitch detected"
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002615 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2616 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2617 timestamp.mPosition);
Andy Hungc8e09c62015-06-03 23:43:36 -07002618 mTimestampStartupGlitchReported = true;
2619 if (previousTimestampValid
2620 && mPreviousTimestamp.mPosition == 0 /* should be true if valid */) {
2621 timestamp = mPreviousTimestamp;
2622 mPreviousTimestampValid = true;
2623 return NO_ERROR;
2624 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002625 return WOULD_BLOCK;
2626 }
Andy Hungc8e09c62015-06-03 23:43:36 -07002627 if (deltaPositionByUs != 0) {
Andy Hungffa36952017-08-17 10:41:51 -07002628 mStartFromZeroUs = 0; // don't check again, we got valid nonzero position.
Andy Hungc8e09c62015-06-03 23:43:36 -07002629 }
2630 } else {
Andy Hungffa36952017-08-17 10:41:51 -07002631 mStartFromZeroUs = 0; // don't check again, start time expired.
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002632 }
Andy Hungc8e09c62015-06-03 23:43:36 -07002633 mTimestampStartupGlitchReported = false;
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002634 }
2635 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002636 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2637 (void) updateAndGetPosition_l();
2638 // Server consumed (mServer) and presented both use the same server time base,
2639 // and server consumed is always >= presented.
2640 // The delta between these represents the number of frames in the buffer pipeline.
2641 // If this delta between these is greater than the client position, it means that
2642 // actually presented is still stuck at the starting line (figuratively speaking),
2643 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
Andy Hung90e8a972015-11-09 16:42:40 -08002644 // Note: We explicitly use non-Modulo comparison here - potential wrap issue when
2645 // mPosition exceeds 32 bits.
2646 // TODO Remove when timestamp is updated to contain pipeline status info.
2647 const int32_t pipelineDepthInFrames = (mServer - timestamp.mPosition).signedValue();
2648 if (pipelineDepthInFrames > 0 /* should be true, but we check anyways */
2649 && (uint32_t)pipelineDepthInFrames > mPosition.value()) {
Glenn Kasten200092b2014-08-15 15:13:30 -07002650 return INVALID_OPERATION;
2651 }
2652 // Convert timestamp position from server time base to client time base.
2653 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2654 // But if we change it to 64-bit then this could fail.
Andy Hung90e8a972015-11-09 16:42:40 -08002655 // Use Modulo computation here.
2656 timestamp.mPosition = (mPosition - mServer + timestamp.mPosition).value();
Glenn Kasten200092b2014-08-15 15:13:30 -07002657 // Immediately after a call to getPosition_l(), mPosition and
2658 // mServer both represent the same frame position. mPosition is
2659 // in client's point of view, and mServer is in server's point of
2660 // view. So the difference between them is the "fudge factor"
2661 // between client and server views due to stop() and/or new
2662 // IAudioTrack. And timestamp.mPosition is initially in server's
2663 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002664 }
Phil Burk1b420972015-04-22 10:52:21 -07002665
2666 // Prevent retrograde motion in timestamp.
2667 // This is sometimes caused by erratic reports of the available space in the ALSA drivers.
2668 if (status == NO_ERROR) {
Andy Hungffa36952017-08-17 10:41:51 -07002669 // previousTimestampValid is set to false when starting after a stop or flush.
Phil Burk1b420972015-04-22 10:52:21 -07002670 if (previousTimestampValid) {
Andy Hung2b01f002017-07-05 12:01:36 -07002671 const int64_t previousTimeNanos =
2672 audio_utils_ns_from_timespec(&mPreviousTimestamp.mTime);
Andy Hungffa36952017-08-17 10:41:51 -07002673 int64_t currentTimeNanos = audio_utils_ns_from_timespec(&timestamp.mTime);
2674
2675 // Fix stale time when checking timestamp right after start().
2676 //
2677 // For offload compatibility, use a default lag value here.
2678 // Any time discrepancy between this update and the pause timestamp is handled
2679 // by the retrograde check afterwards.
2680 const int64_t lagNs = int64_t(mAfLatency * 1000000LL);
2681 const int64_t limitNs = mStartNs - lagNs;
2682 if (currentTimeNanos < limitNs) {
2683 ALOGD("correcting timestamp time for pause, "
2684 "currentTimeNanos: %lld < limitNs: %lld < mStartNs: %lld",
2685 (long long)currentTimeNanos, (long long)limitNs, (long long)mStartNs);
2686 timestamp.mTime = convertNsToTimespec(limitNs);
2687 currentTimeNanos = limitNs;
2688 }
2689
2690 // retrograde check
Phil Burk1b420972015-04-22 10:52:21 -07002691 if (currentTimeNanos < previousTimeNanos) {
Andy Hung5d313802016-10-10 15:09:39 -07002692 ALOGW("retrograde timestamp time corrected, %lld < %lld",
2693 (long long)currentTimeNanos, (long long)previousTimeNanos);
2694 timestamp.mTime = mPreviousTimestamp.mTime;
Andy Hungffa36952017-08-17 10:41:51 -07002695 // currentTimeNanos not used below.
Phil Burk1b420972015-04-22 10:52:21 -07002696 }
2697
2698 // Looking at signed delta will work even when the timestamps
2699 // are wrapping around.
Andy Hung90e8a972015-11-09 16:42:40 -08002700 int32_t deltaPosition = (Modulo<uint32_t>(timestamp.mPosition)
2701 - mPreviousTimestamp.mPosition).signedValue();
Phil Burk4c5a3672015-04-30 16:18:53 -07002702 if (deltaPosition < 0) {
2703 // Only report once per position instead of spamming the log.
2704 if (!mRetrogradeMotionReported) {
2705 ALOGW("retrograde timestamp position corrected, %d = %u - %u",
2706 deltaPosition,
2707 timestamp.mPosition,
2708 mPreviousTimestamp.mPosition);
2709 mRetrogradeMotionReported = true;
2710 }
2711 } else {
2712 mRetrogradeMotionReported = false;
2713 }
Andy Hung5d313802016-10-10 15:09:39 -07002714 if (deltaPosition < 0) {
2715 timestamp.mPosition = mPreviousTimestamp.mPosition;
2716 deltaPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -07002717 }
Andy Hung5d313802016-10-10 15:09:39 -07002718#if 0
2719 // Uncomment this to verify audio timestamp rate.
2720 const int64_t deltaTime =
Andy Hung2b01f002017-07-05 12:01:36 -07002721 audio_utils_ns_from_timespec(&timestamp.mTime) - previousTimeNanos;
Andy Hung5d313802016-10-10 15:09:39 -07002722 if (deltaTime != 0) {
2723 const int64_t computedSampleRate =
2724 deltaPosition * (long long)NANOS_PER_SECOND / deltaTime;
2725 ALOGD("computedSampleRate:%u sampleRate:%u",
2726 (unsigned)computedSampleRate, mSampleRate);
2727 }
2728#endif
Phil Burk1b420972015-04-22 10:52:21 -07002729 }
2730 mPreviousTimestamp = timestamp;
2731 mPreviousTimestampValid = true;
2732 }
2733
Glenn Kastenfe346c72013-08-30 13:28:22 -07002734 return status;
Glenn Kastence703742013-07-19 16:33:58 -07002735}
2736
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002737String8 AudioTrack::getParameters(const String8& keys)
2738{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002739 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07002740 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08002741 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002742 } else {
2743 return String8::empty();
2744 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002745}
2746
Glenn Kasten23a75452014-01-13 10:37:17 -08002747bool AudioTrack::isOffloaded() const
2748{
2749 AutoMutex lock(mLock);
2750 return isOffloaded_l();
2751}
2752
Eric Laurentab5cdba2014-06-09 17:22:27 -07002753bool AudioTrack::isDirect() const
2754{
2755 AutoMutex lock(mLock);
2756 return isDirect_l();
2757}
2758
2759bool AudioTrack::isOffloadedOrDirect() const
2760{
2761 AutoMutex lock(mLock);
2762 return isOffloadedOrDirect_l();
2763}
2764
2765
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002766status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002767{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002768 String8 result;
2769
2770 result.append(" AudioTrack::dump\n");
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002771 result.appendFormat(" status(%d), state(%d), session Id(%d), flags(%#x)\n",
Eric Laurentd114b622017-11-27 18:37:04 -08002772 mStatus, mState, mSessionId, mFlags);
2773 result.appendFormat(" stream type(%d), left - right volume(%f, %f)\n",
2774 (mStreamType == AUDIO_STREAM_DEFAULT) ?
2775 audio_attributes_to_stream_type(&mAttributes) : mStreamType,
2776 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002777 result.appendFormat(" format(%#x), channel mask(%#x), channel count(%u)\n",
Eric Laurentd114b622017-11-27 18:37:04 -08002778 mFormat, mChannelMask, mChannelCount);
2779 result.appendFormat(" sample rate(%u), original sample rate(%u), speed(%f)\n",
2780 mSampleRate, mOriginalSampleRate, mPlaybackRate.mSpeed);
2781 result.appendFormat(" frame count(%zu), req. frame count(%zu)\n",
2782 mFrameCount, mReqFrameCount);
2783 result.appendFormat(" notif. frame count(%u), req. notif. frame count(%u),"
2784 " req. notif. per buff(%u)\n",
2785 mNotificationFramesAct, mNotificationFramesReq, mNotificationsPerBufferReq);
2786 result.appendFormat(" latency (%d), selected device Id(%d), routed device Id(%d)\n",
2787 mLatency, mSelectedDeviceId, mRoutedDeviceId);
2788 result.appendFormat(" output(%d) AF latency (%u) AF frame count(%zu) AF SampleRate(%u)\n",
2789 mOutput, mAfLatency, mAfFrameCount, mAfSampleRate);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002790 ::write(fd, result.string(), result.size());
2791 return NO_ERROR;
2792}
2793
Phil Burk2812d9e2016-01-04 10:34:30 -08002794uint32_t AudioTrack::getUnderrunCount() const
2795{
2796 AutoMutex lock(mLock);
2797 return getUnderrunCount_l();
2798}
2799
2800uint32_t AudioTrack::getUnderrunCount_l() const
2801{
2802 return mProxy->getUnderrunCount() + mUnderrunCountOffset;
2803}
2804
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002805uint32_t AudioTrack::getUnderrunFrames() const
2806{
2807 AutoMutex lock(mLock);
2808 return mProxy->getUnderrunFrames();
2809}
2810
Eric Laurent296fb132015-05-01 11:38:42 -07002811status_t AudioTrack::addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback)
2812{
2813 if (callback == 0) {
2814 ALOGW("%s adding NULL callback!", __FUNCTION__);
2815 return BAD_VALUE;
2816 }
2817 AutoMutex lock(mLock);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002818 if (mDeviceCallback.unsafe_get() == callback.get()) {
Eric Laurent296fb132015-05-01 11:38:42 -07002819 ALOGW("%s adding same callback!", __FUNCTION__);
2820 return INVALID_OPERATION;
2821 }
2822 status_t status = NO_ERROR;
2823 if (mOutput != AUDIO_IO_HANDLE_NONE) {
2824 if (mDeviceCallback != 0) {
2825 ALOGW("%s callback already present!", __FUNCTION__);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002826 AudioSystem::removeAudioDeviceCallback(this, mOutput);
Eric Laurent296fb132015-05-01 11:38:42 -07002827 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002828 status = AudioSystem::addAudioDeviceCallback(this, mOutput);
Eric Laurent296fb132015-05-01 11:38:42 -07002829 }
2830 mDeviceCallback = callback;
2831 return status;
2832}
2833
2834status_t AudioTrack::removeAudioDeviceCallback(
2835 const sp<AudioSystem::AudioDeviceCallback>& callback)
2836{
2837 if (callback == 0) {
2838 ALOGW("%s removing NULL callback!", __FUNCTION__);
2839 return BAD_VALUE;
2840 }
2841 AutoMutex lock(mLock);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002842 if (mDeviceCallback.unsafe_get() != callback.get()) {
Eric Laurent296fb132015-05-01 11:38:42 -07002843 ALOGW("%s removing different callback!", __FUNCTION__);
2844 return INVALID_OPERATION;
2845 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002846 mDeviceCallback.clear();
Eric Laurent296fb132015-05-01 11:38:42 -07002847 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002848 AudioSystem::removeAudioDeviceCallback(this, mOutput);
Eric Laurent296fb132015-05-01 11:38:42 -07002849 }
Eric Laurent296fb132015-05-01 11:38:42 -07002850 return NO_ERROR;
2851}
2852
Eric Laurentad2e7b92017-09-14 20:06:42 -07002853
2854void AudioTrack::onAudioDeviceUpdate(audio_io_handle_t audioIo,
2855 audio_port_handle_t deviceId)
2856{
2857 sp<AudioSystem::AudioDeviceCallback> callback;
2858 {
2859 AutoMutex lock(mLock);
2860 if (audioIo != mOutput) {
2861 return;
2862 }
2863 callback = mDeviceCallback.promote();
2864 // only update device if the track is active as route changes due to other use cases are
2865 // irrelevant for this client
2866 if (mState == STATE_ACTIVE) {
2867 mRoutedDeviceId = deviceId;
2868 }
2869 }
2870 if (callback.get() != nullptr) {
2871 callback->onAudioDeviceUpdate(mOutput, mRoutedDeviceId);
2872 }
2873}
2874
Andy Hunge13f8a62016-03-30 14:20:42 -07002875status_t AudioTrack::pendingDuration(int32_t *msec, ExtendedTimestamp::Location location)
2876{
2877 if (msec == nullptr ||
2878 (location != ExtendedTimestamp::LOCATION_SERVER
2879 && location != ExtendedTimestamp::LOCATION_KERNEL)) {
2880 return BAD_VALUE;
2881 }
2882 AutoMutex lock(mLock);
2883 // inclusive of offloaded and direct tracks.
2884 //
2885 // It is possible, but not enabled, to allow duration computation for non-pcm
2886 // audio_has_proportional_frames() formats because currently they have
2887 // the drain rate equivalent to the pcm sample rate * framesize.
2888 if (!isPurePcmData_l()) {
2889 return INVALID_OPERATION;
2890 }
2891 ExtendedTimestamp ets;
2892 if (getTimestamp_l(&ets) == OK
2893 && ets.mTimeNs[location] > 0) {
2894 int64_t diff = ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT]
2895 - ets.mPosition[location];
2896 if (diff < 0) {
2897 *msec = 0;
2898 } else {
2899 // ms is the playback time by frames
2900 int64_t ms = (int64_t)((double)diff * 1000 /
2901 ((double)mSampleRate * mPlaybackRate.mSpeed));
2902 // clockdiff is the timestamp age (negative)
2903 int64_t clockdiff = (mState != STATE_ACTIVE) ? 0 :
2904 ets.mTimeNs[location]
2905 + ets.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_MONOTONIC]
2906 - systemTime(SYSTEM_TIME_MONOTONIC);
2907
2908 //ALOGV("ms: %lld clockdiff: %lld", (long long)ms, (long long)clockdiff);
2909 static const int NANOS_PER_MILLIS = 1000000;
2910 *msec = (int32_t)(ms + clockdiff / NANOS_PER_MILLIS);
2911 }
2912 return NO_ERROR;
2913 }
2914 if (location != ExtendedTimestamp::LOCATION_SERVER) {
2915 return INVALID_OPERATION; // LOCATION_KERNEL is not available
2916 }
2917 // use server position directly (offloaded and direct arrive here)
2918 updateAndGetPosition_l();
2919 int32_t diff = (Modulo<uint32_t>(mFramesWritten) - mPosition).signedValue();
2920 *msec = (diff <= 0) ? 0
2921 : (int32_t)((double)diff * 1000 / ((double)mSampleRate * mPlaybackRate.mSpeed));
2922 return NO_ERROR;
2923}
2924
Andy Hung65ffdfc2016-10-10 15:52:11 -07002925bool AudioTrack::hasStarted()
2926{
2927 AutoMutex lock(mLock);
2928 switch (mState) {
2929 case STATE_STOPPED:
2930 if (isOffloadedOrDirect_l()) {
2931 // check if we have started in the past to return true.
Andy Hungffa36952017-08-17 10:41:51 -07002932 return mStartFromZeroUs > 0;
Andy Hung65ffdfc2016-10-10 15:52:11 -07002933 }
2934 // A normal audio track may still be draining, so
2935 // check if stream has ended. This covers fasttrack position
2936 // instability and start/stop without any data written.
2937 if (mProxy->getStreamEndDone()) {
2938 return true;
2939 }
2940 // fall through
2941 case STATE_ACTIVE:
2942 case STATE_STOPPING:
2943 break;
2944 case STATE_PAUSED:
2945 case STATE_PAUSED_STOPPING:
2946 case STATE_FLUSHED:
2947 return false; // we're not active
2948 default:
2949 LOG_ALWAYS_FATAL("Invalid mState in hasStarted(): %d", mState);
2950 break;
2951 }
2952
2953 // wait indicates whether we need to wait for a timestamp.
2954 // This is conservatively figured - if we encounter an unexpected error
2955 // then we will not wait.
2956 bool wait = false;
2957 if (isOffloadedOrDirect_l()) {
2958 AudioTimestamp ts;
2959 status_t status = getTimestamp_l(ts);
2960 if (status == WOULD_BLOCK) {
2961 wait = true;
2962 } else if (status == OK) {
2963 wait = (ts.mPosition == 0 || ts.mPosition == mStartTs.mPosition);
2964 }
2965 ALOGV("hasStarted wait:%d ts:%u start position:%lld",
2966 (int)wait,
2967 ts.mPosition,
2968 (long long)mStartTs.mPosition);
2969 } else {
2970 int location = ExtendedTimestamp::LOCATION_SERVER; // for ALOG
2971 ExtendedTimestamp ets;
2972 status_t status = getTimestamp_l(&ets);
2973 if (status == WOULD_BLOCK) { // no SERVER or KERNEL frame info in ets
2974 wait = true;
2975 } else if (status == OK) {
2976 for (location = ExtendedTimestamp::LOCATION_KERNEL;
2977 location >= ExtendedTimestamp::LOCATION_SERVER; --location) {
2978 if (ets.mTimeNs[location] < 0 || mStartEts.mTimeNs[location] < 0) {
2979 continue;
2980 }
2981 wait = ets.mPosition[location] == 0
2982 || ets.mPosition[location] == mStartEts.mPosition[location];
2983 break;
2984 }
2985 }
2986 ALOGV("hasStarted wait:%d ets:%lld start position:%lld",
2987 (int)wait,
2988 (long long)ets.mPosition[location],
2989 (long long)mStartEts.mPosition[location]);
2990 }
2991 return !wait;
2992}
2993
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002994// =========================================================================
2995
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002996void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002997{
2998 sp<AudioTrack> audioTrack = mAudioTrack.promote();
2999 if (audioTrack != 0) {
3000 AutoMutex lock(audioTrack->mLock);
3001 audioTrack->mProxy->binderDied();
3002 }
3003}
3004
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003005// =========================================================================
3006
3007AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
Glenn Kasten598de6c2013-10-16 17:02:13 -07003008 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
3009 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08003010{
3011}
3012
3013AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003014{
3015}
3016
3017bool AudioTrack::AudioTrackThread::threadLoop()
3018{
Glenn Kasten3acbd052012-02-28 10:39:56 -08003019 {
3020 AutoMutex _l(mMyLock);
3021 if (mPaused) {
Glenn Kasten75f79032017-05-23 11:22:44 -07003022 // TODO check return value and handle or log
Glenn Kasten3acbd052012-02-28 10:39:56 -08003023 mMyCond.wait(mMyLock);
3024 // caller will check for exitPending()
3025 return true;
3026 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07003027 if (mIgnoreNextPausedInt) {
3028 mIgnoreNextPausedInt = false;
3029 mPausedInt = false;
3030 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003031 if (mPausedInt) {
Glenn Kasten47d55172017-05-23 11:19:30 -07003032 // TODO use futex instead of condition, for event flag "or"
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003033 if (mPausedNs > 0) {
Glenn Kasten75f79032017-05-23 11:22:44 -07003034 // TODO check return value and handle or log
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003035 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
3036 } else {
Glenn Kasten75f79032017-05-23 11:22:44 -07003037 // TODO check return value and handle or log
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003038 mMyCond.wait(mMyLock);
3039 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07003040 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003041 return true;
3042 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08003043 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07003044 if (exitPending()) {
3045 return false;
3046 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08003047 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003048 switch (ns) {
3049 case 0:
3050 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003051 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003052 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003053 return true;
3054 case NS_NEVER:
3055 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003056 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08003057 // Event driven: call wake() when callback notifications conditions change.
3058 ns = INT64_MAX;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003059 // fall through
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003060 default:
Mark Salyzyn34fb2962014-06-18 16:30:56 -07003061 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003062 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003063 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07003064 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003065}
3066
Glenn Kasten3acbd052012-02-28 10:39:56 -08003067void AudioTrack::AudioTrackThread::requestExit()
3068{
3069 // must be in this order to avoid a race condition
3070 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07003071 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08003072}
3073
3074void AudioTrack::AudioTrackThread::pause()
3075{
3076 AutoMutex _l(mMyLock);
3077 mPaused = true;
3078}
3079
3080void AudioTrack::AudioTrackThread::resume()
3081{
3082 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07003083 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07003084 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08003085 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07003086 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08003087 mMyCond.signal();
3088 }
3089}
3090
Andy Hung3c09c782014-12-29 18:39:32 -08003091void AudioTrack::AudioTrackThread::wake()
3092{
3093 AutoMutex _l(mMyLock);
Andy Hunga8d08902015-07-22 11:52:13 -07003094 if (!mPaused) {
3095 // wake() might be called while servicing a callback - ignore the next
3096 // pause time and call processAudioBuffer.
Andy Hung3c09c782014-12-29 18:39:32 -08003097 mIgnoreNextPausedInt = true;
Andy Hunga8d08902015-07-22 11:52:13 -07003098 if (mPausedInt && mPausedNs > 0) {
3099 // audio track is active and internally paused with timeout.
3100 mPausedInt = false;
3101 mMyCond.signal();
3102 }
Andy Hung3c09c782014-12-29 18:39:32 -08003103 }
3104}
3105
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003106void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
3107{
3108 AutoMutex _l(mMyLock);
3109 mPausedInt = true;
3110 mPausedNs = ns;
3111}
3112
Glenn Kasten40bc9062015-03-20 09:09:33 -07003113} // namespace android