blob: d2f714a2617d4eff1f02d665ce9bf447f703bfe7 [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
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080025#include <android/media/IAudioPolicyService.h>
Chih-Hung Hsiehffe35582018-09-13 13:59:28 -070026#include <android-base/macros.h>
Andy Hung2b01f002017-07-05 12:01:36 -070027#include <audio_utils/clock.h>
Glenn Kasten9f80dd22012-12-18 15:57:32 -080028#include <audio_utils/primitives.h>
29#include <binder/IPCThreadState.h>
30#include <media/AudioTrack.h>
31#include <utils/Log.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080032#include <private/media/AudioTrackShared.h>
Suren Baghdasaryan7435e7d2018-12-19 17:09:28 -080033#include <processgroup/sched_policy.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070034#include <media/IAudioFlinger.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
Kuowei Lid4adbdb2020-08-13 14:44:25 +080054using ::android::aidl_utils::statusTFromBinderStatus;
55
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080056namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080057// ---------------------------------------------------------------------------
58
Ivan Lozano8cf3a072017-08-09 09:01:33 -070059using media::VolumeShaper;
60
Andy Hunga7f03352015-05-31 21:54:49 -070061// TODO: Move to a separate .h
62
Andy Hung4ede21d2014-12-12 15:37:34 -080063template <typename T>
Andy Hunga7f03352015-05-31 21:54:49 -070064static inline const T &min(const T &x, const T &y) {
Andy Hung4ede21d2014-12-12 15:37:34 -080065 return x < y ? x : y;
66}
67
Andy Hunga7f03352015-05-31 21:54:49 -070068template <typename T>
69static inline const T &max(const T &x, const T &y) {
70 return x > y ? x : y;
71}
72
73static inline nsecs_t framesToNanoseconds(ssize_t frames, uint32_t sampleRate, float speed)
74{
75 return ((double)frames * 1000000000) / ((double)sampleRate * speed);
76}
77
Andy Hung7f1bc8a2014-09-12 14:43:11 -070078static int64_t convertTimespecToUs(const struct timespec &tv)
79{
Chih-Hung Hsieh50fa06c2018-12-11 13:51:36 -080080 return tv.tv_sec * 1000000LL + tv.tv_nsec / 1000;
Andy Hung7f1bc8a2014-09-12 14:43:11 -070081}
82
Andy Hungffa36952017-08-17 10:41:51 -070083// TODO move to audio_utils.
84static inline struct timespec convertNsToTimespec(int64_t ns) {
85 struct timespec tv;
86 tv.tv_sec = static_cast<time_t>(ns / NANOS_PER_SECOND);
Andy Hung06a730b2020-04-09 13:28:31 -070087 tv.tv_nsec = static_cast<int64_t>(ns % NANOS_PER_SECOND);
Andy Hungffa36952017-08-17 10:41:51 -070088 return tv;
89}
90
Andy Hung7f1bc8a2014-09-12 14:43:11 -070091// current monotonic time in microseconds.
92static int64_t getNowUs()
93{
94 struct timespec tv;
95 (void) clock_gettime(CLOCK_MONOTONIC, &tv);
96 return convertTimespecToUs(tv);
97}
98
Andy Hung26145642015-04-15 21:56:53 -070099// FIXME: we don't use the pitch setting in the time stretcher (not working);
100// instead we emulate it using our sample rate converter.
101static const bool kFixPitch = true; // enable pitch fix
102static inline uint32_t adjustSampleRate(uint32_t sampleRate, float pitch)
103{
104 return kFixPitch ? (sampleRate * pitch + 0.5) : sampleRate;
105}
106
107static inline float adjustSpeed(float speed, float pitch)
108{
Ricardo Garcia6c7f0622015-04-30 18:39:16 -0700109 return kFixPitch ? speed / max(pitch, AUDIO_TIMESTRETCH_PITCH_MIN_DELTA) : speed;
Andy Hung26145642015-04-15 21:56:53 -0700110}
111
112static inline float adjustPitch(float pitch)
113{
114 return kFixPitch ? AUDIO_TIMESTRETCH_PITCH_NORMAL : pitch;
115}
116
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800117// static
118status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -0800119 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800120 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800121 uint32_t sampleRate)
122{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700123 if (frameCount == NULL) {
124 return BAD_VALUE;
125 }
Glenn Kasten04cd0182012-06-25 11:49:27 -0700126
Andy Hung0e48d252015-01-26 11:43:15 -0800127 // FIXME handle in server, like createTrack_l(), possible missing info:
Glenn Kastene0fa4672012-04-24 14:35:14 -0700128 // audio_io_handle_t output
129 // audio_format_t format
130 // audio_channel_mask_t channelMask
Andy Hung0e48d252015-01-26 11:43:15 -0800131 // audio_output_flags_t flags (FAST)
Glenn Kasten3b16c762012-11-14 08:44:39 -0800132 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -0800133 status_t status;
134 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
135 if (status != NO_ERROR) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700136 ALOGE("%s(): Unable to query output sample rate for stream type %d; status %d",
137 __func__, streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800138 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800139 }
Glenn Kastene33054e2012-11-14 12:54:39 -0800140 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -0800141 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
142 if (status != NO_ERROR) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700143 ALOGE("%s(): Unable to query output frame count for stream type %d; status %d",
144 __func__, streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800145 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800146 }
147 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -0800148 status = AudioSystem::getOutputLatency(&afLatency, streamType);
149 if (status != NO_ERROR) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700150 ALOGE("%s(): Unable to query output latency for stream type %d; status %d",
151 __func__, streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800152 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800153 }
154
Andy Hung8edb8dc2015-03-26 19:13:55 -0700155 // When called from createTrack, speed is 1.0f (normal speed).
156 // This is rechecked again on setting playback rate (TODO: on setting sample rate, too).
Eric Laurent21da6472017-11-09 16:29:26 -0800157 *frameCount = AudioSystem::calculateMinFrameCount(afLatency, afFrameCount, afSampleRate,
158 sampleRate, 1.0f /*, 0 notificationsPerBufferReq*/);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800159
Andy Hung0e48d252015-01-26 11:43:15 -0800160 // The formula above should always produce a non-zero value under normal circumstances:
161 // AudioTrack.SAMPLE_RATE_HZ_MIN <= sampleRate <= AudioTrack.SAMPLE_RATE_HZ_MAX.
162 // 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 -0800163 if (*frameCount == 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700164 ALOGE("%s(): failed for streamType %d, sampleRate %u",
165 __func__, streamType, sampleRate);
Glenn Kasten66a04672014-01-08 08:53:44 -0800166 return BAD_VALUE;
167 }
Andy Hungfb8ede22018-09-12 19:03:24 -0700168 ALOGV("%s(): getMinFrameCount=%zu: afFrameCount=%zu, afSampleRate=%u, afLatency=%u",
169 __func__, *frameCount, afFrameCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800170 return NO_ERROR;
171}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800172
Michael Chana94fbb22018-04-24 14:31:19 +1000173// static
174bool AudioTrack::isDirectOutputSupported(const audio_config_base_t& config,
175 const audio_attributes_t& attributes) {
176 ALOGV("%s()", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800177 const sp<media::IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
Michael Chana94fbb22018-04-24 14:31:19 +1000178 if (aps == 0) return false;
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800179
180 auto result = [&]() -> ConversionResult<bool> {
181 media::AudioConfigBase configAidl = VALUE_OR_RETURN(
182 legacy2aidl_audio_config_base_t_AudioConfigBase(config));
183 media::AudioAttributesInternal attributesAidl = VALUE_OR_RETURN(
184 legacy2aidl_audio_attributes_t_AudioAttributesInternal(attributes));
185 bool retAidl;
186 RETURN_IF_ERROR(aidl_utils::statusTFromBinderStatus(
187 aps->isDirectOutputSupported(configAidl, attributesAidl, &retAidl)));
188 return retAidl;
189 }();
190 return result.value_or(false);
Michael Chana94fbb22018-04-24 14:31:19 +1000191}
192
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800193// ---------------------------------------------------------------------------
194
Ray Essicked304702017-12-12 14:00:57 -0800195void AudioTrack::MediaMetrics::gather(const AudioTrack *track)
196{
Ray Essick88394302018-01-24 14:52:05 -0800197 // only if we're in a good state...
198 // XXX: shall we gather alternative info if failing?
199 const status_t lstatus = track->initCheck();
200 if (lstatus != NO_ERROR) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700201 ALOGD("%s(): no metrics gathered, track status=%d", __func__, (int) lstatus);
Ray Essick88394302018-01-24 14:52:05 -0800202 return;
203 }
204
Andy Hungd0979812019-02-21 15:51:44 -0800205#define MM_PREFIX "android.media.audiotrack." // avoid cut-n-paste errors.
Ray Essicked304702017-12-12 14:00:57 -0800206
Andy Hungd0979812019-02-21 15:51:44 -0800207 // Java API 28 entries, do not change.
Ray Essickf27e9872019-12-07 06:28:46 -0800208 mMetricsItem->setCString(MM_PREFIX "streamtype", toString(track->streamType()).c_str());
209 mMetricsItem->setCString(MM_PREFIX "type",
Andy Hungd0979812019-02-21 15:51:44 -0800210 toString(track->mAttributes.content_type).c_str());
Ray Essickf27e9872019-12-07 06:28:46 -0800211 mMetricsItem->setCString(MM_PREFIX "usage", toString(track->mAttributes.usage).c_str());
Ray Essicked304702017-12-12 14:00:57 -0800212
Andy Hungd0979812019-02-21 15:51:44 -0800213 // Non-API entries, these can change due to a Java string mistake.
Ray Essickf27e9872019-12-07 06:28:46 -0800214 mMetricsItem->setInt32(MM_PREFIX "sampleRate", (int32_t)track->mSampleRate);
215 mMetricsItem->setInt64(MM_PREFIX "channelMask", (int64_t)track->mChannelMask);
Andy Hungd0979812019-02-21 15:51:44 -0800216 // Non-API entries, these can change.
Ray Essickf27e9872019-12-07 06:28:46 -0800217 mMetricsItem->setInt32(MM_PREFIX "portId", (int32_t)track->mPortId);
218 mMetricsItem->setCString(MM_PREFIX "encoding", toString(track->mFormat).c_str());
219 mMetricsItem->setInt32(MM_PREFIX "frameCount", (int32_t)track->mFrameCount);
220 mMetricsItem->setCString(MM_PREFIX "attributes", toString(track->mAttributes).c_str());
Andy Hung6f451f02021-02-24 21:53:29 -0800221 mMetricsItem->setCString(MM_PREFIX "logSessionId", track->mLogSessionId.c_str());
Ray Essicked304702017-12-12 14:00:57 -0800222}
223
Ray Essick88394302018-01-24 14:52:05 -0800224// hand the user a snapshot of the metrics.
Ray Essickf27e9872019-12-07 06:28:46 -0800225status_t AudioTrack::getMetrics(mediametrics::Item * &item)
Ray Essick88394302018-01-24 14:52:05 -0800226{
227 mMediaMetrics.gather(this);
Ray Essickf27e9872019-12-07 06:28:46 -0800228 mediametrics::Item *tmp = mMediaMetrics.dup();
Ray Essick88394302018-01-24 14:52:05 -0800229 if (tmp == nullptr) {
230 return BAD_VALUE;
231 }
232 item = tmp;
233 return NO_ERROR;
234}
Ray Essicked304702017-12-12 14:00:57 -0800235
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000236AudioTrack::AudioTrack() : AudioTrack("" /*opPackageName*/)
237{
238}
239
240AudioTrack::AudioTrack(const std::string& opPackageName)
Glenn Kasten87913512011-06-22 16:15:25 -0700241 : mStatus(NO_INIT),
Haynes Mathew George9b3359f2016-03-23 19:09:10 -0700242 mState(STATE_STOPPED),
John Grossman4ff14ba2012-02-08 16:37:41 -0800243 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800244 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700245 mPausedPosition(0),
Eric Laurent20b9ef02016-12-05 11:03:16 -0800246 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabinf6eb4c32020-02-25 14:06:25 -0800247 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000248 mOpPackageName(opPackageName),
jiabinf6eb4c32020-02-25 14:06:25 -0800249 mAudioTrackCallback(new AudioTrackCallback())
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800250{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700251 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
252 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
Mikhail Naganov55773032020-10-01 15:08:13 -0700253 mAttributes.flags = AUDIO_FLAG_NONE;
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700254 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800255}
256
257AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800258 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800259 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800260 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700261 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800262 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700263 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800264 callback_t cbf,
265 void* user,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700266 int32_t notificationFrames,
Glenn Kastend848eb42016-03-08 13:42:11 -0800267 audio_session_t sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000268 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800269 const audio_offload_info_t *offloadInfo,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800270 uid_t uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700271 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700272 const audio_attributes_t* pAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -0700273 bool doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -0700274 float maxRequiredSpeed,
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000275 audio_port_handle_t selectedDeviceId,
276 const std::string& opPackageName)
Glenn Kasten87913512011-06-22 16:15:25 -0700277 : mStatus(NO_INIT),
Haynes Mathew George9b3359f2016-03-23 19:09:10 -0700278 mState(STATE_STOPPED),
John Grossman4ff14ba2012-02-08 16:37:41 -0800279 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800280 mPreviousSchedulingGroup(SP_DEFAULT),
jiabinf6eb4c32020-02-25 14:06:25 -0800281 mPausedPosition(0),
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000282 mOpPackageName(opPackageName),
jiabinf6eb4c32020-02-25 14:06:25 -0800283 mAudioTrackCallback(new AudioTrackCallback())
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800284{
François Gaffie393f0e02019-04-10 09:09:08 +0200285 mAttributes = AUDIO_ATTRIBUTES_INITIALIZER;
Ippei Murata5fa32ed2018-10-01 17:37:50 +0900286
Eric Laurentf32d7812017-11-30 14:44:07 -0800287 (void)set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700288 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800289 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
jiabin156c6872017-10-06 09:47:15 -0700290 offloadInfo, uid, pid, pAttributes, doNotReconnect, maxRequiredSpeed, selectedDeviceId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800291}
292
Andreas Huberc8139852012-01-18 10:51:55 -0800293AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800294 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800295 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800296 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700297 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800298 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700299 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800300 callback_t cbf,
301 void* user,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700302 int32_t notificationFrames,
Glenn Kastend848eb42016-03-08 13:42:11 -0800303 audio_session_t sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000304 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800305 const audio_offload_info_t *offloadInfo,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800306 uid_t uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700307 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700308 const audio_attributes_t* pAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -0700309 bool doNotReconnect,
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000310 float maxRequiredSpeed,
311 const std::string& opPackageName)
Glenn Kasten87913512011-06-22 16:15:25 -0700312 : mStatus(NO_INIT),
Haynes Mathew George9b3359f2016-03-23 19:09:10 -0700313 mState(STATE_STOPPED),
John Grossman4ff14ba2012-02-08 16:37:41 -0800314 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800315 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700316 mPausedPosition(0),
jiabinf6eb4c32020-02-25 14:06:25 -0800317 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000318 mOpPackageName(opPackageName),
jiabinf6eb4c32020-02-25 14:06:25 -0800319 mAudioTrackCallback(new AudioTrackCallback())
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800320{
François Gaffie393f0e02019-04-10 09:09:08 +0200321 mAttributes = AUDIO_ATTRIBUTES_INITIALIZER;
Ippei Murata5fa32ed2018-10-01 17:37:50 +0900322
Eric Laurentf32d7812017-11-30 14:44:07 -0800323 (void)set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800324 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800325 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Andy Hungff874dc2016-04-11 16:49:09 -0700326 uid, pid, pAttributes, doNotReconnect, maxRequiredSpeed);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800327}
328
329AudioTrack::~AudioTrack()
330{
Ray Essicked304702017-12-12 14:00:57 -0800331 // pull together the numbers, before we clean up our structures
332 mMediaMetrics.gather(this);
333
Andy Hungb68f5eb2019-12-03 16:49:17 -0800334 mediametrics::LogItem(mMetricsId)
335 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DTOR)
Phil Burkd3813f32020-04-23 16:26:15 -0700336 .set(AMEDIAMETRICS_PROP_CALLERNAME,
337 mCallerName.empty()
Andy Hunga6b27032020-04-27 10:34:24 -0700338 ? AMEDIAMETRICS_PROP_CALLERNAME_VALUE_UNKNOWN
Phil Burkd3813f32020-04-23 16:26:15 -0700339 : mCallerName.c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -0800340 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
341 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)mStatus)
342 .record();
343
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800344 if (mStatus == NO_ERROR) {
345 // Make sure that callback function exits in the case where
346 // it is looping on buffer full condition in obtainBuffer().
347 // Otherwise the callback thread will never exit.
348 stop();
349 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100350 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800351 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800352 mAudioTrackThread->requestExitAndWait();
353 mAudioTrackThread.clear();
354 }
Eric Laurent296fb132015-05-01 11:38:42 -0700355 // No lock here: worst case we remove a NULL callback which will be a nop
356 if (mDeviceCallback != 0 && mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent09f1ed22019-04-24 17:45:17 -0700357 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -0700358 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800359 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700360 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700361 mCblkMemory.clear();
362 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800363 IPCThreadState::self()->flushCommands();
Andy Hungfb8ede22018-09-12 19:03:24 -0700364 ALOGV("%s(%d), releasing session id %d from %d on behalf of %d",
Eric Laurent973db022018-11-20 14:54:31 -0800365 __func__, mPortId,
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700366 mSessionId, IPCThreadState::self()->getCallingPid(), mClientPid);
Marco Nelissend457c972014-02-11 08:47:07 -0800367 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800368 }
369}
370
371status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800372 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800373 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800374 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700375 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800376 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700377 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800378 callback_t cbf,
379 void* user,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700380 int32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800381 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700382 bool threadCanCallJava,
Glenn Kastend848eb42016-03-08 13:42:11 -0800383 audio_session_t sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000384 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800385 const audio_offload_info_t *offloadInfo,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800386 uid_t uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700387 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700388 const audio_attributes_t* pAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -0700389 bool doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -0700390 float maxRequiredSpeed,
391 audio_port_handle_t selectedDeviceId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800392{
Eric Laurentf32d7812017-11-30 14:44:07 -0800393 status_t status;
394 uint32_t channelCount;
395 pid_t callingPid;
396 pid_t myPid;
397
Eric Laurent973db022018-11-20 14:54:31 -0800398 // Note mPortId is not valid until the track is created, so omit mPortId in ALOG for set.
Andy Hungfb8ede22018-09-12 19:03:24 -0700399 ALOGV("%s(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kastenea38ee72016-04-18 11:08:01 -0700400 "flags #%x, notificationFrames %d, sessionId %d, transferType %d, uid %d, pid %d",
Andy Hungfb8ede22018-09-12 19:03:24 -0700401 __func__,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800402 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700403 sessionId, transferType, uid, pid);
Glenn Kasten86f04662014-02-24 15:13:05 -0800404
Phil Burk33ff89b2015-11-30 11:16:01 -0800405 mThreadCanCallJava = threadCanCallJava;
jiabin156c6872017-10-06 09:47:15 -0700406 mSelectedDeviceId = selectedDeviceId;
Eric Laurent21da6472017-11-09 16:29:26 -0800407 mSessionId = sessionId;
Phil Burk33ff89b2015-11-30 11:16:01 -0800408
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800409 switch (transferType) {
410 case TRANSFER_DEFAULT:
411 if (sharedBuffer != 0) {
412 transferType = TRANSFER_SHARED;
413 } else if (cbf == NULL || threadCanCallJava) {
414 transferType = TRANSFER_SYNC;
415 } else {
416 transferType = TRANSFER_CALLBACK;
417 }
418 break;
419 case TRANSFER_CALLBACK:
Jean-Michel Trivif4158d82018-09-25 12:43:58 -0700420 case TRANSFER_SYNC_NOTIF_CALLBACK:
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800421 if (cbf == NULL || sharedBuffer != 0) {
Jean-Michel Trivif4158d82018-09-25 12:43:58 -0700422 ALOGE("%s(): Transfer type %s but cbf == NULL || sharedBuffer != 0",
423 convertTransferToText(transferType), __func__);
Eric Laurentf32d7812017-11-30 14:44:07 -0800424 status = BAD_VALUE;
425 goto exit;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800426 }
427 break;
428 case TRANSFER_OBTAIN:
429 case TRANSFER_SYNC:
430 if (sharedBuffer != 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700431 ALOGE("%s(): Transfer type TRANSFER_OBTAIN but sharedBuffer != 0", __func__);
Eric Laurentf32d7812017-11-30 14:44:07 -0800432 status = BAD_VALUE;
433 goto exit;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800434 }
435 break;
436 case TRANSFER_SHARED:
437 if (sharedBuffer == 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700438 ALOGE("%s(): Transfer type TRANSFER_SHARED but sharedBuffer == 0", __func__);
Eric Laurentf32d7812017-11-30 14:44:07 -0800439 status = BAD_VALUE;
440 goto exit;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800441 }
442 break;
443 default:
Andy Hungfb8ede22018-09-12 19:03:24 -0700444 ALOGE("%s(): Invalid transfer type %d",
445 __func__, transferType);
Eric Laurentf32d7812017-11-30 14:44:07 -0800446 status = BAD_VALUE;
447 goto exit;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800448 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800449 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800450 mTransfer = transferType;
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700451 mDoNotReconnect = doNotReconnect;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800452
Andy Hungfb8ede22018-09-12 19:03:24 -0700453 ALOGV_IF(sharedBuffer != 0, "%s(): sharedBuffer: %p, size: %zu",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700454 __func__, sharedBuffer->unsecurePointer(), sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800455
Andy Hungfb8ede22018-09-12 19:03:24 -0700456 ALOGV("%s(): streamType %d frameCount %zu flags %04x",
457 __func__, streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700458
Glenn Kasten53cec222013-08-29 09:01:02 -0700459 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700460 if (mAudioTrack != 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700461 ALOGE("%s(): Track already in use", __func__);
Eric Laurentf32d7812017-11-30 14:44:07 -0800462 status = INVALID_OPERATION;
463 goto exit;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800464 }
465
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800466 // handle default values first.
Eric Laurente83b55d2014-11-14 10:06:21 -0800467 if (streamType == AUDIO_STREAM_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700468 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800469 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700470 if (pAttributes == NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800471 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700472 ALOGE("%s(): Invalid stream type %d", __func__, streamType);
Eric Laurentf32d7812017-11-30 14:44:07 -0800473 status = BAD_VALUE;
474 goto exit;
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700475 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700476 mStreamType = streamType;
Eric Laurente83b55d2014-11-14 10:06:21 -0800477
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700478 } else {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700479 // stream type shouldn't be looked at, this track has audio attributes
480 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Andy Hungfb8ede22018-09-12 19:03:24 -0700481 ALOGV("%s(): Building AudioTrack with attributes:"
482 " usage=%d content=%d flags=0x%x tags=[%s]",
483 __func__,
484 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800485 mStreamType = AUDIO_STREAM_DEFAULT;
François Gaffie58d4be52018-11-06 15:30:12 +0100486 audio_flags_to_audio_output_flags(mAttributes.flags, &flags);
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800487 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700488
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800489 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800490 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700491 format = AUDIO_FORMAT_PCM_16_BIT;
Phil Burkfdb3c072016-02-09 10:47:02 -0800492 } else if (format == AUDIO_FORMAT_IEC61937) { // HDMI pass-through?
Mikhail Naganov55773032020-10-01 15:08:13 -0700493 flags = static_cast<audio_output_flags_t>(flags | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800494 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800495
496 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700497 if (!audio_is_valid_format(format)) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700498 ALOGE("%s(): Invalid format %#x", __func__, format);
Eric Laurentf32d7812017-11-30 14:44:07 -0800499 status = BAD_VALUE;
500 goto exit;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800501 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800502 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700503
Glenn Kasten8ba90322013-10-30 11:29:27 -0700504 if (!audio_is_output_channel(channelMask)) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700505 ALOGE("%s(): Invalid channel mask %#x", __func__, channelMask);
Eric Laurentf32d7812017-11-30 14:44:07 -0800506 status = BAD_VALUE;
507 goto exit;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700508 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800509 mChannelMask = channelMask;
Eric Laurentf32d7812017-11-30 14:44:07 -0800510 channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800511 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700512
Eric Laurentc2f1f072009-07-17 12:17:14 -0700513 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100514 // or offload was requested
515 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
516 || !audio_is_linear_pcm(format)) {
517 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
Andy Hungfb8ede22018-09-12 19:03:24 -0700518 ? "%s(): Offload request, forcing to Direct Output"
519 : "%s(): Not linear PCM, forcing to Direct Output",
520 __func__);
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700521 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800522 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700523 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700524 }
525
Eric Laurentd1f69b02014-12-15 14:33:13 -0800526 // force direct flag if HW A/V sync requested
527 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
528 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
529 }
530
Glenn Kastenb7730382014-04-30 15:50:31 -0700531 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Phil Burkfdb3c072016-02-09 10:47:02 -0800532 if (audio_has_proportional_frames(format)) {
Glenn Kastenb7730382014-04-30 15:50:31 -0700533 mFrameSize = channelCount * audio_bytes_per_sample(format);
534 } else {
535 mFrameSize = sizeof(uint8_t);
536 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800537 } else {
Phil Burkfdb3c072016-02-09 10:47:02 -0800538 ALOG_ASSERT(audio_has_proportional_frames(format));
Glenn Kastenb7730382014-04-30 15:50:31 -0700539 mFrameSize = channelCount * audio_bytes_per_sample(format);
Glenn Kastenb7730382014-04-30 15:50:31 -0700540 // createTrack will return an error if PCM format is not supported by server,
541 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800542 }
543
Eric Laurent0d6db582014-11-12 18:39:44 -0800544 // sampling rate must be specified for direct outputs
545 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentf32d7812017-11-30 14:44:07 -0800546 status = BAD_VALUE;
547 goto exit;
Eric Laurent0d6db582014-11-12 18:39:44 -0800548 }
549 mSampleRate = sampleRate;
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700550 mOriginalSampleRate = sampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700551 mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT;
Andy Hungff874dc2016-04-11 16:49:09 -0700552 // 1.0 <= mMaxRequiredSpeed <= AUDIO_TIMESTRETCH_SPEED_MAX
553 mMaxRequiredSpeed = min(max(maxRequiredSpeed, 1.0f), AUDIO_TIMESTRETCH_SPEED_MAX);
Eric Laurent0d6db582014-11-12 18:39:44 -0800554
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800555 // Make copy of input parameter offloadInfo so that in the future:
556 // (a) createTrack_l doesn't need it as an input parameter
557 // (b) we can support re-creation of offloaded tracks
558 if (offloadInfo != NULL) {
559 mOffloadInfoCopy = *offloadInfo;
560 mOffloadInfo = &mOffloadInfoCopy;
561 } else {
562 mOffloadInfo = NULL;
Eric Laurent20b9ef02016-12-05 11:03:16 -0800563 memset(&mOffloadInfoCopy, 0, sizeof(audio_offload_info_t));
Ytai Ben-Tsviffa2fd92020-10-20 09:13:53 -0700564 mOffloadInfoCopy = AUDIO_INFO_INITIALIZER;
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800565 }
566
Glenn Kasten66e46352014-01-16 17:44:23 -0800567 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
568 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800569 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800570 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800571 mReqFrameCount = frameCount;
Glenn Kastenea38ee72016-04-18 11:08:01 -0700572 if (notificationFrames >= 0) {
573 mNotificationFramesReq = notificationFrames;
574 mNotificationsPerBufferReq = 0;
575 } else {
576 if (!(flags & AUDIO_OUTPUT_FLAG_FAST)) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700577 ALOGE("%s(): notificationFrames=%d not permitted for non-fast track",
578 __func__, notificationFrames);
Eric Laurentf32d7812017-11-30 14:44:07 -0800579 status = BAD_VALUE;
580 goto exit;
Glenn Kastenea38ee72016-04-18 11:08:01 -0700581 }
582 if (frameCount > 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700583 ALOGE("%s(): notificationFrames=%d not permitted with non-zero frameCount=%zu",
584 __func__, notificationFrames, frameCount);
Eric Laurentf32d7812017-11-30 14:44:07 -0800585 status = BAD_VALUE;
586 goto exit;
Glenn Kastenea38ee72016-04-18 11:08:01 -0700587 }
588 mNotificationFramesReq = 0;
589 const uint32_t minNotificationsPerBuffer = 1;
590 const uint32_t maxNotificationsPerBuffer = 8;
591 mNotificationsPerBufferReq = min(maxNotificationsPerBuffer,
592 max((uint32_t) -notificationFrames, minNotificationsPerBuffer));
593 ALOGW_IF(mNotificationsPerBufferReq != (uint32_t) -notificationFrames,
Andy Hungfb8ede22018-09-12 19:03:24 -0700594 "%s(): notificationFrames=%d clamped to the range -%u to -%u",
595 __func__,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700596 notificationFrames, minNotificationsPerBuffer, maxNotificationsPerBuffer);
597 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800598 mNotificationFramesAct = 0;
Eric Laurentf32d7812017-11-30 14:44:07 -0800599 callingPid = IPCThreadState::self()->getCallingPid();
600 myPid = getpid();
601 if (uid == AUDIO_UID_INVALID || (callingPid != myPid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800602 mClientUid = IPCThreadState::self()->getCallingUid();
603 } else {
604 mClientUid = uid;
605 }
Eric Laurentf32d7812017-11-30 14:44:07 -0800606 if (pid == -1 || (callingPid != myPid)) {
607 mClientPid = callingPid;
Marco Nelissend457c972014-02-11 08:47:07 -0800608 } else {
609 mClientPid = pid;
610 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700611 mAuxEffectId = 0;
Haynes Mathew Georgeae34ed22016-01-28 11:58:39 -0800612 mOrigFlags = mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700613 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700614
Glenn Kastena997e7a2012-08-07 09:44:19 -0700615 if (cbf != NULL) {
Andy Hungca353672019-03-06 11:54:38 -0800616 mAudioTrackThread = new AudioTrackThread(*this);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700617 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
Glenn Kastenbfd31842015-03-20 09:01:44 -0700618 // thread begins in paused state, and will not reference us until start()
Glenn Kastena997e7a2012-08-07 09:44:19 -0700619 }
620
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800621 // create the IAudioTrack
Francois Gaffie24a9fb02019-01-18 17:51:34 +0100622 {
623 AutoMutex lock(mLock);
624 status = createTrack_l();
625 }
Glenn Kastena997e7a2012-08-07 09:44:19 -0700626 if (status != NO_ERROR) {
627 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100628 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
629 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700630 mAudioTrackThread.clear();
631 }
Eric Laurentf32d7812017-11-30 14:44:07 -0800632 goto exit;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700633 }
634
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800635 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800636 mLoopCount = 0;
637 mLoopStart = 0;
638 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800639 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800640 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700641 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800642 mNewPosition = 0;
643 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700644 mPosition = 0;
645 mReleased = 0;
Andy Hungffa36952017-08-17 10:41:51 -0700646 mStartNs = 0;
647 mStartFromZeroUs = 0;
Andy Hung8b0bfd92019-12-23 13:11:11 -0800648 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid, mClientUid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800649 mSequence = 1;
650 mObservedSequence = mSequence;
651 mInUnderrun = false;
Phil Burk1b420972015-04-22 10:52:21 -0700652 mPreviousTimestampValid = false;
Andy Hungc8e09c62015-06-03 23:43:36 -0700653 mTimestampStartupGlitchReported = false;
Andy Hungcf3b7152019-04-19 18:29:21 -0700654 mTimestampRetrogradePositionReported = false;
655 mTimestampRetrogradeTimeReported = false;
656 mTimestampStallReported = false;
657 mTimestampStaleTimeReported = false;
Andy Hungb01faa32016-04-27 12:51:32 -0700658 mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
Andy Hung65ffdfc2016-10-10 15:52:11 -0700659 mStartTs.mPosition = 0;
Phil Burk2812d9e2016-01-04 10:34:30 -0800660 mUnderrunCountOffset = 0;
Andy Hungea2b9c02016-02-12 17:06:53 -0800661 mFramesWritten = 0;
662 mFramesWrittenServerOffset = 0;
Andy Hungf20a4e92016-08-15 19:10:34 -0700663 mFramesWrittenAtRestore = -1; // -1 is a unique initializer.
Ivan Lozano8cf3a072017-08-09 09:01:33 -0700664 mVolumeHandler = new media::VolumeHandler();
Eric Laurentf32d7812017-11-30 14:44:07 -0800665
666exit:
667 mStatus = status;
668 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800669}
670
Mikhail Naganov55773032020-10-01 15:08:13 -0700671
672status_t AudioTrack::set(
673 audio_stream_type_t streamType,
674 uint32_t sampleRate,
675 audio_format_t format,
676 uint32_t channelMask,
677 size_t frameCount,
678 audio_output_flags_t flags,
679 callback_t cbf,
680 void* user,
681 int32_t notificationFrames,
682 const sp<IMemory>& sharedBuffer,
683 bool threadCanCallJava,
684 audio_session_t sessionId,
685 transfer_type transferType,
686 const audio_offload_info_t *offloadInfo,
687 uid_t uid,
688 pid_t pid,
689 const audio_attributes_t* pAttributes,
690 bool doNotReconnect,
691 float maxRequiredSpeed,
692 audio_port_handle_t selectedDeviceId)
693{
694 return set(streamType, sampleRate, format,
695 static_cast<audio_channel_mask_t>(channelMask),
696 frameCount, flags, cbf, user, notificationFrames, sharedBuffer,
697 threadCanCallJava, sessionId, transferType, offloadInfo, uid, pid,
698 pAttributes, doNotReconnect, maxRequiredSpeed, selectedDeviceId);
699}
700
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800701// -------------------------------------------------------------------------
702
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100703status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800704{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800705 AutoMutex lock(mLock);
Andy Hungb68f5eb2019-12-03 16:49:17 -0800706
Andy Hung10fb4be2020-05-27 22:22:22 -0700707 if (mState == STATE_ACTIVE) {
708 return INVALID_OPERATION;
709 }
710
711 ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
712
713 // Defer logging here due to OpenSL ES repeated start calls.
714 // TODO(b/154868033) after fix, restore this logging back to the beginning of start().
715 const int64_t beginNs = systemTime();
Andy Hungb68f5eb2019-12-03 16:49:17 -0800716 status_t status = NO_ERROR; // logged: make sure to set this before returning.
Andy Hung06a730b2020-04-09 13:28:31 -0700717 mediametrics::Defer defer([&] {
Andy Hungb68f5eb2019-12-03 16:49:17 -0800718 mediametrics::LogItem(mMetricsId)
Andy Hunga6b27032020-04-27 10:34:24 -0700719 .set(AMEDIAMETRICS_PROP_CALLERNAME,
720 mCallerName.empty()
721 ? AMEDIAMETRICS_PROP_CALLERNAME_VALUE_UNKNOWN
722 : mCallerName.c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -0800723 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_START)
Andy Hungea840382020-05-05 21:50:17 -0700724 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
Andy Hungb68f5eb2019-12-03 16:49:17 -0800725 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
726 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)status)
727 .record(); });
728
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800729
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800730 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800731
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800732 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100733 if (previousState == STATE_PAUSED_STOPPING) {
734 mState = STATE_STOPPING;
735 } else {
736 mState = STATE_ACTIVE;
737 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700738 (void) updateAndGetPosition_l();
Andy Hung65ffdfc2016-10-10 15:52:11 -0700739
740 // save start timestamp
741 if (isOffloadedOrDirect_l()) {
742 if (getTimestamp_l(mStartTs) != OK) {
743 mStartTs.mPosition = 0;
744 }
745 } else {
746 if (getTimestamp_l(&mStartEts) != OK) {
747 mStartEts.clear();
748 }
749 }
Andy Hungffa36952017-08-17 10:41:51 -0700750 mStartNs = systemTime(); // save this for timestamp adjustment after starting.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800751 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
752 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700753 mPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -0700754 mPreviousTimestampValid = false;
Andy Hungc8e09c62015-06-03 23:43:36 -0700755 mTimestampStartupGlitchReported = false;
Andy Hungcf3b7152019-04-19 18:29:21 -0700756 mTimestampRetrogradePositionReported = false;
757 mTimestampRetrogradeTimeReported = false;
758 mTimestampStallReported = false;
759 mTimestampStaleTimeReported = false;
Andy Hungb01faa32016-04-27 12:51:32 -0700760 mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
Phil Burk1b420972015-04-22 10:52:21 -0700761
Andy Hung65ffdfc2016-10-10 15:52:11 -0700762 if (!isOffloadedOrDirect_l()
763 && mStartEts.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] > 0) {
Andy Hunge1e98462016-04-12 10:18:51 -0700764 // Server side has consumed something, but is it finished consuming?
765 // It is possible since flush and stop are asynchronous that the server
766 // is still active at this point.
Andy Hungfb8ede22018-09-12 19:03:24 -0700767 ALOGV("%s(%d): server read:%lld cumulative flushed:%lld client written:%lld",
Eric Laurent973db022018-11-20 14:54:31 -0800768 __func__, mPortId,
Andy Hunge1e98462016-04-12 10:18:51 -0700769 (long long)(mFramesWrittenServerOffset
Andy Hung65ffdfc2016-10-10 15:52:11 -0700770 + mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER]),
771 (long long)mStartEts.mFlushed,
Andy Hunge1e98462016-04-12 10:18:51 -0700772 (long long)mFramesWritten);
Andy Hungc4e60eb2017-09-06 11:14:57 -0700773 // mStartEts is already adjusted by mFramesWrittenServerOffset, so we delta adjust.
774 mFramesWrittenServerOffset -= mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung61be8412015-10-06 10:51:09 -0700775 }
Andy Hunge1e98462016-04-12 10:18:51 -0700776 mFramesWritten = 0;
777 mProxy->clearTimestamp(); // need new server push for valid timestamp
778 mMarkerReached = false;
Andy Hung61be8412015-10-06 10:51:09 -0700779
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700780 // For offloaded tracks, we don't know if the hardware counters are really zero here,
781 // since the flush is asynchronous and stop may not fully drain.
782 // We save the time when the track is started to later verify whether
783 // the counters are realistic (i.e. start from zero after this time).
Andy Hungffa36952017-08-17 10:41:51 -0700784 mStartFromZeroUs = mStartNs / 1000;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700785
Eric Laurentec9a0322013-08-28 10:23:01 -0700786 // force refresh of remaining frames by processAudioBuffer() as last
787 // write before stop could be partial.
788 mRefreshRemaining = true;
Tomoharu Kasahara6e8bf982017-06-09 16:17:33 +0900789
790 // for static track, clear the old flags when starting from stopped state
791 if (mSharedBuffer != 0) {
792 android_atomic_and(
793 ~(CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
794 &mCblk->mFlags);
795 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800796 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700797 mNewPosition = mPosition + mUpdatePeriod;
Andy Hung4be3b832016-10-13 17:51:43 -0700798 int32_t flags = android_atomic_and(~(CBLK_STREAM_END_DONE | CBLK_DISABLED), &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800799
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800800 if (!(flags & CBLK_INVALID)) {
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800801 mAudioTrack->start(&status);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800802 if (status == DEAD_OBJECT) {
803 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800804 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800805 }
806 if (flags & CBLK_INVALID) {
807 status = restoreTrack_l("start");
808 }
809
Andy Hung79629f02016-03-24 13:57:40 -0700810 // resume or pause the callback thread as needed.
811 sp<AudioTrackThread> t = mAudioTrackThread;
812 if (status == NO_ERROR) {
813 if (t != 0) {
814 if (previousState == STATE_STOPPING) {
815 mProxy->interrupt();
816 } else {
817 t->resume();
818 }
819 } else {
820 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
821 get_sched_policy(0, &mPreviousSchedulingGroup);
822 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
823 }
Andy Hung39399b62017-04-21 15:07:45 -0700824
825 // Start our local VolumeHandler for restoration purposes.
826 mVolumeHandler->setStarted();
Andy Hung79629f02016-03-24 13:57:40 -0700827 } else {
Eric Laurent973db022018-11-20 14:54:31 -0800828 ALOGE("%s(%d): status %d", __func__, mPortId, status);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800829 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800830 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100831 if (previousState != STATE_STOPPING) {
832 t->pause();
833 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800834 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700835 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700836 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800837 }
838 }
839
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100840 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800841}
842
843void AudioTrack::stop()
844{
Andy Hungb68f5eb2019-12-03 16:49:17 -0800845 const int64_t beginNs = systemTime();
846
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800847 AutoMutex lock(mLock);
Andy Hung06a730b2020-04-09 13:28:31 -0700848 mediametrics::Defer defer([&]() {
Andy Hungb68f5eb2019-12-03 16:49:17 -0800849 mediametrics::LogItem(mMetricsId)
850 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_STOP)
Andy Hungea840382020-05-05 21:50:17 -0700851 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
Andy Hungb68f5eb2019-12-03 16:49:17 -0800852 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
Phil Burk64e16a72020-06-01 13:25:51 -0700853 .set(AMEDIAMETRICS_PROP_BUFFERSIZEFRAMES, (int32_t)mProxy->getBufferSizeInFrames())
854 .set(AMEDIAMETRICS_PROP_UNDERRUN, (int32_t) getUnderrunCount_l())
Phil Burka9876702020-04-20 18:16:15 -0700855 .record();
Phil Burka9876702020-04-20 18:16:15 -0700856 });
Andy Hungb68f5eb2019-12-03 16:49:17 -0800857
Eric Laurent973db022018-11-20 14:54:31 -0800858 ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
Andy Hungfb8ede22018-09-12 19:03:24 -0700859
Glenn Kasten397edb32013-08-30 15:10:13 -0700860 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800861 return;
862 }
863
Glenn Kasten23a75452014-01-13 10:37:17 -0800864 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100865 mState = STATE_STOPPING;
866 } else {
867 mState = STATE_STOPPED;
Andy Hung2148bf02016-11-28 19:01:02 -0800868 ALOGD_IF(mSharedBuffer == nullptr,
Eric Laurent973db022018-11-20 14:54:31 -0800869 "%s(%d): called with %u frames delivered", __func__, mPortId, mReleased.value());
Andy Hungc2813e52014-10-16 17:54:34 -0700870 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100871 }
872
Andy Hung1d3556d2018-03-29 16:30:14 -0700873 mProxy->stop(); // notify server not to read beyond current client position until start().
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800874 mProxy->interrupt();
875 mAudioTrack->stop();
Andy Hung61be8412015-10-06 10:51:09 -0700876
877 // Note: legacy handling - stop does not clear playback marker
878 // and periodic update counter, but flush does for streaming tracks.
Andy Hung9b461582014-12-01 17:56:29 -0800879
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800880 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800881 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800882 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
883 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800884 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100885
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800886 sp<AudioTrackThread> t = mAudioTrackThread;
887 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800888 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100889 t->pause();
Jean-Michel Trivia60e9a22018-11-15 16:13:36 -0800890 } else if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
Jean-Michel Trivi0248a2a2018-11-21 10:05:57 -0800891 // causes wake up of the playback thread, that will callback the client for
892 // EVENT_STREAM_END in processAudioBuffer()
893 t->wake();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100894 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800895 } else {
896 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
897 set_sched_policy(0, mPreviousSchedulingGroup);
898 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800899}
900
901bool AudioTrack::stopped() const
902{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800903 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800904 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800905}
906
907void AudioTrack::flush()
908{
Andy Hungb68f5eb2019-12-03 16:49:17 -0800909 const int64_t beginNs = systemTime();
Andy Hungfb8ede22018-09-12 19:03:24 -0700910 AutoMutex lock(mLock);
Andy Hung06a730b2020-04-09 13:28:31 -0700911 mediametrics::Defer defer([&]() {
Andy Hungb68f5eb2019-12-03 16:49:17 -0800912 mediametrics::LogItem(mMetricsId)
913 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_FLUSH)
Andy Hungea840382020-05-05 21:50:17 -0700914 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
Andy Hungb68f5eb2019-12-03 16:49:17 -0800915 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
916 .record(); });
917
Eric Laurent973db022018-11-20 14:54:31 -0800918 ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
Andy Hungfb8ede22018-09-12 19:03:24 -0700919
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800920 if (mSharedBuffer != 0) {
921 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800922 }
Andy Hung4c5ed302018-05-09 11:16:21 -0700923 if (mState == STATE_ACTIVE) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800924 return;
925 }
926 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800927}
928
Eric Laurent1703cdf2011-03-07 14:52:59 -0800929void AudioTrack::flush_l()
930{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800931 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700932
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700933 // clear playback marker and periodic update counter
934 mMarkerPosition = 0;
935 mMarkerReached = false;
936 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100937 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700938
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800939 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700940 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800941 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100942 mProxy->interrupt();
943 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800944 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800945 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800946}
947
948void AudioTrack::pause()
949{
Andy Hungb68f5eb2019-12-03 16:49:17 -0800950 const int64_t beginNs = systemTime();
Eric Laurentf5aafb22010-11-18 08:40:16 -0800951 AutoMutex lock(mLock);
Andy Hunga6b27032020-04-27 10:34:24 -0700952 mediametrics::Defer defer([&]() {
Andy Hungb68f5eb2019-12-03 16:49:17 -0800953 mediametrics::LogItem(mMetricsId)
954 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_PAUSE)
Andy Hungea840382020-05-05 21:50:17 -0700955 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
Andy Hungb68f5eb2019-12-03 16:49:17 -0800956 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
957 .record(); });
958
Eric Laurent973db022018-11-20 14:54:31 -0800959 ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
Andy Hungfb8ede22018-09-12 19:03:24 -0700960
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100961 if (mState == STATE_ACTIVE) {
962 mState = STATE_PAUSED;
963 } else if (mState == STATE_STOPPING) {
964 mState = STATE_PAUSED_STOPPING;
965 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800966 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800967 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800968 mProxy->interrupt();
969 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800970
Marco Nelissen3a90f282014-03-10 11:21:43 -0700971 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700972 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700973 // An offload output can be re-used between two audio tracks having
974 // the same configuration. A timestamp query for a paused track
975 // while the other is running would return an incorrect time.
976 // To fix this, cache the playback position on a pause() and return
977 // this time when requested until the track is resumed.
978
979 // OffloadThread sends HAL pause in its threadLoop. Time saved
980 // here can be slightly off.
981
982 // TODO: check return code for getRenderPosition.
983
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800984 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800985 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
Andy Hungfb8ede22018-09-12 19:03:24 -0700986 ALOGV("%s(%d): for offload, cache current position %u",
Eric Laurent973db022018-11-20 14:54:31 -0800987 __func__, mPortId, mPausedPosition);
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800988 }
989 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800990}
991
Eric Laurentbe916aa2010-06-01 23:49:17 -0700992status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800993{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700994 // This duplicates a test by AudioTrack JNI, but that is not the only caller
995 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
996 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700997 return BAD_VALUE;
998 }
999
Andy Hungb68f5eb2019-12-03 16:49:17 -08001000 mediametrics::LogItem(mMetricsId)
1001 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETVOLUME)
1002 .set(AMEDIAMETRICS_PROP_VOLUME_LEFT, (double)left)
1003 .set(AMEDIAMETRICS_PROP_VOLUME_RIGHT, (double)right)
1004 .record();
1005
Eric Laurent1703cdf2011-03-07 14:52:59 -08001006 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -08001007 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
1008 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001009
Glenn Kastenc56f3422014-03-21 17:53:17 -07001010 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -07001011
Glenn Kasten23a75452014-01-13 10:37:17 -08001012 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -07001013 mAudioTrack->signal();
1014 }
Eric Laurentbe916aa2010-06-01 23:49:17 -07001015 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001016}
1017
Glenn Kastenb1c09932012-02-27 16:21:04 -08001018status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001019{
Glenn Kastenb1c09932012-02-27 16:21:04 -08001020 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -07001021}
1022
Eric Laurent2beeb502010-07-16 07:43:46 -07001023status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -07001024{
Glenn Kastenc56f3422014-03-21 17:53:17 -07001025 // This duplicates a test by AudioTrack JNI, but that is not the only caller
1026 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -07001027 return BAD_VALUE;
1028 }
1029
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001030 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -07001031 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001032 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -07001033
1034 return NO_ERROR;
1035}
1036
Glenn Kastena5224f32012-01-04 12:41:44 -08001037void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -07001038{
1039 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001040 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -07001041 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001042}
1043
Glenn Kasten3b16c762012-11-14 08:44:39 -08001044status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001045{
Andy Hung5cbb5782015-03-27 18:39:59 -07001046 AutoMutex lock(mLock);
Eric Laurent973db022018-11-20 14:54:31 -08001047 ALOGV("%s(%d): prior state:%s rate:%u", __func__, mPortId, stateToString(mState), rate);
Andy Hungfb8ede22018-09-12 19:03:24 -07001048
Andy Hung5cbb5782015-03-27 18:39:59 -07001049 if (rate == mSampleRate) {
1050 return NO_ERROR;
1051 }
jiabinf4de6112018-12-19 12:40:08 -08001052 if (isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)
1053 || (mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001054 return INVALID_OPERATION;
1055 }
Eric Laurent0d6db582014-11-12 18:39:44 -08001056 if (mOutput == AUDIO_IO_HANDLE_NONE) {
1057 return NO_INIT;
1058 }
Andy Hung5cbb5782015-03-27 18:39:59 -07001059 // NOTE: it is theoretically possible, but highly unlikely, that a device change
1060 // could mean a previously allowed sampling rate is no longer allowed.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001061 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -08001062 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -07001063 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001064 }
Andy Hung26145642015-04-15 21:56:53 -07001065 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001066 const uint32_t effectiveSampleRate = adjustSampleRate(rate, mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001067 if (rate == 0 || effectiveSampleRate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001068 return BAD_VALUE;
1069 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001070 // TODO: Should we also check if the buffer size is compatible?
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001071
Glenn Kastene3aa6592012-12-04 12:22:46 -08001072 mSampleRate = rate;
Andy Hung26145642015-04-15 21:56:53 -07001073 mProxy->setSampleRate(effectiveSampleRate);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001074
Eric Laurent57326622009-07-07 07:10:45 -07001075 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001076}
1077
Glenn Kastena5224f32012-01-04 12:41:44 -08001078uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001079{
Eric Laurent1703cdf2011-03-07 14:52:59 -08001080 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07001081
1082 // sample rate can be updated during playback by the offloaded decoder so we need to
1083 // query the HAL and update if needed.
1084// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -07001085 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -07001086 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -07001087 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001088 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -07001089 if (status == NO_ERROR) {
1090 mSampleRate = sampleRate;
1091 }
1092 }
1093 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001094 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001095}
1096
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001097uint32_t AudioTrack::getOriginalSampleRate() const
1098{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001099 return mOriginalSampleRate;
1100}
1101
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001102status_t AudioTrack::setDualMonoMode(audio_dual_mono_mode_t mode)
1103{
1104 AutoMutex lock(mLock);
1105 return setDualMonoMode_l(mode);
1106}
1107
1108status_t AudioTrack::setDualMonoMode_l(audio_dual_mono_mode_t mode)
1109{
1110 const status_t status = statusTFromBinderStatus(
1111 mAudioTrack->setDualMonoMode(VALUE_OR_RETURN_STATUS(
1112 legacy2aidl_audio_dual_mono_mode_t_AudioDualMonoMode(mode))));
1113 if (status == NO_ERROR) mDualMonoMode = mode;
1114 return status;
1115}
1116
1117status_t AudioTrack::getDualMonoMode(audio_dual_mono_mode_t* mode) const
1118{
1119 AutoMutex lock(mLock);
1120 media::AudioDualMonoMode mediaMode;
1121 const status_t status = statusTFromBinderStatus(mAudioTrack->getDualMonoMode(&mediaMode));
1122 if (status == NO_ERROR) {
1123 *mode = VALUE_OR_RETURN_STATUS(
1124 aidl2legacy_AudioDualMonoMode_audio_dual_mono_mode_t(mediaMode));
1125 }
1126 return status;
1127}
1128
1129status_t AudioTrack::setAudioDescriptionMixLevel(float leveldB)
1130{
1131 AutoMutex lock(mLock);
1132 return setAudioDescriptionMixLevel_l(leveldB);
1133}
1134
1135status_t AudioTrack::setAudioDescriptionMixLevel_l(float leveldB)
1136{
1137 const status_t status = statusTFromBinderStatus(
1138 mAudioTrack->setAudioDescriptionMixLevel(leveldB));
1139 if (status == NO_ERROR) mAudioDescriptionMixLeveldB = leveldB;
1140 return status;
1141}
1142
1143status_t AudioTrack::getAudioDescriptionMixLevel(float* leveldB) const
1144{
1145 AutoMutex lock(mLock);
1146 return statusTFromBinderStatus(mAudioTrack->getAudioDescriptionMixLevel(leveldB));
1147}
1148
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001149status_t AudioTrack::setPlaybackRate(const AudioPlaybackRate &playbackRate)
Andy Hung8edb8dc2015-03-26 19:13:55 -07001150{
Andy Hung8edb8dc2015-03-26 19:13:55 -07001151 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001152 if (isAudioPlaybackRateEqual(playbackRate, mPlaybackRate)) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001153 return NO_ERROR;
1154 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001155 if (isOffloadedOrDirect_l()) {
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001156 const status_t status = statusTFromBinderStatus(mAudioTrack->setPlaybackRateParameters(
1157 VALUE_OR_RETURN_STATUS(
1158 legacy2aidl_audio_playback_rate_t_AudioPlaybackRate(playbackRate))));
1159 if (status == NO_ERROR) {
1160 mPlaybackRate = playbackRate;
1161 }
1162 return status;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001163 }
1164 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1165 return INVALID_OPERATION;
1166 }
Andy Hungff874dc2016-04-11 16:49:09 -07001167
Andy Hungfb8ede22018-09-12 19:03:24 -07001168 ALOGV("%s(%d): mSampleRate:%u mSpeed:%f mPitch:%f",
Eric Laurent973db022018-11-20 14:54:31 -08001169 __func__, mPortId, mSampleRate, playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001170 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001171 const uint32_t effectiveRate = adjustSampleRate(mSampleRate, playbackRate.mPitch);
1172 const float effectiveSpeed = adjustSpeed(playbackRate.mSpeed, playbackRate.mPitch);
1173 const float effectivePitch = adjustPitch(playbackRate.mPitch);
Ricardo Garcia6c7f0622015-04-30 18:39:16 -07001174 AudioPlaybackRate playbackRateTemp = playbackRate;
1175 playbackRateTemp.mSpeed = effectiveSpeed;
1176 playbackRateTemp.mPitch = effectivePitch;
1177
Andy Hungfb8ede22018-09-12 19:03:24 -07001178 ALOGV("%s(%d) (effective) mSampleRate:%u mSpeed:%f mPitch:%f",
Eric Laurent973db022018-11-20 14:54:31 -08001179 __func__, mPortId, effectiveRate, effectiveSpeed, effectivePitch);
Andy Hungff874dc2016-04-11 16:49:09 -07001180
Ricardo Garcia6c7f0622015-04-30 18:39:16 -07001181 if (!isAudioPlaybackRateValid(playbackRateTemp)) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001182 ALOGW("%s(%d) (%f, %f) failed (effective rate out of bounds)",
Eric Laurent973db022018-11-20 14:54:31 -08001183 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001184 return BAD_VALUE;
1185 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001186 // Check if the buffer size is compatible.
Andy Hung26145642015-04-15 21:56:53 -07001187 if (!isSampleRateSpeedAllowed_l(effectiveRate, effectiveSpeed)) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001188 ALOGW("%s(%d) (%f, %f) failed (buffer size)",
Eric Laurent973db022018-11-20 14:54:31 -08001189 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung8edb8dc2015-03-26 19:13:55 -07001190 return BAD_VALUE;
1191 }
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001192
Ricardo Garcia6c7f0622015-04-30 18:39:16 -07001193 // Check resampler ratios are within bounds
Glenn Kastend3bb6452016-12-05 18:14:37 -08001194 if ((uint64_t)effectiveRate > (uint64_t)mSampleRate *
1195 (uint64_t)AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001196 ALOGW("%s(%d) (%f, %f) failed. Resample rate exceeds max accepted value",
Eric Laurent973db022018-11-20 14:54:31 -08001197 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
Ricardo Garcia6c7f0622015-04-30 18:39:16 -07001198 return BAD_VALUE;
1199 }
1200
Dan Austine34eae22015-10-27 16:14:52 -07001201 if ((uint64_t)effectiveRate * (uint64_t)AUDIO_RESAMPLER_UP_RATIO_MAX < (uint64_t)mSampleRate) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001202 ALOGW("%s(%d) (%f, %f) failed. Resample rate below min accepted value",
Eric Laurent973db022018-11-20 14:54:31 -08001203 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
Ricardo Garcia6c7f0622015-04-30 18:39:16 -07001204 return BAD_VALUE;
1205 }
1206 mPlaybackRate = playbackRate;
1207 //set effective rates
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001208 mProxy->setPlaybackRate(playbackRateTemp);
Andy Hung26145642015-04-15 21:56:53 -07001209 mProxy->setSampleRate(effectiveRate); // FIXME: not quite "atomic" with setPlaybackRate
Andy Hungb68f5eb2019-12-03 16:49:17 -08001210
1211 mediametrics::LogItem(mMetricsId)
1212 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETPLAYBACKPARAM)
1213 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
1214 .set(AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)mPlaybackRate.mSpeed)
1215 .set(AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)mPlaybackRate.mPitch)
1216 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1217 AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)effectiveRate)
1218 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1219 AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)playbackRateTemp.mSpeed)
1220 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1221 AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)playbackRateTemp.mPitch)
1222 .record();
1223
Andy Hung8edb8dc2015-03-26 19:13:55 -07001224 return NO_ERROR;
1225}
1226
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001227const AudioPlaybackRate& AudioTrack::getPlaybackRate()
Andy Hung8edb8dc2015-03-26 19:13:55 -07001228{
1229 AutoMutex lock(mLock);
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001230 if (isOffloadedOrDirect_l()) {
1231 media::AudioPlaybackRate playbackRateTemp;
1232 const status_t status = statusTFromBinderStatus(
1233 mAudioTrack->getPlaybackRateParameters(&playbackRateTemp));
1234 if (status == NO_ERROR) { // update local version if changed.
1235 mPlaybackRate =
1236 aidl2legacy_AudioPlaybackRate_audio_playback_rate_t(playbackRateTemp).value();
1237 }
1238 }
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001239 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001240}
1241
Phil Burkc0adecb2016-01-08 12:44:11 -08001242ssize_t AudioTrack::getBufferSizeInFrames()
1243{
1244 AutoMutex lock(mLock);
1245 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1246 return NO_INIT;
1247 }
Phil Burka9876702020-04-20 18:16:15 -07001248
Phil Burke8972b02016-03-04 11:29:57 -08001249 return (ssize_t) mProxy->getBufferSizeInFrames();
Phil Burkc0adecb2016-01-08 12:44:11 -08001250}
1251
Andy Hungf2c87b32016-04-07 19:49:29 -07001252status_t AudioTrack::getBufferDurationInUs(int64_t *duration)
1253{
1254 if (duration == nullptr) {
1255 return BAD_VALUE;
1256 }
1257 AutoMutex lock(mLock);
1258 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1259 return NO_INIT;
1260 }
1261 ssize_t bufferSizeInFrames = (ssize_t) mProxy->getBufferSizeInFrames();
1262 if (bufferSizeInFrames < 0) {
1263 return (status_t)bufferSizeInFrames;
1264 }
1265 *duration = (int64_t)((double)bufferSizeInFrames * 1000000
1266 / ((double)mSampleRate * mPlaybackRate.mSpeed));
1267 return NO_ERROR;
1268}
1269
Phil Burkc0adecb2016-01-08 12:44:11 -08001270ssize_t AudioTrack::setBufferSizeInFrames(size_t bufferSizeInFrames)
1271{
1272 AutoMutex lock(mLock);
1273 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1274 return NO_INIT;
1275 }
1276 // Reject if timed track or compressed audio.
Glenn Kastend79072e2016-01-06 08:41:20 -08001277 if (!audio_is_linear_pcm(mFormat)) {
Phil Burkc0adecb2016-01-08 12:44:11 -08001278 return INVALID_OPERATION;
1279 }
Phil Burka9876702020-04-20 18:16:15 -07001280
1281 ssize_t originalBufferSize = mProxy->getBufferSizeInFrames();
1282 ssize_t finalBufferSize = mProxy->setBufferSizeInFrames((uint32_t) bufferSizeInFrames);
1283 if (originalBufferSize != finalBufferSize) {
Phil Burk64e16a72020-06-01 13:25:51 -07001284 android::mediametrics::LogItem(mMetricsId)
1285 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETBUFFERSIZE)
1286 .set(AMEDIAMETRICS_PROP_BUFFERSIZEFRAMES, (int32_t)mProxy->getBufferSizeInFrames())
1287 .set(AMEDIAMETRICS_PROP_UNDERRUN, (int32_t)getUnderrunCount_l())
1288 .record();
Phil Burka9876702020-04-20 18:16:15 -07001289 }
1290 return finalBufferSize;
Phil Burkc0adecb2016-01-08 12:44:11 -08001291}
1292
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001293status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
1294{
Glenn Kastend79072e2016-01-06 08:41:20 -08001295 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -08001296 return INVALID_OPERATION;
1297 }
1298
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001299 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001300 ;
1301 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
1302 loopEnd - loopStart >= MIN_LOOP) {
1303 ;
1304 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001305 return BAD_VALUE;
1306 }
1307
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001308 AutoMutex lock(mLock);
1309 // See setPosition() regarding setting parameters such as loop points or position while active
1310 if (mState == STATE_ACTIVE) {
1311 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001312 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001313 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001314 return NO_ERROR;
1315}
1316
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001317void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
1318{
Andy Hung4ede21d2014-12-12 15:37:34 -08001319 // We do not update the periodic notification point.
1320 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
1321 mLoopCount = loopCount;
1322 mLoopEnd = loopEnd;
1323 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -08001324 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001325 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -08001326
1327 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001328}
1329
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001330status_t AudioTrack::setMarkerPosition(uint32_t marker)
1331{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001332 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -07001333 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001334 return INVALID_OPERATION;
1335 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001336
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001337 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001338 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -07001339 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001340
Andy Hung3c09c782014-12-29 18:39:32 -08001341 sp<AudioTrackThread> t = mAudioTrackThread;
1342 if (t != 0) {
1343 t->wake();
1344 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001345 return NO_ERROR;
1346}
1347
Glenn Kastena5224f32012-01-04 12:41:44 -08001348status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001349{
Eric Laurentab5cdba2014-06-09 17:22:27 -07001350 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001351 return INVALID_OPERATION;
1352 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001353 if (marker == NULL) {
1354 return BAD_VALUE;
1355 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001356
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001357 AutoMutex lock(mLock);
Andy Hung90e8a972015-11-09 16:42:40 -08001358 mMarkerPosition.getValue(marker);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001359
1360 return NO_ERROR;
1361}
1362
1363status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
1364{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001365 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -07001366 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001367 return INVALID_OPERATION;
1368 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001369
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001370 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001371 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001372 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -08001373
Andy Hung3c09c782014-12-29 18:39:32 -08001374 sp<AudioTrackThread> t = mAudioTrackThread;
1375 if (t != 0) {
1376 t->wake();
1377 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001378 return NO_ERROR;
1379}
1380
Glenn Kastena5224f32012-01-04 12:41:44 -08001381status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001382{
Eric Laurentab5cdba2014-06-09 17:22:27 -07001383 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001384 return INVALID_OPERATION;
1385 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001386 if (updatePeriod == NULL) {
1387 return BAD_VALUE;
1388 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001389
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001390 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001391 *updatePeriod = mUpdatePeriod;
1392
1393 return NO_ERROR;
1394}
1395
1396status_t AudioTrack::setPosition(uint32_t position)
1397{
Glenn Kastend79072e2016-01-06 08:41:20 -08001398 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001399 return INVALID_OPERATION;
1400 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001401 if (position > mFrameCount) {
1402 return BAD_VALUE;
1403 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001404
Eric Laurent1703cdf2011-03-07 14:52:59 -08001405 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001406 // Currently we require that the player is inactive before setting parameters such as position
1407 // or loop points. Otherwise, there could be a race condition: the application could read the
1408 // current position, compute a new position or loop parameters, and then set that position or
1409 // loop parameters but it would do the "wrong" thing since the position has continued to advance
1410 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
1411 // to specify how it wants to handle such scenarios.
1412 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001413 return INVALID_OPERATION;
1414 }
Andy Hung9b461582014-12-01 17:56:29 -08001415 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -07001416 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -08001417 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -08001418
1419 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001420 return NO_ERROR;
1421}
1422
Glenn Kasten200092b2014-08-15 15:13:30 -07001423status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001424{
Glenn Kastend65d73c2012-06-22 17:21:07 -07001425 if (position == NULL) {
1426 return BAD_VALUE;
1427 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001428
Eric Laurent1703cdf2011-03-07 14:52:59 -08001429 AutoMutex lock(mLock);
Andy Hung7a490e72016-03-23 15:58:10 -07001430 // FIXME: offloaded and direct tracks call into the HAL for render positions
1431 // for compressed/synced data; however, we use proxy position for pure linear pcm data
1432 // as we do not know the capability of the HAL for pcm position support and standby.
1433 // There may be some latency differences between the HAL position and the proxy position.
1434 if (isOffloadedOrDirect_l() && !isPurePcmData_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001435 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001436
Eric Laurentab5cdba2014-06-09 17:22:27 -07001437 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001438 ALOGV("%s(%d): called in paused state, return cached position %u",
Eric Laurent973db022018-11-20 14:54:31 -08001439 __func__, mPortId, mPausedPosition);
Haynes Mathew George7064fd22014-01-08 13:59:53 -08001440 *position = mPausedPosition;
1441 return NO_ERROR;
1442 }
1443
Glenn Kasten142f5192014-03-25 17:44:59 -07001444 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung1f1db832015-06-08 13:26:10 -07001445 uint32_t halFrames; // actually unused
1446 (void) AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
1447 // FIXME: on getRenderPosition() error, we return OK with frame position 0.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001448 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001449 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
1450 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001451 *position = dspFrames;
1452 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -08001453 if (mCblk->mFlags & CBLK_INVALID) {
Andy Hung1f1db832015-06-08 13:26:10 -07001454 (void) restoreTrack_l("getPosition");
1455 // FIXME: for compatibility with the Java API we ignore the restoreTrack_l()
1456 // error here (e.g. DEAD_OBJECT) and return OK with the last recorded server position.
Eric Laurent275e8e92014-11-30 15:14:47 -08001457 }
1458
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001459 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -07001460 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
Andy Hung90e8a972015-11-09 16:42:40 -08001461 0 : updateAndGetPosition_l().value();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001462 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001463 return NO_ERROR;
1464}
1465
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001466status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001467{
Glenn Kastend79072e2016-01-06 08:41:20 -08001468 if (mSharedBuffer == 0) {
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001469 return INVALID_OPERATION;
1470 }
1471 if (position == NULL) {
1472 return BAD_VALUE;
1473 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001474
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001475 AutoMutex lock(mLock);
1476 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001477 return NO_ERROR;
1478}
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001479
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001480status_t AudioTrack::reload()
1481{
Glenn Kastend79072e2016-01-06 08:41:20 -08001482 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -08001483 return INVALID_OPERATION;
1484 }
1485
Eric Laurent1703cdf2011-03-07 14:52:59 -08001486 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001487 // See setPosition() regarding setting parameters such as loop points or position while active
1488 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001489 return INVALID_OPERATION;
1490 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001491 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -08001492 (void) updateAndGetPosition_l();
1493 mPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -07001494 mPreviousTimestampValid = false;
Andy Hung53c3b5f2014-12-15 16:42:05 -08001495#if 0
Andy Hung9b461582014-12-01 17:56:29 -08001496 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -08001497 // of loop count. Historically we have not restored loop count, start, end,
1498 // but it makes sense if one desires to repeat playing a particular sound.
1499 if (mLoopCount != 0) {
1500 mLoopCountNotified = mLoopCount;
1501 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
1502 }
1503#endif
Andy Hung9b461582014-12-01 17:56:29 -08001504 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001505 return NO_ERROR;
1506}
1507
Glenn Kasten38e905b2014-01-13 10:21:48 -08001508audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -07001509{
Eric Laurent1703cdf2011-03-07 14:52:59 -08001510 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001511 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001512}
1513
Paul McLeanaa981192015-03-21 09:55:15 -07001514status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
1515 AutoMutex lock(mLock);
1516 if (mSelectedDeviceId != deviceId) {
1517 mSelectedDeviceId = deviceId;
Eric Laurentfb00fc72017-05-25 18:17:12 -07001518 if (mStatus == NO_ERROR) {
1519 android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
jiabin156c6872017-10-06 09:47:15 -07001520 mProxy->interrupt();
Eric Laurentfb00fc72017-05-25 18:17:12 -07001521 }
Paul McLeanaa981192015-03-21 09:55:15 -07001522 }
Eric Laurent493404d2015-04-21 15:07:36 -07001523 return NO_ERROR;
Paul McLeanaa981192015-03-21 09:55:15 -07001524}
1525
1526audio_port_handle_t AudioTrack::getOutputDevice() {
1527 AutoMutex lock(mLock);
1528 return mSelectedDeviceId;
1529}
1530
Eric Laurentad2e7b92017-09-14 20:06:42 -07001531// must be called with mLock held
1532void AudioTrack::updateRoutedDeviceId_l()
1533{
1534 // if the track is inactive, do not update actual device as the output stream maybe routed
1535 // to a device not relevant to this client because of other active use cases.
1536 if (mState != STATE_ACTIVE) {
1537 return;
1538 }
1539 if (mOutput != AUDIO_IO_HANDLE_NONE) {
1540 audio_port_handle_t deviceId = AudioSystem::getDeviceIdForIo(mOutput);
1541 if (deviceId != AUDIO_PORT_HANDLE_NONE) {
1542 mRoutedDeviceId = deviceId;
1543 }
1544 }
1545}
1546
Eric Laurent296fb132015-05-01 11:38:42 -07001547audio_port_handle_t AudioTrack::getRoutedDeviceId() {
1548 AutoMutex lock(mLock);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001549 updateRoutedDeviceId_l();
1550 return mRoutedDeviceId;
Eric Laurent296fb132015-05-01 11:38:42 -07001551}
1552
Eric Laurentbe916aa2010-06-01 23:49:17 -07001553status_t AudioTrack::attachAuxEffect(int effectId)
1554{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001555 AutoMutex lock(mLock);
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08001556 status_t status;
1557 mAudioTrack->attachAuxEffect(effectId, &status);
Eric Laurent2beeb502010-07-16 07:43:46 -07001558 if (status == NO_ERROR) {
1559 mAuxEffectId = effectId;
1560 }
1561 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -07001562}
1563
Eric Laurente83b55d2014-11-14 10:06:21 -08001564audio_stream_type_t AudioTrack::streamType() const
1565{
1566 if (mStreamType == AUDIO_STREAM_DEFAULT) {
François Gaffie58d4be52018-11-06 15:30:12 +01001567 return AudioSystem::attributesToStreamType(mAttributes);
Eric Laurente83b55d2014-11-14 10:06:21 -08001568 }
1569 return mStreamType;
1570}
1571
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001572uint32_t AudioTrack::latency()
1573{
1574 AutoMutex lock(mLock);
1575 updateLatency_l();
1576 return mLatency;
1577}
1578
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001579// -------------------------------------------------------------------------
1580
Eric Laurent1703cdf2011-03-07 14:52:59 -08001581// must be called with mLock held
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001582void AudioTrack::updateLatency_l()
1583{
1584 status_t status = AudioSystem::getLatency(mOutput, &mAfLatency);
1585 if (status != NO_ERROR) {
Eric Laurent973db022018-11-20 14:54:31 -08001586 ALOGW("%s(%d): getLatency(%d) failed status %d", __func__, mPortId, mOutput, status);
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001587 } else {
1588 // FIXME don't believe this lie
Andy Hung13969262017-09-11 17:24:21 -07001589 mLatency = mAfLatency + (1000LL * mFrameCount) / mSampleRate;
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001590 }
1591}
1592
Phil Burkadbb75a2017-06-16 12:19:42 -07001593// TODO Move this macro to a common header file for enum to string conversion in audio framework.
1594#define MEDIA_CASE_ENUM(name) case name: return #name
1595const char * AudioTrack::convertTransferToText(transfer_type transferType) {
1596 switch (transferType) {
1597 MEDIA_CASE_ENUM(TRANSFER_DEFAULT);
1598 MEDIA_CASE_ENUM(TRANSFER_CALLBACK);
1599 MEDIA_CASE_ENUM(TRANSFER_OBTAIN);
1600 MEDIA_CASE_ENUM(TRANSFER_SYNC);
1601 MEDIA_CASE_ENUM(TRANSFER_SHARED);
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07001602 MEDIA_CASE_ENUM(TRANSFER_SYNC_NOTIF_CALLBACK);
Phil Burkadbb75a2017-06-16 12:19:42 -07001603 default:
1604 return "UNRECOGNIZED";
1605 }
1606}
1607
Glenn Kasten200092b2014-08-15 15:13:30 -07001608status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001609{
Eric Laurentf32d7812017-11-30 14:44:07 -08001610 status_t status;
1611 bool callbackAdded = false;
1612
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001613 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
1614 if (audioFlinger == 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001615 ALOGE("%s(%d): Could not get audioflinger",
Eric Laurent973db022018-11-20 14:54:31 -08001616 __func__, mPortId);
Eric Laurentf32d7812017-11-30 14:44:07 -08001617 status = NO_INIT;
1618 goto exit;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001619 }
1620
Eric Laurent21da6472017-11-09 16:29:26 -08001621 {
Haynes Mathew Georgeae34ed22016-01-28 11:58:39 -08001622 // mFlags (not mOrigFlags) is modified depending on whether fast request is accepted.
1623 // After fast request is denied, we will request again if IAudioTrack is re-created.
Glenn Kastend79072e2016-01-06 08:41:20 -08001624 // Client can only express a preference for FAST. Server will perform additional tests.
Phil Burk33ff89b2015-11-30 11:16:01 -08001625 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Phil Burkadbb75a2017-06-16 12:19:42 -07001626 // either of these use cases:
1627 // use case 1: shared buffer
1628 bool sharedBuffer = mSharedBuffer != 0;
1629 bool transferAllowed =
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001630 // use case 2: callback transfer mode
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001631 (mTransfer == TRANSFER_CALLBACK) ||
1632 // use case 3: obtain/release mode
Phil Burk33ff89b2015-11-30 11:16:01 -08001633 (mTransfer == TRANSFER_OBTAIN) ||
1634 // use case 4: synchronous write
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07001635 ((mTransfer == TRANSFER_SYNC || mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK)
1636 && mThreadCanCallJava);
Phil Burkadbb75a2017-06-16 12:19:42 -07001637
Eric Laurent21da6472017-11-09 16:29:26 -08001638 bool fastAllowed = sharedBuffer || transferAllowed;
1639 if (!fastAllowed) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001640 ALOGW("%s(%d): AUDIO_OUTPUT_FLAG_FAST denied by client,"
1641 " not shared buffer and transfer = %s",
Eric Laurent973db022018-11-20 14:54:31 -08001642 __func__, mPortId,
Phil Burkadbb75a2017-06-16 12:19:42 -07001643 convertTransferToText(mTransfer));
Phil Burk33ff89b2015-11-30 11:16:01 -08001644 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1645 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001646 }
1647
Eric Laurent21da6472017-11-09 16:29:26 -08001648 IAudioFlinger::CreateTrackInput input;
1649 if (mStreamType != AUDIO_STREAM_DEFAULT) {
François Gaffie58d4be52018-11-06 15:30:12 +01001650 input.attr = AudioSystem::streamTypeToAttributes(mStreamType);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001651 } else {
Eric Laurent21da6472017-11-09 16:29:26 -08001652 input.attr = mAttributes;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001653 }
Eric Laurent21da6472017-11-09 16:29:26 -08001654 input.config = AUDIO_CONFIG_INITIALIZER;
1655 input.config.sample_rate = mSampleRate;
1656 input.config.channel_mask = mChannelMask;
1657 input.config.format = mFormat;
1658 input.config.offload_info = mOffloadInfoCopy;
1659 input.clientInfo.clientUid = mClientUid;
1660 input.clientInfo.clientPid = mClientPid;
1661 input.clientInfo.clientTid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001662 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten47d55172017-05-23 11:19:30 -07001663 // It is currently meaningless to request SCHED_FIFO for a Java thread. Even if the
1664 // application-level code follows all non-blocking design rules, the language runtime
1665 // doesn't also follow those rules, so the thread will not benefit overall.
Phil Burk33ff89b2015-11-30 11:16:01 -08001666 if (mAudioTrackThread != 0 && !mThreadCanCallJava) {
Eric Laurent21da6472017-11-09 16:29:26 -08001667 input.clientInfo.clientTid = mAudioTrackThread->getTid();
Glenn Kasten3acbd052012-02-28 10:39:56 -08001668 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001669 }
Eric Laurent21da6472017-11-09 16:29:26 -08001670 input.sharedBuffer = mSharedBuffer;
1671 input.notificationsPerBuffer = mNotificationsPerBufferReq;
1672 input.speed = 1.0;
1673 if (audio_has_proportional_frames(mFormat) && mSharedBuffer == 0 &&
1674 (mFlags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1675 input.speed = !isPurePcmData_l() || isOffloadedOrDirect_l() ? 1.0f :
1676 max(mMaxRequiredSpeed, mPlaybackRate.mSpeed);
1677 }
1678 input.flags = mFlags;
1679 input.frameCount = mReqFrameCount;
1680 input.notificationFrameCount = mNotificationFramesReq;
1681 input.selectedDeviceId = mSelectedDeviceId;
1682 input.sessionId = mSessionId;
jiabinf6eb4c32020-02-25 14:06:25 -08001683 input.audioTrackCallback = mAudioTrackCallback;
Colin Crossb8a9dbb2020-08-27 04:12:26 +00001684 input.opPackageName = mOpPackageName;
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001685
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08001686 media::CreateTrackResponse response;
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001687 status = audioFlinger->createTrack(VALUE_OR_FATAL(input.toAidl()), response);
Ytai Ben-Tsvi357e26a2021-01-05 13:21:19 -08001688
1689 IAudioFlinger::CreateTrackOutput output{};
1690 if (status == NO_ERROR) {
1691 output = VALUE_OR_FATAL(IAudioFlinger::CreateTrackOutput::fromAidl(response));
1692 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001693
Eric Laurent21da6472017-11-09 16:29:26 -08001694 if (status != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001695 ALOGE("%s(%d): AudioFlinger could not create track, status: %d output %d",
Eric Laurent973db022018-11-20 14:54:31 -08001696 __func__, mPortId, status, output.outputId);
Eric Laurentf32d7812017-11-30 14:44:07 -08001697 if (status == NO_ERROR) {
1698 status = NO_INIT;
1699 }
1700 goto exit;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001701 }
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001702 ALOG_ASSERT(output.audioTrack != 0);
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001703
Eric Laurent21da6472017-11-09 16:29:26 -08001704 mFrameCount = output.frameCount;
1705 mNotificationFramesAct = (uint32_t)output.notificationFrameCount;
1706 mRoutedDeviceId = output.selectedDeviceId;
1707 mSessionId = output.sessionId;
1708
1709 mSampleRate = output.sampleRate;
1710 if (mOriginalSampleRate == 0) {
1711 mOriginalSampleRate = mSampleRate;
1712 }
1713
1714 mAfFrameCount = output.afFrameCount;
1715 mAfSampleRate = output.afSampleRate;
1716 mAfLatency = output.afLatencyMs;
1717
1718 mLatency = mAfLatency + (1000LL * mFrameCount) / mSampleRate;
1719
Glenn Kasten38e905b2014-01-13 10:21:48 -08001720 // AudioFlinger now owns the reference to the I/O handle,
1721 // so we are no longer responsible for releasing it.
1722
Glenn Kasten7fd04222016-02-02 12:38:16 -08001723 // FIXME compare to AudioRecord
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08001724 std::optional<media::SharedFileRegion> sfr;
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001725 output.audioTrack->getCblk(&sfr);
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08001726 sp<IMemory> iMem = VALUE_OR_FATAL(aidl2legacy_NullableSharedFileRegion_IMemory(sfr));
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001727 if (iMem == 0) {
Eric Laurent973db022018-11-20 14:54:31 -08001728 ALOGE("%s(%d): Could not get control block", __func__, mPortId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001729 status = NO_INIT;
Eric Laurentf32d7812017-11-30 14:44:07 -08001730 goto exit;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001731 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07001732 // TODO: Using unsecurePointer() has some associated security pitfalls
1733 // (see declaration for details).
1734 // Either document why it is safe in this case or address the
1735 // issue (e.g. by copying).
1736 void *iMemPointer = iMem->unsecurePointer();
Glenn Kasten0cde0762014-01-16 15:06:36 -08001737 if (iMemPointer == NULL) {
Eric Laurent973db022018-11-20 14:54:31 -08001738 ALOGE("%s(%d): Could not get control block pointer", __func__, mPortId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001739 status = NO_INIT;
Eric Laurentf32d7812017-11-30 14:44:07 -08001740 goto exit;
Glenn Kasten0cde0762014-01-16 15:06:36 -08001741 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001742 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001743 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001744 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001745 mDeathNotifier.clear();
1746 }
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001747 mAudioTrack = output.audioTrack;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001748 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001749 IPCThreadState::self()->flushCommands();
1750
Glenn Kasten0cde0762014-01-16 15:06:36 -08001751 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001752 mCblk = cblk;
Glenn Kasten5f631512014-02-24 15:16:07 -08001753
Glenn Kastena07f17c2013-04-23 12:39:37 -07001754 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001755 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent21da6472017-11-09 16:29:26 -08001756 if (output.flags & AUDIO_OUTPUT_FLAG_FAST) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001757 ALOGI("%s(%d): AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu -> %zu",
Eric Laurent973db022018-11-20 14:54:31 -08001758 __func__, mPortId, mReqFrameCount, mFrameCount);
Phil Burk33ff89b2015-11-30 11:16:01 -08001759 if (!mThreadCanCallJava) {
1760 mAwaitBoost = true;
1761 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001762 } else {
Phil Burkcc6ed2d2020-05-18 13:06:54 -07001763 ALOGD("%s(%d): AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu -> %zu",
Eric Laurent973db022018-11-20 14:54:31 -08001764 __func__, mPortId, mReqFrameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001765 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001766 }
Eric Laurent21da6472017-11-09 16:29:26 -08001767 mFlags = output.flags;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001768
Eric Laurentad2e7b92017-09-14 20:06:42 -07001769 //mOutput != output includes the case where mOutput == AUDIO_IO_HANDLE_NONE for first creation
Eric Laurent09f1ed22019-04-24 17:45:17 -07001770 if (mDeviceCallback != 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001771 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent09f1ed22019-04-24 17:45:17 -07001772 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001773 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07001774 AudioSystem::addAudioDeviceCallback(this, output.outputId, output.portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001775 callbackAdded = true;
1776 }
1777
Eric Laurent09f1ed22019-04-24 17:45:17 -07001778 mPortId = output.portId;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001779 // We retain a copy of the I/O handle, but don't own the reference
Eric Laurent21da6472017-11-09 16:29:26 -08001780 mOutput = output.outputId;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001781 mRefreshRemaining = true;
1782
1783 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1784 // is the value of pointer() for the shared buffer, otherwise buffers points
1785 // immediately after the control block. This address is for the mapping within client
1786 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1787 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001788 if (mSharedBuffer == 0) {
Glenn Kasten138d6f92015-03-20 10:54:51 -07001789 buffers = cblk + 1;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001790 } else {
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07001791 // TODO: Using unsecurePointer() has some associated security pitfalls
1792 // (see declaration for details).
1793 // Either document why it is safe in this case or address the
1794 // issue (e.g. by copying).
1795 buffers = mSharedBuffer->unsecurePointer();
Glenn Kasten138d6f92015-03-20 10:54:51 -07001796 if (buffers == NULL) {
Eric Laurent973db022018-11-20 14:54:31 -08001797 ALOGE("%s(%d): Could not get buffer pointer", __func__, mPortId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001798 status = NO_INIT;
Eric Laurentf32d7812017-11-30 14:44:07 -08001799 goto exit;
Glenn Kasten138d6f92015-03-20 10:54:51 -07001800 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001801 }
1802
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08001803 mAudioTrack->attachAuxEffect(mAuxEffectId, &status);
Glenn Kasten5f631512014-02-24 15:16:07 -08001804
Glenn Kasten093000f2012-05-03 09:35:36 -07001805 // If IAudioTrack is re-created, don't let the requested frameCount
1806 // decrease. This can confuse clients that cache frameCount().
Eric Laurent21da6472017-11-09 16:29:26 -08001807 if (mFrameCount > mReqFrameCount) {
1808 mReqFrameCount = mFrameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001809 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001810
Andy Hungd7bd69e2015-07-24 07:52:41 -07001811 // reset server position to 0 as we have new cblk.
1812 mServer = 0;
1813
Glenn Kastene3aa6592012-12-04 12:22:46 -08001814 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001815 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001816 mStaticProxy.clear();
Eric Laurent21da6472017-11-09 16:29:26 -08001817 mProxy = new AudioTrackClientProxy(cblk, buffers, mFrameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001818 } else {
Eric Laurent21da6472017-11-09 16:29:26 -08001819 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, mFrameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001820 mProxy = mStaticProxy;
1821 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001822
1823 mProxy->setVolumeLR(gain_minifloat_pack(
1824 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1825 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1826
Glenn Kastene3aa6592012-12-04 12:22:46 -08001827 mProxy->setSendLevel(mSendLevel);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001828 const uint32_t effectiveSampleRate = adjustSampleRate(mSampleRate, mPlaybackRate.mPitch);
1829 const float effectiveSpeed = adjustSpeed(mPlaybackRate.mSpeed, mPlaybackRate.mPitch);
1830 const float effectivePitch = adjustPitch(mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001831 mProxy->setSampleRate(effectiveSampleRate);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001832
1833 AudioPlaybackRate playbackRateTemp = mPlaybackRate;
1834 playbackRateTemp.mSpeed = effectiveSpeed;
1835 playbackRateTemp.mPitch = effectivePitch;
1836 mProxy->setPlaybackRate(playbackRateTemp);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001837 mProxy->setMinimum(mNotificationFramesAct);
1838
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001839 if (mDualMonoMode != AUDIO_DUAL_MONO_MODE_OFF) {
1840 setDualMonoMode_l(mDualMonoMode);
1841 }
1842 if (mAudioDescriptionMixLeveldB != -std::numeric_limits<float>::infinity()) {
1843 setAudioDescriptionMixLevel_l(mAudioDescriptionMixLeveldB);
1844 }
1845
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001846 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001847 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001848
Andy Hungb68f5eb2019-12-03 16:49:17 -08001849 // This is the first log sent from the AudioTrack client.
1850 // The creation of the audio track by AudioFlinger (in the code above)
1851 // is the first log of the AudioTrack and must be present before
1852 // any AudioTrack client logs will be accepted.
Andy Hungea840382020-05-05 21:50:17 -07001853
Andy Hungb68f5eb2019-12-03 16:49:17 -08001854 mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_TRACK) + std::to_string(mPortId);
1855 mediametrics::LogItem(mMetricsId)
1856 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CREATE)
1857 // the following are immutable
Andy Hunga629bd12020-06-05 16:03:53 -07001858 .set(AMEDIAMETRICS_PROP_FLAGS, toString(mFlags).c_str())
1859 .set(AMEDIAMETRICS_PROP_ORIGINALFLAGS, toString(mOrigFlags).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08001860 .set(AMEDIAMETRICS_PROP_SESSIONID, (int32_t)mSessionId)
Andy Hung3a5c2f32021-02-17 15:06:42 -08001861 .set(AMEDIAMETRICS_PROP_LOGSESSIONID, mLogSessionId)
Andy Hung839a3062021-02-17 11:15:16 -08001862 .set(AMEDIAMETRICS_PROP_PLAYERIID, mPlayerIId)
Andy Hungb68f5eb2019-12-03 16:49:17 -08001863 .set(AMEDIAMETRICS_PROP_TRACKID, mPortId) // dup from key
Andy Hungb68f5eb2019-12-03 16:49:17 -08001864 .set(AMEDIAMETRICS_PROP_CONTENTTYPE, toString(mAttributes.content_type).c_str())
1865 .set(AMEDIAMETRICS_PROP_USAGE, toString(mAttributes.usage).c_str())
1866 .set(AMEDIAMETRICS_PROP_THREADID, (int32_t)output.outputId)
1867 .set(AMEDIAMETRICS_PROP_SELECTEDDEVICEID, (int32_t)mSelectedDeviceId)
1868 .set(AMEDIAMETRICS_PROP_ROUTEDDEVICEID, (int32_t)mRoutedDeviceId)
1869 .set(AMEDIAMETRICS_PROP_ENCODING, toString(mFormat).c_str())
1870 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
1871 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
1872 // the following are NOT immutable
1873 .set(AMEDIAMETRICS_PROP_VOLUME_LEFT, (double)mVolume[AUDIO_INTERLEAVE_LEFT])
1874 .set(AMEDIAMETRICS_PROP_VOLUME_RIGHT, (double)mVolume[AUDIO_INTERLEAVE_RIGHT])
1875 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
1876 .set(AMEDIAMETRICS_PROP_AUXEFFECTID, (int32_t)mAuxEffectId)
1877 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
1878 .set(AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)mPlaybackRate.mSpeed)
1879 .set(AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)mPlaybackRate.mPitch)
1880 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1881 AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)effectiveSampleRate)
1882 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1883 AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)effectiveSpeed)
1884 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1885 AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)effectivePitch)
1886 .record();
1887
1888 // mSendLevel
1889 // mReqFrameCount?
1890 // mNotificationFramesAct, mNotificationFramesReq, mNotificationsPerBufferReq
1891 // mLatency, mAfLatency, mAfFrameCount, mAfSampleRate
1892
Glenn Kasten38e905b2014-01-13 10:21:48 -08001893 }
1894
Eric Laurentf32d7812017-11-30 14:44:07 -08001895exit:
1896 if (status != NO_ERROR && callbackAdded) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001897 // note: mOutput is always valid is callbackAdded is true
Eric Laurent09f1ed22019-04-24 17:45:17 -07001898 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001899 }
Eric Laurentf32d7812017-11-30 14:44:07 -08001900
1901 mStatus = status;
Eric Laurent21da6472017-11-09 16:29:26 -08001902
1903 // sp<IAudioTrack> track destructor will cause releaseOutput() to be called by AudioFlinger
Glenn Kasten38e905b2014-01-13 10:21:48 -08001904 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001905}
1906
Glenn Kastenb46f3942015-03-09 12:00:30 -07001907status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001908{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001909 if (audioBuffer == NULL) {
Glenn Kasten551b5352015-03-20 11:30:28 -07001910 if (nonContig != NULL) {
1911 *nonContig = 0;
1912 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001913 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001914 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001915 if (mTransfer != TRANSFER_OBTAIN) {
1916 audioBuffer->frameCount = 0;
1917 audioBuffer->size = 0;
1918 audioBuffer->raw = NULL;
Glenn Kasten551b5352015-03-20 11:30:28 -07001919 if (nonContig != NULL) {
1920 *nonContig = 0;
1921 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001922 return INVALID_OPERATION;
1923 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001924
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001925 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001926 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001927 if (waitCount == -1) {
1928 requested = &ClientProxy::kForever;
1929 } else if (waitCount == 0) {
1930 requested = &ClientProxy::kNonBlocking;
1931 } else if (waitCount > 0) {
Chih-Hung Hsiehbca74292018-08-10 16:06:07 -07001932 time_t ms = WAIT_PERIOD_MS * (time_t) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001933 timeout.tv_sec = ms / 1000;
Andy Hung06a730b2020-04-09 13:28:31 -07001934 timeout.tv_nsec = (ms % 1000) * 1000000;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001935 requested = &timeout;
1936 } else {
Eric Laurent973db022018-11-20 14:54:31 -08001937 ALOGE("%s(%d): invalid waitCount %d", __func__, mPortId, waitCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001938 requested = NULL;
1939 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001940 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001941}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001942
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001943status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1944 struct timespec *elapsed, size_t *nonContig)
1945{
1946 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1947 uint32_t oldSequence = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001948
1949 Proxy::Buffer buffer;
1950 status_t status = NO_ERROR;
1951
1952 static const int32_t kMaxTries = 5;
1953 int32_t tryCounter = kMaxTries;
1954
1955 do {
1956 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1957 // keep them from going away if another thread re-creates the track during obtainBuffer()
1958 sp<AudioTrackClientProxy> proxy;
1959 sp<IMemory> iMem;
1960
1961 { // start of lock scope
1962 AutoMutex lock(mLock);
1963
Glenn Kasten305996c2020-01-27 08:03:37 -08001964 uint32_t newSequence = mSequence;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001965 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1966 if (status == DEAD_OBJECT) {
1967 // re-create track, unless someone else has already done so
1968 if (newSequence == oldSequence) {
1969 status = restoreTrack_l("obtainBuffer");
1970 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001971 buffer.mFrameCount = 0;
1972 buffer.mRaw = NULL;
1973 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001974 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001975 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001976 }
1977 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001978 oldSequence = newSequence;
1979
Eric Laurent4d231dc2016-03-11 18:38:23 -08001980 if (status == NOT_ENOUGH_DATA) {
1981 restartIfDisabled();
1982 }
1983
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001984 // Keep the extra references
1985 proxy = mProxy;
1986 iMem = mCblkMemory;
1987
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001988 if (mState == STATE_STOPPING) {
1989 status = -EINTR;
1990 buffer.mFrameCount = 0;
1991 buffer.mRaw = NULL;
1992 buffer.mNonContig = 0;
1993 break;
1994 }
1995
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001996 // Non-blocking if track is stopped or paused
1997 if (mState != STATE_ACTIVE) {
1998 requested = &ClientProxy::kNonBlocking;
1999 }
2000
2001 } // end of lock scope
2002
2003 buffer.mFrameCount = audioBuffer->frameCount;
2004 // FIXME starts the requested timeout and elapsed over from scratch
2005 status = proxy->obtainBuffer(&buffer, requested, elapsed);
Eric Laurent4d231dc2016-03-11 18:38:23 -08002006 } while (((status == DEAD_OBJECT) || (status == NOT_ENOUGH_DATA)) && (tryCounter-- > 0));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002007
2008 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08002009 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002010 audioBuffer->raw = buffer.mRaw;
Glenn Kasten305996c2020-01-27 08:03:37 -08002011 audioBuffer->sequence = oldSequence;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002012 if (nonContig != NULL) {
2013 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002014 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002015 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002016}
2017
Glenn Kasten54a8a452015-03-09 12:03:00 -07002018void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002019{
Glenn Kasten3f02be22015-03-09 11:59:04 -07002020 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002021 if (mTransfer == TRANSFER_SHARED) {
2022 return;
2023 }
2024
Andy Hungabdb9902015-01-12 15:08:22 -08002025 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002026 if (stepCount == 0) {
2027 return;
2028 }
2029
2030 Proxy::Buffer buffer;
2031 buffer.mFrameCount = stepCount;
2032 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08002033
Eric Laurent1703cdf2011-03-07 14:52:59 -08002034 AutoMutex lock(mLock);
Glenn Kasten305996c2020-01-27 08:03:37 -08002035 if (audioBuffer->sequence != mSequence) {
2036 // This Buffer came from a different IAudioTrack instance, so ignore the releaseBuffer
2037 ALOGD("%s is no-op due to IAudioTrack sequence mismatch %u != %u",
2038 __func__, audioBuffer->sequence, mSequence);
2039 return;
2040 }
Glenn Kasten200092b2014-08-15 15:13:30 -07002041 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002042 mInUnderrun = false;
2043 mProxy->releaseBuffer(&buffer);
2044
2045 // restart track if it was disabled by audioflinger due to previous underrun
Eric Laurent4d231dc2016-03-11 18:38:23 -08002046 restartIfDisabled();
2047}
2048
2049void AudioTrack::restartIfDisabled()
2050{
2051 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
2052 if ((mState == STATE_ACTIVE) && (flags & CBLK_DISABLED)) {
Andy Hungfb8ede22018-09-12 19:03:24 -07002053 ALOGW("%s(%d): releaseBuffer() track %p disabled due to previous underrun, restarting",
Eric Laurent973db022018-11-20 14:54:31 -08002054 __func__, mPortId, this);
Eric Laurent4d231dc2016-03-11 18:38:23 -08002055 // FIXME ignoring status
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002056 status_t status;
2057 mAudioTrack->start(&status);
Eric Laurentdf839842012-05-31 14:27:14 -07002058 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002059}
2060
2061// -------------------------------------------------------------------------
2062
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08002063ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002064{
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07002065 if (mTransfer != TRANSFER_SYNC && mTransfer != TRANSFER_SYNC_NOTIF_CALLBACK) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07002066 return INVALID_OPERATION;
2067 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002068
Eric Laurentab5cdba2014-06-09 17:22:27 -07002069 if (isDirect()) {
2070 AutoMutex lock(mLock);
2071 int32_t flags = android_atomic_and(
2072 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
2073 &mCblk->mFlags);
2074 if (flags & CBLK_INVALID) {
2075 return DEAD_OBJECT;
2076 }
2077 }
2078
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002079 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Jiabin Huang447cea72020-07-28 22:35:18 +00002080 // Validation: user is most-likely passing an error code, and it would
Glenn Kasten99e53b82012-01-19 08:59:58 -08002081 // make the return value ambiguous (actualSize vs error).
Andy Hungfb8ede22018-09-12 19:03:24 -07002082 ALOGE("%s(%d): AudioTrack::write(buffer=%p, size=%zu (%zd)",
Eric Laurent973db022018-11-20 14:54:31 -08002083 __func__, mPortId, buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002084 return BAD_VALUE;
2085 }
2086
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002087 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002088 Buffer audioBuffer;
2089
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002090 while (userSize >= mFrameSize) {
2091 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07002092
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08002093 status_t err = obtainBuffer(&audioBuffer,
2094 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002095 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002096 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002097 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07002098 }
Glenn Kasten0a2f1512016-07-22 08:06:37 -07002099 if (err == TIMED_OUT || err == -EINTR) {
2100 err = WOULD_BLOCK;
2101 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002102 return ssize_t(err);
2103 }
2104
Glenn Kastenae4b8792015-03-20 09:04:21 -07002105 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08002106 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002107 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002108 userSize -= toWrite;
2109 written += toWrite;
2110
2111 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002112 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002113
Andy Hungea2b9c02016-02-12 17:06:53 -08002114 if (written > 0) {
2115 mFramesWritten += written / mFrameSize;
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07002116
2117 if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
2118 const sp<AudioTrackThread> t = mAudioTrackThread;
2119 if (t != 0) {
2120 // causes wake up of the playback thread, that will callback the client for
2121 // more data (with EVENT_CAN_WRITE_MORE_DATA) in processAudioBuffer()
2122 t->wake();
2123 }
2124 }
Andy Hungea2b9c02016-02-12 17:06:53 -08002125 }
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07002126
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002127 return written;
2128}
2129
2130// -------------------------------------------------------------------------
2131
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002132nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002133{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07002134 // Currently the AudioTrack thread is not created if there are no callbacks.
2135 // Would it ever make sense to run the thread, even without callbacks?
2136 // If so, then replace this by checks at each use for mCbf != NULL.
2137 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
2138
Eric Laurent1703cdf2011-03-07 14:52:59 -08002139 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07002140 if (mAwaitBoost) {
2141 mAwaitBoost = false;
2142 mLock.unlock();
2143 static const int32_t kMaxTries = 5;
2144 int32_t tryCounter = kMaxTries;
2145 uint32_t pollUs = 10000;
2146 do {
Glenn Kasten8255ba72016-08-23 13:54:23 -07002147 int policy = sched_getscheduler(0) & ~SCHED_RESET_ON_FORK;
Glenn Kastena07f17c2013-04-23 12:39:37 -07002148 if (policy == SCHED_FIFO || policy == SCHED_RR) {
2149 break;
2150 }
2151 usleep(pollUs);
2152 pollUs <<= 1;
2153 } while (tryCounter-- > 0);
2154 if (tryCounter < 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -07002155 ALOGE("%s(%d): did not receive expected priority boost on time",
Eric Laurent973db022018-11-20 14:54:31 -08002156 __func__, mPortId);
Glenn Kastena07f17c2013-04-23 12:39:37 -07002157 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07002158 // Run again immediately
2159 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07002160 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002161
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002162 // Can only reference mCblk while locked
2163 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07002164 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08002165
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002166 // Check for track invalidation
2167 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002168 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
2169 // AudioSystem cache. We should not exit here but after calling the callback so
2170 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07002171 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Lajos Molnarf1063e22015-04-17 15:19:42 -07002172 status_t status __unused = restoreTrack_l("processAudioBuffer");
2173 // FIXME unused status
Andy Hung53c3b5f2014-12-15 16:42:05 -08002174 // after restoration, continue below to make sure that the loop and buffer events
2175 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002176 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002177 }
2178
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002179 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002180 bool active = mState == STATE_ACTIVE;
2181
2182 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
2183 bool newUnderrun = false;
2184 if (flags & CBLK_UNDERRUN) {
2185#if 0
2186 // Currently in shared buffer mode, when the server reaches the end of buffer,
2187 // the track stays active in continuous underrun state. It's up to the application
2188 // to pause or stop the track, or set the position to a new offset within buffer.
2189 // This was some experimental code to auto-pause on underrun. Keeping it here
2190 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
2191 if (mTransfer == TRANSFER_SHARED) {
2192 mState = STATE_PAUSED;
2193 active = false;
2194 }
2195#endif
2196 if (!mInUnderrun) {
2197 mInUnderrun = true;
2198 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002199 }
2200 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07002201
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002202 // Get current position of server
Andy Hung90e8a972015-11-09 16:42:40 -08002203 Modulo<uint32_t> position(updateAndGetPosition_l());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002204
2205 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002206 bool markerReached = false;
Andy Hung90e8a972015-11-09 16:42:40 -08002207 Modulo<uint32_t> markerPosition(mMarkerPosition);
2208 // uses 32 bit wraparound for comparison with position.
2209 if (!mMarkerReached && markerPosition.value() > 0 && position >= markerPosition) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002210 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002211 }
2212
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002213 // Determine number of new position callback(s) that will be needed, while locked
2214 size_t newPosCount = 0;
Andy Hung90e8a972015-11-09 16:42:40 -08002215 Modulo<uint32_t> newPosition(mNewPosition);
2216 uint32_t updatePeriod = mUpdatePeriod;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002217 // FIXME fails for wraparound, need 64 bits
2218 if (updatePeriod > 0 && position >= newPosition) {
Andy Hung90e8a972015-11-09 16:42:40 -08002219 newPosCount = ((position - newPosition).value() / updatePeriod) + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002220 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002221 }
2222
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002223 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002224 uint32_t sampleRate = mSampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002225 float speed = mPlaybackRate.mSpeed;
Andy Hunga7f03352015-05-31 21:54:49 -07002226 const uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002227 if (mRefreshRemaining) {
2228 mRefreshRemaining = false;
2229 mRemainingFrames = notificationFrames;
2230 mRetryOnPartialBuffer = false;
2231 }
2232 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002233 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07002234 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002235
Andy Hung53c3b5f2014-12-15 16:42:05 -08002236 // Determine the number of new loop callback(s) that will be needed, while locked.
2237 int loopCountNotifications = 0;
2238 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
2239
2240 if (mLoopCount > 0) {
2241 int loopCount;
2242 size_t bufferPosition;
2243 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
2244 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
2245 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
2246 mLoopCountNotified = loopCount; // discard any excess notifications
2247 } else if (mLoopCount < 0) {
2248 // FIXME: We're not accurate with notification count and position with infinite looping
2249 // since loopCount from server side will always return -1 (we could decrement it).
2250 size_t bufferPosition = mStaticProxy->getBufferPosition();
2251 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
2252 loopPeriod = mLoopEnd - bufferPosition;
2253 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
2254 size_t bufferPosition = mStaticProxy->getBufferPosition();
2255 loopPeriod = mFrameCount - bufferPosition;
2256 }
2257
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002258 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08002259 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002260 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
2261
2262 mLock.unlock();
2263
Andy Hunga7f03352015-05-31 21:54:49 -07002264 // get anchor time to account for callbacks.
2265 const nsecs_t timeBeforeCallbacks = systemTime();
2266
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002267 if (waitStreamEnd) {
Andy Hunga7f03352015-05-31 21:54:49 -07002268 // FIXME: Instead of blocking in proxy->waitStreamEndDone(), Callback thread
2269 // should wait on proxy futex and handle CBLK_STREAM_END_DONE within this function
2270 // (and make sure we don't callback for more data while we're stopping).
2271 // This helps with position, marker notifications, and track invalidation.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002272 struct timespec timeout;
2273 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
2274 timeout.tv_nsec = 0;
2275
Glenn Kasten96f04882013-09-20 09:28:56 -07002276 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002277 switch (status) {
2278 case NO_ERROR:
2279 case DEAD_OBJECT:
2280 case TIMED_OUT:
Andy Hung39609a02015-09-03 16:38:38 -07002281 if (status != DEAD_OBJECT) {
2282 // for DEAD_OBJECT, we do not send a EVENT_STREAM_END after stop();
2283 // instead, the application should handle the EVENT_NEW_IAUDIOTRACK.
2284 mCbf(EVENT_STREAM_END, mUserData, NULL);
2285 }
Glenn Kasten96f04882013-09-20 09:28:56 -07002286 {
2287 AutoMutex lock(mLock);
2288 // The previously assigned value of waitStreamEnd is no longer valid,
2289 // since the mutex has been unlocked and either the callback handler
2290 // or another thread could have re-started the AudioTrack during that time.
2291 waitStreamEnd = mState == STATE_STOPPING;
2292 if (waitStreamEnd) {
2293 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07002294 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002295 }
2296 }
Glenn Kasten96f04882013-09-20 09:28:56 -07002297 if (waitStreamEnd && status != DEAD_OBJECT) {
2298 return NS_INACTIVE;
2299 }
2300 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002301 }
Glenn Kasten96f04882013-09-20 09:28:56 -07002302 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002303 }
2304
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002305 // perform callbacks while unlocked
2306 if (newUnderrun) {
2307 mCbf(EVENT_UNDERRUN, mUserData, NULL);
2308 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08002309 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002310 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002311 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002312 }
2313 if (flags & CBLK_BUFFER_END) {
2314 mCbf(EVENT_BUFFER_END, mUserData, NULL);
2315 }
2316 if (markerReached) {
2317 mCbf(EVENT_MARKER, mUserData, &markerPosition);
2318 }
2319 while (newPosCount > 0) {
Andy Hung90e8a972015-11-09 16:42:40 -08002320 size_t temp = newPosition.value(); // FIXME size_t != uint32_t
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002321 mCbf(EVENT_NEW_POS, mUserData, &temp);
2322 newPosition += updatePeriod;
2323 newPosCount--;
2324 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002325
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002326 if (mObservedSequence != sequence) {
2327 mObservedSequence = sequence;
2328 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002329 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07002330 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002331 return NS_INACTIVE;
2332 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002333 }
2334
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002335 // if inactive, then don't run me again until re-started
2336 if (!active) {
2337 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07002338 }
2339
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002340 // Compute the estimated time until the next timed event (position, markers, loops)
2341 // FIXME only for non-compressed audio
2342 uint32_t minFrames = ~0;
2343 if (!markerReached && position < markerPosition) {
Andy Hung90e8a972015-11-09 16:42:40 -08002344 minFrames = (markerPosition - position).value();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002345 }
2346 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08002347 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002348 minFrames = loopPeriod;
2349 }
Andy Hung2d85f092015-01-07 12:45:13 -08002350 if (updatePeriod > 0) {
Andy Hung90e8a972015-11-09 16:42:40 -08002351 minFrames = min(minFrames, (newPosition - position).value());
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002352 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002353
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002354 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
2355 static const uint32_t kPoll = 0;
2356 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
2357 minFrames = kPoll * notificationFrames;
2358 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07002359
Andy Hunga7f03352015-05-31 21:54:49 -07002360 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
2361 static const nsecs_t kWaitPeriodNs = WAIT_PERIOD_MS * 1000000LL;
2362 const nsecs_t timeAfterCallbacks = systemTime();
2363
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002364 // Convert frame units to time units
2365 nsecs_t ns = NS_WHENEVER;
2366 if (minFrames != (uint32_t) ~0) {
jiabinc7bb8322017-09-06 18:20:11 -07002367 // AudioFlinger consumption of client data may be irregular when coming out of device
2368 // standby since the kernel buffers require filling. This is throttled to no more than 2x
2369 // the expected rate in the MixerThread. Hence, we reduce the estimated time to wait by one
2370 // half (but no more than half a second) to improve callback accuracy during these temporary
2371 // data surges.
2372 const nsecs_t estimatedNs = framesToNanoseconds(minFrames, sampleRate, speed);
2373 constexpr nsecs_t maxThrottleCompensationNs = 500000000LL;
2374 ns = estimatedNs - min(estimatedNs / 2, maxThrottleCompensationNs) + kWaitPeriodNs;
Andy Hunga7f03352015-05-31 21:54:49 -07002375 ns -= (timeAfterCallbacks - timeBeforeCallbacks); // account for callback time
2376 // TODO: Should we warn if the callback time is too long?
2377 if (ns < 0) ns = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002378 }
2379
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07002380 // If not supplying data by EVENT_MORE_DATA or EVENT_CAN_WRITE_MORE_DATA, then we're done
2381 if (mTransfer != TRANSFER_CALLBACK && mTransfer != TRANSFER_SYNC_NOTIF_CALLBACK) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002382 return ns;
2383 }
2384
Andy Hunga7f03352015-05-31 21:54:49 -07002385 // EVENT_MORE_DATA callback handling.
2386 // Timing for linear pcm audio data formats can be derived directly from the
2387 // buffer fill level.
2388 // Timing for compressed data is not directly available from the buffer fill level,
2389 // rather indirectly from waiting for blocking mode callbacks or waiting for obtain()
2390 // to return a certain fill level.
2391
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002392 struct timespec timeout;
2393 const struct timespec *requested = &ClientProxy::kForever;
2394 if (ns != NS_WHENEVER) {
2395 timeout.tv_sec = ns / 1000000000LL;
2396 timeout.tv_nsec = ns % 1000000000LL;
Andy Hungfb8ede22018-09-12 19:03:24 -07002397 ALOGV("%s(%d): timeout %ld.%03d",
Eric Laurent973db022018-11-20 14:54:31 -08002398 __func__, mPortId, timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002399 requested = &timeout;
2400 }
2401
Andy Hungea2b9c02016-02-12 17:06:53 -08002402 size_t writtenFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002403 while (mRemainingFrames > 0) {
2404
2405 Buffer audioBuffer;
2406 audioBuffer.frameCount = mRemainingFrames;
2407 size_t nonContig;
2408 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
2409 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Andy Hungfb8ede22018-09-12 19:03:24 -07002410 "%s(%d): obtainBuffer() err=%d frameCount=%zu",
Eric Laurent973db022018-11-20 14:54:31 -08002411 __func__, mPortId, err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002412 requested = &ClientProxy::kNonBlocking;
2413 size_t avail = audioBuffer.frameCount + nonContig;
Andy Hungfb8ede22018-09-12 19:03:24 -07002414 ALOGV("%s(%d): obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Eric Laurent973db022018-11-20 14:54:31 -08002415 __func__, mPortId, mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002416 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002417 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
2418 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten606fbc12015-10-22 15:28:15 -07002419 // FIXME bug 25195759
2420 return 1000000;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002421 }
Andy Hungfb8ede22018-09-12 19:03:24 -07002422 ALOGE("%s(%d): Error %d obtaining an audio buffer, giving up.",
Eric Laurent973db022018-11-20 14:54:31 -08002423 __func__, mPortId, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002424 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002425 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002426
Phil Burkfdb3c072016-02-09 10:47:02 -08002427 if (mRetryOnPartialBuffer && audio_has_proportional_frames(mFormat)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002428 mRetryOnPartialBuffer = false;
2429 if (avail < mRemainingFrames) {
Andy Hunga7f03352015-05-31 21:54:49 -07002430 if (ns > 0) { // account for obtain time
2431 const nsecs_t timeNow = systemTime();
2432 ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2433 }
Andy Hungeb6e6502019-04-29 13:47:40 -07002434
2435 // delayNs is first computed by the additional frames required in the buffer.
2436 nsecs_t delayNs = framesToNanoseconds(
2437 mRemainingFrames - avail, sampleRate, speed);
2438
2439 // afNs is the AudioFlinger mixer period in ns.
2440 const nsecs_t afNs = framesToNanoseconds(mAfFrameCount, mAfSampleRate, speed);
2441
2442 // If the AudioTrack is double buffered based on the AudioFlinger mixer period,
2443 // we may have a race if we wait based on the number of frames desired.
2444 // This is a possible issue with resampling and AAudio.
2445 //
2446 // The granularity of audioflinger processing is one mixer period; if
2447 // our wait time is less than one mixer period, wait at most half the period.
2448 if (delayNs < afNs) {
2449 delayNs = std::min(delayNs, afNs / 2);
2450 }
2451
2452 // adjust our ns wait by delayNs.
2453 if (ns < 0 /* NS_WHENEVER */ || delayNs < ns) {
2454 ns = delayNs;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002455 }
2456 return ns;
2457 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07002458 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002459
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002460 size_t reqSize = audioBuffer.size;
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07002461 if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
2462 // when notifying client it can write more data, pass the total size that can be
2463 // written in the next write() call, since it's not passed through the callback
2464 audioBuffer.size += nonContig;
2465 }
2466 mCbf(mTransfer == TRANSFER_CALLBACK ? EVENT_MORE_DATA : EVENT_CAN_WRITE_MORE_DATA,
2467 mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002468 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002469
Jiabin Huang447cea72020-07-28 22:35:18 +00002470 // Validate on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002471 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Andy Hungfb8ede22018-09-12 19:03:24 -07002472 ALOGE("%s(%d): EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
Eric Laurent973db022018-11-20 14:54:31 -08002473 __func__, mPortId, reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002474 return NS_NEVER;
2475 }
2476
2477 if (writtenSize == 0) {
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07002478 if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
2479 // The callback EVENT_CAN_WRITE_MORE_DATA was processed in the JNI of
2480 // android.media.AudioTrack. The JNI is not using the callback to provide data,
2481 // it only signals to the Java client that it can provide more data, which
2482 // this track is read to accept now.
2483 // The playback thread will be awaken at the next ::write()
2484 return NS_WHENEVER;
2485 }
The Android Open Source Project8555d082009-03-05 14:34:35 -08002486 // The callback is done filling buffers
2487 // Keep this thread going to handle timed events and
2488 // still try to get more data in intervals of WAIT_PERIOD_MS
2489 // but don't just loop and block the CPU, so wait
Andy Hunga7f03352015-05-31 21:54:49 -07002490
2491 // mCbf(EVENT_MORE_DATA, ...) might either
2492 // (1) Block until it can fill the buffer, returning 0 size on EOS.
2493 // (2) Block until it can fill the buffer, returning 0 data (silence) on EOS.
2494 // (3) Return 0 size when no data is available, does not wait for more data.
2495 //
2496 // (1) and (2) occurs with AudioPlayer/AwesomePlayer; (3) occurs with NuPlayer.
2497 // We try to compute the wait time to avoid a tight sleep-wait cycle,
2498 // especially for case (3).
2499 //
2500 // The decision to support (1) and (2) affect the sizing of mRemainingFrames
2501 // and this loop; whereas for case (3) we could simply check once with the full
2502 // buffer size and skip the loop entirely.
2503
2504 nsecs_t myns;
Phil Burkfdb3c072016-02-09 10:47:02 -08002505 if (audio_has_proportional_frames(mFormat)) {
Andy Hunga7f03352015-05-31 21:54:49 -07002506 // time to wait based on buffer occupancy
2507 const nsecs_t datans = mRemainingFrames <= avail ? 0 :
2508 framesToNanoseconds(mRemainingFrames - avail, sampleRate, speed);
2509 // audio flinger thread buffer size (TODO: adjust for fast tracks)
Glenn Kastenea38ee72016-04-18 11:08:01 -07002510 // FIXME: use mAfFrameCountHAL instead of mAfFrameCount below for fast tracks.
Andy Hunga7f03352015-05-31 21:54:49 -07002511 const nsecs_t afns = framesToNanoseconds(mAfFrameCount, mAfSampleRate, speed);
2512 // add a half the AudioFlinger buffer time to avoid soaking CPU if datans is 0.
2513 myns = datans + (afns / 2);
2514 } else {
2515 // FIXME: This could ping quite a bit if the buffer isn't full.
2516 // Note that when mState is stopping we waitStreamEnd, so it never gets here.
2517 myns = kWaitPeriodNs;
2518 }
2519 if (ns > 0) { // account for obtain and callback time
2520 const nsecs_t timeNow = systemTime();
2521 ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2522 }
2523 if (ns < 0 /* NS_WHENEVER */ || myns < ns) {
2524 ns = myns;
2525 }
2526 return ns;
Glenn Kastend65d73c2012-06-22 17:21:07 -07002527 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002528
Glenn Kasten138d6f92015-03-20 10:54:51 -07002529 size_t releasedFrames = writtenSize / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002530 audioBuffer.frameCount = releasedFrames;
2531 mRemainingFrames -= releasedFrames;
2532 if (misalignment >= releasedFrames) {
2533 misalignment -= releasedFrames;
2534 } else {
2535 misalignment = 0;
2536 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002537
2538 releaseBuffer(&audioBuffer);
Andy Hungea2b9c02016-02-12 17:06:53 -08002539 writtenFrames += releasedFrames;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002540
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002541 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
2542 // if callback doesn't like to accept the full chunk
2543 if (writtenSize < reqSize) {
2544 continue;
2545 }
2546
2547 // There could be enough non-contiguous frames available to satisfy the remaining request
2548 if (mRemainingFrames <= nonContig) {
2549 continue;
2550 }
2551
2552#if 0
2553 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
2554 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
2555 // that total to a sum == notificationFrames.
2556 if (0 < misalignment && misalignment <= mRemainingFrames) {
2557 mRemainingFrames = misalignment;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002558 return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002559 }
2560#endif
2561
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002562 }
Andy Hungea2b9c02016-02-12 17:06:53 -08002563 if (writtenFrames > 0) {
2564 AutoMutex lock(mLock);
2565 mFramesWritten += writtenFrames;
2566 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002567 mRemainingFrames = notificationFrames;
2568 mRetryOnPartialBuffer = true;
2569
2570 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
2571 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002572}
2573
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002574status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08002575{
Andy Hungb68f5eb2019-12-03 16:49:17 -08002576 status_t result = NO_ERROR; // logged: make sure to set this before returning.
2577 const int64_t beginNs = systemTime();
Andy Hunga6b27032020-04-27 10:34:24 -07002578 mediametrics::Defer defer([&] {
Andy Hungb68f5eb2019-12-03 16:49:17 -08002579 mediametrics::LogItem(mMetricsId)
2580 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_RESTORE)
Andy Hungea840382020-05-05 21:50:17 -07002581 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
Andy Hungb68f5eb2019-12-03 16:49:17 -08002582 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
2583 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
2584 .set(AMEDIAMETRICS_PROP_WHERE, from)
2585 .record(); });
2586
Andy Hungfb8ede22018-09-12 19:03:24 -07002587 ALOGW("%s(%d): dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurent973db022018-11-20 14:54:31 -08002588 __func__, mPortId, isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002589 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002590
Glenn Kastena47f3162012-11-07 10:13:08 -08002591 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08002592 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08002593 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07002594
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002595 if (isOffloadedOrDirect_l() || mDoNotReconnect) {
Andy Hung1f1db832015-06-08 13:26:10 -07002596 // FIXME re-creation of offloaded and direct tracks is not yet implemented;
2597 // reconsider enabling for linear PCM encodings when position can be preserved.
Andy Hungb68f5eb2019-12-03 16:49:17 -08002598 result = DEAD_OBJECT;
2599 return result;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002600 }
2601
Phil Burk2812d9e2016-01-04 10:34:30 -08002602 // Save so we can return count since creation.
2603 mUnderrunCountOffset = getUnderrunCount_l();
2604
Glenn Kasten200092b2014-08-15 15:13:30 -07002605 // save the old static buffer position
Andy Hungf20a4e92016-08-15 19:10:34 -07002606 uint32_t staticPosition = 0;
Andy Hung4ede21d2014-12-12 15:37:34 -08002607 size_t bufferPosition = 0;
2608 int loopCount = 0;
2609 if (mStaticProxy != 0) {
2610 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
Andy Hungf20a4e92016-08-15 19:10:34 -07002611 staticPosition = mStaticProxy->getPosition().unsignedValue();
Andy Hung4ede21d2014-12-12 15:37:34 -08002612 }
Glenn Kasten200092b2014-08-15 15:13:30 -07002613
Mikhail Naganovb13b35d2018-03-30 17:21:14 -07002614 // See b/74409267. Connecting to a BT A2DP device supporting multiple codecs
2615 // causes a lot of churn on the service side, and it can reject starting
2616 // playback of a previously created track. May also apply to other cases.
2617 const int INITIAL_RETRIES = 3;
2618 int retries = INITIAL_RETRIES;
2619retry:
2620 if (retries < INITIAL_RETRIES) {
2621 // See the comment for clearAudioConfigCache at the start of the function.
2622 AudioSystem::clearAudioConfigCache();
2623 }
Haynes Mathew Georgeae34ed22016-01-28 11:58:39 -08002624 mFlags = mOrigFlags;
2625
Glenn Kasten200092b2014-08-15 15:13:30 -07002626 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08002627 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07002628 // It will also delete the strong references on previous IAudioTrack and IMemory.
2629 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Andy Hungb68f5eb2019-12-03 16:49:17 -08002630 result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07002631
Eric Laurent6ec546d2018-10-10 16:52:14 -07002632 if (result == NO_ERROR) {
Andy Hungd7bd69e2015-07-24 07:52:41 -07002633 // take the frames that will be lost by track recreation into account in saved position
2634 // For streaming tracks, this is the amount we obtained from the user/client
2635 // (not the number actually consumed at the server - those are already lost).
2636 if (mStaticProxy == 0) {
2637 mPosition = mReleased;
2638 }
Andy Hung4ede21d2014-12-12 15:37:34 -08002639 // Continue playback from last known position and restore loop.
2640 if (mStaticProxy != 0) {
2641 if (loopCount != 0) {
2642 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
2643 mLoopStart, mLoopEnd, loopCount);
2644 } else {
2645 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002646 if (bufferPosition == mFrameCount) {
Eric Laurent973db022018-11-20 14:54:31 -08002647 ALOGD("%s(%d): restoring track at end of static buffer", __func__, mPortId);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002648 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002649 }
2650 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002651 // restore volume handler
Andy Hung39399b62017-04-21 15:07:45 -07002652 mVolumeHandler->forall([this](const VolumeShaper &shaper) -> VolumeShaper::Status {
2653 sp<VolumeShaper::Operation> operationToEnd =
2654 new VolumeShaper::Operation(shaper.mOperation);
Andy Hung4ef88d72017-02-21 19:47:53 -08002655 // TODO: Ideally we would restore to the exact xOffset position
2656 // as returned by getVolumeShaperState(), but we don't have that
2657 // information when restoring at the client unless we periodically poll
2658 // the server or create shared memory state.
2659 //
Andy Hung39399b62017-04-21 15:07:45 -07002660 // For now, we simply advance to the end of the VolumeShaper effect
2661 // if it has been started.
2662 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002663 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002664 }
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002665 media::VolumeShaperConfiguration config;
2666 shaper.mConfiguration->writeToParcelable(&config);
2667 media::VolumeShaperOperation operation;
2668 operationToEnd->writeToParcelable(&operation);
2669 status_t status;
2670 mAudioTrack->applyVolumeShaper(config, operation, &status);
2671 return status;
Andy Hung4ef88d72017-02-21 19:47:53 -08002672 });
2673
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002674 if (mState == STATE_ACTIVE) {
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002675 mAudioTrack->start(&result);
Eric Laurent1703cdf2011-03-07 14:52:59 -08002676 }
Andy Hungf20a4e92016-08-15 19:10:34 -07002677 // server resets to zero so we offset
2678 mFramesWrittenServerOffset =
2679 mStaticProxy.get() != nullptr ? staticPosition : mFramesWritten;
2680 mFramesWrittenAtRestore = mFramesWrittenServerOffset;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002681 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002682 if (result != NO_ERROR) {
Eric Laurent973db022018-11-20 14:54:31 -08002683 ALOGW("%s(%d): failed status %d, retries %d", __func__, mPortId, result, retries);
Mikhail Naganovb13b35d2018-03-30 17:21:14 -07002684 if (--retries > 0) {
Eric Laurent6ec546d2018-10-10 16:52:14 -07002685 // leave time for an eventual race condition to clear before retrying
2686 usleep(500000);
Mikhail Naganovb13b35d2018-03-30 17:21:14 -07002687 goto retry;
2688 }
Eric Laurent6ec546d2018-10-10 16:52:14 -07002689 // if no retries left, set invalid bit to force restoring at next occasion
2690 // and avoid inconsistent active state on client and server sides
2691 if (mCblk != nullptr) {
2692 android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
2693 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002694 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002695 return result;
2696}
2697
Andy Hung90e8a972015-11-09 16:42:40 -08002698Modulo<uint32_t> AudioTrack::updateAndGetPosition_l()
Glenn Kasten200092b2014-08-15 15:13:30 -07002699{
2700 // This is the sole place to read server consumed frames
Andy Hung90e8a972015-11-09 16:42:40 -08002701 Modulo<uint32_t> newServer(mProxy->getPosition());
2702 const int32_t delta = (newServer - mServer).signedValue();
Glenn Kasten200092b2014-08-15 15:13:30 -07002703 // TODO There is controversy about whether there can be "negative jitter" in server position.
2704 // This should be investigated further, and if possible, it should be addressed.
2705 // A more definite failure mode is infrequent polling by client.
2706 // One could call (void)getPosition_l() in releaseBuffer(),
2707 // so mReleased and mPosition are always lock-step as best possible.
2708 // That should ensure delta never goes negative for infrequent polling
2709 // unless the server has more than 2^31 frames in its buffer,
2710 // in which case the use of uint32_t for these counters has bigger issues.
Andy Hung90e8a972015-11-09 16:42:40 -08002711 ALOGE_IF(delta < 0,
Andy Hungfb8ede22018-09-12 19:03:24 -07002712 "%s(%d): detected illegal retrograde motion by the server: mServer advanced by %d",
Eric Laurent973db022018-11-20 14:54:31 -08002713 __func__, mPortId, delta);
Chad Brubaker039c27a2015-09-23 15:17:29 -07002714 mServer = newServer;
Andy Hung90e8a972015-11-09 16:42:40 -08002715 if (delta > 0) { // avoid retrograde
2716 mPosition += delta;
2717 }
2718 return mPosition;
Glenn Kasten200092b2014-08-15 15:13:30 -07002719}
2720
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002721bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed)
Andy Hung8edb8dc2015-03-26 19:13:55 -07002722{
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002723 updateLatency_l();
Andy Hung8edb8dc2015-03-26 19:13:55 -07002724 // applicable for mixing tracks only (not offloaded or direct)
2725 if (mStaticProxy != 0) {
2726 return true; // static tracks do not have issues with buffer sizing.
2727 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07002728 const size_t minFrameCount =
Eric Laurent21da6472017-11-09 16:29:26 -08002729 AudioSystem::calculateMinFrameCount(mAfLatency, mAfFrameCount, mAfSampleRate,
2730 sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002731 const bool allowed = mFrameCount >= minFrameCount;
2732 ALOGD_IF(!allowed,
Andy Hungfb8ede22018-09-12 19:03:24 -07002733 "%s(%d): denied "
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002734 "mAfLatency:%u mAfFrameCount:%zu mAfSampleRate:%u sampleRate:%u speed:%f "
2735 "mFrameCount:%zu < minFrameCount:%zu",
Eric Laurent973db022018-11-20 14:54:31 -08002736 __func__, mPortId,
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002737 mAfLatency, mAfFrameCount, mAfSampleRate, sampleRate, speed,
Andy Hung8edb8dc2015-03-26 19:13:55 -07002738 mFrameCount, minFrameCount);
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002739 return allowed;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002740}
2741
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002742status_t AudioTrack::setParameters(const String8& keyValuePairs)
2743{
2744 AutoMutex lock(mLock);
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002745 status_t status;
2746 mAudioTrack->setParameters(keyValuePairs.c_str(), &status);
2747 return status;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002748}
2749
Dean Wheatleya70eef72018-01-04 14:23:50 +11002750status_t AudioTrack::selectPresentation(int presentationId, int programId)
2751{
2752 AutoMutex lock(mLock);
Eric Laurent973db022018-11-20 14:54:31 -08002753 AudioParameter param = AudioParameter();
2754 param.addInt(String8(AudioParameter::keyPresentationId), presentationId);
2755 param.addInt(String8(AudioParameter::keyProgramId), programId);
2756 ALOGV("%s(%d): PresentationId/ProgramId[%s]",
2757 __func__, mPortId, param.toString().string());
2758
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002759 status_t status;
2760 mAudioTrack->setParameters(param.toString().c_str(), &status);
2761 return status;
Dean Wheatleya70eef72018-01-04 14:23:50 +11002762}
2763
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002764VolumeShaper::Status AudioTrack::applyVolumeShaper(
2765 const sp<VolumeShaper::Configuration>& configuration,
2766 const sp<VolumeShaper::Operation>& operation)
2767{
2768 AutoMutex lock(mLock);
Andy Hung4ef88d72017-02-21 19:47:53 -08002769 mVolumeHandler->setIdIfNecessary(configuration);
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002770 media::VolumeShaperConfiguration config;
2771 configuration->writeToParcelable(&config);
2772 media::VolumeShaperOperation op;
2773 operation->writeToParcelable(&op);
2774 VolumeShaper::Status status;
2775 mAudioTrack->applyVolumeShaper(config, op, &status);
Andy Hung39399b62017-04-21 15:07:45 -07002776
2777 if (status == DEAD_OBJECT) {
2778 if (restoreTrack_l("applyVolumeShaper") == OK) {
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002779 mAudioTrack->applyVolumeShaper(config, op, &status);
Andy Hung39399b62017-04-21 15:07:45 -07002780 }
2781 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002782 if (status >= 0) {
2783 // save VolumeShaper for restore
2784 mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung39399b62017-04-21 15:07:45 -07002785 if (mState == STATE_ACTIVE || mState == STATE_STOPPING) {
2786 mVolumeHandler->setStarted();
2787 }
2788 } else {
2789 // warn only if not an expected restore failure.
2790 ALOGW_IF(!((isOffloadedOrDirect_l() || mDoNotReconnect) && status == DEAD_OBJECT),
Eric Laurent973db022018-11-20 14:54:31 -08002791 "%s(%d): applyVolumeShaper failed: %d", __func__, mPortId, status);
Andy Hung4ef88d72017-02-21 19:47:53 -08002792 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002793 return status;
2794}
2795
2796sp<VolumeShaper::State> AudioTrack::getVolumeShaperState(int id)
2797{
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002798 AutoMutex lock(mLock);
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002799 std::optional<media::VolumeShaperState> vss;
2800 mAudioTrack->getVolumeShaperState(id, &vss);
2801 sp<VolumeShaper::State> state;
2802 if (vss.has_value()) {
2803 state = new VolumeShaper::State();
2804 state->readFromParcelable(vss.value());
2805 }
Andy Hung39399b62017-04-21 15:07:45 -07002806 if (state.get() == nullptr && (mCblk->mFlags & CBLK_INVALID) != 0) {
2807 if (restoreTrack_l("getVolumeShaperState") == OK) {
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002808 mAudioTrack->getVolumeShaperState(id, &vss);
2809 if (vss.has_value()) {
2810 state = new VolumeShaper::State();
2811 state->readFromParcelable(vss.value());
2812 }
Andy Hung39399b62017-04-21 15:07:45 -07002813 }
2814 }
2815 return state;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002816}
2817
Andy Hungea2b9c02016-02-12 17:06:53 -08002818status_t AudioTrack::getTimestamp(ExtendedTimestamp *timestamp)
2819{
2820 if (timestamp == nullptr) {
2821 return BAD_VALUE;
2822 }
2823 AutoMutex lock(mLock);
Andy Hunge13f8a62016-03-30 14:20:42 -07002824 return getTimestamp_l(timestamp);
2825}
2826
2827status_t AudioTrack::getTimestamp_l(ExtendedTimestamp *timestamp)
2828{
Andy Hungea2b9c02016-02-12 17:06:53 -08002829 if (mCblk->mFlags & CBLK_INVALID) {
2830 const status_t status = restoreTrack_l("getTimestampExtended");
2831 if (status != OK) {
2832 // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
2833 // recommending that the track be recreated.
2834 return DEAD_OBJECT;
2835 }
2836 }
2837 // check for offloaded/direct here in case restoring somehow changed those flags.
2838 if (isOffloadedOrDirect_l()) {
2839 return INVALID_OPERATION; // not supported
2840 }
2841 status_t status = mProxy->getTimestamp(timestamp);
Andy Hungfb8ede22018-09-12 19:03:24 -07002842 LOG_ALWAYS_FATAL_IF(status != OK, "%s(%d): status %d not allowed from proxy getTimestamp",
Eric Laurent973db022018-11-20 14:54:31 -08002843 __func__, mPortId, status);
Andy Hungea2b9c02016-02-12 17:06:53 -08002844 bool found = false;
Andy Hunge1e98462016-04-12 10:18:51 -07002845 timestamp->mPosition[ExtendedTimestamp::LOCATION_CLIENT] = mFramesWritten;
2846 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_CLIENT] = 0;
2847 // server side frame offset in case AudioTrack has been restored.
2848 for (int i = ExtendedTimestamp::LOCATION_SERVER;
2849 i < ExtendedTimestamp::LOCATION_MAX; ++i) {
2850 if (timestamp->mTimeNs[i] >= 0) {
2851 // apply server offset (frames flushed is ignored
2852 // so we don't report the jump when the flush occurs).
2853 timestamp->mPosition[i] += mFramesWrittenServerOffset;
2854 found = true;
Andy Hungea2b9c02016-02-12 17:06:53 -08002855 }
2856 }
2857 return found ? OK : WOULD_BLOCK;
2858}
2859
Glenn Kastence703742013-07-19 16:33:58 -07002860status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
2861{
Glenn Kasten53cec222013-08-29 09:01:02 -07002862 AutoMutex lock(mLock);
Andy Hung65ffdfc2016-10-10 15:52:11 -07002863 return getTimestamp_l(timestamp);
2864}
Phil Burk1b420972015-04-22 10:52:21 -07002865
Andy Hung65ffdfc2016-10-10 15:52:11 -07002866status_t AudioTrack::getTimestamp_l(AudioTimestamp& timestamp)
2867{
Phil Burk1b420972015-04-22 10:52:21 -07002868 bool previousTimestampValid = mPreviousTimestampValid;
2869 // Set false here to cover all the error return cases.
2870 mPreviousTimestampValid = false;
2871
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002872 switch (mState) {
2873 case STATE_ACTIVE:
2874 case STATE_PAUSED:
2875 break; // handle below
2876 case STATE_FLUSHED:
2877 case STATE_STOPPED:
2878 return WOULD_BLOCK;
2879 case STATE_STOPPING:
2880 case STATE_PAUSED_STOPPING:
2881 if (!isOffloaded_l()) {
2882 return INVALID_OPERATION;
2883 }
2884 break; // offloaded tracks handled below
2885 default:
Andy Hungfb8ede22018-09-12 19:03:24 -07002886 LOG_ALWAYS_FATAL("%s(%d): Invalid mState in getTimestamp(): %d",
Eric Laurent973db022018-11-20 14:54:31 -08002887 __func__, mPortId, mState);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002888 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07002889 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002890
Eric Laurent275e8e92014-11-30 15:14:47 -08002891 if (mCblk->mFlags & CBLK_INVALID) {
Andy Hung6653c932015-06-08 13:27:48 -07002892 const status_t status = restoreTrack_l("getTimestamp");
2893 if (status != OK) {
2894 // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
2895 // recommending that the track be recreated.
2896 return DEAD_OBJECT;
2897 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002898 }
2899
Glenn Kasten200092b2014-08-15 15:13:30 -07002900 // The presented frame count must always lag behind the consumed frame count.
2901 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Andy Hung6ae58432016-02-16 18:32:24 -08002902
2903 status_t status;
Andy Hung818e7a32016-02-16 18:08:07 -08002904 if (isOffloadedOrDirect_l()) {
Andy Hung6ae58432016-02-16 18:32:24 -08002905 // use Binder to get timestamp
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002906 media::AudioTimestampInternal ts;
2907 mAudioTrack->getTimestamp(&ts, &status);
2908 if (status == OK) {
Andy Hung973638a2020-12-08 20:47:45 -08002909 timestamp = VALUE_OR_FATAL(aidl2legacy_AudioTimestampInternal_AudioTimestamp(ts));
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -08002910 }
Andy Hung6ae58432016-02-16 18:32:24 -08002911 } else {
2912 // read timestamp from shared memory
2913 ExtendedTimestamp ets;
2914 status = mProxy->getTimestamp(&ets);
2915 if (status == OK) {
Andy Hungb01faa32016-04-27 12:51:32 -07002916 ExtendedTimestamp::Location location;
2917 status = ets.getBestTimestamp(&timestamp, &location);
2918
2919 if (status == OK) {
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002920 updateLatency_l();
Andy Hungb01faa32016-04-27 12:51:32 -07002921 // It is possible that the best location has moved from the kernel to the server.
2922 // In this case we adjust the position from the previous computed latency.
2923 if (location == ExtendedTimestamp::LOCATION_SERVER) {
2924 ALOGW_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_KERNEL,
Andy Hungfb8ede22018-09-12 19:03:24 -07002925 "%s(%d): location moved from kernel to server",
Eric Laurent973db022018-11-20 14:54:31 -08002926 __func__, mPortId);
Andy Hung07eee802016-06-21 16:47:16 -07002927 // check that the last kernel OK time info exists and the positions
2928 // are valid (if they predate the current track, the positions may
2929 // be zero or negative).
Andy Hungb01faa32016-04-27 12:51:32 -07002930 const int64_t frames =
Andy Hung6d7b1192016-05-07 22:59:48 -07002931 (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
Andy Hung07eee802016-06-21 16:47:16 -07002932 ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0 ||
2933 ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] <= 0 ||
2934 ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] <= 0)
Andy Hung6d7b1192016-05-07 22:59:48 -07002935 ?
2936 int64_t((double)mAfLatency * mSampleRate * mPlaybackRate.mSpeed
2937 / 1000)
2938 :
2939 (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
2940 - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK]);
Andy Hungfb8ede22018-09-12 19:03:24 -07002941 ALOGV("%s(%d): frame adjustment:%lld timestamp:%s",
Eric Laurent973db022018-11-20 14:54:31 -08002942 __func__, mPortId, (long long)frames, ets.toString().c_str());
Andy Hungb01faa32016-04-27 12:51:32 -07002943 if (frames >= ets.mPosition[location]) {
2944 timestamp.mPosition = 0;
2945 } else {
2946 timestamp.mPosition = (uint32_t)(ets.mPosition[location] - frames);
2947 }
Andy Hung69488c42016-05-16 18:43:33 -07002948 } else if (location == ExtendedTimestamp::LOCATION_KERNEL) {
2949 ALOGV_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_SERVER,
Andy Hungfb8ede22018-09-12 19:03:24 -07002950 "%s(%d): location moved from server to kernel",
Eric Laurent973db022018-11-20 14:54:31 -08002951 __func__, mPortId);
Andy Hung98731a22019-04-08 19:19:07 -07002952
2953 if (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER] ==
2954 ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL]) {
2955 // In Q, we don't return errors as an invalid time
2956 // but instead we leave the last kernel good timestamp alone.
2957 //
2958 // If server is identical to kernel, the device data pipeline is idle.
2959 // A better start time is now. The retrograde check ensures
2960 // timestamp monotonicity.
2961 const int64_t nowNs = systemTime();
Andy Hungcf3b7152019-04-19 18:29:21 -07002962 if (!mTimestampStallReported) {
2963 ALOGD("%s(%d): device stall time corrected using current time %lld",
2964 __func__, mPortId, (long long)nowNs);
2965 mTimestampStallReported = true;
2966 }
Andy Hung98731a22019-04-08 19:19:07 -07002967 timestamp.mTime = convertNsToTimespec(nowNs);
Andy Hungcf3b7152019-04-19 18:29:21 -07002968 } else {
2969 mTimestampStallReported = false;
Andy Hung98731a22019-04-08 19:19:07 -07002970 }
Andy Hungb01faa32016-04-27 12:51:32 -07002971 }
Andy Hung5d313802016-10-10 15:09:39 -07002972
2973 // We update the timestamp time even when paused.
2974 if (mState == STATE_PAUSED /* not needed: STATE_PAUSED_STOPPING */) {
2975 const int64_t now = systemTime();
Andy Hung2b01f002017-07-05 12:01:36 -07002976 const int64_t at = audio_utils_ns_from_timespec(&timestamp.mTime);
Andy Hung5d313802016-10-10 15:09:39 -07002977 const int64_t lag =
2978 (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
2979 ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0)
2980 ? int64_t(mAfLatency * 1000000LL)
2981 : (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
2982 - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK])
2983 * NANOS_PER_SECOND / mSampleRate;
2984 const int64_t limit = now - lag; // no earlier than this limit
2985 if (at < limit) {
2986 ALOGV("timestamp pause lag:%lld adjusting from %lld to %lld",
2987 (long long)lag, (long long)at, (long long)limit);
Andy Hungffa36952017-08-17 10:41:51 -07002988 timestamp.mTime = convertNsToTimespec(limit);
Andy Hung5d313802016-10-10 15:09:39 -07002989 }
2990 }
Andy Hungb01faa32016-04-27 12:51:32 -07002991 mPreviousLocation = location;
2992 } else {
2993 // right after AudioTrack is started, one may not find a timestamp
Eric Laurent973db022018-11-20 14:54:31 -08002994 ALOGV("%s(%d): getBestTimestamp did not find timestamp", __func__, mPortId);
Andy Hungb01faa32016-04-27 12:51:32 -07002995 }
Andy Hung6ae58432016-02-16 18:32:24 -08002996 }
2997 if (status == INVALID_OPERATION) {
Andy Hungf20a4e92016-08-15 19:10:34 -07002998 // INVALID_OPERATION occurs when no timestamp has been issued by the server;
2999 // other failures are signaled by a negative time.
3000 // If we come out of FLUSHED or STOPPED where the position is known
3001 // to be zero we convert this to WOULD_BLOCK (with the implicit meaning of
3002 // "zero" for NuPlayer). We don't convert for track restoration as position
3003 // does not reset.
Andy Hungfb8ede22018-09-12 19:03:24 -07003004 ALOGV("%s(%d): timestamp server offset:%lld restore frames:%lld",
Eric Laurent973db022018-11-20 14:54:31 -08003005 __func__, mPortId,
Andy Hungf20a4e92016-08-15 19:10:34 -07003006 (long long)mFramesWrittenServerOffset, (long long)mFramesWrittenAtRestore);
3007 if (mFramesWrittenServerOffset != mFramesWrittenAtRestore) {
3008 status = WOULD_BLOCK;
3009 }
Andy Hung6ae58432016-02-16 18:32:24 -08003010 }
3011 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07003012 if (status != NO_ERROR) {
Eric Laurent973db022018-11-20 14:54:31 -08003013 ALOGV_IF(status != WOULD_BLOCK, "%s(%d): getTimestamp error:%#x", __func__, mPortId, status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07003014 return status;
3015 }
3016 if (isOffloadedOrDirect_l()) {
3017 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
3018 // use cached paused position in case another offloaded track is running.
3019 timestamp.mPosition = mPausedPosition;
3020 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
Andy Hung5d313802016-10-10 15:09:39 -07003021 // TODO: adjust for delay
Andy Hung7f1bc8a2014-09-12 14:43:11 -07003022 return NO_ERROR;
3023 }
3024
3025 // Check whether a pending flush or stop has completed, as those commands may
Andy Hungc8e09c62015-06-03 23:43:36 -07003026 // be asynchronous or return near finish or exhibit glitchy behavior.
3027 //
3028 // Originally this showed up as the first timestamp being a continuation of
3029 // the previous song under gapless playback.
3030 // However, we sometimes see zero timestamps, then a glitch of
3031 // the previous song's position, and then correct timestamps afterwards.
Andy Hungffa36952017-08-17 10:41:51 -07003032 if (mStartFromZeroUs != 0 && mSampleRate != 0) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -07003033 static const int kTimeJitterUs = 100000; // 100 ms
3034 static const int k1SecUs = 1000000;
3035
3036 const int64_t timeNow = getNowUs();
3037
Andy Hungffa36952017-08-17 10:41:51 -07003038 if (timeNow < mStartFromZeroUs + k1SecUs) { // within first second of starting
Andy Hung7f1bc8a2014-09-12 14:43:11 -07003039 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
Andy Hungffa36952017-08-17 10:41:51 -07003040 if (timestampTimeUs < mStartFromZeroUs) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -07003041 return WOULD_BLOCK; // stale timestamp time, occurs before start.
3042 }
Andy Hungffa36952017-08-17 10:41:51 -07003043 const int64_t deltaTimeUs = timestampTimeUs - mStartFromZeroUs;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003044 const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003045 / ((double)mSampleRate * mPlaybackRate.mSpeed);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07003046
3047 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
3048 // Verify that the counter can't count faster than the sample rate
Andy Hungc8e09c62015-06-03 23:43:36 -07003049 // since the start time. If greater, then that means we may have failed
Andy Hung7f1bc8a2014-09-12 14:43:11 -07003050 // to completely flush or stop the previous playing track.
Andy Hungc8e09c62015-06-03 23:43:36 -07003051 ALOGW_IF(!mTimestampStartupGlitchReported,
Andy Hungfb8ede22018-09-12 19:03:24 -07003052 "%s(%d): startup glitch detected"
Andy Hung7f1bc8a2014-09-12 14:43:11 -07003053 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
Eric Laurent973db022018-11-20 14:54:31 -08003054 __func__, mPortId,
Andy Hung7f1bc8a2014-09-12 14:43:11 -07003055 (long long)deltaTimeUs, (long long)deltaPositionByUs,
3056 timestamp.mPosition);
Andy Hungc8e09c62015-06-03 23:43:36 -07003057 mTimestampStartupGlitchReported = true;
3058 if (previousTimestampValid
3059 && mPreviousTimestamp.mPosition == 0 /* should be true if valid */) {
3060 timestamp = mPreviousTimestamp;
3061 mPreviousTimestampValid = true;
3062 return NO_ERROR;
3063 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07003064 return WOULD_BLOCK;
3065 }
Andy Hungc8e09c62015-06-03 23:43:36 -07003066 if (deltaPositionByUs != 0) {
Andy Hungffa36952017-08-17 10:41:51 -07003067 mStartFromZeroUs = 0; // don't check again, we got valid nonzero position.
Andy Hungc8e09c62015-06-03 23:43:36 -07003068 }
3069 } else {
Andy Hungffa36952017-08-17 10:41:51 -07003070 mStartFromZeroUs = 0; // don't check again, start time expired.
Andy Hung7f1bc8a2014-09-12 14:43:11 -07003071 }
Andy Hungc8e09c62015-06-03 23:43:36 -07003072 mTimestampStartupGlitchReported = false;
Andy Hung7f1bc8a2014-09-12 14:43:11 -07003073 }
3074 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07003075 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
3076 (void) updateAndGetPosition_l();
3077 // Server consumed (mServer) and presented both use the same server time base,
3078 // and server consumed is always >= presented.
3079 // The delta between these represents the number of frames in the buffer pipeline.
3080 // If this delta between these is greater than the client position, it means that
3081 // actually presented is still stuck at the starting line (figuratively speaking),
3082 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
Andy Hung90e8a972015-11-09 16:42:40 -08003083 // Note: We explicitly use non-Modulo comparison here - potential wrap issue when
3084 // mPosition exceeds 32 bits.
3085 // TODO Remove when timestamp is updated to contain pipeline status info.
3086 const int32_t pipelineDepthInFrames = (mServer - timestamp.mPosition).signedValue();
3087 if (pipelineDepthInFrames > 0 /* should be true, but we check anyways */
3088 && (uint32_t)pipelineDepthInFrames > mPosition.value()) {
Glenn Kasten200092b2014-08-15 15:13:30 -07003089 return INVALID_OPERATION;
3090 }
3091 // Convert timestamp position from server time base to client time base.
3092 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
3093 // But if we change it to 64-bit then this could fail.
Andy Hung90e8a972015-11-09 16:42:40 -08003094 // Use Modulo computation here.
3095 timestamp.mPosition = (mPosition - mServer + timestamp.mPosition).value();
Glenn Kasten200092b2014-08-15 15:13:30 -07003096 // Immediately after a call to getPosition_l(), mPosition and
3097 // mServer both represent the same frame position. mPosition is
3098 // in client's point of view, and mServer is in server's point of
3099 // view. So the difference between them is the "fudge factor"
3100 // between client and server views due to stop() and/or new
3101 // IAudioTrack. And timestamp.mPosition is initially in server's
3102 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07003103 }
Phil Burk1b420972015-04-22 10:52:21 -07003104
3105 // Prevent retrograde motion in timestamp.
3106 // This is sometimes caused by erratic reports of the available space in the ALSA drivers.
3107 if (status == NO_ERROR) {
Andy Hung3b8c6332019-04-03 19:29:36 -07003108 // Fix stale time when checking timestamp right after start().
3109 // The position is at the last reported location but the time can be stale
3110 // due to pause or standby or cold start latency.
3111 //
3112 // We keep advancing the time (but not the position) to ensure that the
3113 // stale value does not confuse the application.
3114 //
3115 // For offload compatibility, use a default lag value here.
3116 // Any time discrepancy between this update and the pause timestamp is handled
3117 // by the retrograde check afterwards.
3118 int64_t currentTimeNanos = audio_utils_ns_from_timespec(&timestamp.mTime);
3119 const int64_t lagNs = int64_t(mAfLatency * 1000000LL);
3120 const int64_t limitNs = mStartNs - lagNs;
3121 if (currentTimeNanos < limitNs) {
Andy Hungcf3b7152019-04-19 18:29:21 -07003122 if (!mTimestampStaleTimeReported) {
3123 ALOGD("%s(%d): stale timestamp time corrected, "
3124 "currentTimeNanos: %lld < limitNs: %lld < mStartNs: %lld",
3125 __func__, mPortId,
3126 (long long)currentTimeNanos, (long long)limitNs, (long long)mStartNs);
3127 mTimestampStaleTimeReported = true;
3128 }
Andy Hung3b8c6332019-04-03 19:29:36 -07003129 timestamp.mTime = convertNsToTimespec(limitNs);
3130 currentTimeNanos = limitNs;
Andy Hungcf3b7152019-04-19 18:29:21 -07003131 } else {
3132 mTimestampStaleTimeReported = false;
Andy Hung3b8c6332019-04-03 19:29:36 -07003133 }
3134
Andy Hungffa36952017-08-17 10:41:51 -07003135 // previousTimestampValid is set to false when starting after a stop or flush.
Phil Burk1b420972015-04-22 10:52:21 -07003136 if (previousTimestampValid) {
Andy Hung2b01f002017-07-05 12:01:36 -07003137 const int64_t previousTimeNanos =
3138 audio_utils_ns_from_timespec(&mPreviousTimestamp.mTime);
Andy Hungffa36952017-08-17 10:41:51 -07003139
3140 // retrograde check
Phil Burk1b420972015-04-22 10:52:21 -07003141 if (currentTimeNanos < previousTimeNanos) {
Andy Hungcf3b7152019-04-19 18:29:21 -07003142 if (!mTimestampRetrogradeTimeReported) {
3143 ALOGW("%s(%d): retrograde timestamp time corrected, %lld < %lld",
3144 __func__, mPortId,
3145 (long long)currentTimeNanos, (long long)previousTimeNanos);
3146 mTimestampRetrogradeTimeReported = true;
3147 }
Andy Hung5d313802016-10-10 15:09:39 -07003148 timestamp.mTime = mPreviousTimestamp.mTime;
Andy Hungcf3b7152019-04-19 18:29:21 -07003149 } else {
3150 mTimestampRetrogradeTimeReported = false;
Phil Burk1b420972015-04-22 10:52:21 -07003151 }
3152
3153 // Looking at signed delta will work even when the timestamps
3154 // are wrapping around.
Andy Hung90e8a972015-11-09 16:42:40 -08003155 int32_t deltaPosition = (Modulo<uint32_t>(timestamp.mPosition)
3156 - mPreviousTimestamp.mPosition).signedValue();
Phil Burk4c5a3672015-04-30 16:18:53 -07003157 if (deltaPosition < 0) {
3158 // Only report once per position instead of spamming the log.
Andy Hungcf3b7152019-04-19 18:29:21 -07003159 if (!mTimestampRetrogradePositionReported) {
Andy Hungfb8ede22018-09-12 19:03:24 -07003160 ALOGW("%s(%d): retrograde timestamp position corrected, %d = %u - %u",
Eric Laurent973db022018-11-20 14:54:31 -08003161 __func__, mPortId,
Phil Burk4c5a3672015-04-30 16:18:53 -07003162 deltaPosition,
3163 timestamp.mPosition,
3164 mPreviousTimestamp.mPosition);
Andy Hungcf3b7152019-04-19 18:29:21 -07003165 mTimestampRetrogradePositionReported = true;
Phil Burk4c5a3672015-04-30 16:18:53 -07003166 }
3167 } else {
Andy Hungcf3b7152019-04-19 18:29:21 -07003168 mTimestampRetrogradePositionReported = false;
Phil Burk4c5a3672015-04-30 16:18:53 -07003169 }
Andy Hung5d313802016-10-10 15:09:39 -07003170 if (deltaPosition < 0) {
3171 timestamp.mPosition = mPreviousTimestamp.mPosition;
3172 deltaPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -07003173 }
Andy Hung5d313802016-10-10 15:09:39 -07003174#if 0
3175 // Uncomment this to verify audio timestamp rate.
3176 const int64_t deltaTime =
Andy Hung2b01f002017-07-05 12:01:36 -07003177 audio_utils_ns_from_timespec(&timestamp.mTime) - previousTimeNanos;
Andy Hung5d313802016-10-10 15:09:39 -07003178 if (deltaTime != 0) {
3179 const int64_t computedSampleRate =
3180 deltaPosition * (long long)NANOS_PER_SECOND / deltaTime;
Andy Hungfb8ede22018-09-12 19:03:24 -07003181 ALOGD("%s(%d): computedSampleRate:%u sampleRate:%u",
Eric Laurent973db022018-11-20 14:54:31 -08003182 __func__, mPortId,
Andy Hung5d313802016-10-10 15:09:39 -07003183 (unsigned)computedSampleRate, mSampleRate);
3184 }
3185#endif
Phil Burk1b420972015-04-22 10:52:21 -07003186 }
3187 mPreviousTimestamp = timestamp;
3188 mPreviousTimestampValid = true;
3189 }
3190
Glenn Kastenfe346c72013-08-30 13:28:22 -07003191 return status;
Glenn Kastence703742013-07-19 16:33:58 -07003192}
3193
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00003194String8 AudioTrack::getParameters(const String8& keys)
3195{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08003196 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07003197 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08003198 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01003199 } else {
3200 return String8::empty();
3201 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00003202}
3203
Glenn Kasten23a75452014-01-13 10:37:17 -08003204bool AudioTrack::isOffloaded() const
3205{
3206 AutoMutex lock(mLock);
3207 return isOffloaded_l();
3208}
3209
Eric Laurentab5cdba2014-06-09 17:22:27 -07003210bool AudioTrack::isDirect() const
3211{
3212 AutoMutex lock(mLock);
3213 return isDirect_l();
3214}
3215
3216bool AudioTrack::isOffloadedOrDirect() const
3217{
3218 AutoMutex lock(mLock);
3219 return isOffloadedOrDirect_l();
3220}
3221
3222
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08003223status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003224{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003225 String8 result;
3226
3227 result.append(" AudioTrack::dump\n");
Andy Hungfb8ede22018-09-12 19:03:24 -07003228 result.appendFormat(" id(%d) status(%d), state(%d), session Id(%d), flags(%#x)\n",
Eric Laurent973db022018-11-20 14:54:31 -08003229 mPortId, mStatus, mState, mSessionId, mFlags);
Eric Laurentd114b622017-11-27 18:37:04 -08003230 result.appendFormat(" stream type(%d), left - right volume(%f, %f)\n",
3231 (mStreamType == AUDIO_STREAM_DEFAULT) ?
François Gaffie58d4be52018-11-06 15:30:12 +01003232 AudioSystem::attributesToStreamType(mAttributes) :
3233 mStreamType,
Eric Laurentd114b622017-11-27 18:37:04 -08003234 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003235 result.appendFormat(" format(%#x), channel mask(%#x), channel count(%u)\n",
Eric Laurentd114b622017-11-27 18:37:04 -08003236 mFormat, mChannelMask, mChannelCount);
3237 result.appendFormat(" sample rate(%u), original sample rate(%u), speed(%f)\n",
3238 mSampleRate, mOriginalSampleRate, mPlaybackRate.mSpeed);
3239 result.appendFormat(" frame count(%zu), req. frame count(%zu)\n",
3240 mFrameCount, mReqFrameCount);
3241 result.appendFormat(" notif. frame count(%u), req. notif. frame count(%u),"
3242 " req. notif. per buff(%u)\n",
3243 mNotificationFramesAct, mNotificationFramesReq, mNotificationsPerBufferReq);
3244 result.appendFormat(" latency (%d), selected device Id(%d), routed device Id(%d)\n",
3245 mLatency, mSelectedDeviceId, mRoutedDeviceId);
3246 result.appendFormat(" output(%d) AF latency (%u) AF frame count(%zu) AF SampleRate(%u)\n",
3247 mOutput, mAfLatency, mAfFrameCount, mAfSampleRate);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003248 ::write(fd, result.string(), result.size());
3249 return NO_ERROR;
3250}
3251
Phil Burk2812d9e2016-01-04 10:34:30 -08003252uint32_t AudioTrack::getUnderrunCount() const
3253{
3254 AutoMutex lock(mLock);
3255 return getUnderrunCount_l();
3256}
3257
3258uint32_t AudioTrack::getUnderrunCount_l() const
3259{
3260 return mProxy->getUnderrunCount() + mUnderrunCountOffset;
3261}
3262
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003263uint32_t AudioTrack::getUnderrunFrames() const
3264{
3265 AutoMutex lock(mLock);
3266 return mProxy->getUnderrunFrames();
3267}
3268
Andy Hung3a5c2f32021-02-17 15:06:42 -08003269void AudioTrack::setLogSessionId(const char *logSessionId)
3270{
3271 AutoMutex lock(mLock);
Andy Hung1a9c21b2021-02-25 20:43:18 -08003272 if (logSessionId == nullptr) logSessionId = ""; // an empty string is an unset session id.
Andy Hung3a5c2f32021-02-17 15:06:42 -08003273 if (mLogSessionId == logSessionId) return;
3274
3275 mLogSessionId = logSessionId;
3276 mediametrics::LogItem(mMetricsId)
3277 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETLOGSESSIONID)
3278 .set(AMEDIAMETRICS_PROP_LOGSESSIONID, logSessionId)
3279 .record();
3280}
3281
Andy Hung839a3062021-02-17 11:15:16 -08003282void AudioTrack::setPlayerIId(int playerIId)
3283{
3284 AutoMutex lock(mLock);
3285 if (mPlayerIId == playerIId) return;
3286
3287 mPlayerIId = playerIId;
3288 mediametrics::LogItem(mMetricsId)
3289 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETPLAYERIID)
3290 .set(AMEDIAMETRICS_PROP_PLAYERIID, playerIId)
3291 .record();
3292}
3293
Eric Laurent296fb132015-05-01 11:38:42 -07003294status_t AudioTrack::addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback)
3295{
Eric Laurent09f1ed22019-04-24 17:45:17 -07003296
Eric Laurent296fb132015-05-01 11:38:42 -07003297 if (callback == 0) {
Eric Laurent973db022018-11-20 14:54:31 -08003298 ALOGW("%s(%d): adding NULL callback!", __func__, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07003299 return BAD_VALUE;
3300 }
3301 AutoMutex lock(mLock);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003302 if (mDeviceCallback.unsafe_get() == callback.get()) {
Eric Laurent973db022018-11-20 14:54:31 -08003303 ALOGW("%s(%d): adding same callback!", __func__, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07003304 return INVALID_OPERATION;
3305 }
3306 status_t status = NO_ERROR;
3307 if (mOutput != AUDIO_IO_HANDLE_NONE) {
3308 if (mDeviceCallback != 0) {
Eric Laurent973db022018-11-20 14:54:31 -08003309 ALOGW("%s(%d): callback already present!", __func__, mPortId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003310 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07003311 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07003312 status = AudioSystem::addAudioDeviceCallback(this, mOutput, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07003313 }
3314 mDeviceCallback = callback;
3315 return status;
3316}
3317
3318status_t AudioTrack::removeAudioDeviceCallback(
3319 const sp<AudioSystem::AudioDeviceCallback>& callback)
3320{
3321 if (callback == 0) {
Eric Laurent973db022018-11-20 14:54:31 -08003322 ALOGW("%s(%d): removing NULL callback!", __func__, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07003323 return BAD_VALUE;
3324 }
Eric Laurent4463ff52019-02-07 13:56:09 -08003325 AutoMutex lock(mLock);
3326 if (mDeviceCallback.unsafe_get() != callback.get()) {
3327 ALOGW("%s removing different callback!", __FUNCTION__);
3328 return INVALID_OPERATION;
Eric Laurent296fb132015-05-01 11:38:42 -07003329 }
Eric Laurent4463ff52019-02-07 13:56:09 -08003330 mDeviceCallback.clear();
Eric Laurent296fb132015-05-01 11:38:42 -07003331 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent09f1ed22019-04-24 17:45:17 -07003332 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07003333 }
Eric Laurent296fb132015-05-01 11:38:42 -07003334 return NO_ERROR;
3335}
3336
Eric Laurentad2e7b92017-09-14 20:06:42 -07003337
3338void AudioTrack::onAudioDeviceUpdate(audio_io_handle_t audioIo,
3339 audio_port_handle_t deviceId)
3340{
3341 sp<AudioSystem::AudioDeviceCallback> callback;
3342 {
3343 AutoMutex lock(mLock);
3344 if (audioIo != mOutput) {
3345 return;
3346 }
3347 callback = mDeviceCallback.promote();
3348 // only update device if the track is active as route changes due to other use cases are
3349 // irrelevant for this client
3350 if (mState == STATE_ACTIVE) {
3351 mRoutedDeviceId = deviceId;
3352 }
3353 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07003354
Eric Laurentad2e7b92017-09-14 20:06:42 -07003355 if (callback.get() != nullptr) {
3356 callback->onAudioDeviceUpdate(mOutput, mRoutedDeviceId);
3357 }
3358}
3359
Andy Hunge13f8a62016-03-30 14:20:42 -07003360status_t AudioTrack::pendingDuration(int32_t *msec, ExtendedTimestamp::Location location)
3361{
3362 if (msec == nullptr ||
3363 (location != ExtendedTimestamp::LOCATION_SERVER
3364 && location != ExtendedTimestamp::LOCATION_KERNEL)) {
3365 return BAD_VALUE;
3366 }
3367 AutoMutex lock(mLock);
3368 // inclusive of offloaded and direct tracks.
3369 //
3370 // It is possible, but not enabled, to allow duration computation for non-pcm
3371 // audio_has_proportional_frames() formats because currently they have
3372 // the drain rate equivalent to the pcm sample rate * framesize.
3373 if (!isPurePcmData_l()) {
3374 return INVALID_OPERATION;
3375 }
3376 ExtendedTimestamp ets;
3377 if (getTimestamp_l(&ets) == OK
3378 && ets.mTimeNs[location] > 0) {
3379 int64_t diff = ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT]
3380 - ets.mPosition[location];
3381 if (diff < 0) {
3382 *msec = 0;
3383 } else {
3384 // ms is the playback time by frames
3385 int64_t ms = (int64_t)((double)diff * 1000 /
3386 ((double)mSampleRate * mPlaybackRate.mSpeed));
3387 // clockdiff is the timestamp age (negative)
3388 int64_t clockdiff = (mState != STATE_ACTIVE) ? 0 :
3389 ets.mTimeNs[location]
3390 + ets.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_MONOTONIC]
3391 - systemTime(SYSTEM_TIME_MONOTONIC);
3392
3393 //ALOGV("ms: %lld clockdiff: %lld", (long long)ms, (long long)clockdiff);
3394 static const int NANOS_PER_MILLIS = 1000000;
3395 *msec = (int32_t)(ms + clockdiff / NANOS_PER_MILLIS);
3396 }
3397 return NO_ERROR;
3398 }
3399 if (location != ExtendedTimestamp::LOCATION_SERVER) {
3400 return INVALID_OPERATION; // LOCATION_KERNEL is not available
3401 }
3402 // use server position directly (offloaded and direct arrive here)
3403 updateAndGetPosition_l();
3404 int32_t diff = (Modulo<uint32_t>(mFramesWritten) - mPosition).signedValue();
3405 *msec = (diff <= 0) ? 0
3406 : (int32_t)((double)diff * 1000 / ((double)mSampleRate * mPlaybackRate.mSpeed));
3407 return NO_ERROR;
3408}
3409
Andy Hung65ffdfc2016-10-10 15:52:11 -07003410bool AudioTrack::hasStarted()
3411{
3412 AutoMutex lock(mLock);
3413 switch (mState) {
3414 case STATE_STOPPED:
3415 if (isOffloadedOrDirect_l()) {
3416 // check if we have started in the past to return true.
Andy Hungffa36952017-08-17 10:41:51 -07003417 return mStartFromZeroUs > 0;
Andy Hung65ffdfc2016-10-10 15:52:11 -07003418 }
3419 // A normal audio track may still be draining, so
3420 // check if stream has ended. This covers fasttrack position
3421 // instability and start/stop without any data written.
3422 if (mProxy->getStreamEndDone()) {
3423 return true;
3424 }
Chih-Hung Hsiehffe35582018-09-13 13:59:28 -07003425 FALLTHROUGH_INTENDED;
Andy Hung65ffdfc2016-10-10 15:52:11 -07003426 case STATE_ACTIVE:
3427 case STATE_STOPPING:
3428 break;
3429 case STATE_PAUSED:
3430 case STATE_PAUSED_STOPPING:
3431 case STATE_FLUSHED:
3432 return false; // we're not active
3433 default:
Eric Laurent973db022018-11-20 14:54:31 -08003434 LOG_ALWAYS_FATAL("%s(%d): Invalid mState in hasStarted(): %d", __func__, mPortId, mState);
Andy Hung65ffdfc2016-10-10 15:52:11 -07003435 break;
3436 }
3437
3438 // wait indicates whether we need to wait for a timestamp.
3439 // This is conservatively figured - if we encounter an unexpected error
3440 // then we will not wait.
3441 bool wait = false;
3442 if (isOffloadedOrDirect_l()) {
3443 AudioTimestamp ts;
3444 status_t status = getTimestamp_l(ts);
3445 if (status == WOULD_BLOCK) {
3446 wait = true;
3447 } else if (status == OK) {
3448 wait = (ts.mPosition == 0 || ts.mPosition == mStartTs.mPosition);
3449 }
Andy Hungfb8ede22018-09-12 19:03:24 -07003450 ALOGV("%s(%d): hasStarted wait:%d ts:%u start position:%lld",
Eric Laurent973db022018-11-20 14:54:31 -08003451 __func__, mPortId,
Andy Hung65ffdfc2016-10-10 15:52:11 -07003452 (int)wait,
3453 ts.mPosition,
3454 (long long)mStartTs.mPosition);
3455 } else {
3456 int location = ExtendedTimestamp::LOCATION_SERVER; // for ALOG
3457 ExtendedTimestamp ets;
3458 status_t status = getTimestamp_l(&ets);
3459 if (status == WOULD_BLOCK) { // no SERVER or KERNEL frame info in ets
3460 wait = true;
3461 } else if (status == OK) {
3462 for (location = ExtendedTimestamp::LOCATION_KERNEL;
3463 location >= ExtendedTimestamp::LOCATION_SERVER; --location) {
3464 if (ets.mTimeNs[location] < 0 || mStartEts.mTimeNs[location] < 0) {
3465 continue;
3466 }
3467 wait = ets.mPosition[location] == 0
3468 || ets.mPosition[location] == mStartEts.mPosition[location];
3469 break;
3470 }
3471 }
Andy Hungfb8ede22018-09-12 19:03:24 -07003472 ALOGV("%s(%d): hasStarted wait:%d ets:%lld start position:%lld",
Eric Laurent973db022018-11-20 14:54:31 -08003473 __func__, mPortId,
Andy Hung65ffdfc2016-10-10 15:52:11 -07003474 (int)wait,
3475 (long long)ets.mPosition[location],
3476 (long long)mStartEts.mPosition[location]);
3477 }
3478 return !wait;
3479}
3480
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003481// =========================================================================
3482
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08003483void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003484{
3485 sp<AudioTrack> audioTrack = mAudioTrack.promote();
3486 if (audioTrack != 0) {
3487 AutoMutex lock(audioTrack->mLock);
3488 audioTrack->mProxy->binderDied();
3489 }
3490}
3491
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003492// =========================================================================
3493
Andy Hungca353672019-03-06 11:54:38 -08003494AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver)
Andy Hungeb46cf92019-03-06 10:13:38 -08003495 : Thread(true /* bCanCallJava */) // binder recursion on restoreTrack_l() may call Java.
3496 , mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
Glenn Kasten598de6c2013-10-16 17:02:13 -07003497 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08003498{
3499}
3500
3501AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003502{
3503}
3504
3505bool AudioTrack::AudioTrackThread::threadLoop()
3506{
Glenn Kasten3acbd052012-02-28 10:39:56 -08003507 {
3508 AutoMutex _l(mMyLock);
3509 if (mPaused) {
Glenn Kasten75f79032017-05-23 11:22:44 -07003510 // TODO check return value and handle or log
Glenn Kasten3acbd052012-02-28 10:39:56 -08003511 mMyCond.wait(mMyLock);
3512 // caller will check for exitPending()
3513 return true;
3514 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07003515 if (mIgnoreNextPausedInt) {
3516 mIgnoreNextPausedInt = false;
3517 mPausedInt = false;
3518 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003519 if (mPausedInt) {
Glenn Kasten47d55172017-05-23 11:19:30 -07003520 // TODO use futex instead of condition, for event flag "or"
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003521 if (mPausedNs > 0) {
Glenn Kasten75f79032017-05-23 11:22:44 -07003522 // TODO check return value and handle or log
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003523 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
3524 } else {
Glenn Kasten75f79032017-05-23 11:22:44 -07003525 // TODO check return value and handle or log
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003526 mMyCond.wait(mMyLock);
3527 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07003528 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003529 return true;
3530 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08003531 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07003532 if (exitPending()) {
3533 return false;
3534 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08003535 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003536 switch (ns) {
3537 case 0:
3538 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003539 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003540 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003541 return true;
3542 case NS_NEVER:
3543 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003544 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08003545 // Event driven: call wake() when callback notifications conditions change.
3546 ns = INT64_MAX;
Chih-Hung Hsiehffe35582018-09-13 13:59:28 -07003547 FALLTHROUGH_INTENDED;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003548 default:
Andy Hungfb8ede22018-09-12 19:03:24 -07003549 LOG_ALWAYS_FATAL_IF(ns < 0, "%s(%d): processAudioBuffer() returned %lld",
Eric Laurent973db022018-11-20 14:54:31 -08003550 __func__, mReceiver.mPortId, (long long)ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003551 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003552 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07003553 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003554}
3555
Glenn Kasten3acbd052012-02-28 10:39:56 -08003556void AudioTrack::AudioTrackThread::requestExit()
3557{
3558 // must be in this order to avoid a race condition
3559 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07003560 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08003561}
3562
3563void AudioTrack::AudioTrackThread::pause()
3564{
3565 AutoMutex _l(mMyLock);
3566 mPaused = true;
3567}
3568
3569void AudioTrack::AudioTrackThread::resume()
3570{
3571 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07003572 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07003573 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08003574 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07003575 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08003576 mMyCond.signal();
3577 }
3578}
3579
Andy Hung3c09c782014-12-29 18:39:32 -08003580void AudioTrack::AudioTrackThread::wake()
3581{
3582 AutoMutex _l(mMyLock);
Andy Hunga8d08902015-07-22 11:52:13 -07003583 if (!mPaused) {
3584 // wake() might be called while servicing a callback - ignore the next
3585 // pause time and call processAudioBuffer.
Andy Hung3c09c782014-12-29 18:39:32 -08003586 mIgnoreNextPausedInt = true;
Andy Hunga8d08902015-07-22 11:52:13 -07003587 if (mPausedInt && mPausedNs > 0) {
3588 // audio track is active and internally paused with timeout.
3589 mPausedInt = false;
3590 mMyCond.signal();
3591 }
Andy Hung3c09c782014-12-29 18:39:32 -08003592 }
3593}
3594
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003595void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
3596{
3597 AutoMutex _l(mMyLock);
3598 mPausedInt = true;
3599 mPausedNs = ns;
3600}
3601
jiabinf6eb4c32020-02-25 14:06:25 -08003602binder::Status AudioTrack::AudioTrackCallback::onCodecFormatChanged(
3603 const std::vector<uint8_t>& audioMetadata)
3604{
3605 AutoMutex _l(mAudioTrackCbLock);
3606 sp<media::IAudioTrackCallback> callback = mCallback.promote();
3607 if (callback.get() != nullptr) {
3608 callback->onCodecFormatChanged(audioMetadata);
3609 } else {
3610 mCallback.clear();
3611 }
3612 return binder::Status::ok();
3613}
3614
3615void AudioTrack::AudioTrackCallback::setAudioTrackCallback(
3616 const sp<media::IAudioTrackCallback> &callback) {
3617 AutoMutex lock(mAudioTrackCbLock);
3618 mCallback = callback;
3619}
3620
Glenn Kasten40bc9062015-03-20 09:09:33 -07003621} // namespace android