blob: 8c53c5b1e7ed57a658d6b831b7f2b3173dc0cb1b [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
Chih-Hung Hsiehffe35582018-09-13 13:59:28 -070025#include <android-base/macros.h>
Andy Hung2b01f002017-07-05 12:01:36 -070026#include <audio_utils/clock.h>
Glenn Kasten9f80dd22012-12-18 15:57:32 -080027#include <audio_utils/primitives.h>
28#include <binder/IPCThreadState.h>
29#include <media/AudioTrack.h>
30#include <utils/Log.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080031#include <private/media/AudioTrackShared.h>
Suren Baghdasaryan7435e7d2018-12-19 17:09:28 -080032#include <processgroup/sched_policy.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070033#include <media/IAudioFlinger.h>
Michael Chana94fbb22018-04-24 14:31:19 +100034#include <media/IAudioPolicyService.h>
Dean Wheatleya70eef72018-01-04 14:23:50 +110035#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070036#include <media/AudioResamplerPublic.h>
Michael Chana94fbb22018-04-24 14:31:19 +100037#include <media/AudioSystem.h>
Ray Essickf27e9872019-12-07 06:28:46 -080038#include <media/MediaMetricsItem.h>
Ray Essicked304702017-12-12 14:00:57 -080039#include <media/TypeConverter.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080040
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -080041#define VALUE_OR_FATAL(result) \
42 ({ \
43 auto _tmp = (result); \
44 LOG_ALWAYS_FATAL_IF(!_tmp.ok(), \
45 "Failed result (%d)", \
46 _tmp.error()); \
47 std::move(_tmp.value()); \
48 })
49
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010050#define WAIT_PERIOD_MS 10
51#define WAIT_STREAM_END_TIMEOUT_SEC 120
Andy Hung53c3b5f2014-12-15 16:42:05 -080052static const int kMaxLoopCountNotifications = 32;
Glenn Kasten511754b2012-01-11 09:52:19 -080053
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080054namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080055// ---------------------------------------------------------------------------
56
Ivan Lozano8cf3a072017-08-09 09:01:33 -070057using media::VolumeShaper;
58
Andy Hunga7f03352015-05-31 21:54:49 -070059// TODO: Move to a separate .h
60
Andy Hung4ede21d2014-12-12 15:37:34 -080061template <typename T>
Andy Hunga7f03352015-05-31 21:54:49 -070062static inline const T &min(const T &x, const T &y) {
Andy Hung4ede21d2014-12-12 15:37:34 -080063 return x < y ? x : y;
64}
65
Andy Hunga7f03352015-05-31 21:54:49 -070066template <typename T>
67static inline const T &max(const T &x, const T &y) {
68 return x > y ? x : y;
69}
70
71static inline nsecs_t framesToNanoseconds(ssize_t frames, uint32_t sampleRate, float speed)
72{
73 return ((double)frames * 1000000000) / ((double)sampleRate * speed);
74}
75
Andy Hung7f1bc8a2014-09-12 14:43:11 -070076static int64_t convertTimespecToUs(const struct timespec &tv)
77{
Chih-Hung Hsieh50fa06c2018-12-11 13:51:36 -080078 return tv.tv_sec * 1000000LL + tv.tv_nsec / 1000;
Andy Hung7f1bc8a2014-09-12 14:43:11 -070079}
80
Andy Hungffa36952017-08-17 10:41:51 -070081// TODO move to audio_utils.
82static inline struct timespec convertNsToTimespec(int64_t ns) {
83 struct timespec tv;
84 tv.tv_sec = static_cast<time_t>(ns / NANOS_PER_SECOND);
Andy Hung06a730b2020-04-09 13:28:31 -070085 tv.tv_nsec = static_cast<int64_t>(ns % NANOS_PER_SECOND);
Andy Hungffa36952017-08-17 10:41:51 -070086 return tv;
87}
88
Andy Hung7f1bc8a2014-09-12 14:43:11 -070089// current monotonic time in microseconds.
90static int64_t getNowUs()
91{
92 struct timespec tv;
93 (void) clock_gettime(CLOCK_MONOTONIC, &tv);
94 return convertTimespecToUs(tv);
95}
96
Andy Hung26145642015-04-15 21:56:53 -070097// FIXME: we don't use the pitch setting in the time stretcher (not working);
98// instead we emulate it using our sample rate converter.
99static const bool kFixPitch = true; // enable pitch fix
100static inline uint32_t adjustSampleRate(uint32_t sampleRate, float pitch)
101{
102 return kFixPitch ? (sampleRate * pitch + 0.5) : sampleRate;
103}
104
105static inline float adjustSpeed(float speed, float pitch)
106{
Ricardo Garcia6c7f0622015-04-30 18:39:16 -0700107 return kFixPitch ? speed / max(pitch, AUDIO_TIMESTRETCH_PITCH_MIN_DELTA) : speed;
Andy Hung26145642015-04-15 21:56:53 -0700108}
109
110static inline float adjustPitch(float pitch)
111{
112 return kFixPitch ? AUDIO_TIMESTRETCH_PITCH_NORMAL : pitch;
113}
114
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800115// static
116status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -0800117 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800118 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800119 uint32_t sampleRate)
120{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700121 if (frameCount == NULL) {
122 return BAD_VALUE;
123 }
Glenn Kasten04cd0182012-06-25 11:49:27 -0700124
Andy Hung0e48d252015-01-26 11:43:15 -0800125 // FIXME handle in server, like createTrack_l(), possible missing info:
Glenn Kastene0fa4672012-04-24 14:35:14 -0700126 // audio_io_handle_t output
127 // audio_format_t format
128 // audio_channel_mask_t channelMask
Andy Hung0e48d252015-01-26 11:43:15 -0800129 // audio_output_flags_t flags (FAST)
Glenn Kasten3b16c762012-11-14 08:44:39 -0800130 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -0800131 status_t status;
132 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
133 if (status != NO_ERROR) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700134 ALOGE("%s(): Unable to query output sample rate for stream type %d; status %d",
135 __func__, streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800136 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800137 }
Glenn Kastene33054e2012-11-14 12:54:39 -0800138 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -0800139 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
140 if (status != NO_ERROR) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700141 ALOGE("%s(): Unable to query output frame count for stream type %d; status %d",
142 __func__, streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800143 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800144 }
145 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -0800146 status = AudioSystem::getOutputLatency(&afLatency, streamType);
147 if (status != NO_ERROR) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700148 ALOGE("%s(): Unable to query output latency for stream type %d; status %d",
149 __func__, streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800150 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800151 }
152
Andy Hung8edb8dc2015-03-26 19:13:55 -0700153 // When called from createTrack, speed is 1.0f (normal speed).
154 // This is rechecked again on setting playback rate (TODO: on setting sample rate, too).
Eric Laurent21da6472017-11-09 16:29:26 -0800155 *frameCount = AudioSystem::calculateMinFrameCount(afLatency, afFrameCount, afSampleRate,
156 sampleRate, 1.0f /*, 0 notificationsPerBufferReq*/);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800157
Andy Hung0e48d252015-01-26 11:43:15 -0800158 // The formula above should always produce a non-zero value under normal circumstances:
159 // AudioTrack.SAMPLE_RATE_HZ_MIN <= sampleRate <= AudioTrack.SAMPLE_RATE_HZ_MAX.
160 // 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 -0800161 if (*frameCount == 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700162 ALOGE("%s(): failed for streamType %d, sampleRate %u",
163 __func__, streamType, sampleRate);
Glenn Kasten66a04672014-01-08 08:53:44 -0800164 return BAD_VALUE;
165 }
Andy Hungfb8ede22018-09-12 19:03:24 -0700166 ALOGV("%s(): getMinFrameCount=%zu: afFrameCount=%zu, afSampleRate=%u, afLatency=%u",
167 __func__, *frameCount, afFrameCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800168 return NO_ERROR;
169}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800170
Michael Chana94fbb22018-04-24 14:31:19 +1000171// static
172bool AudioTrack::isDirectOutputSupported(const audio_config_base_t& config,
173 const audio_attributes_t& attributes) {
174 ALOGV("%s()", __FUNCTION__);
175 const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
176 if (aps == 0) return false;
177 return aps->isDirectOutputSupported(config, attributes);
178}
179
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800180// ---------------------------------------------------------------------------
181
Ray Essicked304702017-12-12 14:00:57 -0800182void AudioTrack::MediaMetrics::gather(const AudioTrack *track)
183{
Ray Essick88394302018-01-24 14:52:05 -0800184 // only if we're in a good state...
185 // XXX: shall we gather alternative info if failing?
186 const status_t lstatus = track->initCheck();
187 if (lstatus != NO_ERROR) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700188 ALOGD("%s(): no metrics gathered, track status=%d", __func__, (int) lstatus);
Ray Essick88394302018-01-24 14:52:05 -0800189 return;
190 }
191
Andy Hungd0979812019-02-21 15:51:44 -0800192#define MM_PREFIX "android.media.audiotrack." // avoid cut-n-paste errors.
Ray Essicked304702017-12-12 14:00:57 -0800193
Andy Hungd0979812019-02-21 15:51:44 -0800194 // Java API 28 entries, do not change.
Ray Essickf27e9872019-12-07 06:28:46 -0800195 mMetricsItem->setCString(MM_PREFIX "streamtype", toString(track->streamType()).c_str());
196 mMetricsItem->setCString(MM_PREFIX "type",
Andy Hungd0979812019-02-21 15:51:44 -0800197 toString(track->mAttributes.content_type).c_str());
Ray Essickf27e9872019-12-07 06:28:46 -0800198 mMetricsItem->setCString(MM_PREFIX "usage", toString(track->mAttributes.usage).c_str());
Ray Essicked304702017-12-12 14:00:57 -0800199
Andy Hungd0979812019-02-21 15:51:44 -0800200 // Non-API entries, these can change due to a Java string mistake.
Ray Essickf27e9872019-12-07 06:28:46 -0800201 mMetricsItem->setInt32(MM_PREFIX "sampleRate", (int32_t)track->mSampleRate);
202 mMetricsItem->setInt64(MM_PREFIX "channelMask", (int64_t)track->mChannelMask);
Andy Hungd0979812019-02-21 15:51:44 -0800203 // Non-API entries, these can change.
Ray Essickf27e9872019-12-07 06:28:46 -0800204 mMetricsItem->setInt32(MM_PREFIX "portId", (int32_t)track->mPortId);
205 mMetricsItem->setCString(MM_PREFIX "encoding", toString(track->mFormat).c_str());
206 mMetricsItem->setInt32(MM_PREFIX "frameCount", (int32_t)track->mFrameCount);
207 mMetricsItem->setCString(MM_PREFIX "attributes", toString(track->mAttributes).c_str());
Ray Essicked304702017-12-12 14:00:57 -0800208}
209
Ray Essick88394302018-01-24 14:52:05 -0800210// hand the user a snapshot of the metrics.
Ray Essickf27e9872019-12-07 06:28:46 -0800211status_t AudioTrack::getMetrics(mediametrics::Item * &item)
Ray Essick88394302018-01-24 14:52:05 -0800212{
213 mMediaMetrics.gather(this);
Ray Essickf27e9872019-12-07 06:28:46 -0800214 mediametrics::Item *tmp = mMediaMetrics.dup();
Ray Essick88394302018-01-24 14:52:05 -0800215 if (tmp == nullptr) {
216 return BAD_VALUE;
217 }
218 item = tmp;
219 return NO_ERROR;
220}
Ray Essicked304702017-12-12 14:00:57 -0800221
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000222AudioTrack::AudioTrack() : AudioTrack("" /*opPackageName*/)
223{
224}
225
226AudioTrack::AudioTrack(const std::string& opPackageName)
Glenn Kasten87913512011-06-22 16:15:25 -0700227 : mStatus(NO_INIT),
Haynes Mathew George9b3359f2016-03-23 19:09:10 -0700228 mState(STATE_STOPPED),
John Grossman4ff14ba2012-02-08 16:37:41 -0800229 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800230 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700231 mPausedPosition(0),
Eric Laurent20b9ef02016-12-05 11:03:16 -0800232 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabinf6eb4c32020-02-25 14:06:25 -0800233 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000234 mOpPackageName(opPackageName),
jiabinf6eb4c32020-02-25 14:06:25 -0800235 mAudioTrackCallback(new AudioTrackCallback())
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800236{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700237 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
238 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
Mikhail Naganov55773032020-10-01 15:08:13 -0700239 mAttributes.flags = AUDIO_FLAG_NONE;
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700240 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800241}
242
243AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800244 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800245 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800246 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700247 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800248 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700249 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800250 callback_t cbf,
251 void* user,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700252 int32_t notificationFrames,
Glenn Kastend848eb42016-03-08 13:42:11 -0800253 audio_session_t sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000254 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800255 const audio_offload_info_t *offloadInfo,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800256 uid_t uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700257 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700258 const audio_attributes_t* pAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -0700259 bool doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -0700260 float maxRequiredSpeed,
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000261 audio_port_handle_t selectedDeviceId,
262 const std::string& opPackageName)
Glenn Kasten87913512011-06-22 16:15:25 -0700263 : mStatus(NO_INIT),
Haynes Mathew George9b3359f2016-03-23 19:09:10 -0700264 mState(STATE_STOPPED),
John Grossman4ff14ba2012-02-08 16:37:41 -0800265 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800266 mPreviousSchedulingGroup(SP_DEFAULT),
jiabinf6eb4c32020-02-25 14:06:25 -0800267 mPausedPosition(0),
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000268 mOpPackageName(opPackageName),
jiabinf6eb4c32020-02-25 14:06:25 -0800269 mAudioTrackCallback(new AudioTrackCallback())
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800270{
François Gaffie393f0e02019-04-10 09:09:08 +0200271 mAttributes = AUDIO_ATTRIBUTES_INITIALIZER;
Ippei Murata5fa32ed2018-10-01 17:37:50 +0900272
Eric Laurentf32d7812017-11-30 14:44:07 -0800273 (void)set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700274 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800275 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
jiabin156c6872017-10-06 09:47:15 -0700276 offloadInfo, uid, pid, pAttributes, doNotReconnect, maxRequiredSpeed, selectedDeviceId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800277}
278
Andreas Huberc8139852012-01-18 10:51:55 -0800279AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800280 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800281 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800282 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700283 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800284 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700285 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800286 callback_t cbf,
287 void* user,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700288 int32_t notificationFrames,
Glenn Kastend848eb42016-03-08 13:42:11 -0800289 audio_session_t sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000290 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800291 const audio_offload_info_t *offloadInfo,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800292 uid_t uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700293 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700294 const audio_attributes_t* pAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -0700295 bool doNotReconnect,
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000296 float maxRequiredSpeed,
297 const std::string& opPackageName)
Glenn Kasten87913512011-06-22 16:15:25 -0700298 : mStatus(NO_INIT),
Haynes Mathew George9b3359f2016-03-23 19:09:10 -0700299 mState(STATE_STOPPED),
John Grossman4ff14ba2012-02-08 16:37:41 -0800300 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800301 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700302 mPausedPosition(0),
jiabinf6eb4c32020-02-25 14:06:25 -0800303 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000304 mOpPackageName(opPackageName),
jiabinf6eb4c32020-02-25 14:06:25 -0800305 mAudioTrackCallback(new AudioTrackCallback())
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800306{
François Gaffie393f0e02019-04-10 09:09:08 +0200307 mAttributes = AUDIO_ATTRIBUTES_INITIALIZER;
Ippei Murata5fa32ed2018-10-01 17:37:50 +0900308
Eric Laurentf32d7812017-11-30 14:44:07 -0800309 (void)set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800310 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800311 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Andy Hungff874dc2016-04-11 16:49:09 -0700312 uid, pid, pAttributes, doNotReconnect, maxRequiredSpeed);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800313}
314
315AudioTrack::~AudioTrack()
316{
Ray Essicked304702017-12-12 14:00:57 -0800317 // pull together the numbers, before we clean up our structures
318 mMediaMetrics.gather(this);
319
Andy Hungb68f5eb2019-12-03 16:49:17 -0800320 mediametrics::LogItem(mMetricsId)
321 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DTOR)
Phil Burkd3813f32020-04-23 16:26:15 -0700322 .set(AMEDIAMETRICS_PROP_CALLERNAME,
323 mCallerName.empty()
Andy Hunga6b27032020-04-27 10:34:24 -0700324 ? AMEDIAMETRICS_PROP_CALLERNAME_VALUE_UNKNOWN
Phil Burkd3813f32020-04-23 16:26:15 -0700325 : mCallerName.c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -0800326 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
327 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)mStatus)
328 .record();
329
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800330 if (mStatus == NO_ERROR) {
331 // Make sure that callback function exits in the case where
332 // it is looping on buffer full condition in obtainBuffer().
333 // Otherwise the callback thread will never exit.
334 stop();
335 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100336 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800337 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800338 mAudioTrackThread->requestExitAndWait();
339 mAudioTrackThread.clear();
340 }
Eric Laurent296fb132015-05-01 11:38:42 -0700341 // No lock here: worst case we remove a NULL callback which will be a nop
342 if (mDeviceCallback != 0 && mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent09f1ed22019-04-24 17:45:17 -0700343 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -0700344 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800345 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700346 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700347 mCblkMemory.clear();
348 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800349 IPCThreadState::self()->flushCommands();
Andy Hungfb8ede22018-09-12 19:03:24 -0700350 ALOGV("%s(%d), releasing session id %d from %d on behalf of %d",
Eric Laurent973db022018-11-20 14:54:31 -0800351 __func__, mPortId,
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700352 mSessionId, IPCThreadState::self()->getCallingPid(), mClientPid);
Marco Nelissend457c972014-02-11 08:47:07 -0800353 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800354 }
355}
356
357status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800358 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800359 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800360 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700361 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800362 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700363 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800364 callback_t cbf,
365 void* user,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700366 int32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800367 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700368 bool threadCanCallJava,
Glenn Kastend848eb42016-03-08 13:42:11 -0800369 audio_session_t sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000370 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800371 const audio_offload_info_t *offloadInfo,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800372 uid_t uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700373 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700374 const audio_attributes_t* pAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -0700375 bool doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -0700376 float maxRequiredSpeed,
377 audio_port_handle_t selectedDeviceId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800378{
Eric Laurentf32d7812017-11-30 14:44:07 -0800379 status_t status;
380 uint32_t channelCount;
381 pid_t callingPid;
382 pid_t myPid;
383
Eric Laurent973db022018-11-20 14:54:31 -0800384 // Note mPortId is not valid until the track is created, so omit mPortId in ALOG for set.
Andy Hungfb8ede22018-09-12 19:03:24 -0700385 ALOGV("%s(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kastenea38ee72016-04-18 11:08:01 -0700386 "flags #%x, notificationFrames %d, sessionId %d, transferType %d, uid %d, pid %d",
Andy Hungfb8ede22018-09-12 19:03:24 -0700387 __func__,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800388 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700389 sessionId, transferType, uid, pid);
Glenn Kasten86f04662014-02-24 15:13:05 -0800390
Phil Burk33ff89b2015-11-30 11:16:01 -0800391 mThreadCanCallJava = threadCanCallJava;
jiabin156c6872017-10-06 09:47:15 -0700392 mSelectedDeviceId = selectedDeviceId;
Eric Laurent21da6472017-11-09 16:29:26 -0800393 mSessionId = sessionId;
Phil Burk33ff89b2015-11-30 11:16:01 -0800394
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800395 switch (transferType) {
396 case TRANSFER_DEFAULT:
397 if (sharedBuffer != 0) {
398 transferType = TRANSFER_SHARED;
399 } else if (cbf == NULL || threadCanCallJava) {
400 transferType = TRANSFER_SYNC;
401 } else {
402 transferType = TRANSFER_CALLBACK;
403 }
404 break;
405 case TRANSFER_CALLBACK:
Jean-Michel Trivif4158d82018-09-25 12:43:58 -0700406 case TRANSFER_SYNC_NOTIF_CALLBACK:
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800407 if (cbf == NULL || sharedBuffer != 0) {
Jean-Michel Trivif4158d82018-09-25 12:43:58 -0700408 ALOGE("%s(): Transfer type %s but cbf == NULL || sharedBuffer != 0",
409 convertTransferToText(transferType), __func__);
Eric Laurentf32d7812017-11-30 14:44:07 -0800410 status = BAD_VALUE;
411 goto exit;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800412 }
413 break;
414 case TRANSFER_OBTAIN:
415 case TRANSFER_SYNC:
416 if (sharedBuffer != 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700417 ALOGE("%s(): Transfer type TRANSFER_OBTAIN but sharedBuffer != 0", __func__);
Eric Laurentf32d7812017-11-30 14:44:07 -0800418 status = BAD_VALUE;
419 goto exit;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800420 }
421 break;
422 case TRANSFER_SHARED:
423 if (sharedBuffer == 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700424 ALOGE("%s(): Transfer type TRANSFER_SHARED but sharedBuffer == 0", __func__);
Eric Laurentf32d7812017-11-30 14:44:07 -0800425 status = BAD_VALUE;
426 goto exit;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800427 }
428 break;
429 default:
Andy Hungfb8ede22018-09-12 19:03:24 -0700430 ALOGE("%s(): Invalid transfer type %d",
431 __func__, transferType);
Eric Laurentf32d7812017-11-30 14:44:07 -0800432 status = BAD_VALUE;
433 goto exit;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800434 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800435 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800436 mTransfer = transferType;
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700437 mDoNotReconnect = doNotReconnect;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800438
Andy Hungfb8ede22018-09-12 19:03:24 -0700439 ALOGV_IF(sharedBuffer != 0, "%s(): sharedBuffer: %p, size: %zu",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700440 __func__, sharedBuffer->unsecurePointer(), sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800441
Andy Hungfb8ede22018-09-12 19:03:24 -0700442 ALOGV("%s(): streamType %d frameCount %zu flags %04x",
443 __func__, streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700444
Glenn Kasten53cec222013-08-29 09:01:02 -0700445 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700446 if (mAudioTrack != 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700447 ALOGE("%s(): Track already in use", __func__);
Eric Laurentf32d7812017-11-30 14:44:07 -0800448 status = INVALID_OPERATION;
449 goto exit;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800450 }
451
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800452 // handle default values first.
Eric Laurente83b55d2014-11-14 10:06:21 -0800453 if (streamType == AUDIO_STREAM_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700454 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800455 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700456 if (pAttributes == NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800457 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700458 ALOGE("%s(): Invalid stream type %d", __func__, streamType);
Eric Laurentf32d7812017-11-30 14:44:07 -0800459 status = BAD_VALUE;
460 goto exit;
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700461 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700462 mStreamType = streamType;
Eric Laurente83b55d2014-11-14 10:06:21 -0800463
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700464 } else {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700465 // stream type shouldn't be looked at, this track has audio attributes
466 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Andy Hungfb8ede22018-09-12 19:03:24 -0700467 ALOGV("%s(): Building AudioTrack with attributes:"
468 " usage=%d content=%d flags=0x%x tags=[%s]",
469 __func__,
470 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800471 mStreamType = AUDIO_STREAM_DEFAULT;
François Gaffie58d4be52018-11-06 15:30:12 +0100472 audio_flags_to_audio_output_flags(mAttributes.flags, &flags);
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800473 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700474
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800475 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800476 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700477 format = AUDIO_FORMAT_PCM_16_BIT;
Phil Burkfdb3c072016-02-09 10:47:02 -0800478 } else if (format == AUDIO_FORMAT_IEC61937) { // HDMI pass-through?
Mikhail Naganov55773032020-10-01 15:08:13 -0700479 flags = static_cast<audio_output_flags_t>(flags | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800480 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800481
482 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700483 if (!audio_is_valid_format(format)) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700484 ALOGE("%s(): Invalid format %#x", __func__, format);
Eric Laurentf32d7812017-11-30 14:44:07 -0800485 status = BAD_VALUE;
486 goto exit;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800487 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800488 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700489
Glenn Kasten8ba90322013-10-30 11:29:27 -0700490 if (!audio_is_output_channel(channelMask)) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700491 ALOGE("%s(): Invalid channel mask %#x", __func__, channelMask);
Eric Laurentf32d7812017-11-30 14:44:07 -0800492 status = BAD_VALUE;
493 goto exit;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700494 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800495 mChannelMask = channelMask;
Eric Laurentf32d7812017-11-30 14:44:07 -0800496 channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800497 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700498
Eric Laurentc2f1f072009-07-17 12:17:14 -0700499 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100500 // or offload was requested
501 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
502 || !audio_is_linear_pcm(format)) {
503 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
Andy Hungfb8ede22018-09-12 19:03:24 -0700504 ? "%s(): Offload request, forcing to Direct Output"
505 : "%s(): Not linear PCM, forcing to Direct Output",
506 __func__);
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700507 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800508 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700509 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700510 }
511
Eric Laurentd1f69b02014-12-15 14:33:13 -0800512 // force direct flag if HW A/V sync requested
513 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
514 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
515 }
516
Glenn Kastenb7730382014-04-30 15:50:31 -0700517 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Phil Burkfdb3c072016-02-09 10:47:02 -0800518 if (audio_has_proportional_frames(format)) {
Glenn Kastenb7730382014-04-30 15:50:31 -0700519 mFrameSize = channelCount * audio_bytes_per_sample(format);
520 } else {
521 mFrameSize = sizeof(uint8_t);
522 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800523 } else {
Phil Burkfdb3c072016-02-09 10:47:02 -0800524 ALOG_ASSERT(audio_has_proportional_frames(format));
Glenn Kastenb7730382014-04-30 15:50:31 -0700525 mFrameSize = channelCount * audio_bytes_per_sample(format);
Glenn Kastenb7730382014-04-30 15:50:31 -0700526 // createTrack will return an error if PCM format is not supported by server,
527 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800528 }
529
Eric Laurent0d6db582014-11-12 18:39:44 -0800530 // sampling rate must be specified for direct outputs
531 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentf32d7812017-11-30 14:44:07 -0800532 status = BAD_VALUE;
533 goto exit;
Eric Laurent0d6db582014-11-12 18:39:44 -0800534 }
535 mSampleRate = sampleRate;
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700536 mOriginalSampleRate = sampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700537 mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT;
Andy Hungff874dc2016-04-11 16:49:09 -0700538 // 1.0 <= mMaxRequiredSpeed <= AUDIO_TIMESTRETCH_SPEED_MAX
539 mMaxRequiredSpeed = min(max(maxRequiredSpeed, 1.0f), AUDIO_TIMESTRETCH_SPEED_MAX);
Eric Laurent0d6db582014-11-12 18:39:44 -0800540
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800541 // Make copy of input parameter offloadInfo so that in the future:
542 // (a) createTrack_l doesn't need it as an input parameter
543 // (b) we can support re-creation of offloaded tracks
544 if (offloadInfo != NULL) {
545 mOffloadInfoCopy = *offloadInfo;
546 mOffloadInfo = &mOffloadInfoCopy;
547 } else {
548 mOffloadInfo = NULL;
Eric Laurent20b9ef02016-12-05 11:03:16 -0800549 memset(&mOffloadInfoCopy, 0, sizeof(audio_offload_info_t));
Ytai Ben-Tsviffa2fd92020-10-20 09:13:53 -0700550 mOffloadInfoCopy = AUDIO_INFO_INITIALIZER;
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800551 }
552
Glenn Kasten66e46352014-01-16 17:44:23 -0800553 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
554 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800555 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800556 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800557 mReqFrameCount = frameCount;
Glenn Kastenea38ee72016-04-18 11:08:01 -0700558 if (notificationFrames >= 0) {
559 mNotificationFramesReq = notificationFrames;
560 mNotificationsPerBufferReq = 0;
561 } else {
562 if (!(flags & AUDIO_OUTPUT_FLAG_FAST)) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700563 ALOGE("%s(): notificationFrames=%d not permitted for non-fast track",
564 __func__, notificationFrames);
Eric Laurentf32d7812017-11-30 14:44:07 -0800565 status = BAD_VALUE;
566 goto exit;
Glenn Kastenea38ee72016-04-18 11:08:01 -0700567 }
568 if (frameCount > 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700569 ALOGE("%s(): notificationFrames=%d not permitted with non-zero frameCount=%zu",
570 __func__, notificationFrames, frameCount);
Eric Laurentf32d7812017-11-30 14:44:07 -0800571 status = BAD_VALUE;
572 goto exit;
Glenn Kastenea38ee72016-04-18 11:08:01 -0700573 }
574 mNotificationFramesReq = 0;
575 const uint32_t minNotificationsPerBuffer = 1;
576 const uint32_t maxNotificationsPerBuffer = 8;
577 mNotificationsPerBufferReq = min(maxNotificationsPerBuffer,
578 max((uint32_t) -notificationFrames, minNotificationsPerBuffer));
579 ALOGW_IF(mNotificationsPerBufferReq != (uint32_t) -notificationFrames,
Andy Hungfb8ede22018-09-12 19:03:24 -0700580 "%s(): notificationFrames=%d clamped to the range -%u to -%u",
581 __func__,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700582 notificationFrames, minNotificationsPerBuffer, maxNotificationsPerBuffer);
583 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800584 mNotificationFramesAct = 0;
Eric Laurentf32d7812017-11-30 14:44:07 -0800585 callingPid = IPCThreadState::self()->getCallingPid();
586 myPid = getpid();
587 if (uid == AUDIO_UID_INVALID || (callingPid != myPid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800588 mClientUid = IPCThreadState::self()->getCallingUid();
589 } else {
590 mClientUid = uid;
591 }
Eric Laurentf32d7812017-11-30 14:44:07 -0800592 if (pid == -1 || (callingPid != myPid)) {
593 mClientPid = callingPid;
Marco Nelissend457c972014-02-11 08:47:07 -0800594 } else {
595 mClientPid = pid;
596 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700597 mAuxEffectId = 0;
Haynes Mathew Georgeae34ed22016-01-28 11:58:39 -0800598 mOrigFlags = mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700599 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700600
Glenn Kastena997e7a2012-08-07 09:44:19 -0700601 if (cbf != NULL) {
Andy Hungca353672019-03-06 11:54:38 -0800602 mAudioTrackThread = new AudioTrackThread(*this);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700603 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
Glenn Kastenbfd31842015-03-20 09:01:44 -0700604 // thread begins in paused state, and will not reference us until start()
Glenn Kastena997e7a2012-08-07 09:44:19 -0700605 }
606
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800607 // create the IAudioTrack
Francois Gaffie24a9fb02019-01-18 17:51:34 +0100608 {
609 AutoMutex lock(mLock);
610 status = createTrack_l();
611 }
Glenn Kastena997e7a2012-08-07 09:44:19 -0700612 if (status != NO_ERROR) {
613 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100614 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
615 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700616 mAudioTrackThread.clear();
617 }
Eric Laurentf32d7812017-11-30 14:44:07 -0800618 goto exit;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700619 }
620
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800621 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800622 mLoopCount = 0;
623 mLoopStart = 0;
624 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800625 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800626 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700627 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800628 mNewPosition = 0;
629 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700630 mPosition = 0;
631 mReleased = 0;
Andy Hungffa36952017-08-17 10:41:51 -0700632 mStartNs = 0;
633 mStartFromZeroUs = 0;
Andy Hung8b0bfd92019-12-23 13:11:11 -0800634 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid, mClientUid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800635 mSequence = 1;
636 mObservedSequence = mSequence;
637 mInUnderrun = false;
Phil Burk1b420972015-04-22 10:52:21 -0700638 mPreviousTimestampValid = false;
Andy Hungc8e09c62015-06-03 23:43:36 -0700639 mTimestampStartupGlitchReported = false;
Andy Hungcf3b7152019-04-19 18:29:21 -0700640 mTimestampRetrogradePositionReported = false;
641 mTimestampRetrogradeTimeReported = false;
642 mTimestampStallReported = false;
643 mTimestampStaleTimeReported = false;
Andy Hungb01faa32016-04-27 12:51:32 -0700644 mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
Andy Hung65ffdfc2016-10-10 15:52:11 -0700645 mStartTs.mPosition = 0;
Phil Burk2812d9e2016-01-04 10:34:30 -0800646 mUnderrunCountOffset = 0;
Andy Hungea2b9c02016-02-12 17:06:53 -0800647 mFramesWritten = 0;
648 mFramesWrittenServerOffset = 0;
Andy Hungf20a4e92016-08-15 19:10:34 -0700649 mFramesWrittenAtRestore = -1; // -1 is a unique initializer.
Ivan Lozano8cf3a072017-08-09 09:01:33 -0700650 mVolumeHandler = new media::VolumeHandler();
Eric Laurentf32d7812017-11-30 14:44:07 -0800651
652exit:
653 mStatus = status;
654 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800655}
656
Mikhail Naganov55773032020-10-01 15:08:13 -0700657
658status_t AudioTrack::set(
659 audio_stream_type_t streamType,
660 uint32_t sampleRate,
661 audio_format_t format,
662 uint32_t channelMask,
663 size_t frameCount,
664 audio_output_flags_t flags,
665 callback_t cbf,
666 void* user,
667 int32_t notificationFrames,
668 const sp<IMemory>& sharedBuffer,
669 bool threadCanCallJava,
670 audio_session_t sessionId,
671 transfer_type transferType,
672 const audio_offload_info_t *offloadInfo,
673 uid_t uid,
674 pid_t pid,
675 const audio_attributes_t* pAttributes,
676 bool doNotReconnect,
677 float maxRequiredSpeed,
678 audio_port_handle_t selectedDeviceId)
679{
680 return set(streamType, sampleRate, format,
681 static_cast<audio_channel_mask_t>(channelMask),
682 frameCount, flags, cbf, user, notificationFrames, sharedBuffer,
683 threadCanCallJava, sessionId, transferType, offloadInfo, uid, pid,
684 pAttributes, doNotReconnect, maxRequiredSpeed, selectedDeviceId);
685}
686
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800687// -------------------------------------------------------------------------
688
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100689status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800690{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800691 AutoMutex lock(mLock);
Andy Hungb68f5eb2019-12-03 16:49:17 -0800692
Andy Hung10fb4be2020-05-27 22:22:22 -0700693 if (mState == STATE_ACTIVE) {
694 return INVALID_OPERATION;
695 }
696
697 ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
698
699 // Defer logging here due to OpenSL ES repeated start calls.
700 // TODO(b/154868033) after fix, restore this logging back to the beginning of start().
701 const int64_t beginNs = systemTime();
Andy Hungb68f5eb2019-12-03 16:49:17 -0800702 status_t status = NO_ERROR; // logged: make sure to set this before returning.
Andy Hung06a730b2020-04-09 13:28:31 -0700703 mediametrics::Defer defer([&] {
Andy Hungb68f5eb2019-12-03 16:49:17 -0800704 mediametrics::LogItem(mMetricsId)
Andy Hunga6b27032020-04-27 10:34:24 -0700705 .set(AMEDIAMETRICS_PROP_CALLERNAME,
706 mCallerName.empty()
707 ? AMEDIAMETRICS_PROP_CALLERNAME_VALUE_UNKNOWN
708 : mCallerName.c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -0800709 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_START)
Andy Hungea840382020-05-05 21:50:17 -0700710 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
Andy Hungb68f5eb2019-12-03 16:49:17 -0800711 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
712 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)status)
713 .record(); });
714
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800715
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800716 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800717
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800718 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100719 if (previousState == STATE_PAUSED_STOPPING) {
720 mState = STATE_STOPPING;
721 } else {
722 mState = STATE_ACTIVE;
723 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700724 (void) updateAndGetPosition_l();
Andy Hung65ffdfc2016-10-10 15:52:11 -0700725
726 // save start timestamp
727 if (isOffloadedOrDirect_l()) {
728 if (getTimestamp_l(mStartTs) != OK) {
729 mStartTs.mPosition = 0;
730 }
731 } else {
732 if (getTimestamp_l(&mStartEts) != OK) {
733 mStartEts.clear();
734 }
735 }
Andy Hungffa36952017-08-17 10:41:51 -0700736 mStartNs = systemTime(); // save this for timestamp adjustment after starting.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800737 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
738 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700739 mPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -0700740 mPreviousTimestampValid = false;
Andy Hungc8e09c62015-06-03 23:43:36 -0700741 mTimestampStartupGlitchReported = false;
Andy Hungcf3b7152019-04-19 18:29:21 -0700742 mTimestampRetrogradePositionReported = false;
743 mTimestampRetrogradeTimeReported = false;
744 mTimestampStallReported = false;
745 mTimestampStaleTimeReported = false;
Andy Hungb01faa32016-04-27 12:51:32 -0700746 mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
Phil Burk1b420972015-04-22 10:52:21 -0700747
Andy Hung65ffdfc2016-10-10 15:52:11 -0700748 if (!isOffloadedOrDirect_l()
749 && mStartEts.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] > 0) {
Andy Hunge1e98462016-04-12 10:18:51 -0700750 // Server side has consumed something, but is it finished consuming?
751 // It is possible since flush and stop are asynchronous that the server
752 // is still active at this point.
Andy Hungfb8ede22018-09-12 19:03:24 -0700753 ALOGV("%s(%d): server read:%lld cumulative flushed:%lld client written:%lld",
Eric Laurent973db022018-11-20 14:54:31 -0800754 __func__, mPortId,
Andy Hunge1e98462016-04-12 10:18:51 -0700755 (long long)(mFramesWrittenServerOffset
Andy Hung65ffdfc2016-10-10 15:52:11 -0700756 + mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER]),
757 (long long)mStartEts.mFlushed,
Andy Hunge1e98462016-04-12 10:18:51 -0700758 (long long)mFramesWritten);
Andy Hungc4e60eb2017-09-06 11:14:57 -0700759 // mStartEts is already adjusted by mFramesWrittenServerOffset, so we delta adjust.
760 mFramesWrittenServerOffset -= mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung61be8412015-10-06 10:51:09 -0700761 }
Andy Hunge1e98462016-04-12 10:18:51 -0700762 mFramesWritten = 0;
763 mProxy->clearTimestamp(); // need new server push for valid timestamp
764 mMarkerReached = false;
Andy Hung61be8412015-10-06 10:51:09 -0700765
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700766 // For offloaded tracks, we don't know if the hardware counters are really zero here,
767 // since the flush is asynchronous and stop may not fully drain.
768 // We save the time when the track is started to later verify whether
769 // the counters are realistic (i.e. start from zero after this time).
Andy Hungffa36952017-08-17 10:41:51 -0700770 mStartFromZeroUs = mStartNs / 1000;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700771
Eric Laurentec9a0322013-08-28 10:23:01 -0700772 // force refresh of remaining frames by processAudioBuffer() as last
773 // write before stop could be partial.
774 mRefreshRemaining = true;
Tomoharu Kasahara6e8bf982017-06-09 16:17:33 +0900775
776 // for static track, clear the old flags when starting from stopped state
777 if (mSharedBuffer != 0) {
778 android_atomic_and(
779 ~(CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
780 &mCblk->mFlags);
781 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800782 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700783 mNewPosition = mPosition + mUpdatePeriod;
Andy Hung4be3b832016-10-13 17:51:43 -0700784 int32_t flags = android_atomic_and(~(CBLK_STREAM_END_DONE | CBLK_DISABLED), &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800785
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800786 if (!(flags & CBLK_INVALID)) {
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800787 mAudioTrack->start(&status);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800788 if (status == DEAD_OBJECT) {
789 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800790 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800791 }
792 if (flags & CBLK_INVALID) {
793 status = restoreTrack_l("start");
794 }
795
Andy Hung79629f02016-03-24 13:57:40 -0700796 // resume or pause the callback thread as needed.
797 sp<AudioTrackThread> t = mAudioTrackThread;
798 if (status == NO_ERROR) {
799 if (t != 0) {
800 if (previousState == STATE_STOPPING) {
801 mProxy->interrupt();
802 } else {
803 t->resume();
804 }
805 } else {
806 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
807 get_sched_policy(0, &mPreviousSchedulingGroup);
808 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
809 }
Andy Hung39399b62017-04-21 15:07:45 -0700810
811 // Start our local VolumeHandler for restoration purposes.
812 mVolumeHandler->setStarted();
Andy Hung79629f02016-03-24 13:57:40 -0700813 } else {
Eric Laurent973db022018-11-20 14:54:31 -0800814 ALOGE("%s(%d): status %d", __func__, mPortId, status);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800815 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800816 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100817 if (previousState != STATE_STOPPING) {
818 t->pause();
819 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800820 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700821 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700822 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800823 }
824 }
825
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100826 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800827}
828
829void AudioTrack::stop()
830{
Andy Hungb68f5eb2019-12-03 16:49:17 -0800831 const int64_t beginNs = systemTime();
832
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800833 AutoMutex lock(mLock);
Andy Hung06a730b2020-04-09 13:28:31 -0700834 mediametrics::Defer defer([&]() {
Andy Hungb68f5eb2019-12-03 16:49:17 -0800835 mediametrics::LogItem(mMetricsId)
836 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_STOP)
Andy Hungea840382020-05-05 21:50:17 -0700837 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
Andy Hungb68f5eb2019-12-03 16:49:17 -0800838 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
Phil Burk64e16a72020-06-01 13:25:51 -0700839 .set(AMEDIAMETRICS_PROP_BUFFERSIZEFRAMES, (int32_t)mProxy->getBufferSizeInFrames())
840 .set(AMEDIAMETRICS_PROP_UNDERRUN, (int32_t) getUnderrunCount_l())
Phil Burka9876702020-04-20 18:16:15 -0700841 .record();
Phil Burka9876702020-04-20 18:16:15 -0700842 });
Andy Hungb68f5eb2019-12-03 16:49:17 -0800843
Eric Laurent973db022018-11-20 14:54:31 -0800844 ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
Andy Hungfb8ede22018-09-12 19:03:24 -0700845
Glenn Kasten397edb32013-08-30 15:10:13 -0700846 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800847 return;
848 }
849
Glenn Kasten23a75452014-01-13 10:37:17 -0800850 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100851 mState = STATE_STOPPING;
852 } else {
853 mState = STATE_STOPPED;
Andy Hung2148bf02016-11-28 19:01:02 -0800854 ALOGD_IF(mSharedBuffer == nullptr,
Eric Laurent973db022018-11-20 14:54:31 -0800855 "%s(%d): called with %u frames delivered", __func__, mPortId, mReleased.value());
Andy Hungc2813e52014-10-16 17:54:34 -0700856 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100857 }
858
Andy Hung1d3556d2018-03-29 16:30:14 -0700859 mProxy->stop(); // notify server not to read beyond current client position until start().
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800860 mProxy->interrupt();
861 mAudioTrack->stop();
Andy Hung61be8412015-10-06 10:51:09 -0700862
863 // Note: legacy handling - stop does not clear playback marker
864 // and periodic update counter, but flush does for streaming tracks.
Andy Hung9b461582014-12-01 17:56:29 -0800865
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800866 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800867 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800868 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
869 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800870 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100871
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800872 sp<AudioTrackThread> t = mAudioTrackThread;
873 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800874 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100875 t->pause();
Jean-Michel Trivia60e9a22018-11-15 16:13:36 -0800876 } else if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
Jean-Michel Trivi0248a2a2018-11-21 10:05:57 -0800877 // causes wake up of the playback thread, that will callback the client for
878 // EVENT_STREAM_END in processAudioBuffer()
879 t->wake();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100880 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800881 } else {
882 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
883 set_sched_policy(0, mPreviousSchedulingGroup);
884 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800885}
886
887bool AudioTrack::stopped() const
888{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800889 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800890 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800891}
892
893void AudioTrack::flush()
894{
Andy Hungb68f5eb2019-12-03 16:49:17 -0800895 const int64_t beginNs = systemTime();
Andy Hungfb8ede22018-09-12 19:03:24 -0700896 AutoMutex lock(mLock);
Andy Hung06a730b2020-04-09 13:28:31 -0700897 mediametrics::Defer defer([&]() {
Andy Hungb68f5eb2019-12-03 16:49:17 -0800898 mediametrics::LogItem(mMetricsId)
899 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_FLUSH)
Andy Hungea840382020-05-05 21:50:17 -0700900 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
Andy Hungb68f5eb2019-12-03 16:49:17 -0800901 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
902 .record(); });
903
Eric Laurent973db022018-11-20 14:54:31 -0800904 ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
Andy Hungfb8ede22018-09-12 19:03:24 -0700905
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800906 if (mSharedBuffer != 0) {
907 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800908 }
Andy Hung4c5ed302018-05-09 11:16:21 -0700909 if (mState == STATE_ACTIVE) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800910 return;
911 }
912 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800913}
914
Eric Laurent1703cdf2011-03-07 14:52:59 -0800915void AudioTrack::flush_l()
916{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800917 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700918
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700919 // clear playback marker and periodic update counter
920 mMarkerPosition = 0;
921 mMarkerReached = false;
922 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100923 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700924
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800925 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700926 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800927 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100928 mProxy->interrupt();
929 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800930 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800931 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800932}
933
934void AudioTrack::pause()
935{
Andy Hungb68f5eb2019-12-03 16:49:17 -0800936 const int64_t beginNs = systemTime();
Eric Laurentf5aafb22010-11-18 08:40:16 -0800937 AutoMutex lock(mLock);
Andy Hunga6b27032020-04-27 10:34:24 -0700938 mediametrics::Defer defer([&]() {
Andy Hungb68f5eb2019-12-03 16:49:17 -0800939 mediametrics::LogItem(mMetricsId)
940 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_PAUSE)
Andy Hungea840382020-05-05 21:50:17 -0700941 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
Andy Hungb68f5eb2019-12-03 16:49:17 -0800942 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
943 .record(); });
944
Eric Laurent973db022018-11-20 14:54:31 -0800945 ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
Andy Hungfb8ede22018-09-12 19:03:24 -0700946
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100947 if (mState == STATE_ACTIVE) {
948 mState = STATE_PAUSED;
949 } else if (mState == STATE_STOPPING) {
950 mState = STATE_PAUSED_STOPPING;
951 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800952 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800953 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800954 mProxy->interrupt();
955 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800956
Marco Nelissen3a90f282014-03-10 11:21:43 -0700957 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700958 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700959 // An offload output can be re-used between two audio tracks having
960 // the same configuration. A timestamp query for a paused track
961 // while the other is running would return an incorrect time.
962 // To fix this, cache the playback position on a pause() and return
963 // this time when requested until the track is resumed.
964
965 // OffloadThread sends HAL pause in its threadLoop. Time saved
966 // here can be slightly off.
967
968 // TODO: check return code for getRenderPosition.
969
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800970 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800971 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
Andy Hungfb8ede22018-09-12 19:03:24 -0700972 ALOGV("%s(%d): for offload, cache current position %u",
Eric Laurent973db022018-11-20 14:54:31 -0800973 __func__, mPortId, mPausedPosition);
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800974 }
975 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800976}
977
Eric Laurentbe916aa2010-06-01 23:49:17 -0700978status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800979{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700980 // This duplicates a test by AudioTrack JNI, but that is not the only caller
981 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
982 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700983 return BAD_VALUE;
984 }
985
Andy Hungb68f5eb2019-12-03 16:49:17 -0800986 mediametrics::LogItem(mMetricsId)
987 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETVOLUME)
988 .set(AMEDIAMETRICS_PROP_VOLUME_LEFT, (double)left)
989 .set(AMEDIAMETRICS_PROP_VOLUME_RIGHT, (double)right)
990 .record();
991
Eric Laurent1703cdf2011-03-07 14:52:59 -0800992 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800993 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
994 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800995
Glenn Kastenc56f3422014-03-21 17:53:17 -0700996 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700997
Glenn Kasten23a75452014-01-13 10:37:17 -0800998 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700999 mAudioTrack->signal();
1000 }
Eric Laurentbe916aa2010-06-01 23:49:17 -07001001 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001002}
1003
Glenn Kastenb1c09932012-02-27 16:21:04 -08001004status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001005{
Glenn Kastenb1c09932012-02-27 16:21:04 -08001006 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -07001007}
1008
Eric Laurent2beeb502010-07-16 07:43:46 -07001009status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -07001010{
Glenn Kastenc56f3422014-03-21 17:53:17 -07001011 // This duplicates a test by AudioTrack JNI, but that is not the only caller
1012 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -07001013 return BAD_VALUE;
1014 }
1015
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001016 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -07001017 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001018 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -07001019
1020 return NO_ERROR;
1021}
1022
Glenn Kastena5224f32012-01-04 12:41:44 -08001023void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -07001024{
1025 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001026 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -07001027 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001028}
1029
Glenn Kasten3b16c762012-11-14 08:44:39 -08001030status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001031{
Andy Hung5cbb5782015-03-27 18:39:59 -07001032 AutoMutex lock(mLock);
Eric Laurent973db022018-11-20 14:54:31 -08001033 ALOGV("%s(%d): prior state:%s rate:%u", __func__, mPortId, stateToString(mState), rate);
Andy Hungfb8ede22018-09-12 19:03:24 -07001034
Andy Hung5cbb5782015-03-27 18:39:59 -07001035 if (rate == mSampleRate) {
1036 return NO_ERROR;
1037 }
jiabinf4de6112018-12-19 12:40:08 -08001038 if (isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)
1039 || (mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001040 return INVALID_OPERATION;
1041 }
Eric Laurent0d6db582014-11-12 18:39:44 -08001042 if (mOutput == AUDIO_IO_HANDLE_NONE) {
1043 return NO_INIT;
1044 }
Andy Hung5cbb5782015-03-27 18:39:59 -07001045 // NOTE: it is theoretically possible, but highly unlikely, that a device change
1046 // could mean a previously allowed sampling rate is no longer allowed.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001047 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -08001048 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -07001049 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001050 }
Andy Hung26145642015-04-15 21:56:53 -07001051 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001052 const uint32_t effectiveSampleRate = adjustSampleRate(rate, mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001053 if (rate == 0 || effectiveSampleRate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001054 return BAD_VALUE;
1055 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001056 // TODO: Should we also check if the buffer size is compatible?
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001057
Glenn Kastene3aa6592012-12-04 12:22:46 -08001058 mSampleRate = rate;
Andy Hung26145642015-04-15 21:56:53 -07001059 mProxy->setSampleRate(effectiveSampleRate);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001060
Eric Laurent57326622009-07-07 07:10:45 -07001061 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001062}
1063
Glenn Kastena5224f32012-01-04 12:41:44 -08001064uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001065{
Eric Laurent1703cdf2011-03-07 14:52:59 -08001066 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07001067
1068 // sample rate can be updated during playback by the offloaded decoder so we need to
1069 // query the HAL and update if needed.
1070// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -07001071 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -07001072 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -07001073 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001074 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -07001075 if (status == NO_ERROR) {
1076 mSampleRate = sampleRate;
1077 }
1078 }
1079 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001080 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001081}
1082
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001083uint32_t AudioTrack::getOriginalSampleRate() const
1084{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001085 return mOriginalSampleRate;
1086}
1087
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001088status_t AudioTrack::setPlaybackRate(const AudioPlaybackRate &playbackRate)
Andy Hung8edb8dc2015-03-26 19:13:55 -07001089{
Andy Hung8edb8dc2015-03-26 19:13:55 -07001090 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001091 if (isAudioPlaybackRateEqual(playbackRate, mPlaybackRate)) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001092 return NO_ERROR;
1093 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001094 if (isOffloadedOrDirect_l()) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001095 return INVALID_OPERATION;
1096 }
1097 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1098 return INVALID_OPERATION;
1099 }
Andy Hungff874dc2016-04-11 16:49:09 -07001100
Andy Hungfb8ede22018-09-12 19:03:24 -07001101 ALOGV("%s(%d): mSampleRate:%u mSpeed:%f mPitch:%f",
Eric Laurent973db022018-11-20 14:54:31 -08001102 __func__, mPortId, mSampleRate, playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001103 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001104 const uint32_t effectiveRate = adjustSampleRate(mSampleRate, playbackRate.mPitch);
1105 const float effectiveSpeed = adjustSpeed(playbackRate.mSpeed, playbackRate.mPitch);
1106 const float effectivePitch = adjustPitch(playbackRate.mPitch);
Ricardo Garcia6c7f0622015-04-30 18:39:16 -07001107 AudioPlaybackRate playbackRateTemp = playbackRate;
1108 playbackRateTemp.mSpeed = effectiveSpeed;
1109 playbackRateTemp.mPitch = effectivePitch;
1110
Andy Hungfb8ede22018-09-12 19:03:24 -07001111 ALOGV("%s(%d) (effective) mSampleRate:%u mSpeed:%f mPitch:%f",
Eric Laurent973db022018-11-20 14:54:31 -08001112 __func__, mPortId, effectiveRate, effectiveSpeed, effectivePitch);
Andy Hungff874dc2016-04-11 16:49:09 -07001113
Ricardo Garcia6c7f0622015-04-30 18:39:16 -07001114 if (!isAudioPlaybackRateValid(playbackRateTemp)) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001115 ALOGW("%s(%d) (%f, %f) failed (effective rate out of bounds)",
Eric Laurent973db022018-11-20 14:54:31 -08001116 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001117 return BAD_VALUE;
1118 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001119 // Check if the buffer size is compatible.
Andy Hung26145642015-04-15 21:56:53 -07001120 if (!isSampleRateSpeedAllowed_l(effectiveRate, effectiveSpeed)) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001121 ALOGW("%s(%d) (%f, %f) failed (buffer size)",
Eric Laurent973db022018-11-20 14:54:31 -08001122 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung8edb8dc2015-03-26 19:13:55 -07001123 return BAD_VALUE;
1124 }
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001125
Ricardo Garcia6c7f0622015-04-30 18:39:16 -07001126 // Check resampler ratios are within bounds
Glenn Kastend3bb6452016-12-05 18:14:37 -08001127 if ((uint64_t)effectiveRate > (uint64_t)mSampleRate *
1128 (uint64_t)AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001129 ALOGW("%s(%d) (%f, %f) failed. Resample rate exceeds max accepted value",
Eric Laurent973db022018-11-20 14:54:31 -08001130 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
Ricardo Garcia6c7f0622015-04-30 18:39:16 -07001131 return BAD_VALUE;
1132 }
1133
Dan Austine34eae22015-10-27 16:14:52 -07001134 if ((uint64_t)effectiveRate * (uint64_t)AUDIO_RESAMPLER_UP_RATIO_MAX < (uint64_t)mSampleRate) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001135 ALOGW("%s(%d) (%f, %f) failed. Resample rate below min accepted value",
Eric Laurent973db022018-11-20 14:54:31 -08001136 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
Ricardo Garcia6c7f0622015-04-30 18:39:16 -07001137 return BAD_VALUE;
1138 }
1139 mPlaybackRate = playbackRate;
1140 //set effective rates
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001141 mProxy->setPlaybackRate(playbackRateTemp);
Andy Hung26145642015-04-15 21:56:53 -07001142 mProxy->setSampleRate(effectiveRate); // FIXME: not quite "atomic" with setPlaybackRate
Andy Hungb68f5eb2019-12-03 16:49:17 -08001143
1144 mediametrics::LogItem(mMetricsId)
1145 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETPLAYBACKPARAM)
1146 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
1147 .set(AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)mPlaybackRate.mSpeed)
1148 .set(AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)mPlaybackRate.mPitch)
1149 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1150 AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)effectiveRate)
1151 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1152 AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)playbackRateTemp.mSpeed)
1153 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1154 AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)playbackRateTemp.mPitch)
1155 .record();
1156
Andy Hung8edb8dc2015-03-26 19:13:55 -07001157 return NO_ERROR;
1158}
1159
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001160const AudioPlaybackRate& AudioTrack::getPlaybackRate() const
Andy Hung8edb8dc2015-03-26 19:13:55 -07001161{
1162 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001163 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001164}
1165
Phil Burkc0adecb2016-01-08 12:44:11 -08001166ssize_t AudioTrack::getBufferSizeInFrames()
1167{
1168 AutoMutex lock(mLock);
1169 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1170 return NO_INIT;
1171 }
Phil Burka9876702020-04-20 18:16:15 -07001172
Phil Burke8972b02016-03-04 11:29:57 -08001173 return (ssize_t) mProxy->getBufferSizeInFrames();
Phil Burkc0adecb2016-01-08 12:44:11 -08001174}
1175
Andy Hungf2c87b32016-04-07 19:49:29 -07001176status_t AudioTrack::getBufferDurationInUs(int64_t *duration)
1177{
1178 if (duration == nullptr) {
1179 return BAD_VALUE;
1180 }
1181 AutoMutex lock(mLock);
1182 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1183 return NO_INIT;
1184 }
1185 ssize_t bufferSizeInFrames = (ssize_t) mProxy->getBufferSizeInFrames();
1186 if (bufferSizeInFrames < 0) {
1187 return (status_t)bufferSizeInFrames;
1188 }
1189 *duration = (int64_t)((double)bufferSizeInFrames * 1000000
1190 / ((double)mSampleRate * mPlaybackRate.mSpeed));
1191 return NO_ERROR;
1192}
1193
Phil Burkc0adecb2016-01-08 12:44:11 -08001194ssize_t AudioTrack::setBufferSizeInFrames(size_t bufferSizeInFrames)
1195{
1196 AutoMutex lock(mLock);
1197 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1198 return NO_INIT;
1199 }
1200 // Reject if timed track or compressed audio.
Glenn Kastend79072e2016-01-06 08:41:20 -08001201 if (!audio_is_linear_pcm(mFormat)) {
Phil Burkc0adecb2016-01-08 12:44:11 -08001202 return INVALID_OPERATION;
1203 }
Phil Burka9876702020-04-20 18:16:15 -07001204
1205 ssize_t originalBufferSize = mProxy->getBufferSizeInFrames();
1206 ssize_t finalBufferSize = mProxy->setBufferSizeInFrames((uint32_t) bufferSizeInFrames);
1207 if (originalBufferSize != finalBufferSize) {
Phil Burk64e16a72020-06-01 13:25:51 -07001208 android::mediametrics::LogItem(mMetricsId)
1209 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETBUFFERSIZE)
1210 .set(AMEDIAMETRICS_PROP_BUFFERSIZEFRAMES, (int32_t)mProxy->getBufferSizeInFrames())
1211 .set(AMEDIAMETRICS_PROP_UNDERRUN, (int32_t)getUnderrunCount_l())
1212 .record();
Phil Burka9876702020-04-20 18:16:15 -07001213 }
1214 return finalBufferSize;
Phil Burkc0adecb2016-01-08 12:44:11 -08001215}
1216
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001217status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
1218{
Glenn Kastend79072e2016-01-06 08:41:20 -08001219 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -08001220 return INVALID_OPERATION;
1221 }
1222
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001223 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001224 ;
1225 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
1226 loopEnd - loopStart >= MIN_LOOP) {
1227 ;
1228 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001229 return BAD_VALUE;
1230 }
1231
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001232 AutoMutex lock(mLock);
1233 // See setPosition() regarding setting parameters such as loop points or position while active
1234 if (mState == STATE_ACTIVE) {
1235 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001236 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001237 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001238 return NO_ERROR;
1239}
1240
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001241void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
1242{
Andy Hung4ede21d2014-12-12 15:37:34 -08001243 // We do not update the periodic notification point.
1244 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
1245 mLoopCount = loopCount;
1246 mLoopEnd = loopEnd;
1247 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -08001248 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001249 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -08001250
1251 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001252}
1253
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001254status_t AudioTrack::setMarkerPosition(uint32_t marker)
1255{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001256 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -07001257 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001258 return INVALID_OPERATION;
1259 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001260
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001261 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001262 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -07001263 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001264
Andy Hung3c09c782014-12-29 18:39:32 -08001265 sp<AudioTrackThread> t = mAudioTrackThread;
1266 if (t != 0) {
1267 t->wake();
1268 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001269 return NO_ERROR;
1270}
1271
Glenn Kastena5224f32012-01-04 12:41:44 -08001272status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001273{
Eric Laurentab5cdba2014-06-09 17:22:27 -07001274 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001275 return INVALID_OPERATION;
1276 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001277 if (marker == NULL) {
1278 return BAD_VALUE;
1279 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001280
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001281 AutoMutex lock(mLock);
Andy Hung90e8a972015-11-09 16:42:40 -08001282 mMarkerPosition.getValue(marker);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001283
1284 return NO_ERROR;
1285}
1286
1287status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
1288{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001289 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -07001290 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001291 return INVALID_OPERATION;
1292 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001293
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001294 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001295 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001296 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -08001297
Andy Hung3c09c782014-12-29 18:39:32 -08001298 sp<AudioTrackThread> t = mAudioTrackThread;
1299 if (t != 0) {
1300 t->wake();
1301 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001302 return NO_ERROR;
1303}
1304
Glenn Kastena5224f32012-01-04 12:41:44 -08001305status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001306{
Eric Laurentab5cdba2014-06-09 17:22:27 -07001307 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001308 return INVALID_OPERATION;
1309 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001310 if (updatePeriod == NULL) {
1311 return BAD_VALUE;
1312 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001313
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001314 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001315 *updatePeriod = mUpdatePeriod;
1316
1317 return NO_ERROR;
1318}
1319
1320status_t AudioTrack::setPosition(uint32_t position)
1321{
Glenn Kastend79072e2016-01-06 08:41:20 -08001322 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001323 return INVALID_OPERATION;
1324 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001325 if (position > mFrameCount) {
1326 return BAD_VALUE;
1327 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001328
Eric Laurent1703cdf2011-03-07 14:52:59 -08001329 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001330 // Currently we require that the player is inactive before setting parameters such as position
1331 // or loop points. Otherwise, there could be a race condition: the application could read the
1332 // current position, compute a new position or loop parameters, and then set that position or
1333 // loop parameters but it would do the "wrong" thing since the position has continued to advance
1334 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
1335 // to specify how it wants to handle such scenarios.
1336 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001337 return INVALID_OPERATION;
1338 }
Andy Hung9b461582014-12-01 17:56:29 -08001339 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -07001340 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -08001341 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -08001342
1343 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001344 return NO_ERROR;
1345}
1346
Glenn Kasten200092b2014-08-15 15:13:30 -07001347status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001348{
Glenn Kastend65d73c2012-06-22 17:21:07 -07001349 if (position == NULL) {
1350 return BAD_VALUE;
1351 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001352
Eric Laurent1703cdf2011-03-07 14:52:59 -08001353 AutoMutex lock(mLock);
Andy Hung7a490e72016-03-23 15:58:10 -07001354 // FIXME: offloaded and direct tracks call into the HAL for render positions
1355 // for compressed/synced data; however, we use proxy position for pure linear pcm data
1356 // as we do not know the capability of the HAL for pcm position support and standby.
1357 // There may be some latency differences between the HAL position and the proxy position.
1358 if (isOffloadedOrDirect_l() && !isPurePcmData_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001359 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001360
Eric Laurentab5cdba2014-06-09 17:22:27 -07001361 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001362 ALOGV("%s(%d): called in paused state, return cached position %u",
Eric Laurent973db022018-11-20 14:54:31 -08001363 __func__, mPortId, mPausedPosition);
Haynes Mathew George7064fd22014-01-08 13:59:53 -08001364 *position = mPausedPosition;
1365 return NO_ERROR;
1366 }
1367
Glenn Kasten142f5192014-03-25 17:44:59 -07001368 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung1f1db832015-06-08 13:26:10 -07001369 uint32_t halFrames; // actually unused
1370 (void) AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
1371 // FIXME: on getRenderPosition() error, we return OK with frame position 0.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001372 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001373 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
1374 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001375 *position = dspFrames;
1376 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -08001377 if (mCblk->mFlags & CBLK_INVALID) {
Andy Hung1f1db832015-06-08 13:26:10 -07001378 (void) restoreTrack_l("getPosition");
1379 // FIXME: for compatibility with the Java API we ignore the restoreTrack_l()
1380 // error here (e.g. DEAD_OBJECT) and return OK with the last recorded server position.
Eric Laurent275e8e92014-11-30 15:14:47 -08001381 }
1382
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001383 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -07001384 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
Andy Hung90e8a972015-11-09 16:42:40 -08001385 0 : updateAndGetPosition_l().value();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001386 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001387 return NO_ERROR;
1388}
1389
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001390status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001391{
Glenn Kastend79072e2016-01-06 08:41:20 -08001392 if (mSharedBuffer == 0) {
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001393 return INVALID_OPERATION;
1394 }
1395 if (position == NULL) {
1396 return BAD_VALUE;
1397 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001398
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001399 AutoMutex lock(mLock);
1400 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001401 return NO_ERROR;
1402}
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001403
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001404status_t AudioTrack::reload()
1405{
Glenn Kastend79072e2016-01-06 08:41:20 -08001406 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -08001407 return INVALID_OPERATION;
1408 }
1409
Eric Laurent1703cdf2011-03-07 14:52:59 -08001410 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001411 // See setPosition() regarding setting parameters such as loop points or position while active
1412 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001413 return INVALID_OPERATION;
1414 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001415 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -08001416 (void) updateAndGetPosition_l();
1417 mPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -07001418 mPreviousTimestampValid = false;
Andy Hung53c3b5f2014-12-15 16:42:05 -08001419#if 0
Andy Hung9b461582014-12-01 17:56:29 -08001420 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -08001421 // of loop count. Historically we have not restored loop count, start, end,
1422 // but it makes sense if one desires to repeat playing a particular sound.
1423 if (mLoopCount != 0) {
1424 mLoopCountNotified = mLoopCount;
1425 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
1426 }
1427#endif
Andy Hung9b461582014-12-01 17:56:29 -08001428 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001429 return NO_ERROR;
1430}
1431
Glenn Kasten38e905b2014-01-13 10:21:48 -08001432audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -07001433{
Eric Laurent1703cdf2011-03-07 14:52:59 -08001434 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001435 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001436}
1437
Paul McLeanaa981192015-03-21 09:55:15 -07001438status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
1439 AutoMutex lock(mLock);
1440 if (mSelectedDeviceId != deviceId) {
1441 mSelectedDeviceId = deviceId;
Eric Laurentfb00fc72017-05-25 18:17:12 -07001442 if (mStatus == NO_ERROR) {
1443 android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
jiabin156c6872017-10-06 09:47:15 -07001444 mProxy->interrupt();
Eric Laurentfb00fc72017-05-25 18:17:12 -07001445 }
Paul McLeanaa981192015-03-21 09:55:15 -07001446 }
Eric Laurent493404d2015-04-21 15:07:36 -07001447 return NO_ERROR;
Paul McLeanaa981192015-03-21 09:55:15 -07001448}
1449
1450audio_port_handle_t AudioTrack::getOutputDevice() {
1451 AutoMutex lock(mLock);
1452 return mSelectedDeviceId;
1453}
1454
Eric Laurentad2e7b92017-09-14 20:06:42 -07001455// must be called with mLock held
1456void AudioTrack::updateRoutedDeviceId_l()
1457{
1458 // if the track is inactive, do not update actual device as the output stream maybe routed
1459 // to a device not relevant to this client because of other active use cases.
1460 if (mState != STATE_ACTIVE) {
1461 return;
1462 }
1463 if (mOutput != AUDIO_IO_HANDLE_NONE) {
1464 audio_port_handle_t deviceId = AudioSystem::getDeviceIdForIo(mOutput);
1465 if (deviceId != AUDIO_PORT_HANDLE_NONE) {
1466 mRoutedDeviceId = deviceId;
1467 }
1468 }
1469}
1470
Eric Laurent296fb132015-05-01 11:38:42 -07001471audio_port_handle_t AudioTrack::getRoutedDeviceId() {
1472 AutoMutex lock(mLock);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001473 updateRoutedDeviceId_l();
1474 return mRoutedDeviceId;
Eric Laurent296fb132015-05-01 11:38:42 -07001475}
1476
Eric Laurentbe916aa2010-06-01 23:49:17 -07001477status_t AudioTrack::attachAuxEffect(int effectId)
1478{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001479 AutoMutex lock(mLock);
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08001480 status_t status;
1481 mAudioTrack->attachAuxEffect(effectId, &status);
Eric Laurent2beeb502010-07-16 07:43:46 -07001482 if (status == NO_ERROR) {
1483 mAuxEffectId = effectId;
1484 }
1485 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -07001486}
1487
Eric Laurente83b55d2014-11-14 10:06:21 -08001488audio_stream_type_t AudioTrack::streamType() const
1489{
1490 if (mStreamType == AUDIO_STREAM_DEFAULT) {
François Gaffie58d4be52018-11-06 15:30:12 +01001491 return AudioSystem::attributesToStreamType(mAttributes);
Eric Laurente83b55d2014-11-14 10:06:21 -08001492 }
1493 return mStreamType;
1494}
1495
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001496uint32_t AudioTrack::latency()
1497{
1498 AutoMutex lock(mLock);
1499 updateLatency_l();
1500 return mLatency;
1501}
1502
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001503// -------------------------------------------------------------------------
1504
Eric Laurent1703cdf2011-03-07 14:52:59 -08001505// must be called with mLock held
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001506void AudioTrack::updateLatency_l()
1507{
1508 status_t status = AudioSystem::getLatency(mOutput, &mAfLatency);
1509 if (status != NO_ERROR) {
Eric Laurent973db022018-11-20 14:54:31 -08001510 ALOGW("%s(%d): getLatency(%d) failed status %d", __func__, mPortId, mOutput, status);
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001511 } else {
1512 // FIXME don't believe this lie
Andy Hung13969262017-09-11 17:24:21 -07001513 mLatency = mAfLatency + (1000LL * mFrameCount) / mSampleRate;
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001514 }
1515}
1516
Phil Burkadbb75a2017-06-16 12:19:42 -07001517// TODO Move this macro to a common header file for enum to string conversion in audio framework.
1518#define MEDIA_CASE_ENUM(name) case name: return #name
1519const char * AudioTrack::convertTransferToText(transfer_type transferType) {
1520 switch (transferType) {
1521 MEDIA_CASE_ENUM(TRANSFER_DEFAULT);
1522 MEDIA_CASE_ENUM(TRANSFER_CALLBACK);
1523 MEDIA_CASE_ENUM(TRANSFER_OBTAIN);
1524 MEDIA_CASE_ENUM(TRANSFER_SYNC);
1525 MEDIA_CASE_ENUM(TRANSFER_SHARED);
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07001526 MEDIA_CASE_ENUM(TRANSFER_SYNC_NOTIF_CALLBACK);
Phil Burkadbb75a2017-06-16 12:19:42 -07001527 default:
1528 return "UNRECOGNIZED";
1529 }
1530}
1531
Glenn Kasten200092b2014-08-15 15:13:30 -07001532status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001533{
Eric Laurentf32d7812017-11-30 14:44:07 -08001534 status_t status;
1535 bool callbackAdded = false;
1536
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001537 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
1538 if (audioFlinger == 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001539 ALOGE("%s(%d): Could not get audioflinger",
Eric Laurent973db022018-11-20 14:54:31 -08001540 __func__, mPortId);
Eric Laurentf32d7812017-11-30 14:44:07 -08001541 status = NO_INIT;
1542 goto exit;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001543 }
1544
Eric Laurent21da6472017-11-09 16:29:26 -08001545 {
Haynes Mathew Georgeae34ed22016-01-28 11:58:39 -08001546 // mFlags (not mOrigFlags) is modified depending on whether fast request is accepted.
1547 // After fast request is denied, we will request again if IAudioTrack is re-created.
Glenn Kastend79072e2016-01-06 08:41:20 -08001548 // Client can only express a preference for FAST. Server will perform additional tests.
Phil Burk33ff89b2015-11-30 11:16:01 -08001549 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Phil Burkadbb75a2017-06-16 12:19:42 -07001550 // either of these use cases:
1551 // use case 1: shared buffer
1552 bool sharedBuffer = mSharedBuffer != 0;
1553 bool transferAllowed =
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001554 // use case 2: callback transfer mode
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001555 (mTransfer == TRANSFER_CALLBACK) ||
1556 // use case 3: obtain/release mode
Phil Burk33ff89b2015-11-30 11:16:01 -08001557 (mTransfer == TRANSFER_OBTAIN) ||
1558 // use case 4: synchronous write
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07001559 ((mTransfer == TRANSFER_SYNC || mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK)
1560 && mThreadCanCallJava);
Phil Burkadbb75a2017-06-16 12:19:42 -07001561
Eric Laurent21da6472017-11-09 16:29:26 -08001562 bool fastAllowed = sharedBuffer || transferAllowed;
1563 if (!fastAllowed) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001564 ALOGW("%s(%d): AUDIO_OUTPUT_FLAG_FAST denied by client,"
1565 " not shared buffer and transfer = %s",
Eric Laurent973db022018-11-20 14:54:31 -08001566 __func__, mPortId,
Phil Burkadbb75a2017-06-16 12:19:42 -07001567 convertTransferToText(mTransfer));
Phil Burk33ff89b2015-11-30 11:16:01 -08001568 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1569 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001570 }
1571
Eric Laurent21da6472017-11-09 16:29:26 -08001572 IAudioFlinger::CreateTrackInput input;
1573 if (mStreamType != AUDIO_STREAM_DEFAULT) {
François Gaffie58d4be52018-11-06 15:30:12 +01001574 input.attr = AudioSystem::streamTypeToAttributes(mStreamType);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001575 } else {
Eric Laurent21da6472017-11-09 16:29:26 -08001576 input.attr = mAttributes;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001577 }
Eric Laurent21da6472017-11-09 16:29:26 -08001578 input.config = AUDIO_CONFIG_INITIALIZER;
1579 input.config.sample_rate = mSampleRate;
1580 input.config.channel_mask = mChannelMask;
1581 input.config.format = mFormat;
1582 input.config.offload_info = mOffloadInfoCopy;
1583 input.clientInfo.clientUid = mClientUid;
1584 input.clientInfo.clientPid = mClientPid;
1585 input.clientInfo.clientTid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001586 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten47d55172017-05-23 11:19:30 -07001587 // It is currently meaningless to request SCHED_FIFO for a Java thread. Even if the
1588 // application-level code follows all non-blocking design rules, the language runtime
1589 // doesn't also follow those rules, so the thread will not benefit overall.
Phil Burk33ff89b2015-11-30 11:16:01 -08001590 if (mAudioTrackThread != 0 && !mThreadCanCallJava) {
Eric Laurent21da6472017-11-09 16:29:26 -08001591 input.clientInfo.clientTid = mAudioTrackThread->getTid();
Glenn Kasten3acbd052012-02-28 10:39:56 -08001592 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001593 }
Eric Laurent21da6472017-11-09 16:29:26 -08001594 input.sharedBuffer = mSharedBuffer;
1595 input.notificationsPerBuffer = mNotificationsPerBufferReq;
1596 input.speed = 1.0;
1597 if (audio_has_proportional_frames(mFormat) && mSharedBuffer == 0 &&
1598 (mFlags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1599 input.speed = !isPurePcmData_l() || isOffloadedOrDirect_l() ? 1.0f :
1600 max(mMaxRequiredSpeed, mPlaybackRate.mSpeed);
1601 }
1602 input.flags = mFlags;
1603 input.frameCount = mReqFrameCount;
1604 input.notificationFrameCount = mNotificationFramesReq;
1605 input.selectedDeviceId = mSelectedDeviceId;
1606 input.sessionId = mSessionId;
jiabinf6eb4c32020-02-25 14:06:25 -08001607 input.audioTrackCallback = mAudioTrackCallback;
Colin Crossb8a9dbb2020-08-27 04:12:26 +00001608 input.opPackageName = mOpPackageName;
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001609
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08001610 media::CreateTrackResponse response;
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001611 status = audioFlinger->createTrack(VALUE_OR_FATAL(input.toAidl()), response);
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08001612 IAudioFlinger::CreateTrackOutput output = VALUE_OR_FATAL(
1613 IAudioFlinger::CreateTrackOutput::fromAidl(
1614 response));
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001615
Eric Laurent21da6472017-11-09 16:29:26 -08001616 if (status != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001617 ALOGE("%s(%d): AudioFlinger could not create track, status: %d output %d",
Eric Laurent973db022018-11-20 14:54:31 -08001618 __func__, mPortId, status, output.outputId);
Eric Laurentf32d7812017-11-30 14:44:07 -08001619 if (status == NO_ERROR) {
1620 status = NO_INIT;
1621 }
1622 goto exit;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001623 }
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001624 ALOG_ASSERT(output.audioTrack != 0);
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001625
Eric Laurent21da6472017-11-09 16:29:26 -08001626 mFrameCount = output.frameCount;
1627 mNotificationFramesAct = (uint32_t)output.notificationFrameCount;
1628 mRoutedDeviceId = output.selectedDeviceId;
1629 mSessionId = output.sessionId;
1630
1631 mSampleRate = output.sampleRate;
1632 if (mOriginalSampleRate == 0) {
1633 mOriginalSampleRate = mSampleRate;
1634 }
1635
1636 mAfFrameCount = output.afFrameCount;
1637 mAfSampleRate = output.afSampleRate;
1638 mAfLatency = output.afLatencyMs;
1639
1640 mLatency = mAfLatency + (1000LL * mFrameCount) / mSampleRate;
1641
Glenn Kasten38e905b2014-01-13 10:21:48 -08001642 // AudioFlinger now owns the reference to the I/O handle,
1643 // so we are no longer responsible for releasing it.
1644
Glenn Kasten7fd04222016-02-02 12:38:16 -08001645 // FIXME compare to AudioRecord
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08001646 std::optional<media::SharedFileRegion> sfr;
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001647 output.audioTrack->getCblk(&sfr);
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08001648 sp<IMemory> iMem = VALUE_OR_FATAL(aidl2legacy_NullableSharedFileRegion_IMemory(sfr));
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001649 if (iMem == 0) {
Eric Laurent973db022018-11-20 14:54:31 -08001650 ALOGE("%s(%d): Could not get control block", __func__, mPortId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001651 status = NO_INIT;
Eric Laurentf32d7812017-11-30 14:44:07 -08001652 goto exit;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001653 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07001654 // TODO: Using unsecurePointer() has some associated security pitfalls
1655 // (see declaration for details).
1656 // Either document why it is safe in this case or address the
1657 // issue (e.g. by copying).
1658 void *iMemPointer = iMem->unsecurePointer();
Glenn Kasten0cde0762014-01-16 15:06:36 -08001659 if (iMemPointer == NULL) {
Eric Laurent973db022018-11-20 14:54:31 -08001660 ALOGE("%s(%d): Could not get control block pointer", __func__, mPortId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001661 status = NO_INIT;
Eric Laurentf32d7812017-11-30 14:44:07 -08001662 goto exit;
Glenn Kasten0cde0762014-01-16 15:06:36 -08001663 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001664 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001665 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001666 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001667 mDeathNotifier.clear();
1668 }
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001669 mAudioTrack = output.audioTrack;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001670 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001671 IPCThreadState::self()->flushCommands();
1672
Glenn Kasten0cde0762014-01-16 15:06:36 -08001673 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001674 mCblk = cblk;
Glenn Kasten5f631512014-02-24 15:16:07 -08001675
Glenn Kastena07f17c2013-04-23 12:39:37 -07001676 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001677 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent21da6472017-11-09 16:29:26 -08001678 if (output.flags & AUDIO_OUTPUT_FLAG_FAST) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001679 ALOGI("%s(%d): AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu -> %zu",
Eric Laurent973db022018-11-20 14:54:31 -08001680 __func__, mPortId, mReqFrameCount, mFrameCount);
Phil Burk33ff89b2015-11-30 11:16:01 -08001681 if (!mThreadCanCallJava) {
1682 mAwaitBoost = true;
1683 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001684 } else {
Phil Burkcc6ed2d2020-05-18 13:06:54 -07001685 ALOGD("%s(%d): AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu -> %zu",
Eric Laurent973db022018-11-20 14:54:31 -08001686 __func__, mPortId, mReqFrameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001687 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001688 }
Eric Laurent21da6472017-11-09 16:29:26 -08001689 mFlags = output.flags;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001690
Eric Laurentad2e7b92017-09-14 20:06:42 -07001691 //mOutput != output includes the case where mOutput == AUDIO_IO_HANDLE_NONE for first creation
Eric Laurent09f1ed22019-04-24 17:45:17 -07001692 if (mDeviceCallback != 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001693 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent09f1ed22019-04-24 17:45:17 -07001694 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001695 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07001696 AudioSystem::addAudioDeviceCallback(this, output.outputId, output.portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001697 callbackAdded = true;
1698 }
1699
Eric Laurent09f1ed22019-04-24 17:45:17 -07001700 mPortId = output.portId;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001701 // We retain a copy of the I/O handle, but don't own the reference
Eric Laurent21da6472017-11-09 16:29:26 -08001702 mOutput = output.outputId;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001703 mRefreshRemaining = true;
1704
1705 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1706 // is the value of pointer() for the shared buffer, otherwise buffers points
1707 // immediately after the control block. This address is for the mapping within client
1708 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1709 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001710 if (mSharedBuffer == 0) {
Glenn Kasten138d6f92015-03-20 10:54:51 -07001711 buffers = cblk + 1;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001712 } else {
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07001713 // TODO: Using unsecurePointer() has some associated security pitfalls
1714 // (see declaration for details).
1715 // Either document why it is safe in this case or address the
1716 // issue (e.g. by copying).
1717 buffers = mSharedBuffer->unsecurePointer();
Glenn Kasten138d6f92015-03-20 10:54:51 -07001718 if (buffers == NULL) {
Eric Laurent973db022018-11-20 14:54:31 -08001719 ALOGE("%s(%d): Could not get buffer pointer", __func__, mPortId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001720 status = NO_INIT;
Eric Laurentf32d7812017-11-30 14:44:07 -08001721 goto exit;
Glenn Kasten138d6f92015-03-20 10:54:51 -07001722 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001723 }
1724
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08001725 mAudioTrack->attachAuxEffect(mAuxEffectId, &status);
Glenn Kasten5f631512014-02-24 15:16:07 -08001726
Glenn Kasten093000f2012-05-03 09:35:36 -07001727 // If IAudioTrack is re-created, don't let the requested frameCount
1728 // decrease. This can confuse clients that cache frameCount().
Eric Laurent21da6472017-11-09 16:29:26 -08001729 if (mFrameCount > mReqFrameCount) {
1730 mReqFrameCount = mFrameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001731 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001732
Andy Hungd7bd69e2015-07-24 07:52:41 -07001733 // reset server position to 0 as we have new cblk.
1734 mServer = 0;
1735
Glenn Kastene3aa6592012-12-04 12:22:46 -08001736 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001737 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001738 mStaticProxy.clear();
Eric Laurent21da6472017-11-09 16:29:26 -08001739 mProxy = new AudioTrackClientProxy(cblk, buffers, mFrameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001740 } else {
Eric Laurent21da6472017-11-09 16:29:26 -08001741 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, mFrameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001742 mProxy = mStaticProxy;
1743 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001744
1745 mProxy->setVolumeLR(gain_minifloat_pack(
1746 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1747 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1748
Glenn Kastene3aa6592012-12-04 12:22:46 -08001749 mProxy->setSendLevel(mSendLevel);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001750 const uint32_t effectiveSampleRate = adjustSampleRate(mSampleRate, mPlaybackRate.mPitch);
1751 const float effectiveSpeed = adjustSpeed(mPlaybackRate.mSpeed, mPlaybackRate.mPitch);
1752 const float effectivePitch = adjustPitch(mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001753 mProxy->setSampleRate(effectiveSampleRate);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001754
1755 AudioPlaybackRate playbackRateTemp = mPlaybackRate;
1756 playbackRateTemp.mSpeed = effectiveSpeed;
1757 playbackRateTemp.mPitch = effectivePitch;
1758 mProxy->setPlaybackRate(playbackRateTemp);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001759 mProxy->setMinimum(mNotificationFramesAct);
1760
1761 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001762 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001763
Andy Hungb68f5eb2019-12-03 16:49:17 -08001764 // This is the first log sent from the AudioTrack client.
1765 // The creation of the audio track by AudioFlinger (in the code above)
1766 // is the first log of the AudioTrack and must be present before
1767 // any AudioTrack client logs will be accepted.
Andy Hungea840382020-05-05 21:50:17 -07001768
Andy Hungb68f5eb2019-12-03 16:49:17 -08001769 mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_TRACK) + std::to_string(mPortId);
1770 mediametrics::LogItem(mMetricsId)
1771 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CREATE)
1772 // the following are immutable
Andy Hunga629bd12020-06-05 16:03:53 -07001773 .set(AMEDIAMETRICS_PROP_FLAGS, toString(mFlags).c_str())
1774 .set(AMEDIAMETRICS_PROP_ORIGINALFLAGS, toString(mOrigFlags).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08001775 .set(AMEDIAMETRICS_PROP_SESSIONID, (int32_t)mSessionId)
1776 .set(AMEDIAMETRICS_PROP_TRACKID, mPortId) // dup from key
Andy Hungb68f5eb2019-12-03 16:49:17 -08001777 .set(AMEDIAMETRICS_PROP_CONTENTTYPE, toString(mAttributes.content_type).c_str())
1778 .set(AMEDIAMETRICS_PROP_USAGE, toString(mAttributes.usage).c_str())
1779 .set(AMEDIAMETRICS_PROP_THREADID, (int32_t)output.outputId)
1780 .set(AMEDIAMETRICS_PROP_SELECTEDDEVICEID, (int32_t)mSelectedDeviceId)
1781 .set(AMEDIAMETRICS_PROP_ROUTEDDEVICEID, (int32_t)mRoutedDeviceId)
1782 .set(AMEDIAMETRICS_PROP_ENCODING, toString(mFormat).c_str())
1783 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
1784 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
1785 // the following are NOT immutable
1786 .set(AMEDIAMETRICS_PROP_VOLUME_LEFT, (double)mVolume[AUDIO_INTERLEAVE_LEFT])
1787 .set(AMEDIAMETRICS_PROP_VOLUME_RIGHT, (double)mVolume[AUDIO_INTERLEAVE_RIGHT])
1788 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
1789 .set(AMEDIAMETRICS_PROP_AUXEFFECTID, (int32_t)mAuxEffectId)
1790 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
1791 .set(AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)mPlaybackRate.mSpeed)
1792 .set(AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)mPlaybackRate.mPitch)
1793 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1794 AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)effectiveSampleRate)
1795 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1796 AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)effectiveSpeed)
1797 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1798 AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)effectivePitch)
1799 .record();
1800
1801 // mSendLevel
1802 // mReqFrameCount?
1803 // mNotificationFramesAct, mNotificationFramesReq, mNotificationsPerBufferReq
1804 // mLatency, mAfLatency, mAfFrameCount, mAfSampleRate
1805
Glenn Kasten38e905b2014-01-13 10:21:48 -08001806 }
1807
Eric Laurentf32d7812017-11-30 14:44:07 -08001808exit:
1809 if (status != NO_ERROR && callbackAdded) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001810 // note: mOutput is always valid is callbackAdded is true
Eric Laurent09f1ed22019-04-24 17:45:17 -07001811 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001812 }
Eric Laurentf32d7812017-11-30 14:44:07 -08001813
1814 mStatus = status;
Eric Laurent21da6472017-11-09 16:29:26 -08001815
1816 // sp<IAudioTrack> track destructor will cause releaseOutput() to be called by AudioFlinger
Glenn Kasten38e905b2014-01-13 10:21:48 -08001817 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001818}
1819
Glenn Kastenb46f3942015-03-09 12:00:30 -07001820status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001821{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001822 if (audioBuffer == NULL) {
Glenn Kasten551b5352015-03-20 11:30:28 -07001823 if (nonContig != NULL) {
1824 *nonContig = 0;
1825 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001826 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001827 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001828 if (mTransfer != TRANSFER_OBTAIN) {
1829 audioBuffer->frameCount = 0;
1830 audioBuffer->size = 0;
1831 audioBuffer->raw = NULL;
Glenn Kasten551b5352015-03-20 11:30:28 -07001832 if (nonContig != NULL) {
1833 *nonContig = 0;
1834 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001835 return INVALID_OPERATION;
1836 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001837
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001838 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001839 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001840 if (waitCount == -1) {
1841 requested = &ClientProxy::kForever;
1842 } else if (waitCount == 0) {
1843 requested = &ClientProxy::kNonBlocking;
1844 } else if (waitCount > 0) {
Chih-Hung Hsiehbca74292018-08-10 16:06:07 -07001845 time_t ms = WAIT_PERIOD_MS * (time_t) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001846 timeout.tv_sec = ms / 1000;
Andy Hung06a730b2020-04-09 13:28:31 -07001847 timeout.tv_nsec = (ms % 1000) * 1000000;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001848 requested = &timeout;
1849 } else {
Eric Laurent973db022018-11-20 14:54:31 -08001850 ALOGE("%s(%d): invalid waitCount %d", __func__, mPortId, waitCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001851 requested = NULL;
1852 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001853 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001854}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001855
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001856status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1857 struct timespec *elapsed, size_t *nonContig)
1858{
1859 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1860 uint32_t oldSequence = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001861
1862 Proxy::Buffer buffer;
1863 status_t status = NO_ERROR;
1864
1865 static const int32_t kMaxTries = 5;
1866 int32_t tryCounter = kMaxTries;
1867
1868 do {
1869 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1870 // keep them from going away if another thread re-creates the track during obtainBuffer()
1871 sp<AudioTrackClientProxy> proxy;
1872 sp<IMemory> iMem;
1873
1874 { // start of lock scope
1875 AutoMutex lock(mLock);
1876
Glenn Kasten305996c2020-01-27 08:03:37 -08001877 uint32_t newSequence = mSequence;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001878 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1879 if (status == DEAD_OBJECT) {
1880 // re-create track, unless someone else has already done so
1881 if (newSequence == oldSequence) {
1882 status = restoreTrack_l("obtainBuffer");
1883 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001884 buffer.mFrameCount = 0;
1885 buffer.mRaw = NULL;
1886 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001887 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001888 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001889 }
1890 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001891 oldSequence = newSequence;
1892
Eric Laurent4d231dc2016-03-11 18:38:23 -08001893 if (status == NOT_ENOUGH_DATA) {
1894 restartIfDisabled();
1895 }
1896
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001897 // Keep the extra references
1898 proxy = mProxy;
1899 iMem = mCblkMemory;
1900
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001901 if (mState == STATE_STOPPING) {
1902 status = -EINTR;
1903 buffer.mFrameCount = 0;
1904 buffer.mRaw = NULL;
1905 buffer.mNonContig = 0;
1906 break;
1907 }
1908
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001909 // Non-blocking if track is stopped or paused
1910 if (mState != STATE_ACTIVE) {
1911 requested = &ClientProxy::kNonBlocking;
1912 }
1913
1914 } // end of lock scope
1915
1916 buffer.mFrameCount = audioBuffer->frameCount;
1917 // FIXME starts the requested timeout and elapsed over from scratch
1918 status = proxy->obtainBuffer(&buffer, requested, elapsed);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001919 } while (((status == DEAD_OBJECT) || (status == NOT_ENOUGH_DATA)) && (tryCounter-- > 0));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001920
1921 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001922 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001923 audioBuffer->raw = buffer.mRaw;
Glenn Kasten305996c2020-01-27 08:03:37 -08001924 audioBuffer->sequence = oldSequence;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001925 if (nonContig != NULL) {
1926 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001927 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001928 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001929}
1930
Glenn Kasten54a8a452015-03-09 12:03:00 -07001931void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001932{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001933 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001934 if (mTransfer == TRANSFER_SHARED) {
1935 return;
1936 }
1937
Andy Hungabdb9902015-01-12 15:08:22 -08001938 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001939 if (stepCount == 0) {
1940 return;
1941 }
1942
1943 Proxy::Buffer buffer;
1944 buffer.mFrameCount = stepCount;
1945 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001946
Eric Laurent1703cdf2011-03-07 14:52:59 -08001947 AutoMutex lock(mLock);
Glenn Kasten305996c2020-01-27 08:03:37 -08001948 if (audioBuffer->sequence != mSequence) {
1949 // This Buffer came from a different IAudioTrack instance, so ignore the releaseBuffer
1950 ALOGD("%s is no-op due to IAudioTrack sequence mismatch %u != %u",
1951 __func__, audioBuffer->sequence, mSequence);
1952 return;
1953 }
Glenn Kasten200092b2014-08-15 15:13:30 -07001954 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001955 mInUnderrun = false;
1956 mProxy->releaseBuffer(&buffer);
1957
1958 // restart track if it was disabled by audioflinger due to previous underrun
Eric Laurent4d231dc2016-03-11 18:38:23 -08001959 restartIfDisabled();
1960}
1961
1962void AudioTrack::restartIfDisabled()
1963{
1964 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1965 if ((mState == STATE_ACTIVE) && (flags & CBLK_DISABLED)) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001966 ALOGW("%s(%d): releaseBuffer() track %p disabled due to previous underrun, restarting",
Eric Laurent973db022018-11-20 14:54:31 -08001967 __func__, mPortId, this);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001968 // FIXME ignoring status
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08001969 status_t status;
1970 mAudioTrack->start(&status);
Eric Laurentdf839842012-05-31 14:27:14 -07001971 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001972}
1973
1974// -------------------------------------------------------------------------
1975
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001976ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001977{
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07001978 if (mTransfer != TRANSFER_SYNC && mTransfer != TRANSFER_SYNC_NOTIF_CALLBACK) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001979 return INVALID_OPERATION;
1980 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001981
Eric Laurentab5cdba2014-06-09 17:22:27 -07001982 if (isDirect()) {
1983 AutoMutex lock(mLock);
1984 int32_t flags = android_atomic_and(
1985 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1986 &mCblk->mFlags);
1987 if (flags & CBLK_INVALID) {
1988 return DEAD_OBJECT;
1989 }
1990 }
1991
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001992 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Jiabin Huang447cea72020-07-28 22:35:18 +00001993 // Validation: user is most-likely passing an error code, and it would
Glenn Kasten99e53b82012-01-19 08:59:58 -08001994 // make the return value ambiguous (actualSize vs error).
Andy Hungfb8ede22018-09-12 19:03:24 -07001995 ALOGE("%s(%d): AudioTrack::write(buffer=%p, size=%zu (%zd)",
Eric Laurent973db022018-11-20 14:54:31 -08001996 __func__, mPortId, buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001997 return BAD_VALUE;
1998 }
1999
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002000 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002001 Buffer audioBuffer;
2002
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002003 while (userSize >= mFrameSize) {
2004 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07002005
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08002006 status_t err = obtainBuffer(&audioBuffer,
2007 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002008 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002009 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002010 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07002011 }
Glenn Kasten0a2f1512016-07-22 08:06:37 -07002012 if (err == TIMED_OUT || err == -EINTR) {
2013 err = WOULD_BLOCK;
2014 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002015 return ssize_t(err);
2016 }
2017
Glenn Kastenae4b8792015-03-20 09:04:21 -07002018 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08002019 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002020 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002021 userSize -= toWrite;
2022 written += toWrite;
2023
2024 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002025 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002026
Andy Hungea2b9c02016-02-12 17:06:53 -08002027 if (written > 0) {
2028 mFramesWritten += written / mFrameSize;
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07002029
2030 if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
2031 const sp<AudioTrackThread> t = mAudioTrackThread;
2032 if (t != 0) {
2033 // causes wake up of the playback thread, that will callback the client for
2034 // more data (with EVENT_CAN_WRITE_MORE_DATA) in processAudioBuffer()
2035 t->wake();
2036 }
2037 }
Andy Hungea2b9c02016-02-12 17:06:53 -08002038 }
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07002039
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002040 return written;
2041}
2042
2043// -------------------------------------------------------------------------
2044
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002045nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002046{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07002047 // Currently the AudioTrack thread is not created if there are no callbacks.
2048 // Would it ever make sense to run the thread, even without callbacks?
2049 // If so, then replace this by checks at each use for mCbf != NULL.
2050 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
2051
Eric Laurent1703cdf2011-03-07 14:52:59 -08002052 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07002053 if (mAwaitBoost) {
2054 mAwaitBoost = false;
2055 mLock.unlock();
2056 static const int32_t kMaxTries = 5;
2057 int32_t tryCounter = kMaxTries;
2058 uint32_t pollUs = 10000;
2059 do {
Glenn Kasten8255ba72016-08-23 13:54:23 -07002060 int policy = sched_getscheduler(0) & ~SCHED_RESET_ON_FORK;
Glenn Kastena07f17c2013-04-23 12:39:37 -07002061 if (policy == SCHED_FIFO || policy == SCHED_RR) {
2062 break;
2063 }
2064 usleep(pollUs);
2065 pollUs <<= 1;
2066 } while (tryCounter-- > 0);
2067 if (tryCounter < 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -07002068 ALOGE("%s(%d): did not receive expected priority boost on time",
Eric Laurent973db022018-11-20 14:54:31 -08002069 __func__, mPortId);
Glenn Kastena07f17c2013-04-23 12:39:37 -07002070 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07002071 // Run again immediately
2072 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07002073 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002074
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002075 // Can only reference mCblk while locked
2076 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07002077 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08002078
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002079 // Check for track invalidation
2080 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002081 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
2082 // AudioSystem cache. We should not exit here but after calling the callback so
2083 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07002084 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Lajos Molnarf1063e22015-04-17 15:19:42 -07002085 status_t status __unused = restoreTrack_l("processAudioBuffer");
2086 // FIXME unused status
Andy Hung53c3b5f2014-12-15 16:42:05 -08002087 // after restoration, continue below to make sure that the loop and buffer events
2088 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002089 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002090 }
2091
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002092 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002093 bool active = mState == STATE_ACTIVE;
2094
2095 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
2096 bool newUnderrun = false;
2097 if (flags & CBLK_UNDERRUN) {
2098#if 0
2099 // Currently in shared buffer mode, when the server reaches the end of buffer,
2100 // the track stays active in continuous underrun state. It's up to the application
2101 // to pause or stop the track, or set the position to a new offset within buffer.
2102 // This was some experimental code to auto-pause on underrun. Keeping it here
2103 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
2104 if (mTransfer == TRANSFER_SHARED) {
2105 mState = STATE_PAUSED;
2106 active = false;
2107 }
2108#endif
2109 if (!mInUnderrun) {
2110 mInUnderrun = true;
2111 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002112 }
2113 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07002114
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002115 // Get current position of server
Andy Hung90e8a972015-11-09 16:42:40 -08002116 Modulo<uint32_t> position(updateAndGetPosition_l());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002117
2118 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002119 bool markerReached = false;
Andy Hung90e8a972015-11-09 16:42:40 -08002120 Modulo<uint32_t> markerPosition(mMarkerPosition);
2121 // uses 32 bit wraparound for comparison with position.
2122 if (!mMarkerReached && markerPosition.value() > 0 && position >= markerPosition) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002123 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002124 }
2125
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002126 // Determine number of new position callback(s) that will be needed, while locked
2127 size_t newPosCount = 0;
Andy Hung90e8a972015-11-09 16:42:40 -08002128 Modulo<uint32_t> newPosition(mNewPosition);
2129 uint32_t updatePeriod = mUpdatePeriod;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002130 // FIXME fails for wraparound, need 64 bits
2131 if (updatePeriod > 0 && position >= newPosition) {
Andy Hung90e8a972015-11-09 16:42:40 -08002132 newPosCount = ((position - newPosition).value() / updatePeriod) + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002133 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002134 }
2135
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002136 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002137 uint32_t sampleRate = mSampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002138 float speed = mPlaybackRate.mSpeed;
Andy Hunga7f03352015-05-31 21:54:49 -07002139 const uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002140 if (mRefreshRemaining) {
2141 mRefreshRemaining = false;
2142 mRemainingFrames = notificationFrames;
2143 mRetryOnPartialBuffer = false;
2144 }
2145 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002146 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07002147 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002148
Andy Hung53c3b5f2014-12-15 16:42:05 -08002149 // Determine the number of new loop callback(s) that will be needed, while locked.
2150 int loopCountNotifications = 0;
2151 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
2152
2153 if (mLoopCount > 0) {
2154 int loopCount;
2155 size_t bufferPosition;
2156 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
2157 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
2158 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
2159 mLoopCountNotified = loopCount; // discard any excess notifications
2160 } else if (mLoopCount < 0) {
2161 // FIXME: We're not accurate with notification count and position with infinite looping
2162 // since loopCount from server side will always return -1 (we could decrement it).
2163 size_t bufferPosition = mStaticProxy->getBufferPosition();
2164 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
2165 loopPeriod = mLoopEnd - bufferPosition;
2166 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
2167 size_t bufferPosition = mStaticProxy->getBufferPosition();
2168 loopPeriod = mFrameCount - bufferPosition;
2169 }
2170
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002171 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08002172 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002173 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
2174
2175 mLock.unlock();
2176
Andy Hunga7f03352015-05-31 21:54:49 -07002177 // get anchor time to account for callbacks.
2178 const nsecs_t timeBeforeCallbacks = systemTime();
2179
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002180 if (waitStreamEnd) {
Andy Hunga7f03352015-05-31 21:54:49 -07002181 // FIXME: Instead of blocking in proxy->waitStreamEndDone(), Callback thread
2182 // should wait on proxy futex and handle CBLK_STREAM_END_DONE within this function
2183 // (and make sure we don't callback for more data while we're stopping).
2184 // This helps with position, marker notifications, and track invalidation.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002185 struct timespec timeout;
2186 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
2187 timeout.tv_nsec = 0;
2188
Glenn Kasten96f04882013-09-20 09:28:56 -07002189 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002190 switch (status) {
2191 case NO_ERROR:
2192 case DEAD_OBJECT:
2193 case TIMED_OUT:
Andy Hung39609a02015-09-03 16:38:38 -07002194 if (status != DEAD_OBJECT) {
2195 // for DEAD_OBJECT, we do not send a EVENT_STREAM_END after stop();
2196 // instead, the application should handle the EVENT_NEW_IAUDIOTRACK.
2197 mCbf(EVENT_STREAM_END, mUserData, NULL);
2198 }
Glenn Kasten96f04882013-09-20 09:28:56 -07002199 {
2200 AutoMutex lock(mLock);
2201 // The previously assigned value of waitStreamEnd is no longer valid,
2202 // since the mutex has been unlocked and either the callback handler
2203 // or another thread could have re-started the AudioTrack during that time.
2204 waitStreamEnd = mState == STATE_STOPPING;
2205 if (waitStreamEnd) {
2206 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07002207 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002208 }
2209 }
Glenn Kasten96f04882013-09-20 09:28:56 -07002210 if (waitStreamEnd && status != DEAD_OBJECT) {
2211 return NS_INACTIVE;
2212 }
2213 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002214 }
Glenn Kasten96f04882013-09-20 09:28:56 -07002215 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002216 }
2217
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002218 // perform callbacks while unlocked
2219 if (newUnderrun) {
2220 mCbf(EVENT_UNDERRUN, mUserData, NULL);
2221 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08002222 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002223 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002224 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002225 }
2226 if (flags & CBLK_BUFFER_END) {
2227 mCbf(EVENT_BUFFER_END, mUserData, NULL);
2228 }
2229 if (markerReached) {
2230 mCbf(EVENT_MARKER, mUserData, &markerPosition);
2231 }
2232 while (newPosCount > 0) {
Andy Hung90e8a972015-11-09 16:42:40 -08002233 size_t temp = newPosition.value(); // FIXME size_t != uint32_t
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002234 mCbf(EVENT_NEW_POS, mUserData, &temp);
2235 newPosition += updatePeriod;
2236 newPosCount--;
2237 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002238
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002239 if (mObservedSequence != sequence) {
2240 mObservedSequence = sequence;
2241 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002242 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07002243 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002244 return NS_INACTIVE;
2245 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002246 }
2247
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002248 // if inactive, then don't run me again until re-started
2249 if (!active) {
2250 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07002251 }
2252
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002253 // Compute the estimated time until the next timed event (position, markers, loops)
2254 // FIXME only for non-compressed audio
2255 uint32_t minFrames = ~0;
2256 if (!markerReached && position < markerPosition) {
Andy Hung90e8a972015-11-09 16:42:40 -08002257 minFrames = (markerPosition - position).value();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002258 }
2259 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08002260 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002261 minFrames = loopPeriod;
2262 }
Andy Hung2d85f092015-01-07 12:45:13 -08002263 if (updatePeriod > 0) {
Andy Hung90e8a972015-11-09 16:42:40 -08002264 minFrames = min(minFrames, (newPosition - position).value());
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002265 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002266
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002267 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
2268 static const uint32_t kPoll = 0;
2269 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
2270 minFrames = kPoll * notificationFrames;
2271 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07002272
Andy Hunga7f03352015-05-31 21:54:49 -07002273 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
2274 static const nsecs_t kWaitPeriodNs = WAIT_PERIOD_MS * 1000000LL;
2275 const nsecs_t timeAfterCallbacks = systemTime();
2276
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002277 // Convert frame units to time units
2278 nsecs_t ns = NS_WHENEVER;
2279 if (minFrames != (uint32_t) ~0) {
jiabinc7bb8322017-09-06 18:20:11 -07002280 // AudioFlinger consumption of client data may be irregular when coming out of device
2281 // standby since the kernel buffers require filling. This is throttled to no more than 2x
2282 // the expected rate in the MixerThread. Hence, we reduce the estimated time to wait by one
2283 // half (but no more than half a second) to improve callback accuracy during these temporary
2284 // data surges.
2285 const nsecs_t estimatedNs = framesToNanoseconds(minFrames, sampleRate, speed);
2286 constexpr nsecs_t maxThrottleCompensationNs = 500000000LL;
2287 ns = estimatedNs - min(estimatedNs / 2, maxThrottleCompensationNs) + kWaitPeriodNs;
Andy Hunga7f03352015-05-31 21:54:49 -07002288 ns -= (timeAfterCallbacks - timeBeforeCallbacks); // account for callback time
2289 // TODO: Should we warn if the callback time is too long?
2290 if (ns < 0) ns = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002291 }
2292
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07002293 // If not supplying data by EVENT_MORE_DATA or EVENT_CAN_WRITE_MORE_DATA, then we're done
2294 if (mTransfer != TRANSFER_CALLBACK && mTransfer != TRANSFER_SYNC_NOTIF_CALLBACK) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002295 return ns;
2296 }
2297
Andy Hunga7f03352015-05-31 21:54:49 -07002298 // EVENT_MORE_DATA callback handling.
2299 // Timing for linear pcm audio data formats can be derived directly from the
2300 // buffer fill level.
2301 // Timing for compressed data is not directly available from the buffer fill level,
2302 // rather indirectly from waiting for blocking mode callbacks or waiting for obtain()
2303 // to return a certain fill level.
2304
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002305 struct timespec timeout;
2306 const struct timespec *requested = &ClientProxy::kForever;
2307 if (ns != NS_WHENEVER) {
2308 timeout.tv_sec = ns / 1000000000LL;
2309 timeout.tv_nsec = ns % 1000000000LL;
Andy Hungfb8ede22018-09-12 19:03:24 -07002310 ALOGV("%s(%d): timeout %ld.%03d",
Eric Laurent973db022018-11-20 14:54:31 -08002311 __func__, mPortId, timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002312 requested = &timeout;
2313 }
2314
Andy Hungea2b9c02016-02-12 17:06:53 -08002315 size_t writtenFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002316 while (mRemainingFrames > 0) {
2317
2318 Buffer audioBuffer;
2319 audioBuffer.frameCount = mRemainingFrames;
2320 size_t nonContig;
2321 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
2322 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Andy Hungfb8ede22018-09-12 19:03:24 -07002323 "%s(%d): obtainBuffer() err=%d frameCount=%zu",
Eric Laurent973db022018-11-20 14:54:31 -08002324 __func__, mPortId, err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002325 requested = &ClientProxy::kNonBlocking;
2326 size_t avail = audioBuffer.frameCount + nonContig;
Andy Hungfb8ede22018-09-12 19:03:24 -07002327 ALOGV("%s(%d): obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Eric Laurent973db022018-11-20 14:54:31 -08002328 __func__, mPortId, mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002329 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002330 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
2331 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten606fbc12015-10-22 15:28:15 -07002332 // FIXME bug 25195759
2333 return 1000000;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002334 }
Andy Hungfb8ede22018-09-12 19:03:24 -07002335 ALOGE("%s(%d): Error %d obtaining an audio buffer, giving up.",
Eric Laurent973db022018-11-20 14:54:31 -08002336 __func__, mPortId, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002337 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002338 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002339
Phil Burkfdb3c072016-02-09 10:47:02 -08002340 if (mRetryOnPartialBuffer && audio_has_proportional_frames(mFormat)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002341 mRetryOnPartialBuffer = false;
2342 if (avail < mRemainingFrames) {
Andy Hunga7f03352015-05-31 21:54:49 -07002343 if (ns > 0) { // account for obtain time
2344 const nsecs_t timeNow = systemTime();
2345 ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2346 }
Andy Hungeb6e6502019-04-29 13:47:40 -07002347
2348 // delayNs is first computed by the additional frames required in the buffer.
2349 nsecs_t delayNs = framesToNanoseconds(
2350 mRemainingFrames - avail, sampleRate, speed);
2351
2352 // afNs is the AudioFlinger mixer period in ns.
2353 const nsecs_t afNs = framesToNanoseconds(mAfFrameCount, mAfSampleRate, speed);
2354
2355 // If the AudioTrack is double buffered based on the AudioFlinger mixer period,
2356 // we may have a race if we wait based on the number of frames desired.
2357 // This is a possible issue with resampling and AAudio.
2358 //
2359 // The granularity of audioflinger processing is one mixer period; if
2360 // our wait time is less than one mixer period, wait at most half the period.
2361 if (delayNs < afNs) {
2362 delayNs = std::min(delayNs, afNs / 2);
2363 }
2364
2365 // adjust our ns wait by delayNs.
2366 if (ns < 0 /* NS_WHENEVER */ || delayNs < ns) {
2367 ns = delayNs;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002368 }
2369 return ns;
2370 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07002371 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002372
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002373 size_t reqSize = audioBuffer.size;
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07002374 if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
2375 // when notifying client it can write more data, pass the total size that can be
2376 // written in the next write() call, since it's not passed through the callback
2377 audioBuffer.size += nonContig;
2378 }
2379 mCbf(mTransfer == TRANSFER_CALLBACK ? EVENT_MORE_DATA : EVENT_CAN_WRITE_MORE_DATA,
2380 mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002381 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002382
Jiabin Huang447cea72020-07-28 22:35:18 +00002383 // Validate on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002384 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Andy Hungfb8ede22018-09-12 19:03:24 -07002385 ALOGE("%s(%d): EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
Eric Laurent973db022018-11-20 14:54:31 -08002386 __func__, mPortId, reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002387 return NS_NEVER;
2388 }
2389
2390 if (writtenSize == 0) {
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07002391 if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
2392 // The callback EVENT_CAN_WRITE_MORE_DATA was processed in the JNI of
2393 // android.media.AudioTrack. The JNI is not using the callback to provide data,
2394 // it only signals to the Java client that it can provide more data, which
2395 // this track is read to accept now.
2396 // The playback thread will be awaken at the next ::write()
2397 return NS_WHENEVER;
2398 }
The Android Open Source Project8555d082009-03-05 14:34:35 -08002399 // The callback is done filling buffers
2400 // Keep this thread going to handle timed events and
2401 // still try to get more data in intervals of WAIT_PERIOD_MS
2402 // but don't just loop and block the CPU, so wait
Andy Hunga7f03352015-05-31 21:54:49 -07002403
2404 // mCbf(EVENT_MORE_DATA, ...) might either
2405 // (1) Block until it can fill the buffer, returning 0 size on EOS.
2406 // (2) Block until it can fill the buffer, returning 0 data (silence) on EOS.
2407 // (3) Return 0 size when no data is available, does not wait for more data.
2408 //
2409 // (1) and (2) occurs with AudioPlayer/AwesomePlayer; (3) occurs with NuPlayer.
2410 // We try to compute the wait time to avoid a tight sleep-wait cycle,
2411 // especially for case (3).
2412 //
2413 // The decision to support (1) and (2) affect the sizing of mRemainingFrames
2414 // and this loop; whereas for case (3) we could simply check once with the full
2415 // buffer size and skip the loop entirely.
2416
2417 nsecs_t myns;
Phil Burkfdb3c072016-02-09 10:47:02 -08002418 if (audio_has_proportional_frames(mFormat)) {
Andy Hunga7f03352015-05-31 21:54:49 -07002419 // time to wait based on buffer occupancy
2420 const nsecs_t datans = mRemainingFrames <= avail ? 0 :
2421 framesToNanoseconds(mRemainingFrames - avail, sampleRate, speed);
2422 // audio flinger thread buffer size (TODO: adjust for fast tracks)
Glenn Kastenea38ee72016-04-18 11:08:01 -07002423 // FIXME: use mAfFrameCountHAL instead of mAfFrameCount below for fast tracks.
Andy Hunga7f03352015-05-31 21:54:49 -07002424 const nsecs_t afns = framesToNanoseconds(mAfFrameCount, mAfSampleRate, speed);
2425 // add a half the AudioFlinger buffer time to avoid soaking CPU if datans is 0.
2426 myns = datans + (afns / 2);
2427 } else {
2428 // FIXME: This could ping quite a bit if the buffer isn't full.
2429 // Note that when mState is stopping we waitStreamEnd, so it never gets here.
2430 myns = kWaitPeriodNs;
2431 }
2432 if (ns > 0) { // account for obtain and callback time
2433 const nsecs_t timeNow = systemTime();
2434 ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2435 }
2436 if (ns < 0 /* NS_WHENEVER */ || myns < ns) {
2437 ns = myns;
2438 }
2439 return ns;
Glenn Kastend65d73c2012-06-22 17:21:07 -07002440 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002441
Glenn Kasten138d6f92015-03-20 10:54:51 -07002442 size_t releasedFrames = writtenSize / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002443 audioBuffer.frameCount = releasedFrames;
2444 mRemainingFrames -= releasedFrames;
2445 if (misalignment >= releasedFrames) {
2446 misalignment -= releasedFrames;
2447 } else {
2448 misalignment = 0;
2449 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002450
2451 releaseBuffer(&audioBuffer);
Andy Hungea2b9c02016-02-12 17:06:53 -08002452 writtenFrames += releasedFrames;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002453
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002454 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
2455 // if callback doesn't like to accept the full chunk
2456 if (writtenSize < reqSize) {
2457 continue;
2458 }
2459
2460 // There could be enough non-contiguous frames available to satisfy the remaining request
2461 if (mRemainingFrames <= nonContig) {
2462 continue;
2463 }
2464
2465#if 0
2466 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
2467 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
2468 // that total to a sum == notificationFrames.
2469 if (0 < misalignment && misalignment <= mRemainingFrames) {
2470 mRemainingFrames = misalignment;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002471 return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002472 }
2473#endif
2474
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002475 }
Andy Hungea2b9c02016-02-12 17:06:53 -08002476 if (writtenFrames > 0) {
2477 AutoMutex lock(mLock);
2478 mFramesWritten += writtenFrames;
2479 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002480 mRemainingFrames = notificationFrames;
2481 mRetryOnPartialBuffer = true;
2482
2483 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
2484 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002485}
2486
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002487status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08002488{
Andy Hungb68f5eb2019-12-03 16:49:17 -08002489 status_t result = NO_ERROR; // logged: make sure to set this before returning.
2490 const int64_t beginNs = systemTime();
Andy Hunga6b27032020-04-27 10:34:24 -07002491 mediametrics::Defer defer([&] {
Andy Hungb68f5eb2019-12-03 16:49:17 -08002492 mediametrics::LogItem(mMetricsId)
2493 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_RESTORE)
Andy Hungea840382020-05-05 21:50:17 -07002494 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
Andy Hungb68f5eb2019-12-03 16:49:17 -08002495 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
2496 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
2497 .set(AMEDIAMETRICS_PROP_WHERE, from)
2498 .record(); });
2499
Andy Hungfb8ede22018-09-12 19:03:24 -07002500 ALOGW("%s(%d): dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurent973db022018-11-20 14:54:31 -08002501 __func__, mPortId, isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002502 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002503
Glenn Kastena47f3162012-11-07 10:13:08 -08002504 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08002505 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08002506 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07002507
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002508 if (isOffloadedOrDirect_l() || mDoNotReconnect) {
Andy Hung1f1db832015-06-08 13:26:10 -07002509 // FIXME re-creation of offloaded and direct tracks is not yet implemented;
2510 // reconsider enabling for linear PCM encodings when position can be preserved.
Andy Hungb68f5eb2019-12-03 16:49:17 -08002511 result = DEAD_OBJECT;
2512 return result;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002513 }
2514
Phil Burk2812d9e2016-01-04 10:34:30 -08002515 // Save so we can return count since creation.
2516 mUnderrunCountOffset = getUnderrunCount_l();
2517
Glenn Kasten200092b2014-08-15 15:13:30 -07002518 // save the old static buffer position
Andy Hungf20a4e92016-08-15 19:10:34 -07002519 uint32_t staticPosition = 0;
Andy Hung4ede21d2014-12-12 15:37:34 -08002520 size_t bufferPosition = 0;
2521 int loopCount = 0;
2522 if (mStaticProxy != 0) {
2523 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
Andy Hungf20a4e92016-08-15 19:10:34 -07002524 staticPosition = mStaticProxy->getPosition().unsignedValue();
Andy Hung4ede21d2014-12-12 15:37:34 -08002525 }
Glenn Kasten200092b2014-08-15 15:13:30 -07002526
Mikhail Naganovb13b35d2018-03-30 17:21:14 -07002527 // See b/74409267. Connecting to a BT A2DP device supporting multiple codecs
2528 // causes a lot of churn on the service side, and it can reject starting
2529 // playback of a previously created track. May also apply to other cases.
2530 const int INITIAL_RETRIES = 3;
2531 int retries = INITIAL_RETRIES;
2532retry:
2533 if (retries < INITIAL_RETRIES) {
2534 // See the comment for clearAudioConfigCache at the start of the function.
2535 AudioSystem::clearAudioConfigCache();
2536 }
Haynes Mathew Georgeae34ed22016-01-28 11:58:39 -08002537 mFlags = mOrigFlags;
2538
Glenn Kasten200092b2014-08-15 15:13:30 -07002539 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08002540 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07002541 // It will also delete the strong references on previous IAudioTrack and IMemory.
2542 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Andy Hungb68f5eb2019-12-03 16:49:17 -08002543 result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07002544
Eric Laurent6ec546d2018-10-10 16:52:14 -07002545 if (result == NO_ERROR) {
Andy Hungd7bd69e2015-07-24 07:52:41 -07002546 // take the frames that will be lost by track recreation into account in saved position
2547 // For streaming tracks, this is the amount we obtained from the user/client
2548 // (not the number actually consumed at the server - those are already lost).
2549 if (mStaticProxy == 0) {
2550 mPosition = mReleased;
2551 }
Andy Hung4ede21d2014-12-12 15:37:34 -08002552 // Continue playback from last known position and restore loop.
2553 if (mStaticProxy != 0) {
2554 if (loopCount != 0) {
2555 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
2556 mLoopStart, mLoopEnd, loopCount);
2557 } else {
2558 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002559 if (bufferPosition == mFrameCount) {
Eric Laurent973db022018-11-20 14:54:31 -08002560 ALOGD("%s(%d): restoring track at end of static buffer", __func__, mPortId);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002561 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002562 }
2563 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002564 // restore volume handler
Andy Hung39399b62017-04-21 15:07:45 -07002565 mVolumeHandler->forall([this](const VolumeShaper &shaper) -> VolumeShaper::Status {
2566 sp<VolumeShaper::Operation> operationToEnd =
2567 new VolumeShaper::Operation(shaper.mOperation);
Andy Hung4ef88d72017-02-21 19:47:53 -08002568 // TODO: Ideally we would restore to the exact xOffset position
2569 // as returned by getVolumeShaperState(), but we don't have that
2570 // information when restoring at the client unless we periodically poll
2571 // the server or create shared memory state.
2572 //
Andy Hung39399b62017-04-21 15:07:45 -07002573 // For now, we simply advance to the end of the VolumeShaper effect
2574 // if it has been started.
2575 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002576 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002577 }
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002578 media::VolumeShaperConfiguration config;
2579 shaper.mConfiguration->writeToParcelable(&config);
2580 media::VolumeShaperOperation operation;
2581 operationToEnd->writeToParcelable(&operation);
2582 status_t status;
2583 mAudioTrack->applyVolumeShaper(config, operation, &status);
2584 return status;
Andy Hung4ef88d72017-02-21 19:47:53 -08002585 });
2586
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002587 if (mState == STATE_ACTIVE) {
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002588 mAudioTrack->start(&result);
Eric Laurent1703cdf2011-03-07 14:52:59 -08002589 }
Andy Hungf20a4e92016-08-15 19:10:34 -07002590 // server resets to zero so we offset
2591 mFramesWrittenServerOffset =
2592 mStaticProxy.get() != nullptr ? staticPosition : mFramesWritten;
2593 mFramesWrittenAtRestore = mFramesWrittenServerOffset;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002594 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002595 if (result != NO_ERROR) {
Eric Laurent973db022018-11-20 14:54:31 -08002596 ALOGW("%s(%d): failed status %d, retries %d", __func__, mPortId, result, retries);
Mikhail Naganovb13b35d2018-03-30 17:21:14 -07002597 if (--retries > 0) {
Eric Laurent6ec546d2018-10-10 16:52:14 -07002598 // leave time for an eventual race condition to clear before retrying
2599 usleep(500000);
Mikhail Naganovb13b35d2018-03-30 17:21:14 -07002600 goto retry;
2601 }
Eric Laurent6ec546d2018-10-10 16:52:14 -07002602 // if no retries left, set invalid bit to force restoring at next occasion
2603 // and avoid inconsistent active state on client and server sides
2604 if (mCblk != nullptr) {
2605 android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
2606 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002607 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002608 return result;
2609}
2610
Andy Hung90e8a972015-11-09 16:42:40 -08002611Modulo<uint32_t> AudioTrack::updateAndGetPosition_l()
Glenn Kasten200092b2014-08-15 15:13:30 -07002612{
2613 // This is the sole place to read server consumed frames
Andy Hung90e8a972015-11-09 16:42:40 -08002614 Modulo<uint32_t> newServer(mProxy->getPosition());
2615 const int32_t delta = (newServer - mServer).signedValue();
Glenn Kasten200092b2014-08-15 15:13:30 -07002616 // TODO There is controversy about whether there can be "negative jitter" in server position.
2617 // This should be investigated further, and if possible, it should be addressed.
2618 // A more definite failure mode is infrequent polling by client.
2619 // One could call (void)getPosition_l() in releaseBuffer(),
2620 // so mReleased and mPosition are always lock-step as best possible.
2621 // That should ensure delta never goes negative for infrequent polling
2622 // unless the server has more than 2^31 frames in its buffer,
2623 // in which case the use of uint32_t for these counters has bigger issues.
Andy Hung90e8a972015-11-09 16:42:40 -08002624 ALOGE_IF(delta < 0,
Andy Hungfb8ede22018-09-12 19:03:24 -07002625 "%s(%d): detected illegal retrograde motion by the server: mServer advanced by %d",
Eric Laurent973db022018-11-20 14:54:31 -08002626 __func__, mPortId, delta);
Chad Brubaker039c27a2015-09-23 15:17:29 -07002627 mServer = newServer;
Andy Hung90e8a972015-11-09 16:42:40 -08002628 if (delta > 0) { // avoid retrograde
2629 mPosition += delta;
2630 }
2631 return mPosition;
Glenn Kasten200092b2014-08-15 15:13:30 -07002632}
2633
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002634bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed)
Andy Hung8edb8dc2015-03-26 19:13:55 -07002635{
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002636 updateLatency_l();
Andy Hung8edb8dc2015-03-26 19:13:55 -07002637 // applicable for mixing tracks only (not offloaded or direct)
2638 if (mStaticProxy != 0) {
2639 return true; // static tracks do not have issues with buffer sizing.
2640 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07002641 const size_t minFrameCount =
Eric Laurent21da6472017-11-09 16:29:26 -08002642 AudioSystem::calculateMinFrameCount(mAfLatency, mAfFrameCount, mAfSampleRate,
2643 sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002644 const bool allowed = mFrameCount >= minFrameCount;
2645 ALOGD_IF(!allowed,
Andy Hungfb8ede22018-09-12 19:03:24 -07002646 "%s(%d): denied "
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002647 "mAfLatency:%u mAfFrameCount:%zu mAfSampleRate:%u sampleRate:%u speed:%f "
2648 "mFrameCount:%zu < minFrameCount:%zu",
Eric Laurent973db022018-11-20 14:54:31 -08002649 __func__, mPortId,
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002650 mAfLatency, mAfFrameCount, mAfSampleRate, sampleRate, speed,
Andy Hung8edb8dc2015-03-26 19:13:55 -07002651 mFrameCount, minFrameCount);
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002652 return allowed;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002653}
2654
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002655status_t AudioTrack::setParameters(const String8& keyValuePairs)
2656{
2657 AutoMutex lock(mLock);
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002658 status_t status;
2659 mAudioTrack->setParameters(keyValuePairs.c_str(), &status);
2660 return status;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002661}
2662
Dean Wheatleya70eef72018-01-04 14:23:50 +11002663status_t AudioTrack::selectPresentation(int presentationId, int programId)
2664{
2665 AutoMutex lock(mLock);
Eric Laurent973db022018-11-20 14:54:31 -08002666 AudioParameter param = AudioParameter();
2667 param.addInt(String8(AudioParameter::keyPresentationId), presentationId);
2668 param.addInt(String8(AudioParameter::keyProgramId), programId);
2669 ALOGV("%s(%d): PresentationId/ProgramId[%s]",
2670 __func__, mPortId, param.toString().string());
2671
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002672 status_t status;
2673 mAudioTrack->setParameters(param.toString().c_str(), &status);
2674 return status;
Dean Wheatleya70eef72018-01-04 14:23:50 +11002675}
2676
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002677VolumeShaper::Status AudioTrack::applyVolumeShaper(
2678 const sp<VolumeShaper::Configuration>& configuration,
2679 const sp<VolumeShaper::Operation>& operation)
2680{
2681 AutoMutex lock(mLock);
Andy Hung4ef88d72017-02-21 19:47:53 -08002682 mVolumeHandler->setIdIfNecessary(configuration);
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002683 media::VolumeShaperConfiguration config;
2684 configuration->writeToParcelable(&config);
2685 media::VolumeShaperOperation op;
2686 operation->writeToParcelable(&op);
2687 VolumeShaper::Status status;
2688 mAudioTrack->applyVolumeShaper(config, op, &status);
Andy Hung39399b62017-04-21 15:07:45 -07002689
2690 if (status == DEAD_OBJECT) {
2691 if (restoreTrack_l("applyVolumeShaper") == OK) {
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002692 mAudioTrack->applyVolumeShaper(config, op, &status);
Andy Hung39399b62017-04-21 15:07:45 -07002693 }
2694 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002695 if (status >= 0) {
2696 // save VolumeShaper for restore
2697 mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung39399b62017-04-21 15:07:45 -07002698 if (mState == STATE_ACTIVE || mState == STATE_STOPPING) {
2699 mVolumeHandler->setStarted();
2700 }
2701 } else {
2702 // warn only if not an expected restore failure.
2703 ALOGW_IF(!((isOffloadedOrDirect_l() || mDoNotReconnect) && status == DEAD_OBJECT),
Eric Laurent973db022018-11-20 14:54:31 -08002704 "%s(%d): applyVolumeShaper failed: %d", __func__, mPortId, status);
Andy Hung4ef88d72017-02-21 19:47:53 -08002705 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002706 return status;
2707}
2708
2709sp<VolumeShaper::State> AudioTrack::getVolumeShaperState(int id)
2710{
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002711 AutoMutex lock(mLock);
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002712 std::optional<media::VolumeShaperState> vss;
2713 mAudioTrack->getVolumeShaperState(id, &vss);
2714 sp<VolumeShaper::State> state;
2715 if (vss.has_value()) {
2716 state = new VolumeShaper::State();
2717 state->readFromParcelable(vss.value());
2718 }
Andy Hung39399b62017-04-21 15:07:45 -07002719 if (state.get() == nullptr && (mCblk->mFlags & CBLK_INVALID) != 0) {
2720 if (restoreTrack_l("getVolumeShaperState") == OK) {
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002721 mAudioTrack->getVolumeShaperState(id, &vss);
2722 if (vss.has_value()) {
2723 state = new VolumeShaper::State();
2724 state->readFromParcelable(vss.value());
2725 }
Andy Hung39399b62017-04-21 15:07:45 -07002726 }
2727 }
2728 return state;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002729}
2730
Andy Hungea2b9c02016-02-12 17:06:53 -08002731status_t AudioTrack::getTimestamp(ExtendedTimestamp *timestamp)
2732{
2733 if (timestamp == nullptr) {
2734 return BAD_VALUE;
2735 }
2736 AutoMutex lock(mLock);
Andy Hunge13f8a62016-03-30 14:20:42 -07002737 return getTimestamp_l(timestamp);
2738}
2739
2740status_t AudioTrack::getTimestamp_l(ExtendedTimestamp *timestamp)
2741{
Andy Hungea2b9c02016-02-12 17:06:53 -08002742 if (mCblk->mFlags & CBLK_INVALID) {
2743 const status_t status = restoreTrack_l("getTimestampExtended");
2744 if (status != OK) {
2745 // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
2746 // recommending that the track be recreated.
2747 return DEAD_OBJECT;
2748 }
2749 }
2750 // check for offloaded/direct here in case restoring somehow changed those flags.
2751 if (isOffloadedOrDirect_l()) {
2752 return INVALID_OPERATION; // not supported
2753 }
2754 status_t status = mProxy->getTimestamp(timestamp);
Andy Hungfb8ede22018-09-12 19:03:24 -07002755 LOG_ALWAYS_FATAL_IF(status != OK, "%s(%d): status %d not allowed from proxy getTimestamp",
Eric Laurent973db022018-11-20 14:54:31 -08002756 __func__, mPortId, status);
Andy Hungea2b9c02016-02-12 17:06:53 -08002757 bool found = false;
Andy Hunge1e98462016-04-12 10:18:51 -07002758 timestamp->mPosition[ExtendedTimestamp::LOCATION_CLIENT] = mFramesWritten;
2759 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_CLIENT] = 0;
2760 // server side frame offset in case AudioTrack has been restored.
2761 for (int i = ExtendedTimestamp::LOCATION_SERVER;
2762 i < ExtendedTimestamp::LOCATION_MAX; ++i) {
2763 if (timestamp->mTimeNs[i] >= 0) {
2764 // apply server offset (frames flushed is ignored
2765 // so we don't report the jump when the flush occurs).
2766 timestamp->mPosition[i] += mFramesWrittenServerOffset;
2767 found = true;
Andy Hungea2b9c02016-02-12 17:06:53 -08002768 }
2769 }
2770 return found ? OK : WOULD_BLOCK;
2771}
2772
Glenn Kastence703742013-07-19 16:33:58 -07002773status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
2774{
Glenn Kasten53cec222013-08-29 09:01:02 -07002775 AutoMutex lock(mLock);
Andy Hung65ffdfc2016-10-10 15:52:11 -07002776 return getTimestamp_l(timestamp);
2777}
Phil Burk1b420972015-04-22 10:52:21 -07002778
Andy Hung65ffdfc2016-10-10 15:52:11 -07002779status_t AudioTrack::getTimestamp_l(AudioTimestamp& timestamp)
2780{
Phil Burk1b420972015-04-22 10:52:21 -07002781 bool previousTimestampValid = mPreviousTimestampValid;
2782 // Set false here to cover all the error return cases.
2783 mPreviousTimestampValid = false;
2784
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002785 switch (mState) {
2786 case STATE_ACTIVE:
2787 case STATE_PAUSED:
2788 break; // handle below
2789 case STATE_FLUSHED:
2790 case STATE_STOPPED:
2791 return WOULD_BLOCK;
2792 case STATE_STOPPING:
2793 case STATE_PAUSED_STOPPING:
2794 if (!isOffloaded_l()) {
2795 return INVALID_OPERATION;
2796 }
2797 break; // offloaded tracks handled below
2798 default:
Andy Hungfb8ede22018-09-12 19:03:24 -07002799 LOG_ALWAYS_FATAL("%s(%d): Invalid mState in getTimestamp(): %d",
Eric Laurent973db022018-11-20 14:54:31 -08002800 __func__, mPortId, mState);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002801 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07002802 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002803
Eric Laurent275e8e92014-11-30 15:14:47 -08002804 if (mCblk->mFlags & CBLK_INVALID) {
Andy Hung6653c932015-06-08 13:27:48 -07002805 const status_t status = restoreTrack_l("getTimestamp");
2806 if (status != OK) {
2807 // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
2808 // recommending that the track be recreated.
2809 return DEAD_OBJECT;
2810 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002811 }
2812
Glenn Kasten200092b2014-08-15 15:13:30 -07002813 // The presented frame count must always lag behind the consumed frame count.
2814 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Andy Hung6ae58432016-02-16 18:32:24 -08002815
2816 status_t status;
Andy Hung818e7a32016-02-16 18:08:07 -08002817 if (isOffloadedOrDirect_l()) {
Andy Hung6ae58432016-02-16 18:32:24 -08002818 // use Binder to get timestamp
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002819 media::AudioTimestampInternal ts;
2820 mAudioTrack->getTimestamp(&ts, &status);
2821 if (status == OK) {
2822 timestamp = VALUE_OR_FATAL(aidl2legacy_AudioTimestamp(ts));
2823 }
Andy Hung6ae58432016-02-16 18:32:24 -08002824 } else {
2825 // read timestamp from shared memory
2826 ExtendedTimestamp ets;
2827 status = mProxy->getTimestamp(&ets);
2828 if (status == OK) {
Andy Hungb01faa32016-04-27 12:51:32 -07002829 ExtendedTimestamp::Location location;
2830 status = ets.getBestTimestamp(&timestamp, &location);
2831
2832 if (status == OK) {
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002833 updateLatency_l();
Andy Hungb01faa32016-04-27 12:51:32 -07002834 // It is possible that the best location has moved from the kernel to the server.
2835 // In this case we adjust the position from the previous computed latency.
2836 if (location == ExtendedTimestamp::LOCATION_SERVER) {
2837 ALOGW_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_KERNEL,
Andy Hungfb8ede22018-09-12 19:03:24 -07002838 "%s(%d): location moved from kernel to server",
Eric Laurent973db022018-11-20 14:54:31 -08002839 __func__, mPortId);
Andy Hung07eee802016-06-21 16:47:16 -07002840 // check that the last kernel OK time info exists and the positions
2841 // are valid (if they predate the current track, the positions may
2842 // be zero or negative).
Andy Hungb01faa32016-04-27 12:51:32 -07002843 const int64_t frames =
Andy Hung6d7b1192016-05-07 22:59:48 -07002844 (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
Andy Hung07eee802016-06-21 16:47:16 -07002845 ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0 ||
2846 ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] <= 0 ||
2847 ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] <= 0)
Andy Hung6d7b1192016-05-07 22:59:48 -07002848 ?
2849 int64_t((double)mAfLatency * mSampleRate * mPlaybackRate.mSpeed
2850 / 1000)
2851 :
2852 (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
2853 - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK]);
Andy Hungfb8ede22018-09-12 19:03:24 -07002854 ALOGV("%s(%d): frame adjustment:%lld timestamp:%s",
Eric Laurent973db022018-11-20 14:54:31 -08002855 __func__, mPortId, (long long)frames, ets.toString().c_str());
Andy Hungb01faa32016-04-27 12:51:32 -07002856 if (frames >= ets.mPosition[location]) {
2857 timestamp.mPosition = 0;
2858 } else {
2859 timestamp.mPosition = (uint32_t)(ets.mPosition[location] - frames);
2860 }
Andy Hung69488c42016-05-16 18:43:33 -07002861 } else if (location == ExtendedTimestamp::LOCATION_KERNEL) {
2862 ALOGV_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_SERVER,
Andy Hungfb8ede22018-09-12 19:03:24 -07002863 "%s(%d): location moved from server to kernel",
Eric Laurent973db022018-11-20 14:54:31 -08002864 __func__, mPortId);
Andy Hung98731a22019-04-08 19:19:07 -07002865
2866 if (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER] ==
2867 ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL]) {
2868 // In Q, we don't return errors as an invalid time
2869 // but instead we leave the last kernel good timestamp alone.
2870 //
2871 // If server is identical to kernel, the device data pipeline is idle.
2872 // A better start time is now. The retrograde check ensures
2873 // timestamp monotonicity.
2874 const int64_t nowNs = systemTime();
Andy Hungcf3b7152019-04-19 18:29:21 -07002875 if (!mTimestampStallReported) {
2876 ALOGD("%s(%d): device stall time corrected using current time %lld",
2877 __func__, mPortId, (long long)nowNs);
2878 mTimestampStallReported = true;
2879 }
Andy Hung98731a22019-04-08 19:19:07 -07002880 timestamp.mTime = convertNsToTimespec(nowNs);
Andy Hungcf3b7152019-04-19 18:29:21 -07002881 } else {
2882 mTimestampStallReported = false;
Andy Hung98731a22019-04-08 19:19:07 -07002883 }
Andy Hungb01faa32016-04-27 12:51:32 -07002884 }
Andy Hung5d313802016-10-10 15:09:39 -07002885
2886 // We update the timestamp time even when paused.
2887 if (mState == STATE_PAUSED /* not needed: STATE_PAUSED_STOPPING */) {
2888 const int64_t now = systemTime();
Andy Hung2b01f002017-07-05 12:01:36 -07002889 const int64_t at = audio_utils_ns_from_timespec(&timestamp.mTime);
Andy Hung5d313802016-10-10 15:09:39 -07002890 const int64_t lag =
2891 (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
2892 ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0)
2893 ? int64_t(mAfLatency * 1000000LL)
2894 : (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
2895 - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK])
2896 * NANOS_PER_SECOND / mSampleRate;
2897 const int64_t limit = now - lag; // no earlier than this limit
2898 if (at < limit) {
2899 ALOGV("timestamp pause lag:%lld adjusting from %lld to %lld",
2900 (long long)lag, (long long)at, (long long)limit);
Andy Hungffa36952017-08-17 10:41:51 -07002901 timestamp.mTime = convertNsToTimespec(limit);
Andy Hung5d313802016-10-10 15:09:39 -07002902 }
2903 }
Andy Hungb01faa32016-04-27 12:51:32 -07002904 mPreviousLocation = location;
2905 } else {
2906 // right after AudioTrack is started, one may not find a timestamp
Eric Laurent973db022018-11-20 14:54:31 -08002907 ALOGV("%s(%d): getBestTimestamp did not find timestamp", __func__, mPortId);
Andy Hungb01faa32016-04-27 12:51:32 -07002908 }
Andy Hung6ae58432016-02-16 18:32:24 -08002909 }
2910 if (status == INVALID_OPERATION) {
Andy Hungf20a4e92016-08-15 19:10:34 -07002911 // INVALID_OPERATION occurs when no timestamp has been issued by the server;
2912 // other failures are signaled by a negative time.
2913 // If we come out of FLUSHED or STOPPED where the position is known
2914 // to be zero we convert this to WOULD_BLOCK (with the implicit meaning of
2915 // "zero" for NuPlayer). We don't convert for track restoration as position
2916 // does not reset.
Andy Hungfb8ede22018-09-12 19:03:24 -07002917 ALOGV("%s(%d): timestamp server offset:%lld restore frames:%lld",
Eric Laurent973db022018-11-20 14:54:31 -08002918 __func__, mPortId,
Andy Hungf20a4e92016-08-15 19:10:34 -07002919 (long long)mFramesWrittenServerOffset, (long long)mFramesWrittenAtRestore);
2920 if (mFramesWrittenServerOffset != mFramesWrittenAtRestore) {
2921 status = WOULD_BLOCK;
2922 }
Andy Hung6ae58432016-02-16 18:32:24 -08002923 }
2924 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002925 if (status != NO_ERROR) {
Eric Laurent973db022018-11-20 14:54:31 -08002926 ALOGV_IF(status != WOULD_BLOCK, "%s(%d): getTimestamp error:%#x", __func__, mPortId, status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002927 return status;
2928 }
2929 if (isOffloadedOrDirect_l()) {
2930 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
2931 // use cached paused position in case another offloaded track is running.
2932 timestamp.mPosition = mPausedPosition;
2933 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
Andy Hung5d313802016-10-10 15:09:39 -07002934 // TODO: adjust for delay
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002935 return NO_ERROR;
2936 }
2937
2938 // Check whether a pending flush or stop has completed, as those commands may
Andy Hungc8e09c62015-06-03 23:43:36 -07002939 // be asynchronous or return near finish or exhibit glitchy behavior.
2940 //
2941 // Originally this showed up as the first timestamp being a continuation of
2942 // the previous song under gapless playback.
2943 // However, we sometimes see zero timestamps, then a glitch of
2944 // the previous song's position, and then correct timestamps afterwards.
Andy Hungffa36952017-08-17 10:41:51 -07002945 if (mStartFromZeroUs != 0 && mSampleRate != 0) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002946 static const int kTimeJitterUs = 100000; // 100 ms
2947 static const int k1SecUs = 1000000;
2948
2949 const int64_t timeNow = getNowUs();
2950
Andy Hungffa36952017-08-17 10:41:51 -07002951 if (timeNow < mStartFromZeroUs + k1SecUs) { // within first second of starting
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002952 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
Andy Hungffa36952017-08-17 10:41:51 -07002953 if (timestampTimeUs < mStartFromZeroUs) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002954 return WOULD_BLOCK; // stale timestamp time, occurs before start.
2955 }
Andy Hungffa36952017-08-17 10:41:51 -07002956 const int64_t deltaTimeUs = timestampTimeUs - mStartFromZeroUs;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002957 const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002958 / ((double)mSampleRate * mPlaybackRate.mSpeed);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002959
2960 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2961 // Verify that the counter can't count faster than the sample rate
Andy Hungc8e09c62015-06-03 23:43:36 -07002962 // since the start time. If greater, then that means we may have failed
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002963 // to completely flush or stop the previous playing track.
Andy Hungc8e09c62015-06-03 23:43:36 -07002964 ALOGW_IF(!mTimestampStartupGlitchReported,
Andy Hungfb8ede22018-09-12 19:03:24 -07002965 "%s(%d): startup glitch detected"
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002966 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
Eric Laurent973db022018-11-20 14:54:31 -08002967 __func__, mPortId,
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002968 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2969 timestamp.mPosition);
Andy Hungc8e09c62015-06-03 23:43:36 -07002970 mTimestampStartupGlitchReported = true;
2971 if (previousTimestampValid
2972 && mPreviousTimestamp.mPosition == 0 /* should be true if valid */) {
2973 timestamp = mPreviousTimestamp;
2974 mPreviousTimestampValid = true;
2975 return NO_ERROR;
2976 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002977 return WOULD_BLOCK;
2978 }
Andy Hungc8e09c62015-06-03 23:43:36 -07002979 if (deltaPositionByUs != 0) {
Andy Hungffa36952017-08-17 10:41:51 -07002980 mStartFromZeroUs = 0; // don't check again, we got valid nonzero position.
Andy Hungc8e09c62015-06-03 23:43:36 -07002981 }
2982 } else {
Andy Hungffa36952017-08-17 10:41:51 -07002983 mStartFromZeroUs = 0; // don't check again, start time expired.
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002984 }
Andy Hungc8e09c62015-06-03 23:43:36 -07002985 mTimestampStartupGlitchReported = false;
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002986 }
2987 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002988 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2989 (void) updateAndGetPosition_l();
2990 // Server consumed (mServer) and presented both use the same server time base,
2991 // and server consumed is always >= presented.
2992 // The delta between these represents the number of frames in the buffer pipeline.
2993 // If this delta between these is greater than the client position, it means that
2994 // actually presented is still stuck at the starting line (figuratively speaking),
2995 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
Andy Hung90e8a972015-11-09 16:42:40 -08002996 // Note: We explicitly use non-Modulo comparison here - potential wrap issue when
2997 // mPosition exceeds 32 bits.
2998 // TODO Remove when timestamp is updated to contain pipeline status info.
2999 const int32_t pipelineDepthInFrames = (mServer - timestamp.mPosition).signedValue();
3000 if (pipelineDepthInFrames > 0 /* should be true, but we check anyways */
3001 && (uint32_t)pipelineDepthInFrames > mPosition.value()) {
Glenn Kasten200092b2014-08-15 15:13:30 -07003002 return INVALID_OPERATION;
3003 }
3004 // Convert timestamp position from server time base to client time base.
3005 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
3006 // But if we change it to 64-bit then this could fail.
Andy Hung90e8a972015-11-09 16:42:40 -08003007 // Use Modulo computation here.
3008 timestamp.mPosition = (mPosition - mServer + timestamp.mPosition).value();
Glenn Kasten200092b2014-08-15 15:13:30 -07003009 // Immediately after a call to getPosition_l(), mPosition and
3010 // mServer both represent the same frame position. mPosition is
3011 // in client's point of view, and mServer is in server's point of
3012 // view. So the difference between them is the "fudge factor"
3013 // between client and server views due to stop() and/or new
3014 // IAudioTrack. And timestamp.mPosition is initially in server's
3015 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07003016 }
Phil Burk1b420972015-04-22 10:52:21 -07003017
3018 // Prevent retrograde motion in timestamp.
3019 // This is sometimes caused by erratic reports of the available space in the ALSA drivers.
3020 if (status == NO_ERROR) {
Andy Hung3b8c6332019-04-03 19:29:36 -07003021 // Fix stale time when checking timestamp right after start().
3022 // The position is at the last reported location but the time can be stale
3023 // due to pause or standby or cold start latency.
3024 //
3025 // We keep advancing the time (but not the position) to ensure that the
3026 // stale value does not confuse the application.
3027 //
3028 // For offload compatibility, use a default lag value here.
3029 // Any time discrepancy between this update and the pause timestamp is handled
3030 // by the retrograde check afterwards.
3031 int64_t currentTimeNanos = audio_utils_ns_from_timespec(&timestamp.mTime);
3032 const int64_t lagNs = int64_t(mAfLatency * 1000000LL);
3033 const int64_t limitNs = mStartNs - lagNs;
3034 if (currentTimeNanos < limitNs) {
Andy Hungcf3b7152019-04-19 18:29:21 -07003035 if (!mTimestampStaleTimeReported) {
3036 ALOGD("%s(%d): stale timestamp time corrected, "
3037 "currentTimeNanos: %lld < limitNs: %lld < mStartNs: %lld",
3038 __func__, mPortId,
3039 (long long)currentTimeNanos, (long long)limitNs, (long long)mStartNs);
3040 mTimestampStaleTimeReported = true;
3041 }
Andy Hung3b8c6332019-04-03 19:29:36 -07003042 timestamp.mTime = convertNsToTimespec(limitNs);
3043 currentTimeNanos = limitNs;
Andy Hungcf3b7152019-04-19 18:29:21 -07003044 } else {
3045 mTimestampStaleTimeReported = false;
Andy Hung3b8c6332019-04-03 19:29:36 -07003046 }
3047
Andy Hungffa36952017-08-17 10:41:51 -07003048 // previousTimestampValid is set to false when starting after a stop or flush.
Phil Burk1b420972015-04-22 10:52:21 -07003049 if (previousTimestampValid) {
Andy Hung2b01f002017-07-05 12:01:36 -07003050 const int64_t previousTimeNanos =
3051 audio_utils_ns_from_timespec(&mPreviousTimestamp.mTime);
Andy Hungffa36952017-08-17 10:41:51 -07003052
3053 // retrograde check
Phil Burk1b420972015-04-22 10:52:21 -07003054 if (currentTimeNanos < previousTimeNanos) {
Andy Hungcf3b7152019-04-19 18:29:21 -07003055 if (!mTimestampRetrogradeTimeReported) {
3056 ALOGW("%s(%d): retrograde timestamp time corrected, %lld < %lld",
3057 __func__, mPortId,
3058 (long long)currentTimeNanos, (long long)previousTimeNanos);
3059 mTimestampRetrogradeTimeReported = true;
3060 }
Andy Hung5d313802016-10-10 15:09:39 -07003061 timestamp.mTime = mPreviousTimestamp.mTime;
Andy Hungcf3b7152019-04-19 18:29:21 -07003062 } else {
3063 mTimestampRetrogradeTimeReported = false;
Phil Burk1b420972015-04-22 10:52:21 -07003064 }
3065
3066 // Looking at signed delta will work even when the timestamps
3067 // are wrapping around.
Andy Hung90e8a972015-11-09 16:42:40 -08003068 int32_t deltaPosition = (Modulo<uint32_t>(timestamp.mPosition)
3069 - mPreviousTimestamp.mPosition).signedValue();
Phil Burk4c5a3672015-04-30 16:18:53 -07003070 if (deltaPosition < 0) {
3071 // Only report once per position instead of spamming the log.
Andy Hungcf3b7152019-04-19 18:29:21 -07003072 if (!mTimestampRetrogradePositionReported) {
Andy Hungfb8ede22018-09-12 19:03:24 -07003073 ALOGW("%s(%d): retrograde timestamp position corrected, %d = %u - %u",
Eric Laurent973db022018-11-20 14:54:31 -08003074 __func__, mPortId,
Phil Burk4c5a3672015-04-30 16:18:53 -07003075 deltaPosition,
3076 timestamp.mPosition,
3077 mPreviousTimestamp.mPosition);
Andy Hungcf3b7152019-04-19 18:29:21 -07003078 mTimestampRetrogradePositionReported = true;
Phil Burk4c5a3672015-04-30 16:18:53 -07003079 }
3080 } else {
Andy Hungcf3b7152019-04-19 18:29:21 -07003081 mTimestampRetrogradePositionReported = false;
Phil Burk4c5a3672015-04-30 16:18:53 -07003082 }
Andy Hung5d313802016-10-10 15:09:39 -07003083 if (deltaPosition < 0) {
3084 timestamp.mPosition = mPreviousTimestamp.mPosition;
3085 deltaPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -07003086 }
Andy Hung5d313802016-10-10 15:09:39 -07003087#if 0
3088 // Uncomment this to verify audio timestamp rate.
3089 const int64_t deltaTime =
Andy Hung2b01f002017-07-05 12:01:36 -07003090 audio_utils_ns_from_timespec(&timestamp.mTime) - previousTimeNanos;
Andy Hung5d313802016-10-10 15:09:39 -07003091 if (deltaTime != 0) {
3092 const int64_t computedSampleRate =
3093 deltaPosition * (long long)NANOS_PER_SECOND / deltaTime;
Andy Hungfb8ede22018-09-12 19:03:24 -07003094 ALOGD("%s(%d): computedSampleRate:%u sampleRate:%u",
Eric Laurent973db022018-11-20 14:54:31 -08003095 __func__, mPortId,
Andy Hung5d313802016-10-10 15:09:39 -07003096 (unsigned)computedSampleRate, mSampleRate);
3097 }
3098#endif
Phil Burk1b420972015-04-22 10:52:21 -07003099 }
3100 mPreviousTimestamp = timestamp;
3101 mPreviousTimestampValid = true;
3102 }
3103
Glenn Kastenfe346c72013-08-30 13:28:22 -07003104 return status;
Glenn Kastence703742013-07-19 16:33:58 -07003105}
3106
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00003107String8 AudioTrack::getParameters(const String8& keys)
3108{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08003109 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07003110 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08003111 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01003112 } else {
3113 return String8::empty();
3114 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00003115}
3116
Glenn Kasten23a75452014-01-13 10:37:17 -08003117bool AudioTrack::isOffloaded() const
3118{
3119 AutoMutex lock(mLock);
3120 return isOffloaded_l();
3121}
3122
Eric Laurentab5cdba2014-06-09 17:22:27 -07003123bool AudioTrack::isDirect() const
3124{
3125 AutoMutex lock(mLock);
3126 return isDirect_l();
3127}
3128
3129bool AudioTrack::isOffloadedOrDirect() const
3130{
3131 AutoMutex lock(mLock);
3132 return isOffloadedOrDirect_l();
3133}
3134
3135
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08003136status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003137{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003138 String8 result;
3139
3140 result.append(" AudioTrack::dump\n");
Andy Hungfb8ede22018-09-12 19:03:24 -07003141 result.appendFormat(" id(%d) status(%d), state(%d), session Id(%d), flags(%#x)\n",
Eric Laurent973db022018-11-20 14:54:31 -08003142 mPortId, mStatus, mState, mSessionId, mFlags);
Eric Laurentd114b622017-11-27 18:37:04 -08003143 result.appendFormat(" stream type(%d), left - right volume(%f, %f)\n",
3144 (mStreamType == AUDIO_STREAM_DEFAULT) ?
François Gaffie58d4be52018-11-06 15:30:12 +01003145 AudioSystem::attributesToStreamType(mAttributes) :
3146 mStreamType,
Eric Laurentd114b622017-11-27 18:37:04 -08003147 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003148 result.appendFormat(" format(%#x), channel mask(%#x), channel count(%u)\n",
Eric Laurentd114b622017-11-27 18:37:04 -08003149 mFormat, mChannelMask, mChannelCount);
3150 result.appendFormat(" sample rate(%u), original sample rate(%u), speed(%f)\n",
3151 mSampleRate, mOriginalSampleRate, mPlaybackRate.mSpeed);
3152 result.appendFormat(" frame count(%zu), req. frame count(%zu)\n",
3153 mFrameCount, mReqFrameCount);
3154 result.appendFormat(" notif. frame count(%u), req. notif. frame count(%u),"
3155 " req. notif. per buff(%u)\n",
3156 mNotificationFramesAct, mNotificationFramesReq, mNotificationsPerBufferReq);
3157 result.appendFormat(" latency (%d), selected device Id(%d), routed device Id(%d)\n",
3158 mLatency, mSelectedDeviceId, mRoutedDeviceId);
3159 result.appendFormat(" output(%d) AF latency (%u) AF frame count(%zu) AF SampleRate(%u)\n",
3160 mOutput, mAfLatency, mAfFrameCount, mAfSampleRate);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003161 ::write(fd, result.string(), result.size());
3162 return NO_ERROR;
3163}
3164
Phil Burk2812d9e2016-01-04 10:34:30 -08003165uint32_t AudioTrack::getUnderrunCount() const
3166{
3167 AutoMutex lock(mLock);
3168 return getUnderrunCount_l();
3169}
3170
3171uint32_t AudioTrack::getUnderrunCount_l() const
3172{
3173 return mProxy->getUnderrunCount() + mUnderrunCountOffset;
3174}
3175
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003176uint32_t AudioTrack::getUnderrunFrames() const
3177{
3178 AutoMutex lock(mLock);
3179 return mProxy->getUnderrunFrames();
3180}
3181
Eric Laurent296fb132015-05-01 11:38:42 -07003182status_t AudioTrack::addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback)
3183{
Eric Laurent09f1ed22019-04-24 17:45:17 -07003184
Eric Laurent296fb132015-05-01 11:38:42 -07003185 if (callback == 0) {
Eric Laurent973db022018-11-20 14:54:31 -08003186 ALOGW("%s(%d): adding NULL callback!", __func__, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07003187 return BAD_VALUE;
3188 }
3189 AutoMutex lock(mLock);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003190 if (mDeviceCallback.unsafe_get() == callback.get()) {
Eric Laurent973db022018-11-20 14:54:31 -08003191 ALOGW("%s(%d): adding same callback!", __func__, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07003192 return INVALID_OPERATION;
3193 }
3194 status_t status = NO_ERROR;
3195 if (mOutput != AUDIO_IO_HANDLE_NONE) {
3196 if (mDeviceCallback != 0) {
Eric Laurent973db022018-11-20 14:54:31 -08003197 ALOGW("%s(%d): callback already present!", __func__, mPortId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003198 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07003199 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07003200 status = AudioSystem::addAudioDeviceCallback(this, mOutput, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07003201 }
3202 mDeviceCallback = callback;
3203 return status;
3204}
3205
3206status_t AudioTrack::removeAudioDeviceCallback(
3207 const sp<AudioSystem::AudioDeviceCallback>& callback)
3208{
3209 if (callback == 0) {
Eric Laurent973db022018-11-20 14:54:31 -08003210 ALOGW("%s(%d): removing NULL callback!", __func__, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07003211 return BAD_VALUE;
3212 }
Eric Laurent4463ff52019-02-07 13:56:09 -08003213 AutoMutex lock(mLock);
3214 if (mDeviceCallback.unsafe_get() != callback.get()) {
3215 ALOGW("%s removing different callback!", __FUNCTION__);
3216 return INVALID_OPERATION;
Eric Laurent296fb132015-05-01 11:38:42 -07003217 }
Eric Laurent4463ff52019-02-07 13:56:09 -08003218 mDeviceCallback.clear();
Eric Laurent296fb132015-05-01 11:38:42 -07003219 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent09f1ed22019-04-24 17:45:17 -07003220 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07003221 }
Eric Laurent296fb132015-05-01 11:38:42 -07003222 return NO_ERROR;
3223}
3224
Eric Laurentad2e7b92017-09-14 20:06:42 -07003225
3226void AudioTrack::onAudioDeviceUpdate(audio_io_handle_t audioIo,
3227 audio_port_handle_t deviceId)
3228{
3229 sp<AudioSystem::AudioDeviceCallback> callback;
3230 {
3231 AutoMutex lock(mLock);
3232 if (audioIo != mOutput) {
3233 return;
3234 }
3235 callback = mDeviceCallback.promote();
3236 // only update device if the track is active as route changes due to other use cases are
3237 // irrelevant for this client
3238 if (mState == STATE_ACTIVE) {
3239 mRoutedDeviceId = deviceId;
3240 }
3241 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07003242
Eric Laurentad2e7b92017-09-14 20:06:42 -07003243 if (callback.get() != nullptr) {
3244 callback->onAudioDeviceUpdate(mOutput, mRoutedDeviceId);
3245 }
3246}
3247
Andy Hunge13f8a62016-03-30 14:20:42 -07003248status_t AudioTrack::pendingDuration(int32_t *msec, ExtendedTimestamp::Location location)
3249{
3250 if (msec == nullptr ||
3251 (location != ExtendedTimestamp::LOCATION_SERVER
3252 && location != ExtendedTimestamp::LOCATION_KERNEL)) {
3253 return BAD_VALUE;
3254 }
3255 AutoMutex lock(mLock);
3256 // inclusive of offloaded and direct tracks.
3257 //
3258 // It is possible, but not enabled, to allow duration computation for non-pcm
3259 // audio_has_proportional_frames() formats because currently they have
3260 // the drain rate equivalent to the pcm sample rate * framesize.
3261 if (!isPurePcmData_l()) {
3262 return INVALID_OPERATION;
3263 }
3264 ExtendedTimestamp ets;
3265 if (getTimestamp_l(&ets) == OK
3266 && ets.mTimeNs[location] > 0) {
3267 int64_t diff = ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT]
3268 - ets.mPosition[location];
3269 if (diff < 0) {
3270 *msec = 0;
3271 } else {
3272 // ms is the playback time by frames
3273 int64_t ms = (int64_t)((double)diff * 1000 /
3274 ((double)mSampleRate * mPlaybackRate.mSpeed));
3275 // clockdiff is the timestamp age (negative)
3276 int64_t clockdiff = (mState != STATE_ACTIVE) ? 0 :
3277 ets.mTimeNs[location]
3278 + ets.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_MONOTONIC]
3279 - systemTime(SYSTEM_TIME_MONOTONIC);
3280
3281 //ALOGV("ms: %lld clockdiff: %lld", (long long)ms, (long long)clockdiff);
3282 static const int NANOS_PER_MILLIS = 1000000;
3283 *msec = (int32_t)(ms + clockdiff / NANOS_PER_MILLIS);
3284 }
3285 return NO_ERROR;
3286 }
3287 if (location != ExtendedTimestamp::LOCATION_SERVER) {
3288 return INVALID_OPERATION; // LOCATION_KERNEL is not available
3289 }
3290 // use server position directly (offloaded and direct arrive here)
3291 updateAndGetPosition_l();
3292 int32_t diff = (Modulo<uint32_t>(mFramesWritten) - mPosition).signedValue();
3293 *msec = (diff <= 0) ? 0
3294 : (int32_t)((double)diff * 1000 / ((double)mSampleRate * mPlaybackRate.mSpeed));
3295 return NO_ERROR;
3296}
3297
Andy Hung65ffdfc2016-10-10 15:52:11 -07003298bool AudioTrack::hasStarted()
3299{
3300 AutoMutex lock(mLock);
3301 switch (mState) {
3302 case STATE_STOPPED:
3303 if (isOffloadedOrDirect_l()) {
3304 // check if we have started in the past to return true.
Andy Hungffa36952017-08-17 10:41:51 -07003305 return mStartFromZeroUs > 0;
Andy Hung65ffdfc2016-10-10 15:52:11 -07003306 }
3307 // A normal audio track may still be draining, so
3308 // check if stream has ended. This covers fasttrack position
3309 // instability and start/stop without any data written.
3310 if (mProxy->getStreamEndDone()) {
3311 return true;
3312 }
Chih-Hung Hsiehffe35582018-09-13 13:59:28 -07003313 FALLTHROUGH_INTENDED;
Andy Hung65ffdfc2016-10-10 15:52:11 -07003314 case STATE_ACTIVE:
3315 case STATE_STOPPING:
3316 break;
3317 case STATE_PAUSED:
3318 case STATE_PAUSED_STOPPING:
3319 case STATE_FLUSHED:
3320 return false; // we're not active
3321 default:
Eric Laurent973db022018-11-20 14:54:31 -08003322 LOG_ALWAYS_FATAL("%s(%d): Invalid mState in hasStarted(): %d", __func__, mPortId, mState);
Andy Hung65ffdfc2016-10-10 15:52:11 -07003323 break;
3324 }
3325
3326 // wait indicates whether we need to wait for a timestamp.
3327 // This is conservatively figured - if we encounter an unexpected error
3328 // then we will not wait.
3329 bool wait = false;
3330 if (isOffloadedOrDirect_l()) {
3331 AudioTimestamp ts;
3332 status_t status = getTimestamp_l(ts);
3333 if (status == WOULD_BLOCK) {
3334 wait = true;
3335 } else if (status == OK) {
3336 wait = (ts.mPosition == 0 || ts.mPosition == mStartTs.mPosition);
3337 }
Andy Hungfb8ede22018-09-12 19:03:24 -07003338 ALOGV("%s(%d): hasStarted wait:%d ts:%u start position:%lld",
Eric Laurent973db022018-11-20 14:54:31 -08003339 __func__, mPortId,
Andy Hung65ffdfc2016-10-10 15:52:11 -07003340 (int)wait,
3341 ts.mPosition,
3342 (long long)mStartTs.mPosition);
3343 } else {
3344 int location = ExtendedTimestamp::LOCATION_SERVER; // for ALOG
3345 ExtendedTimestamp ets;
3346 status_t status = getTimestamp_l(&ets);
3347 if (status == WOULD_BLOCK) { // no SERVER or KERNEL frame info in ets
3348 wait = true;
3349 } else if (status == OK) {
3350 for (location = ExtendedTimestamp::LOCATION_KERNEL;
3351 location >= ExtendedTimestamp::LOCATION_SERVER; --location) {
3352 if (ets.mTimeNs[location] < 0 || mStartEts.mTimeNs[location] < 0) {
3353 continue;
3354 }
3355 wait = ets.mPosition[location] == 0
3356 || ets.mPosition[location] == mStartEts.mPosition[location];
3357 break;
3358 }
3359 }
Andy Hungfb8ede22018-09-12 19:03:24 -07003360 ALOGV("%s(%d): hasStarted wait:%d ets:%lld start position:%lld",
Eric Laurent973db022018-11-20 14:54:31 -08003361 __func__, mPortId,
Andy Hung65ffdfc2016-10-10 15:52:11 -07003362 (int)wait,
3363 (long long)ets.mPosition[location],
3364 (long long)mStartEts.mPosition[location]);
3365 }
3366 return !wait;
3367}
3368
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003369// =========================================================================
3370
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08003371void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003372{
3373 sp<AudioTrack> audioTrack = mAudioTrack.promote();
3374 if (audioTrack != 0) {
3375 AutoMutex lock(audioTrack->mLock);
3376 audioTrack->mProxy->binderDied();
3377 }
3378}
3379
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003380// =========================================================================
3381
Andy Hungca353672019-03-06 11:54:38 -08003382AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver)
Andy Hungeb46cf92019-03-06 10:13:38 -08003383 : Thread(true /* bCanCallJava */) // binder recursion on restoreTrack_l() may call Java.
3384 , mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
Glenn Kasten598de6c2013-10-16 17:02:13 -07003385 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08003386{
3387}
3388
3389AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003390{
3391}
3392
3393bool AudioTrack::AudioTrackThread::threadLoop()
3394{
Glenn Kasten3acbd052012-02-28 10:39:56 -08003395 {
3396 AutoMutex _l(mMyLock);
3397 if (mPaused) {
Glenn Kasten75f79032017-05-23 11:22:44 -07003398 // TODO check return value and handle or log
Glenn Kasten3acbd052012-02-28 10:39:56 -08003399 mMyCond.wait(mMyLock);
3400 // caller will check for exitPending()
3401 return true;
3402 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07003403 if (mIgnoreNextPausedInt) {
3404 mIgnoreNextPausedInt = false;
3405 mPausedInt = false;
3406 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003407 if (mPausedInt) {
Glenn Kasten47d55172017-05-23 11:19:30 -07003408 // TODO use futex instead of condition, for event flag "or"
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003409 if (mPausedNs > 0) {
Glenn Kasten75f79032017-05-23 11:22:44 -07003410 // TODO check return value and handle or log
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003411 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
3412 } else {
Glenn Kasten75f79032017-05-23 11:22:44 -07003413 // TODO check return value and handle or log
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003414 mMyCond.wait(mMyLock);
3415 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07003416 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003417 return true;
3418 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08003419 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07003420 if (exitPending()) {
3421 return false;
3422 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08003423 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003424 switch (ns) {
3425 case 0:
3426 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003427 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003428 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003429 return true;
3430 case NS_NEVER:
3431 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003432 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08003433 // Event driven: call wake() when callback notifications conditions change.
3434 ns = INT64_MAX;
Chih-Hung Hsiehffe35582018-09-13 13:59:28 -07003435 FALLTHROUGH_INTENDED;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003436 default:
Andy Hungfb8ede22018-09-12 19:03:24 -07003437 LOG_ALWAYS_FATAL_IF(ns < 0, "%s(%d): processAudioBuffer() returned %lld",
Eric Laurent973db022018-11-20 14:54:31 -08003438 __func__, mReceiver.mPortId, (long long)ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003439 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003440 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07003441 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003442}
3443
Glenn Kasten3acbd052012-02-28 10:39:56 -08003444void AudioTrack::AudioTrackThread::requestExit()
3445{
3446 // must be in this order to avoid a race condition
3447 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07003448 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08003449}
3450
3451void AudioTrack::AudioTrackThread::pause()
3452{
3453 AutoMutex _l(mMyLock);
3454 mPaused = true;
3455}
3456
3457void AudioTrack::AudioTrackThread::resume()
3458{
3459 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07003460 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07003461 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08003462 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07003463 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08003464 mMyCond.signal();
3465 }
3466}
3467
Andy Hung3c09c782014-12-29 18:39:32 -08003468void AudioTrack::AudioTrackThread::wake()
3469{
3470 AutoMutex _l(mMyLock);
Andy Hunga8d08902015-07-22 11:52:13 -07003471 if (!mPaused) {
3472 // wake() might be called while servicing a callback - ignore the next
3473 // pause time and call processAudioBuffer.
Andy Hung3c09c782014-12-29 18:39:32 -08003474 mIgnoreNextPausedInt = true;
Andy Hunga8d08902015-07-22 11:52:13 -07003475 if (mPausedInt && mPausedNs > 0) {
3476 // audio track is active and internally paused with timeout.
3477 mPausedInt = false;
3478 mMyCond.signal();
3479 }
Andy Hung3c09c782014-12-29 18:39:32 -08003480 }
3481}
3482
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003483void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
3484{
3485 AutoMutex _l(mMyLock);
3486 mPausedInt = true;
3487 mPausedNs = ns;
3488}
3489
jiabinf6eb4c32020-02-25 14:06:25 -08003490binder::Status AudioTrack::AudioTrackCallback::onCodecFormatChanged(
3491 const std::vector<uint8_t>& audioMetadata)
3492{
3493 AutoMutex _l(mAudioTrackCbLock);
3494 sp<media::IAudioTrackCallback> callback = mCallback.promote();
3495 if (callback.get() != nullptr) {
3496 callback->onCodecFormatChanged(audioMetadata);
3497 } else {
3498 mCallback.clear();
3499 }
3500 return binder::Status::ok();
3501}
3502
3503void AudioTrack::AudioTrackCallback::setAudioTrackCallback(
3504 const sp<media::IAudioTrackCallback> &callback) {
3505 AutoMutex lock(mAudioTrackCbLock);
3506 mCallback = callback;
3507}
3508
Glenn Kasten40bc9062015-03-20 09:09:33 -07003509} // namespace android