blob: 14950a8cfa509da56218a3835b99e6fd6006ff3b [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080018//#define LOG_NDEBUG 0
19#define LOG_TAG "AudioTrack"
20
Mark Salyzyn34fb2962014-06-18 16:30:56 -070021#include <inttypes.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070022#include <math.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080023#include <sys/resource.h>
Mark Salyzyn34fb2962014-06-18 16:30:56 -070024
Chih-Hung Hsiehffe35582018-09-13 13:59:28 -070025#include <android-base/macros.h>
Andy Hung2b01f002017-07-05 12:01:36 -070026#include <audio_utils/clock.h>
Glenn Kasten9f80dd22012-12-18 15:57:32 -080027#include <audio_utils/primitives.h>
28#include <binder/IPCThreadState.h>
29#include <media/AudioTrack.h>
30#include <utils/Log.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080031#include <private/media/AudioTrackShared.h>
Suren Baghdasaryan7435e7d2018-12-19 17:09:28 -080032#include <processgroup/sched_policy.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070033#include <media/IAudioFlinger.h>
Michael Chana94fbb22018-04-24 14:31:19 +100034#include <media/IAudioPolicyService.h>
Dean Wheatleya70eef72018-01-04 14:23:50 +110035#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070036#include <media/AudioResamplerPublic.h>
Michael Chana94fbb22018-04-24 14:31:19 +100037#include <media/AudioSystem.h>
Ray Essickf27e9872019-12-07 06:28:46 -080038#include <media/MediaMetricsItem.h>
Ray Essicked304702017-12-12 14:00:57 -080039#include <media/TypeConverter.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080040
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -080041#define VALUE_OR_FATAL(result) \
42 ({ \
43 auto _tmp = (result); \
44 LOG_ALWAYS_FATAL_IF(!_tmp.ok(), \
45 "Failed result (%d)", \
46 _tmp.error()); \
47 std::move(_tmp.value()); \
48 })
49
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +010050#define WAIT_PERIOD_MS 10
51#define WAIT_STREAM_END_TIMEOUT_SEC 120
Andy Hung53c3b5f2014-12-15 16:42:05 -080052static const int kMaxLoopCountNotifications = 32;
Glenn Kasten511754b2012-01-11 09:52:19 -080053
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080054namespace android {
Chia-chi Yeh33005a92010-06-16 06:33:13 +080055// ---------------------------------------------------------------------------
56
Ivan Lozano8cf3a072017-08-09 09:01:33 -070057using media::VolumeShaper;
58
Andy Hunga7f03352015-05-31 21:54:49 -070059// TODO: Move to a separate .h
60
Andy Hung4ede21d2014-12-12 15:37:34 -080061template <typename T>
Andy Hunga7f03352015-05-31 21:54:49 -070062static inline const T &min(const T &x, const T &y) {
Andy Hung4ede21d2014-12-12 15:37:34 -080063 return x < y ? x : y;
64}
65
Andy Hunga7f03352015-05-31 21:54:49 -070066template <typename T>
67static inline const T &max(const T &x, const T &y) {
68 return x > y ? x : y;
69}
70
71static inline nsecs_t framesToNanoseconds(ssize_t frames, uint32_t sampleRate, float speed)
72{
73 return ((double)frames * 1000000000) / ((double)sampleRate * speed);
74}
75
Andy Hung7f1bc8a2014-09-12 14:43:11 -070076static int64_t convertTimespecToUs(const struct timespec &tv)
77{
Chih-Hung Hsieh50fa06c2018-12-11 13:51:36 -080078 return tv.tv_sec * 1000000LL + tv.tv_nsec / 1000;
Andy Hung7f1bc8a2014-09-12 14:43:11 -070079}
80
Andy Hungffa36952017-08-17 10:41:51 -070081// TODO move to audio_utils.
82static inline struct timespec convertNsToTimespec(int64_t ns) {
83 struct timespec tv;
84 tv.tv_sec = static_cast<time_t>(ns / NANOS_PER_SECOND);
Andy Hung06a730b2020-04-09 13:28:31 -070085 tv.tv_nsec = static_cast<int64_t>(ns % NANOS_PER_SECOND);
Andy Hungffa36952017-08-17 10:41:51 -070086 return tv;
87}
88
Andy Hung7f1bc8a2014-09-12 14:43:11 -070089// current monotonic time in microseconds.
90static int64_t getNowUs()
91{
92 struct timespec tv;
93 (void) clock_gettime(CLOCK_MONOTONIC, &tv);
94 return convertTimespecToUs(tv);
95}
96
Andy Hung26145642015-04-15 21:56:53 -070097// FIXME: we don't use the pitch setting in the time stretcher (not working);
98// instead we emulate it using our sample rate converter.
99static const bool kFixPitch = true; // enable pitch fix
100static inline uint32_t adjustSampleRate(uint32_t sampleRate, float pitch)
101{
102 return kFixPitch ? (sampleRate * pitch + 0.5) : sampleRate;
103}
104
105static inline float adjustSpeed(float speed, float pitch)
106{
Ricardo Garcia6c7f0622015-04-30 18:39:16 -0700107 return kFixPitch ? speed / max(pitch, AUDIO_TIMESTRETCH_PITCH_MIN_DELTA) : speed;
Andy Hung26145642015-04-15 21:56:53 -0700108}
109
110static inline float adjustPitch(float pitch)
111{
112 return kFixPitch ? AUDIO_TIMESTRETCH_PITCH_NORMAL : pitch;
113}
114
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800115// static
116status_t AudioTrack::getMinFrameCount(
Glenn Kastene33054e2012-11-14 12:54:39 -0800117 size_t* frameCount,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800118 audio_stream_type_t streamType,
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800119 uint32_t sampleRate)
120{
Glenn Kastend65d73c2012-06-22 17:21:07 -0700121 if (frameCount == NULL) {
122 return BAD_VALUE;
123 }
Glenn Kasten04cd0182012-06-25 11:49:27 -0700124
Andy Hung0e48d252015-01-26 11:43:15 -0800125 // FIXME handle in server, like createTrack_l(), possible missing info:
Glenn Kastene0fa4672012-04-24 14:35:14 -0700126 // audio_io_handle_t output
127 // audio_format_t format
128 // audio_channel_mask_t channelMask
Andy Hung0e48d252015-01-26 11:43:15 -0800129 // audio_output_flags_t flags (FAST)
Glenn Kasten3b16c762012-11-14 08:44:39 -0800130 uint32_t afSampleRate;
Glenn Kasten66a04672014-01-08 08:53:44 -0800131 status_t status;
132 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
133 if (status != NO_ERROR) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700134 ALOGE("%s(): Unable to query output sample rate for stream type %d; status %d",
135 __func__, streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800136 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800137 }
Glenn Kastene33054e2012-11-14 12:54:39 -0800138 size_t afFrameCount;
Glenn Kasten66a04672014-01-08 08:53:44 -0800139 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
140 if (status != NO_ERROR) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700141 ALOGE("%s(): Unable to query output frame count for stream type %d; status %d",
142 __func__, streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800143 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800144 }
145 uint32_t afLatency;
Glenn Kasten66a04672014-01-08 08:53:44 -0800146 status = AudioSystem::getOutputLatency(&afLatency, streamType);
147 if (status != NO_ERROR) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700148 ALOGE("%s(): Unable to query output latency for stream type %d; status %d",
149 __func__, streamType, status);
Glenn Kasten66a04672014-01-08 08:53:44 -0800150 return status;
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800151 }
152
Andy Hung8edb8dc2015-03-26 19:13:55 -0700153 // When called from createTrack, speed is 1.0f (normal speed).
154 // This is rechecked again on setting playback rate (TODO: on setting sample rate, too).
Eric Laurent21da6472017-11-09 16:29:26 -0800155 *frameCount = AudioSystem::calculateMinFrameCount(afLatency, afFrameCount, afSampleRate,
156 sampleRate, 1.0f /*, 0 notificationsPerBufferReq*/);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800157
Andy Hung0e48d252015-01-26 11:43:15 -0800158 // The formula above should always produce a non-zero value under normal circumstances:
159 // AudioTrack.SAMPLE_RATE_HZ_MIN <= sampleRate <= AudioTrack.SAMPLE_RATE_HZ_MAX.
160 // Return error in the unlikely event that it does not, as that's part of the API contract.
Glenn Kasten66a04672014-01-08 08:53:44 -0800161 if (*frameCount == 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700162 ALOGE("%s(): failed for streamType %d, sampleRate %u",
163 __func__, streamType, sampleRate);
Glenn Kasten66a04672014-01-08 08:53:44 -0800164 return BAD_VALUE;
165 }
Andy Hungfb8ede22018-09-12 19:03:24 -0700166 ALOGV("%s(): getMinFrameCount=%zu: afFrameCount=%zu, afSampleRate=%u, afLatency=%u",
167 __func__, *frameCount, afFrameCount, afSampleRate, afLatency);
Chia-chi Yeh33005a92010-06-16 06:33:13 +0800168 return NO_ERROR;
169}
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800170
Michael Chana94fbb22018-04-24 14:31:19 +1000171// static
172bool AudioTrack::isDirectOutputSupported(const audio_config_base_t& config,
173 const audio_attributes_t& attributes) {
174 ALOGV("%s()", __FUNCTION__);
175 const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
176 if (aps == 0) return false;
177 return aps->isDirectOutputSupported(config, attributes);
178}
179
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800180// ---------------------------------------------------------------------------
181
Ray Essicked304702017-12-12 14:00:57 -0800182void AudioTrack::MediaMetrics::gather(const AudioTrack *track)
183{
Ray Essick88394302018-01-24 14:52:05 -0800184 // only if we're in a good state...
185 // XXX: shall we gather alternative info if failing?
186 const status_t lstatus = track->initCheck();
187 if (lstatus != NO_ERROR) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700188 ALOGD("%s(): no metrics gathered, track status=%d", __func__, (int) lstatus);
Ray Essick88394302018-01-24 14:52:05 -0800189 return;
190 }
191
Andy Hungd0979812019-02-21 15:51:44 -0800192#define MM_PREFIX "android.media.audiotrack." // avoid cut-n-paste errors.
Ray Essicked304702017-12-12 14:00:57 -0800193
Andy Hungd0979812019-02-21 15:51:44 -0800194 // Java API 28 entries, do not change.
Ray Essickf27e9872019-12-07 06:28:46 -0800195 mMetricsItem->setCString(MM_PREFIX "streamtype", toString(track->streamType()).c_str());
196 mMetricsItem->setCString(MM_PREFIX "type",
Andy Hungd0979812019-02-21 15:51:44 -0800197 toString(track->mAttributes.content_type).c_str());
Ray Essickf27e9872019-12-07 06:28:46 -0800198 mMetricsItem->setCString(MM_PREFIX "usage", toString(track->mAttributes.usage).c_str());
Ray Essicked304702017-12-12 14:00:57 -0800199
Andy Hungd0979812019-02-21 15:51:44 -0800200 // Non-API entries, these can change due to a Java string mistake.
Ray Essickf27e9872019-12-07 06:28:46 -0800201 mMetricsItem->setInt32(MM_PREFIX "sampleRate", (int32_t)track->mSampleRate);
202 mMetricsItem->setInt64(MM_PREFIX "channelMask", (int64_t)track->mChannelMask);
Andy Hungd0979812019-02-21 15:51:44 -0800203 // Non-API entries, these can change.
Ray Essickf27e9872019-12-07 06:28:46 -0800204 mMetricsItem->setInt32(MM_PREFIX "portId", (int32_t)track->mPortId);
205 mMetricsItem->setCString(MM_PREFIX "encoding", toString(track->mFormat).c_str());
206 mMetricsItem->setInt32(MM_PREFIX "frameCount", (int32_t)track->mFrameCount);
207 mMetricsItem->setCString(MM_PREFIX "attributes", toString(track->mAttributes).c_str());
Ray Essicked304702017-12-12 14:00:57 -0800208}
209
Ray Essick88394302018-01-24 14:52:05 -0800210// hand the user a snapshot of the metrics.
Ray Essickf27e9872019-12-07 06:28:46 -0800211status_t AudioTrack::getMetrics(mediametrics::Item * &item)
Ray Essick88394302018-01-24 14:52:05 -0800212{
213 mMediaMetrics.gather(this);
Ray Essickf27e9872019-12-07 06:28:46 -0800214 mediametrics::Item *tmp = mMediaMetrics.dup();
Ray Essick88394302018-01-24 14:52:05 -0800215 if (tmp == nullptr) {
216 return BAD_VALUE;
217 }
218 item = tmp;
219 return NO_ERROR;
220}
Ray Essicked304702017-12-12 14:00:57 -0800221
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000222AudioTrack::AudioTrack() : AudioTrack("" /*opPackageName*/)
223{
224}
225
226AudioTrack::AudioTrack(const std::string& opPackageName)
Glenn Kasten87913512011-06-22 16:15:25 -0700227 : mStatus(NO_INIT),
Haynes Mathew George9b3359f2016-03-23 19:09:10 -0700228 mState(STATE_STOPPED),
John Grossman4ff14ba2012-02-08 16:37:41 -0800229 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800230 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700231 mPausedPosition(0),
Eric Laurent20b9ef02016-12-05 11:03:16 -0800232 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabinf6eb4c32020-02-25 14:06:25 -0800233 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000234 mOpPackageName(opPackageName),
jiabinf6eb4c32020-02-25 14:06:25 -0800235 mAudioTrackCallback(new AudioTrackCallback())
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800236{
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700237 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
238 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
Mikhail Naganov55773032020-10-01 15:08:13 -0700239 mAttributes.flags = AUDIO_FLAG_NONE;
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700240 strcpy(mAttributes.tags, "");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800241}
242
243AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800244 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800245 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800246 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700247 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800248 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700249 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800250 callback_t cbf,
251 void* user,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700252 int32_t notificationFrames,
Glenn Kastend848eb42016-03-08 13:42:11 -0800253 audio_session_t sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000254 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800255 const audio_offload_info_t *offloadInfo,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800256 uid_t uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700257 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700258 const audio_attributes_t* pAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -0700259 bool doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -0700260 float maxRequiredSpeed,
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000261 audio_port_handle_t selectedDeviceId,
262 const std::string& opPackageName)
Glenn Kasten87913512011-06-22 16:15:25 -0700263 : mStatus(NO_INIT),
Haynes Mathew George9b3359f2016-03-23 19:09:10 -0700264 mState(STATE_STOPPED),
John Grossman4ff14ba2012-02-08 16:37:41 -0800265 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800266 mPreviousSchedulingGroup(SP_DEFAULT),
jiabinf6eb4c32020-02-25 14:06:25 -0800267 mPausedPosition(0),
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000268 mOpPackageName(opPackageName),
jiabinf6eb4c32020-02-25 14:06:25 -0800269 mAudioTrackCallback(new AudioTrackCallback())
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800270{
François Gaffie393f0e02019-04-10 09:09:08 +0200271 mAttributes = AUDIO_ATTRIBUTES_INITIALIZER;
Ippei Murata5fa32ed2018-10-01 17:37:50 +0900272
Eric Laurentf32d7812017-11-30 14:44:07 -0800273 (void)set(streamType, sampleRate, format, channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700274 frameCount, flags, cbf, user, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800275 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
jiabin156c6872017-10-06 09:47:15 -0700276 offloadInfo, uid, pid, pAttributes, doNotReconnect, maxRequiredSpeed, selectedDeviceId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800277}
278
Andreas Huberc8139852012-01-18 10:51:55 -0800279AudioTrack::AudioTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800280 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800281 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800282 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700283 audio_channel_mask_t channelMask,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800284 const sp<IMemory>& sharedBuffer,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700285 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800286 callback_t cbf,
287 void* user,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700288 int32_t notificationFrames,
Glenn Kastend848eb42016-03-08 13:42:11 -0800289 audio_session_t sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000290 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800291 const audio_offload_info_t *offloadInfo,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800292 uid_t uid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700293 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700294 const audio_attributes_t* pAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -0700295 bool doNotReconnect,
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000296 float maxRequiredSpeed,
297 const std::string& opPackageName)
Glenn Kasten87913512011-06-22 16:15:25 -0700298 : mStatus(NO_INIT),
Haynes Mathew George9b3359f2016-03-23 19:09:10 -0700299 mState(STATE_STOPPED),
John Grossman4ff14ba2012-02-08 16:37:41 -0800300 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800301 mPreviousSchedulingGroup(SP_DEFAULT),
Paul McLeanaa981192015-03-21 09:55:15 -0700302 mPausedPosition(0),
jiabinf6eb4c32020-02-25 14:06:25 -0800303 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000304 mOpPackageName(opPackageName),
jiabinf6eb4c32020-02-25 14:06:25 -0800305 mAudioTrackCallback(new AudioTrackCallback())
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800306{
François Gaffie393f0e02019-04-10 09:09:08 +0200307 mAttributes = AUDIO_ATTRIBUTES_INITIALIZER;
Ippei Murata5fa32ed2018-10-01 17:37:50 +0900308
Eric Laurentf32d7812017-11-30 14:44:07 -0800309 (void)set(streamType, sampleRate, format, channelMask,
Glenn Kasten17a736c2012-02-14 08:52:15 -0800310 0 /*frameCount*/, flags, cbf, user, notificationFrames,
Marco Nelissend457c972014-02-11 08:47:07 -0800311 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
Andy Hungff874dc2016-04-11 16:49:09 -0700312 uid, pid, pAttributes, doNotReconnect, maxRequiredSpeed);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800313}
314
315AudioTrack::~AudioTrack()
316{
Ray Essicked304702017-12-12 14:00:57 -0800317 // pull together the numbers, before we clean up our structures
318 mMediaMetrics.gather(this);
319
Andy Hungb68f5eb2019-12-03 16:49:17 -0800320 mediametrics::LogItem(mMetricsId)
321 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DTOR)
Phil Burkd3813f32020-04-23 16:26:15 -0700322 .set(AMEDIAMETRICS_PROP_CALLERNAME,
323 mCallerName.empty()
Andy Hunga6b27032020-04-27 10:34:24 -0700324 ? AMEDIAMETRICS_PROP_CALLERNAME_VALUE_UNKNOWN
Phil Burkd3813f32020-04-23 16:26:15 -0700325 : mCallerName.c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -0800326 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
327 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)mStatus)
328 .record();
329
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800330 if (mStatus == NO_ERROR) {
331 // Make sure that callback function exits in the case where
332 // it is looping on buffer full condition in obtainBuffer().
333 // Otherwise the callback thread will never exit.
334 stop();
335 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100336 mProxy->interrupt();
Glenn Kasten3acbd052012-02-28 10:39:56 -0800337 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800338 mAudioTrackThread->requestExitAndWait();
339 mAudioTrackThread.clear();
340 }
Eric Laurent296fb132015-05-01 11:38:42 -0700341 // No lock here: worst case we remove a NULL callback which will be a nop
342 if (mDeviceCallback != 0 && mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent09f1ed22019-04-24 17:45:17 -0700343 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -0700344 }
Marco Nelissenf8880202014-11-14 07:58:25 -0800345 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten53cec222013-08-29 09:01:02 -0700346 mAudioTrack.clear();
Eric Laurent3bcffa12014-06-12 18:38:45 -0700347 mCblkMemory.clear();
348 mSharedBuffer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800349 IPCThreadState::self()->flushCommands();
Andy Hungfb8ede22018-09-12 19:03:24 -0700350 ALOGV("%s(%d), releasing session id %d from %d on behalf of %d",
Eric Laurent973db022018-11-20 14:54:31 -0800351 __func__, mPortId,
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700352 mSessionId, IPCThreadState::self()->getCallingPid(), mClientPid);
Marco Nelissend457c972014-02-11 08:47:07 -0800353 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800354 }
355}
356
357status_t AudioTrack::set(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800358 audio_stream_type_t streamType,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800359 uint32_t sampleRate,
Glenn Kastene1c39622012-01-04 09:36:37 -0800360 audio_format_t format,
Glenn Kasten28b76b32012-07-03 17:24:41 -0700361 audio_channel_mask_t channelMask,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800362 size_t frameCount,
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700363 audio_output_flags_t flags,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800364 callback_t cbf,
365 void* user,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700366 int32_t notificationFrames,
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800367 const sp<IMemory>& sharedBuffer,
Eric Laurentbe916aa2010-06-01 23:49:17 -0700368 bool threadCanCallJava,
Glenn Kastend848eb42016-03-08 13:42:11 -0800369 audio_session_t sessionId,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +0000370 transfer_type transferType,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800371 const audio_offload_info_t *offloadInfo,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800372 uid_t uid,
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700373 pid_t pid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700374 const audio_attributes_t* pAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -0700375 bool doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -0700376 float maxRequiredSpeed,
377 audio_port_handle_t selectedDeviceId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800378{
Eric Laurentf32d7812017-11-30 14:44:07 -0800379 status_t status;
380 uint32_t channelCount;
381 pid_t callingPid;
382 pid_t myPid;
383
Eric Laurent973db022018-11-20 14:54:31 -0800384 // Note mPortId is not valid until the track is created, so omit mPortId in ALOG for set.
Andy Hungfb8ede22018-09-12 19:03:24 -0700385 ALOGV("%s(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
Glenn Kastenea38ee72016-04-18 11:08:01 -0700386 "flags #%x, notificationFrames %d, sessionId %d, transferType %d, uid %d, pid %d",
Andy Hungfb8ede22018-09-12 19:03:24 -0700387 __func__,
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800388 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
Glenn Kasten4c36d6f2015-03-20 09:05:01 -0700389 sessionId, transferType, uid, pid);
Glenn Kasten86f04662014-02-24 15:13:05 -0800390
Phil Burk33ff89b2015-11-30 11:16:01 -0800391 mThreadCanCallJava = threadCanCallJava;
jiabin156c6872017-10-06 09:47:15 -0700392 mSelectedDeviceId = selectedDeviceId;
Eric Laurent21da6472017-11-09 16:29:26 -0800393 mSessionId = sessionId;
Phil Burk33ff89b2015-11-30 11:16:01 -0800394
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800395 switch (transferType) {
396 case TRANSFER_DEFAULT:
397 if (sharedBuffer != 0) {
398 transferType = TRANSFER_SHARED;
399 } else if (cbf == NULL || threadCanCallJava) {
400 transferType = TRANSFER_SYNC;
401 } else {
402 transferType = TRANSFER_CALLBACK;
403 }
404 break;
405 case TRANSFER_CALLBACK:
Jean-Michel Trivif4158d82018-09-25 12:43:58 -0700406 case TRANSFER_SYNC_NOTIF_CALLBACK:
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800407 if (cbf == NULL || sharedBuffer != 0) {
Jean-Michel Trivif4158d82018-09-25 12:43:58 -0700408 ALOGE("%s(): Transfer type %s but cbf == NULL || sharedBuffer != 0",
409 convertTransferToText(transferType), __func__);
Eric Laurentf32d7812017-11-30 14:44:07 -0800410 status = BAD_VALUE;
411 goto exit;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800412 }
413 break;
414 case TRANSFER_OBTAIN:
415 case TRANSFER_SYNC:
416 if (sharedBuffer != 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700417 ALOGE("%s(): Transfer type TRANSFER_OBTAIN but sharedBuffer != 0", __func__);
Eric Laurentf32d7812017-11-30 14:44:07 -0800418 status = BAD_VALUE;
419 goto exit;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800420 }
421 break;
422 case TRANSFER_SHARED:
423 if (sharedBuffer == 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700424 ALOGE("%s(): Transfer type TRANSFER_SHARED but sharedBuffer == 0", __func__);
Eric Laurentf32d7812017-11-30 14:44:07 -0800425 status = BAD_VALUE;
426 goto exit;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800427 }
428 break;
429 default:
Andy Hungfb8ede22018-09-12 19:03:24 -0700430 ALOGE("%s(): Invalid transfer type %d",
431 __func__, transferType);
Eric Laurentf32d7812017-11-30 14:44:07 -0800432 status = BAD_VALUE;
433 goto exit;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800434 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800435 mSharedBuffer = sharedBuffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800436 mTransfer = transferType;
Ronghua Wufaeb0f22015-05-21 12:20:21 -0700437 mDoNotReconnect = doNotReconnect;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800438
Andy Hungfb8ede22018-09-12 19:03:24 -0700439 ALOGV_IF(sharedBuffer != 0, "%s(): sharedBuffer: %p, size: %zu",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700440 __func__, sharedBuffer->unsecurePointer(), sharedBuffer->size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800441
Andy Hungfb8ede22018-09-12 19:03:24 -0700442 ALOGV("%s(): streamType %d frameCount %zu flags %04x",
443 __func__, streamType, frameCount, flags);
Eric Laurent1a9ed112012-03-20 18:36:01 -0700444
Glenn Kasten53cec222013-08-29 09:01:02 -0700445 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Eric Laurent1dd70b92009-04-21 07:56:33 -0700446 if (mAudioTrack != 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700447 ALOGE("%s(): Track already in use", __func__);
Eric Laurentf32d7812017-11-30 14:44:07 -0800448 status = INVALID_OPERATION;
449 goto exit;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800450 }
451
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800452 // handle default values first.
Eric Laurente83b55d2014-11-14 10:06:21 -0800453 if (streamType == AUDIO_STREAM_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700454 streamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800455 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700456 if (pAttributes == NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800457 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700458 ALOGE("%s(): Invalid stream type %d", __func__, streamType);
Eric Laurentf32d7812017-11-30 14:44:07 -0800459 status = BAD_VALUE;
460 goto exit;
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700461 }
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700462 mStreamType = streamType;
Eric Laurente83b55d2014-11-14 10:06:21 -0800463
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700464 } else {
Jean-Michel Trivifaabb512014-06-11 16:55:06 -0700465 // stream type shouldn't be looked at, this track has audio attributes
466 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Andy Hungfb8ede22018-09-12 19:03:24 -0700467 ALOGV("%s(): Building AudioTrack with attributes:"
468 " usage=%d content=%d flags=0x%x tags=[%s]",
469 __func__,
470 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800471 mStreamType = AUDIO_STREAM_DEFAULT;
François Gaffie58d4be52018-11-06 15:30:12 +0100472 audio_flags_to_audio_output_flags(mAttributes.flags, &flags);
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800473 }
Glenn Kastenea7939a2012-03-14 12:56:26 -0700474
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800475 // these below should probably come from the audioFlinger too...
Glenn Kastene1c39622012-01-04 09:36:37 -0800476 if (format == AUDIO_FORMAT_DEFAULT) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700477 format = AUDIO_FORMAT_PCM_16_BIT;
Phil Burkfdb3c072016-02-09 10:47:02 -0800478 } else if (format == AUDIO_FORMAT_IEC61937) { // HDMI pass-through?
Mikhail Naganov55773032020-10-01 15:08:13 -0700479 flags = static_cast<audio_output_flags_t>(flags | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800480 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800481
482 // validate parameters
Dima Zavinfce7a472011-04-19 22:30:36 -0700483 if (!audio_is_valid_format(format)) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700484 ALOGE("%s(): Invalid format %#x", __func__, format);
Eric Laurentf32d7812017-11-30 14:44:07 -0800485 status = BAD_VALUE;
486 goto exit;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800487 }
Glenn Kastendd5f4c82014-01-13 10:26:32 -0800488 mFormat = format;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700489
Glenn Kasten8ba90322013-10-30 11:29:27 -0700490 if (!audio_is_output_channel(channelMask)) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700491 ALOGE("%s(): Invalid channel mask %#x", __func__, channelMask);
Eric Laurentf32d7812017-11-30 14:44:07 -0800492 status = BAD_VALUE;
493 goto exit;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700494 }
Glenn Kastene3247bf2014-02-24 15:19:07 -0800495 mChannelMask = channelMask;
Eric Laurentf32d7812017-11-30 14:44:07 -0800496 channelCount = audio_channel_count_from_out_mask(channelMask);
Glenn Kastene3247bf2014-02-24 15:19:07 -0800497 mChannelCount = channelCount;
Glenn Kasten8ba90322013-10-30 11:29:27 -0700498
Eric Laurentc2f1f072009-07-17 12:17:14 -0700499 // force direct flag if format is not linear PCM
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100500 // or offload was requested
501 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
502 || !audio_is_linear_pcm(format)) {
503 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
Andy Hungfb8ede22018-09-12 19:03:24 -0700504 ? "%s(): Offload request, forcing to Direct Output"
505 : "%s(): Not linear PCM, forcing to Direct Output",
506 __func__);
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700507 flags = (audio_output_flags_t)
Glenn Kasten3acbd052012-02-28 10:39:56 -0800508 // FIXME why can't we allow direct AND fast?
Eric Laurent0ca3cf92012-04-18 09:24:29 -0700509 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700510 }
511
Eric Laurentd1f69b02014-12-15 14:33:13 -0800512 // force direct flag if HW A/V sync requested
513 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
514 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
515 }
516
Glenn Kastenb7730382014-04-30 15:50:31 -0700517 if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Phil Burkfdb3c072016-02-09 10:47:02 -0800518 if (audio_has_proportional_frames(format)) {
Glenn Kastenb7730382014-04-30 15:50:31 -0700519 mFrameSize = channelCount * audio_bytes_per_sample(format);
520 } else {
521 mFrameSize = sizeof(uint8_t);
522 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800523 } else {
Phil Burkfdb3c072016-02-09 10:47:02 -0800524 ALOG_ASSERT(audio_has_proportional_frames(format));
Glenn Kastenb7730382014-04-30 15:50:31 -0700525 mFrameSize = channelCount * audio_bytes_per_sample(format);
Glenn Kastenb7730382014-04-30 15:50:31 -0700526 // createTrack will return an error if PCM format is not supported by server,
527 // so no need to check for specific PCM formats here
Glenn Kastene3aa6592012-12-04 12:22:46 -0800528 }
529
Eric Laurent0d6db582014-11-12 18:39:44 -0800530 // sampling rate must be specified for direct outputs
531 if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentf32d7812017-11-30 14:44:07 -0800532 status = BAD_VALUE;
533 goto exit;
Eric Laurent0d6db582014-11-12 18:39:44 -0800534 }
535 mSampleRate = sampleRate;
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700536 mOriginalSampleRate = sampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700537 mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT;
Andy Hungff874dc2016-04-11 16:49:09 -0700538 // 1.0 <= mMaxRequiredSpeed <= AUDIO_TIMESTRETCH_SPEED_MAX
539 mMaxRequiredSpeed = min(max(maxRequiredSpeed, 1.0f), AUDIO_TIMESTRETCH_SPEED_MAX);
Eric Laurent0d6db582014-11-12 18:39:44 -0800540
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800541 // Make copy of input parameter offloadInfo so that in the future:
542 // (a) createTrack_l doesn't need it as an input parameter
543 // (b) we can support re-creation of offloaded tracks
544 if (offloadInfo != NULL) {
545 mOffloadInfoCopy = *offloadInfo;
546 mOffloadInfo = &mOffloadInfoCopy;
547 } else {
548 mOffloadInfo = NULL;
Eric Laurent20b9ef02016-12-05 11:03:16 -0800549 memset(&mOffloadInfoCopy, 0, sizeof(audio_offload_info_t));
Ytai Ben-Tsviffa2fd92020-10-20 09:13:53 -0700550 mOffloadInfoCopy = AUDIO_INFO_INITIALIZER;
Glenn Kastenb5ccb2d2014-01-13 14:42:43 -0800551 }
552
Glenn Kasten66e46352014-01-16 17:44:23 -0800553 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
554 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
Glenn Kasten05632a52012-01-03 14:22:33 -0800555 mSendLevel = 0.0f;
Glenn Kasten396fabd2014-01-08 08:54:23 -0800556 // mFrameCount is initialized in createTrack_l
Glenn Kastenb6037442012-11-14 13:42:25 -0800557 mReqFrameCount = frameCount;
Glenn Kastenea38ee72016-04-18 11:08:01 -0700558 if (notificationFrames >= 0) {
559 mNotificationFramesReq = notificationFrames;
560 mNotificationsPerBufferReq = 0;
561 } else {
562 if (!(flags & AUDIO_OUTPUT_FLAG_FAST)) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700563 ALOGE("%s(): notificationFrames=%d not permitted for non-fast track",
564 __func__, notificationFrames);
Eric Laurentf32d7812017-11-30 14:44:07 -0800565 status = BAD_VALUE;
566 goto exit;
Glenn Kastenea38ee72016-04-18 11:08:01 -0700567 }
568 if (frameCount > 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -0700569 ALOGE("%s(): notificationFrames=%d not permitted with non-zero frameCount=%zu",
570 __func__, notificationFrames, frameCount);
Eric Laurentf32d7812017-11-30 14:44:07 -0800571 status = BAD_VALUE;
572 goto exit;
Glenn Kastenea38ee72016-04-18 11:08:01 -0700573 }
574 mNotificationFramesReq = 0;
575 const uint32_t minNotificationsPerBuffer = 1;
576 const uint32_t maxNotificationsPerBuffer = 8;
577 mNotificationsPerBufferReq = min(maxNotificationsPerBuffer,
578 max((uint32_t) -notificationFrames, minNotificationsPerBuffer));
579 ALOGW_IF(mNotificationsPerBufferReq != (uint32_t) -notificationFrames,
Andy Hungfb8ede22018-09-12 19:03:24 -0700580 "%s(): notificationFrames=%d clamped to the range -%u to -%u",
581 __func__,
Glenn Kastenea38ee72016-04-18 11:08:01 -0700582 notificationFrames, minNotificationsPerBuffer, maxNotificationsPerBuffer);
583 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800584 mNotificationFramesAct = 0;
Eric Laurentf32d7812017-11-30 14:44:07 -0800585 callingPid = IPCThreadState::self()->getCallingPid();
586 myPid = getpid();
587 if (uid == AUDIO_UID_INVALID || (callingPid != myPid)) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800588 mClientUid = IPCThreadState::self()->getCallingUid();
589 } else {
590 mClientUid = uid;
591 }
Eric Laurentf32d7812017-11-30 14:44:07 -0800592 if (pid == -1 || (callingPid != myPid)) {
593 mClientPid = callingPid;
Marco Nelissend457c972014-02-11 08:47:07 -0800594 } else {
595 mClientPid = pid;
596 }
Eric Laurent2beeb502010-07-16 07:43:46 -0700597 mAuxEffectId = 0;
Haynes Mathew Georgeae34ed22016-01-28 11:58:39 -0800598 mOrigFlags = mFlags = flags;
Glenn Kasten4a4a0952012-03-19 11:38:14 -0700599 mCbf = cbf;
Eric Laurentbe916aa2010-06-01 23:49:17 -0700600
Glenn Kastena997e7a2012-08-07 09:44:19 -0700601 if (cbf != NULL) {
Andy Hungca353672019-03-06 11:54:38 -0800602 mAudioTrackThread = new AudioTrackThread(*this);
Glenn Kastena997e7a2012-08-07 09:44:19 -0700603 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
Glenn Kastenbfd31842015-03-20 09:01:44 -0700604 // thread begins in paused state, and will not reference us until start()
Glenn Kastena997e7a2012-08-07 09:44:19 -0700605 }
606
Eric Laurent34f1d8e2009-11-04 08:27:26 -0800607 // create the IAudioTrack
Francois Gaffie24a9fb02019-01-18 17:51:34 +0100608 {
609 AutoMutex lock(mLock);
610 status = createTrack_l();
611 }
Glenn Kastena997e7a2012-08-07 09:44:19 -0700612 if (status != NO_ERROR) {
613 if (mAudioTrackThread != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100614 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
615 mAudioTrackThread->requestExitAndWait();
Glenn Kastena997e7a2012-08-07 09:44:19 -0700616 mAudioTrackThread.clear();
617 }
Eric Laurentf32d7812017-11-30 14:44:07 -0800618 goto exit;
Glenn Kasten5d464eb2012-06-22 17:19:53 -0700619 }
620
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800621 mUserData = user;
Andy Hung4ede21d2014-12-12 15:37:34 -0800622 mLoopCount = 0;
623 mLoopStart = 0;
624 mLoopEnd = 0;
Andy Hung53c3b5f2014-12-15 16:42:05 -0800625 mLoopCountNotified = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800626 mMarkerPosition = 0;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700627 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800628 mNewPosition = 0;
629 mUpdatePeriod = 0;
Glenn Kasten200092b2014-08-15 15:13:30 -0700630 mPosition = 0;
631 mReleased = 0;
Andy Hungffa36952017-08-17 10:41:51 -0700632 mStartNs = 0;
633 mStartFromZeroUs = 0;
Andy Hung8b0bfd92019-12-23 13:11:11 -0800634 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid, mClientUid);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800635 mSequence = 1;
636 mObservedSequence = mSequence;
637 mInUnderrun = false;
Phil Burk1b420972015-04-22 10:52:21 -0700638 mPreviousTimestampValid = false;
Andy Hungc8e09c62015-06-03 23:43:36 -0700639 mTimestampStartupGlitchReported = false;
Andy Hungcf3b7152019-04-19 18:29:21 -0700640 mTimestampRetrogradePositionReported = false;
641 mTimestampRetrogradeTimeReported = false;
642 mTimestampStallReported = false;
643 mTimestampStaleTimeReported = false;
Andy Hungb01faa32016-04-27 12:51:32 -0700644 mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
Andy Hung65ffdfc2016-10-10 15:52:11 -0700645 mStartTs.mPosition = 0;
Phil Burk2812d9e2016-01-04 10:34:30 -0800646 mUnderrunCountOffset = 0;
Andy Hungea2b9c02016-02-12 17:06:53 -0800647 mFramesWritten = 0;
648 mFramesWrittenServerOffset = 0;
Andy Hungf20a4e92016-08-15 19:10:34 -0700649 mFramesWrittenAtRestore = -1; // -1 is a unique initializer.
Ivan Lozano8cf3a072017-08-09 09:01:33 -0700650 mVolumeHandler = new media::VolumeHandler();
Eric Laurentf32d7812017-11-30 14:44:07 -0800651
652exit:
653 mStatus = status;
654 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800655}
656
Mikhail Naganov55773032020-10-01 15:08:13 -0700657
658status_t AudioTrack::set(
659 audio_stream_type_t streamType,
660 uint32_t sampleRate,
661 audio_format_t format,
662 uint32_t channelMask,
663 size_t frameCount,
664 audio_output_flags_t flags,
665 callback_t cbf,
666 void* user,
667 int32_t notificationFrames,
668 const sp<IMemory>& sharedBuffer,
669 bool threadCanCallJava,
670 audio_session_t sessionId,
671 transfer_type transferType,
672 const audio_offload_info_t *offloadInfo,
673 uid_t uid,
674 pid_t pid,
675 const audio_attributes_t* pAttributes,
676 bool doNotReconnect,
677 float maxRequiredSpeed,
678 audio_port_handle_t selectedDeviceId)
679{
680 return set(streamType, sampleRate, format,
681 static_cast<audio_channel_mask_t>(channelMask),
682 frameCount, flags, cbf, user, notificationFrames, sharedBuffer,
683 threadCanCallJava, sessionId, transferType, offloadInfo, uid, pid,
684 pAttributes, doNotReconnect, maxRequiredSpeed, selectedDeviceId);
685}
686
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800687// -------------------------------------------------------------------------
688
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100689status_t AudioTrack::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800690{
Eric Laurentf5aafb22010-11-18 08:40:16 -0800691 AutoMutex lock(mLock);
Andy Hungb68f5eb2019-12-03 16:49:17 -0800692
Andy Hung10fb4be2020-05-27 22:22:22 -0700693 if (mState == STATE_ACTIVE) {
694 return INVALID_OPERATION;
695 }
696
697 ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
698
699 // Defer logging here due to OpenSL ES repeated start calls.
700 // TODO(b/154868033) after fix, restore this logging back to the beginning of start().
701 const int64_t beginNs = systemTime();
Andy Hungb68f5eb2019-12-03 16:49:17 -0800702 status_t status = NO_ERROR; // logged: make sure to set this before returning.
Andy Hung06a730b2020-04-09 13:28:31 -0700703 mediametrics::Defer defer([&] {
Andy Hungb68f5eb2019-12-03 16:49:17 -0800704 mediametrics::LogItem(mMetricsId)
Andy Hunga6b27032020-04-27 10:34:24 -0700705 .set(AMEDIAMETRICS_PROP_CALLERNAME,
706 mCallerName.empty()
707 ? AMEDIAMETRICS_PROP_CALLERNAME_VALUE_UNKNOWN
708 : mCallerName.c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -0800709 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_START)
Andy Hungea840382020-05-05 21:50:17 -0700710 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
Andy Hungb68f5eb2019-12-03 16:49:17 -0800711 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
712 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)status)
713 .record(); });
714
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800715
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800716 mInUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800717
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800718 State previousState = mState;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100719 if (previousState == STATE_PAUSED_STOPPING) {
720 mState = STATE_STOPPING;
721 } else {
722 mState = STATE_ACTIVE;
723 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700724 (void) updateAndGetPosition_l();
Andy Hung65ffdfc2016-10-10 15:52:11 -0700725
726 // save start timestamp
727 if (isOffloadedOrDirect_l()) {
728 if (getTimestamp_l(mStartTs) != OK) {
729 mStartTs.mPosition = 0;
730 }
731 } else {
732 if (getTimestamp_l(&mStartEts) != OK) {
733 mStartEts.clear();
734 }
735 }
Andy Hungffa36952017-08-17 10:41:51 -0700736 mStartNs = systemTime(); // save this for timestamp adjustment after starting.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800737 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
738 // reset current position as seen by client to 0
Glenn Kasten200092b2014-08-15 15:13:30 -0700739 mPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -0700740 mPreviousTimestampValid = false;
Andy Hungc8e09c62015-06-03 23:43:36 -0700741 mTimestampStartupGlitchReported = false;
Andy Hungcf3b7152019-04-19 18:29:21 -0700742 mTimestampRetrogradePositionReported = false;
743 mTimestampRetrogradeTimeReported = false;
744 mTimestampStallReported = false;
745 mTimestampStaleTimeReported = false;
Andy Hungb01faa32016-04-27 12:51:32 -0700746 mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
Phil Burk1b420972015-04-22 10:52:21 -0700747
Andy Hung65ffdfc2016-10-10 15:52:11 -0700748 if (!isOffloadedOrDirect_l()
749 && mStartEts.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] > 0) {
Andy Hunge1e98462016-04-12 10:18:51 -0700750 // Server side has consumed something, but is it finished consuming?
751 // It is possible since flush and stop are asynchronous that the server
752 // is still active at this point.
Andy Hungfb8ede22018-09-12 19:03:24 -0700753 ALOGV("%s(%d): server read:%lld cumulative flushed:%lld client written:%lld",
Eric Laurent973db022018-11-20 14:54:31 -0800754 __func__, mPortId,
Andy Hunge1e98462016-04-12 10:18:51 -0700755 (long long)(mFramesWrittenServerOffset
Andy Hung65ffdfc2016-10-10 15:52:11 -0700756 + mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER]),
757 (long long)mStartEts.mFlushed,
Andy Hunge1e98462016-04-12 10:18:51 -0700758 (long long)mFramesWritten);
Andy Hungc4e60eb2017-09-06 11:14:57 -0700759 // mStartEts is already adjusted by mFramesWrittenServerOffset, so we delta adjust.
760 mFramesWrittenServerOffset -= mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung61be8412015-10-06 10:51:09 -0700761 }
Andy Hunge1e98462016-04-12 10:18:51 -0700762 mFramesWritten = 0;
763 mProxy->clearTimestamp(); // need new server push for valid timestamp
764 mMarkerReached = false;
Andy Hung61be8412015-10-06 10:51:09 -0700765
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700766 // For offloaded tracks, we don't know if the hardware counters are really zero here,
767 // since the flush is asynchronous and stop may not fully drain.
768 // We save the time when the track is started to later verify whether
769 // the counters are realistic (i.e. start from zero after this time).
Andy Hungffa36952017-08-17 10:41:51 -0700770 mStartFromZeroUs = mStartNs / 1000;
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700771
Eric Laurentec9a0322013-08-28 10:23:01 -0700772 // force refresh of remaining frames by processAudioBuffer() as last
773 // write before stop could be partial.
774 mRefreshRemaining = true;
Tomoharu Kasahara6e8bf982017-06-09 16:17:33 +0900775
776 // for static track, clear the old flags when starting from stopped state
777 if (mSharedBuffer != 0) {
778 android_atomic_and(
779 ~(CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
780 &mCblk->mFlags);
781 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800782 }
Glenn Kasten200092b2014-08-15 15:13:30 -0700783 mNewPosition = mPosition + mUpdatePeriod;
Andy Hung4be3b832016-10-13 17:51:43 -0700784 int32_t flags = android_atomic_and(~(CBLK_STREAM_END_DONE | CBLK_DISABLED), &mCblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800785
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800786 if (!(flags & CBLK_INVALID)) {
787 status = mAudioTrack->start();
788 if (status == DEAD_OBJECT) {
789 flags |= CBLK_INVALID;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800790 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800791 }
792 if (flags & CBLK_INVALID) {
793 status = restoreTrack_l("start");
794 }
795
Andy Hung79629f02016-03-24 13:57:40 -0700796 // resume or pause the callback thread as needed.
797 sp<AudioTrackThread> t = mAudioTrackThread;
798 if (status == NO_ERROR) {
799 if (t != 0) {
800 if (previousState == STATE_STOPPING) {
801 mProxy->interrupt();
802 } else {
803 t->resume();
804 }
805 } else {
806 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
807 get_sched_policy(0, &mPreviousSchedulingGroup);
808 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
809 }
Andy Hung39399b62017-04-21 15:07:45 -0700810
811 // Start our local VolumeHandler for restoration purposes.
812 mVolumeHandler->setStarted();
Andy Hung79629f02016-03-24 13:57:40 -0700813 } else {
Eric Laurent973db022018-11-20 14:54:31 -0800814 ALOGE("%s(%d): status %d", __func__, mPortId, status);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800815 mState = previousState;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800816 if (t != 0) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100817 if (previousState != STATE_STOPPING) {
818 t->pause();
819 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800820 } else {
Glenn Kasten87913512011-06-22 16:15:25 -0700821 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
Glenn Kastena6364332012-04-19 09:35:04 -0700822 set_sched_policy(0, mPreviousSchedulingGroup);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800823 }
824 }
825
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100826 return status;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800827}
828
829void AudioTrack::stop()
830{
Andy Hungb68f5eb2019-12-03 16:49:17 -0800831 const int64_t beginNs = systemTime();
832
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800833 AutoMutex lock(mLock);
Andy Hung06a730b2020-04-09 13:28:31 -0700834 mediametrics::Defer defer([&]() {
Andy Hungb68f5eb2019-12-03 16:49:17 -0800835 mediametrics::LogItem(mMetricsId)
836 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_STOP)
Andy Hungea840382020-05-05 21:50:17 -0700837 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
Andy Hungb68f5eb2019-12-03 16:49:17 -0800838 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
Phil Burk64e16a72020-06-01 13:25:51 -0700839 .set(AMEDIAMETRICS_PROP_BUFFERSIZEFRAMES, (int32_t)mProxy->getBufferSizeInFrames())
840 .set(AMEDIAMETRICS_PROP_UNDERRUN, (int32_t) getUnderrunCount_l())
Phil Burka9876702020-04-20 18:16:15 -0700841 .record();
Phil Burka9876702020-04-20 18:16:15 -0700842 });
Andy Hungb68f5eb2019-12-03 16:49:17 -0800843
Eric Laurent973db022018-11-20 14:54:31 -0800844 ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
Andy Hungfb8ede22018-09-12 19:03:24 -0700845
Glenn Kasten397edb32013-08-30 15:10:13 -0700846 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800847 return;
848 }
849
Glenn Kasten23a75452014-01-13 10:37:17 -0800850 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100851 mState = STATE_STOPPING;
852 } else {
853 mState = STATE_STOPPED;
Andy Hung2148bf02016-11-28 19:01:02 -0800854 ALOGD_IF(mSharedBuffer == nullptr,
Eric Laurent973db022018-11-20 14:54:31 -0800855 "%s(%d): called with %u frames delivered", __func__, mPortId, mReleased.value());
Andy Hungc2813e52014-10-16 17:54:34 -0700856 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100857 }
858
Andy Hung1d3556d2018-03-29 16:30:14 -0700859 mProxy->stop(); // notify server not to read beyond current client position until start().
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800860 mProxy->interrupt();
861 mAudioTrack->stop();
Andy Hung61be8412015-10-06 10:51:09 -0700862
863 // Note: legacy handling - stop does not clear playback marker
864 // and periodic update counter, but flush does for streaming tracks.
Andy Hung9b461582014-12-01 17:56:29 -0800865
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800866 if (mSharedBuffer != 0) {
Andy Hung9b461582014-12-01 17:56:29 -0800867 // clear buffer position and loop count.
Andy Hung9b461582014-12-01 17:56:29 -0800868 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
869 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800870 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100871
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800872 sp<AudioTrackThread> t = mAudioTrackThread;
873 if (t != 0) {
Glenn Kasten23a75452014-01-13 10:37:17 -0800874 if (!isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100875 t->pause();
Jean-Michel Trivia60e9a22018-11-15 16:13:36 -0800876 } else if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
Jean-Michel Trivi0248a2a2018-11-21 10:05:57 -0800877 // causes wake up of the playback thread, that will callback the client for
878 // EVENT_STREAM_END in processAudioBuffer()
879 t->wake();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100880 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800881 } else {
882 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
883 set_sched_policy(0, mPreviousSchedulingGroup);
884 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800885}
886
887bool AudioTrack::stopped() const
888{
Glenn Kasten9a2aaf92012-01-03 09:42:47 -0800889 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800890 return mState != STATE_ACTIVE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800891}
892
893void AudioTrack::flush()
894{
Andy Hungb68f5eb2019-12-03 16:49:17 -0800895 const int64_t beginNs = systemTime();
Andy Hungfb8ede22018-09-12 19:03:24 -0700896 AutoMutex lock(mLock);
Andy Hung06a730b2020-04-09 13:28:31 -0700897 mediametrics::Defer defer([&]() {
Andy Hungb68f5eb2019-12-03 16:49:17 -0800898 mediametrics::LogItem(mMetricsId)
899 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_FLUSH)
Andy Hungea840382020-05-05 21:50:17 -0700900 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
Andy Hungb68f5eb2019-12-03 16:49:17 -0800901 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
902 .record(); });
903
Eric Laurent973db022018-11-20 14:54:31 -0800904 ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
Andy Hungfb8ede22018-09-12 19:03:24 -0700905
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800906 if (mSharedBuffer != 0) {
907 return;
Glenn Kasten4bae3642012-11-30 13:41:12 -0800908 }
Andy Hung4c5ed302018-05-09 11:16:21 -0700909 if (mState == STATE_ACTIVE) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800910 return;
911 }
912 flush_l();
Eric Laurent1703cdf2011-03-07 14:52:59 -0800913}
914
Eric Laurent1703cdf2011-03-07 14:52:59 -0800915void AudioTrack::flush_l()
916{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800917 ALOG_ASSERT(mState != STATE_ACTIVE);
Eric Laurentc2f1f072009-07-17 12:17:14 -0700918
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -0700919 // clear playback marker and periodic update counter
920 mMarkerPosition = 0;
921 mMarkerReached = false;
922 mUpdatePeriod = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100923 mRefreshRemaining = true;
Eric Laurentc2f1f072009-07-17 12:17:14 -0700924
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800925 mState = STATE_FLUSHED;
Andy Hungc2813e52014-10-16 17:54:34 -0700926 mReleased = 0;
Glenn Kasten23a75452014-01-13 10:37:17 -0800927 if (isOffloaded_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100928 mProxy->interrupt();
929 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800930 mProxy->flush();
Glenn Kasten4bae3642012-11-30 13:41:12 -0800931 mAudioTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800932}
933
934void AudioTrack::pause()
935{
Andy Hungb68f5eb2019-12-03 16:49:17 -0800936 const int64_t beginNs = systemTime();
Eric Laurentf5aafb22010-11-18 08:40:16 -0800937 AutoMutex lock(mLock);
Andy Hunga6b27032020-04-27 10:34:24 -0700938 mediametrics::Defer defer([&]() {
Andy Hungb68f5eb2019-12-03 16:49:17 -0800939 mediametrics::LogItem(mMetricsId)
940 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_PAUSE)
Andy Hungea840382020-05-05 21:50:17 -0700941 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
Andy Hungb68f5eb2019-12-03 16:49:17 -0800942 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
943 .record(); });
944
Eric Laurent973db022018-11-20 14:54:31 -0800945 ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
Andy Hungfb8ede22018-09-12 19:03:24 -0700946
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100947 if (mState == STATE_ACTIVE) {
948 mState = STATE_PAUSED;
949 } else if (mState == STATE_STOPPING) {
950 mState = STATE_PAUSED_STOPPING;
951 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800952 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800953 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800954 mProxy->interrupt();
955 mAudioTrack->pause();
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800956
Marco Nelissen3a90f282014-03-10 11:21:43 -0700957 if (isOffloaded_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -0700958 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -0700959 // An offload output can be re-used between two audio tracks having
960 // the same configuration. A timestamp query for a paused track
961 // while the other is running would return an incorrect time.
962 // To fix this, cache the playback position on a pause() and return
963 // this time when requested until the track is resumed.
964
965 // OffloadThread sends HAL pause in its threadLoop. Time saved
966 // here can be slightly off.
967
968 // TODO: check return code for getRenderPosition.
969
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800970 uint32_t halFrames;
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800971 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
Andy Hungfb8ede22018-09-12 19:03:24 -0700972 ALOGV("%s(%d): for offload, cache current position %u",
Eric Laurent973db022018-11-20 14:54:31 -0800973 __func__, mPortId, mPausedPosition);
Haynes Mathew George7064fd22014-01-08 13:59:53 -0800974 }
975 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800976}
977
Eric Laurentbe916aa2010-06-01 23:49:17 -0700978status_t AudioTrack::setVolume(float left, float right)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800979{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700980 // This duplicates a test by AudioTrack JNI, but that is not the only caller
981 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
982 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -0700983 return BAD_VALUE;
984 }
985
Andy Hungb68f5eb2019-12-03 16:49:17 -0800986 mediametrics::LogItem(mMetricsId)
987 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETVOLUME)
988 .set(AMEDIAMETRICS_PROP_VOLUME_LEFT, (double)left)
989 .set(AMEDIAMETRICS_PROP_VOLUME_RIGHT, (double)right)
990 .record();
991
Eric Laurent1703cdf2011-03-07 14:52:59 -0800992 AutoMutex lock(mLock);
Glenn Kasten66e46352014-01-16 17:44:23 -0800993 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
994 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800995
Glenn Kastenc56f3422014-03-21 17:53:17 -0700996 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
Eric Laurentbe916aa2010-06-01 23:49:17 -0700997
Glenn Kasten23a75452014-01-13 10:37:17 -0800998 if (isOffloaded_l()) {
Eric Laurent59fe0102013-09-27 18:48:26 -0700999 mAudioTrack->signal();
1000 }
Eric Laurentbe916aa2010-06-01 23:49:17 -07001001 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001002}
1003
Glenn Kastenb1c09932012-02-27 16:21:04 -08001004status_t AudioTrack::setVolume(float volume)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001005{
Glenn Kastenb1c09932012-02-27 16:21:04 -08001006 return setVolume(volume, volume);
Eric Laurentbe916aa2010-06-01 23:49:17 -07001007}
1008
Eric Laurent2beeb502010-07-16 07:43:46 -07001009status_t AudioTrack::setAuxEffectSendLevel(float level)
Eric Laurentbe916aa2010-06-01 23:49:17 -07001010{
Glenn Kastenc56f3422014-03-21 17:53:17 -07001011 // This duplicates a test by AudioTrack JNI, but that is not the only caller
1012 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
Eric Laurentbe916aa2010-06-01 23:49:17 -07001013 return BAD_VALUE;
1014 }
1015
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001016 AutoMutex lock(mLock);
Eric Laurentbe916aa2010-06-01 23:49:17 -07001017 mSendLevel = level;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001018 mProxy->setSendLevel(level);
Eric Laurentbe916aa2010-06-01 23:49:17 -07001019
1020 return NO_ERROR;
1021}
1022
Glenn Kastena5224f32012-01-04 12:41:44 -08001023void AudioTrack::getAuxEffectSendLevel(float* level) const
Eric Laurentbe916aa2010-06-01 23:49:17 -07001024{
1025 if (level != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001026 *level = mSendLevel;
Eric Laurentbe916aa2010-06-01 23:49:17 -07001027 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001028}
1029
Glenn Kasten3b16c762012-11-14 08:44:39 -08001030status_t AudioTrack::setSampleRate(uint32_t rate)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001031{
Andy Hung5cbb5782015-03-27 18:39:59 -07001032 AutoMutex lock(mLock);
Eric Laurent973db022018-11-20 14:54:31 -08001033 ALOGV("%s(%d): prior state:%s rate:%u", __func__, mPortId, stateToString(mState), rate);
Andy Hungfb8ede22018-09-12 19:03:24 -07001034
Andy Hung5cbb5782015-03-27 18:39:59 -07001035 if (rate == mSampleRate) {
1036 return NO_ERROR;
1037 }
jiabinf4de6112018-12-19 12:40:08 -08001038 if (isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)
1039 || (mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08001040 return INVALID_OPERATION;
1041 }
Eric Laurent0d6db582014-11-12 18:39:44 -08001042 if (mOutput == AUDIO_IO_HANDLE_NONE) {
1043 return NO_INIT;
1044 }
Andy Hung5cbb5782015-03-27 18:39:59 -07001045 // NOTE: it is theoretically possible, but highly unlikely, that a device change
1046 // could mean a previously allowed sampling rate is no longer allowed.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001047 uint32_t afSamplingRate;
Eric Laurent0d6db582014-11-12 18:39:44 -08001048 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
Eric Laurent57326622009-07-07 07:10:45 -07001049 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001050 }
Andy Hung26145642015-04-15 21:56:53 -07001051 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001052 const uint32_t effectiveSampleRate = adjustSampleRate(rate, mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001053 if (rate == 0 || effectiveSampleRate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001054 return BAD_VALUE;
1055 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001056 // TODO: Should we also check if the buffer size is compatible?
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001057
Glenn Kastene3aa6592012-12-04 12:22:46 -08001058 mSampleRate = rate;
Andy Hung26145642015-04-15 21:56:53 -07001059 mProxy->setSampleRate(effectiveSampleRate);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001060
Eric Laurent57326622009-07-07 07:10:45 -07001061 return NO_ERROR;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001062}
1063
Glenn Kastena5224f32012-01-04 12:41:44 -08001064uint32_t AudioTrack::getSampleRate() const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001065{
Eric Laurent1703cdf2011-03-07 14:52:59 -08001066 AutoMutex lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07001067
1068 // sample rate can be updated during playback by the offloaded decoder so we need to
1069 // query the HAL and update if needed.
1070// FIXME use Proxy return channel to update the rate from server and avoid polling here
Eric Laurentab5cdba2014-06-09 17:22:27 -07001071 if (isOffloadedOrDirect_l()) {
Glenn Kasten142f5192014-03-25 17:44:59 -07001072 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6f59db12013-07-26 17:16:50 -07001073 uint32_t sampleRate = 0;
Jean-Michel Trivib7f24b12014-06-11 10:05:30 -07001074 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
Eric Laurent6f59db12013-07-26 17:16:50 -07001075 if (status == NO_ERROR) {
1076 mSampleRate = sampleRate;
1077 }
1078 }
1079 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001080 return mSampleRate;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001081}
1082
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001083uint32_t AudioTrack::getOriginalSampleRate() const
1084{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001085 return mOriginalSampleRate;
1086}
1087
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001088status_t AudioTrack::setPlaybackRate(const AudioPlaybackRate &playbackRate)
Andy Hung8edb8dc2015-03-26 19:13:55 -07001089{
Andy Hung8edb8dc2015-03-26 19:13:55 -07001090 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001091 if (isAudioPlaybackRateEqual(playbackRate, mPlaybackRate)) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001092 return NO_ERROR;
1093 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001094 if (isOffloadedOrDirect_l()) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001095 return INVALID_OPERATION;
1096 }
1097 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1098 return INVALID_OPERATION;
1099 }
Andy Hungff874dc2016-04-11 16:49:09 -07001100
Andy Hungfb8ede22018-09-12 19:03:24 -07001101 ALOGV("%s(%d): mSampleRate:%u mSpeed:%f mPitch:%f",
Eric Laurent973db022018-11-20 14:54:31 -08001102 __func__, mPortId, mSampleRate, playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001103 // pitch is emulated by adjusting speed and sampleRate
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001104 const uint32_t effectiveRate = adjustSampleRate(mSampleRate, playbackRate.mPitch);
1105 const float effectiveSpeed = adjustSpeed(playbackRate.mSpeed, playbackRate.mPitch);
1106 const float effectivePitch = adjustPitch(playbackRate.mPitch);
Ricardo Garcia6c7f0622015-04-30 18:39:16 -07001107 AudioPlaybackRate playbackRateTemp = playbackRate;
1108 playbackRateTemp.mSpeed = effectiveSpeed;
1109 playbackRateTemp.mPitch = effectivePitch;
1110
Andy Hungfb8ede22018-09-12 19:03:24 -07001111 ALOGV("%s(%d) (effective) mSampleRate:%u mSpeed:%f mPitch:%f",
Eric Laurent973db022018-11-20 14:54:31 -08001112 __func__, mPortId, effectiveRate, effectiveSpeed, effectivePitch);
Andy Hungff874dc2016-04-11 16:49:09 -07001113
Ricardo Garcia6c7f0622015-04-30 18:39:16 -07001114 if (!isAudioPlaybackRateValid(playbackRateTemp)) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001115 ALOGW("%s(%d) (%f, %f) failed (effective rate out of bounds)",
Eric Laurent973db022018-11-20 14:54:31 -08001116 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001117 return BAD_VALUE;
1118 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001119 // Check if the buffer size is compatible.
Andy Hung26145642015-04-15 21:56:53 -07001120 if (!isSampleRateSpeedAllowed_l(effectiveRate, effectiveSpeed)) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001121 ALOGW("%s(%d) (%f, %f) failed (buffer size)",
Eric Laurent973db022018-11-20 14:54:31 -08001122 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
Andy Hung8edb8dc2015-03-26 19:13:55 -07001123 return BAD_VALUE;
1124 }
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001125
Ricardo Garcia6c7f0622015-04-30 18:39:16 -07001126 // Check resampler ratios are within bounds
Glenn Kastend3bb6452016-12-05 18:14:37 -08001127 if ((uint64_t)effectiveRate > (uint64_t)mSampleRate *
1128 (uint64_t)AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001129 ALOGW("%s(%d) (%f, %f) failed. Resample rate exceeds max accepted value",
Eric Laurent973db022018-11-20 14:54:31 -08001130 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
Ricardo Garcia6c7f0622015-04-30 18:39:16 -07001131 return BAD_VALUE;
1132 }
1133
Dan Austine34eae22015-10-27 16:14:52 -07001134 if ((uint64_t)effectiveRate * (uint64_t)AUDIO_RESAMPLER_UP_RATIO_MAX < (uint64_t)mSampleRate) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001135 ALOGW("%s(%d) (%f, %f) failed. Resample rate below min accepted value",
Eric Laurent973db022018-11-20 14:54:31 -08001136 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
Ricardo Garcia6c7f0622015-04-30 18:39:16 -07001137 return BAD_VALUE;
1138 }
1139 mPlaybackRate = playbackRate;
1140 //set effective rates
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001141 mProxy->setPlaybackRate(playbackRateTemp);
Andy Hung26145642015-04-15 21:56:53 -07001142 mProxy->setSampleRate(effectiveRate); // FIXME: not quite "atomic" with setPlaybackRate
Andy Hungb68f5eb2019-12-03 16:49:17 -08001143
1144 mediametrics::LogItem(mMetricsId)
1145 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETPLAYBACKPARAM)
1146 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
1147 .set(AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)mPlaybackRate.mSpeed)
1148 .set(AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)mPlaybackRate.mPitch)
1149 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1150 AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)effectiveRate)
1151 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1152 AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)playbackRateTemp.mSpeed)
1153 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1154 AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)playbackRateTemp.mPitch)
1155 .record();
1156
Andy Hung8edb8dc2015-03-26 19:13:55 -07001157 return NO_ERROR;
1158}
1159
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001160const AudioPlaybackRate& AudioTrack::getPlaybackRate() const
Andy Hung8edb8dc2015-03-26 19:13:55 -07001161{
1162 AutoMutex lock(mLock);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001163 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001164}
1165
Phil Burkc0adecb2016-01-08 12:44:11 -08001166ssize_t AudioTrack::getBufferSizeInFrames()
1167{
1168 AutoMutex lock(mLock);
1169 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1170 return NO_INIT;
1171 }
Phil Burka9876702020-04-20 18:16:15 -07001172
Phil Burke8972b02016-03-04 11:29:57 -08001173 return (ssize_t) mProxy->getBufferSizeInFrames();
Phil Burkc0adecb2016-01-08 12:44:11 -08001174}
1175
Andy Hungf2c87b32016-04-07 19:49:29 -07001176status_t AudioTrack::getBufferDurationInUs(int64_t *duration)
1177{
1178 if (duration == nullptr) {
1179 return BAD_VALUE;
1180 }
1181 AutoMutex lock(mLock);
1182 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1183 return NO_INIT;
1184 }
1185 ssize_t bufferSizeInFrames = (ssize_t) mProxy->getBufferSizeInFrames();
1186 if (bufferSizeInFrames < 0) {
1187 return (status_t)bufferSizeInFrames;
1188 }
1189 *duration = (int64_t)((double)bufferSizeInFrames * 1000000
1190 / ((double)mSampleRate * mPlaybackRate.mSpeed));
1191 return NO_ERROR;
1192}
1193
Phil Burkc0adecb2016-01-08 12:44:11 -08001194ssize_t AudioTrack::setBufferSizeInFrames(size_t bufferSizeInFrames)
1195{
1196 AutoMutex lock(mLock);
1197 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1198 return NO_INIT;
1199 }
1200 // Reject if timed track or compressed audio.
Glenn Kastend79072e2016-01-06 08:41:20 -08001201 if (!audio_is_linear_pcm(mFormat)) {
Phil Burkc0adecb2016-01-08 12:44:11 -08001202 return INVALID_OPERATION;
1203 }
Phil Burka9876702020-04-20 18:16:15 -07001204
1205 ssize_t originalBufferSize = mProxy->getBufferSizeInFrames();
1206 ssize_t finalBufferSize = mProxy->setBufferSizeInFrames((uint32_t) bufferSizeInFrames);
1207 if (originalBufferSize != finalBufferSize) {
Phil Burk64e16a72020-06-01 13:25:51 -07001208 android::mediametrics::LogItem(mMetricsId)
1209 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETBUFFERSIZE)
1210 .set(AMEDIAMETRICS_PROP_BUFFERSIZEFRAMES, (int32_t)mProxy->getBufferSizeInFrames())
1211 .set(AMEDIAMETRICS_PROP_UNDERRUN, (int32_t)getUnderrunCount_l())
1212 .record();
Phil Burka9876702020-04-20 18:16:15 -07001213 }
1214 return finalBufferSize;
Phil Burkc0adecb2016-01-08 12:44:11 -08001215}
1216
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001217status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
1218{
Glenn Kastend79072e2016-01-06 08:41:20 -08001219 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -08001220 return INVALID_OPERATION;
1221 }
1222
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001223 if (loopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001224 ;
1225 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
1226 loopEnd - loopStart >= MIN_LOOP) {
1227 ;
1228 } else {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001229 return BAD_VALUE;
1230 }
1231
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001232 AutoMutex lock(mLock);
1233 // See setPosition() regarding setting parameters such as loop points or position while active
1234 if (mState == STATE_ACTIVE) {
1235 return INVALID_OPERATION;
Eric Laurentc2f1f072009-07-17 12:17:14 -07001236 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001237 setLoop_l(loopStart, loopEnd, loopCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001238 return NO_ERROR;
1239}
1240
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001241void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
1242{
Andy Hung4ede21d2014-12-12 15:37:34 -08001243 // We do not update the periodic notification point.
1244 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
1245 mLoopCount = loopCount;
1246 mLoopEnd = loopEnd;
1247 mLoopStart = loopStart;
Andy Hung53c3b5f2014-12-15 16:42:05 -08001248 mLoopCountNotified = loopCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001249 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
Andy Hung3c09c782014-12-29 18:39:32 -08001250
1251 // Waking the AudioTrackThread is not needed as this cannot be called when active.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001252}
1253
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001254status_t AudioTrack::setMarkerPosition(uint32_t marker)
1255{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001256 // The only purpose of setting marker position is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -07001257 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001258 return INVALID_OPERATION;
1259 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001260
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001261 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001262 mMarkerPosition = marker;
Jean-Michel Trivi2c22aeb2009-03-24 18:11:07 -07001263 mMarkerReached = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001264
Andy Hung3c09c782014-12-29 18:39:32 -08001265 sp<AudioTrackThread> t = mAudioTrackThread;
1266 if (t != 0) {
1267 t->wake();
1268 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001269 return NO_ERROR;
1270}
1271
Glenn Kastena5224f32012-01-04 12:41:44 -08001272status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001273{
Eric Laurentab5cdba2014-06-09 17:22:27 -07001274 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001275 return INVALID_OPERATION;
1276 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001277 if (marker == NULL) {
1278 return BAD_VALUE;
1279 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001280
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001281 AutoMutex lock(mLock);
Andy Hung90e8a972015-11-09 16:42:40 -08001282 mMarkerPosition.getValue(marker);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001283
1284 return NO_ERROR;
1285}
1286
1287status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
1288{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001289 // The only purpose of setting position update period is to get a callback
Eric Laurentab5cdba2014-06-09 17:22:27 -07001290 if (mCbf == NULL || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001291 return INVALID_OPERATION;
1292 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001293
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001294 AutoMutex lock(mLock);
Glenn Kasten200092b2014-08-15 15:13:30 -07001295 mNewPosition = updateAndGetPosition_l() + updatePeriod;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001296 mUpdatePeriod = updatePeriod;
Glenn Kasten2b2165c2014-01-13 08:53:36 -08001297
Andy Hung3c09c782014-12-29 18:39:32 -08001298 sp<AudioTrackThread> t = mAudioTrackThread;
1299 if (t != 0) {
1300 t->wake();
1301 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001302 return NO_ERROR;
1303}
1304
Glenn Kastena5224f32012-01-04 12:41:44 -08001305status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001306{
Eric Laurentab5cdba2014-06-09 17:22:27 -07001307 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001308 return INVALID_OPERATION;
1309 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07001310 if (updatePeriod == NULL) {
1311 return BAD_VALUE;
1312 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001313
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001314 AutoMutex lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001315 *updatePeriod = mUpdatePeriod;
1316
1317 return NO_ERROR;
1318}
1319
1320status_t AudioTrack::setPosition(uint32_t position)
1321{
Glenn Kastend79072e2016-01-06 08:41:20 -08001322 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001323 return INVALID_OPERATION;
1324 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001325 if (position > mFrameCount) {
1326 return BAD_VALUE;
1327 }
John Grossman4ff14ba2012-02-08 16:37:41 -08001328
Eric Laurent1703cdf2011-03-07 14:52:59 -08001329 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001330 // Currently we require that the player is inactive before setting parameters such as position
1331 // or loop points. Otherwise, there could be a race condition: the application could read the
1332 // current position, compute a new position or loop parameters, and then set that position or
1333 // loop parameters but it would do the "wrong" thing since the position has continued to advance
1334 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
1335 // to specify how it wants to handle such scenarios.
1336 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001337 return INVALID_OPERATION;
1338 }
Andy Hung9b461582014-12-01 17:56:29 -08001339 // After setting the position, use full update period before notification.
Glenn Kasten200092b2014-08-15 15:13:30 -07001340 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -08001341 mStaticProxy->setBufferPosition(position);
Andy Hung3c09c782014-12-29 18:39:32 -08001342
1343 // Waking the AudioTrackThread is not needed as this cannot be called when active.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001344 return NO_ERROR;
1345}
1346
Glenn Kasten200092b2014-08-15 15:13:30 -07001347status_t AudioTrack::getPosition(uint32_t *position)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001348{
Glenn Kastend65d73c2012-06-22 17:21:07 -07001349 if (position == NULL) {
1350 return BAD_VALUE;
1351 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001352
Eric Laurent1703cdf2011-03-07 14:52:59 -08001353 AutoMutex lock(mLock);
Andy Hung7a490e72016-03-23 15:58:10 -07001354 // FIXME: offloaded and direct tracks call into the HAL for render positions
1355 // for compressed/synced data; however, we use proxy position for pure linear pcm data
1356 // as we do not know the capability of the HAL for pcm position support and standby.
1357 // There may be some latency differences between the HAL position and the proxy position.
1358 if (isOffloadedOrDirect_l() && !isPurePcmData_l()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001359 uint32_t dspFrames = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001360
Eric Laurentab5cdba2014-06-09 17:22:27 -07001361 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001362 ALOGV("%s(%d): called in paused state, return cached position %u",
Eric Laurent973db022018-11-20 14:54:31 -08001363 __func__, mPortId, mPausedPosition);
Haynes Mathew George7064fd22014-01-08 13:59:53 -08001364 *position = mPausedPosition;
1365 return NO_ERROR;
1366 }
1367
Glenn Kasten142f5192014-03-25 17:44:59 -07001368 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Andy Hung1f1db832015-06-08 13:26:10 -07001369 uint32_t halFrames; // actually unused
1370 (void) AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
1371 // FIXME: on getRenderPosition() error, we return OK with frame position 0.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001372 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07001373 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
1374 // due to hardware latency. We leave this behavior for now.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001375 *position = dspFrames;
1376 } else {
Eric Laurent275e8e92014-11-30 15:14:47 -08001377 if (mCblk->mFlags & CBLK_INVALID) {
Andy Hung1f1db832015-06-08 13:26:10 -07001378 (void) restoreTrack_l("getPosition");
1379 // FIXME: for compatibility with the Java API we ignore the restoreTrack_l()
1380 // error here (e.g. DEAD_OBJECT) and return OK with the last recorded server position.
Eric Laurent275e8e92014-11-30 15:14:47 -08001381 }
1382
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001383 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
Glenn Kasten200092b2014-08-15 15:13:30 -07001384 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
Andy Hung90e8a972015-11-09 16:42:40 -08001385 0 : updateAndGetPosition_l().value();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001386 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001387 return NO_ERROR;
1388}
1389
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001390status_t AudioTrack::getBufferPosition(uint32_t *position)
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001391{
Glenn Kastend79072e2016-01-06 08:41:20 -08001392 if (mSharedBuffer == 0) {
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001393 return INVALID_OPERATION;
1394 }
1395 if (position == NULL) {
1396 return BAD_VALUE;
1397 }
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001398
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001399 AutoMutex lock(mLock);
1400 *position = mStaticProxy->getBufferPosition();
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001401 return NO_ERROR;
1402}
Glenn Kasten9c6745f2012-11-30 13:35:29 -08001403
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001404status_t AudioTrack::reload()
1405{
Glenn Kastend79072e2016-01-06 08:41:20 -08001406 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
Glenn Kasten083d1c12012-11-30 15:00:36 -08001407 return INVALID_OPERATION;
1408 }
1409
Eric Laurent1703cdf2011-03-07 14:52:59 -08001410 AutoMutex lock(mLock);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001411 // See setPosition() regarding setting parameters such as loop points or position while active
1412 if (mState == STATE_ACTIVE) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001413 return INVALID_OPERATION;
1414 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001415 mNewPosition = mUpdatePeriod;
Andy Hung9b461582014-12-01 17:56:29 -08001416 (void) updateAndGetPosition_l();
1417 mPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -07001418 mPreviousTimestampValid = false;
Andy Hung53c3b5f2014-12-15 16:42:05 -08001419#if 0
Andy Hung9b461582014-12-01 17:56:29 -08001420 // The documentation is not clear on the behavior of reload() and the restoration
Andy Hung53c3b5f2014-12-15 16:42:05 -08001421 // of loop count. Historically we have not restored loop count, start, end,
1422 // but it makes sense if one desires to repeat playing a particular sound.
1423 if (mLoopCount != 0) {
1424 mLoopCountNotified = mLoopCount;
1425 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
1426 }
1427#endif
Andy Hung9b461582014-12-01 17:56:29 -08001428 mStaticProxy->setBufferPosition(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001429 return NO_ERROR;
1430}
1431
Glenn Kasten38e905b2014-01-13 10:21:48 -08001432audio_io_handle_t AudioTrack::getOutput() const
Eric Laurentc2f1f072009-07-17 12:17:14 -07001433{
Eric Laurent1703cdf2011-03-07 14:52:59 -08001434 AutoMutex lock(mLock);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001435 return mOutput;
Eric Laurent1703cdf2011-03-07 14:52:59 -08001436}
1437
Paul McLeanaa981192015-03-21 09:55:15 -07001438status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
1439 AutoMutex lock(mLock);
1440 if (mSelectedDeviceId != deviceId) {
1441 mSelectedDeviceId = deviceId;
Eric Laurentfb00fc72017-05-25 18:17:12 -07001442 if (mStatus == NO_ERROR) {
1443 android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
jiabin156c6872017-10-06 09:47:15 -07001444 mProxy->interrupt();
Eric Laurentfb00fc72017-05-25 18:17:12 -07001445 }
Paul McLeanaa981192015-03-21 09:55:15 -07001446 }
Eric Laurent493404d2015-04-21 15:07:36 -07001447 return NO_ERROR;
Paul McLeanaa981192015-03-21 09:55:15 -07001448}
1449
1450audio_port_handle_t AudioTrack::getOutputDevice() {
1451 AutoMutex lock(mLock);
1452 return mSelectedDeviceId;
1453}
1454
Eric Laurentad2e7b92017-09-14 20:06:42 -07001455// must be called with mLock held
1456void AudioTrack::updateRoutedDeviceId_l()
1457{
1458 // if the track is inactive, do not update actual device as the output stream maybe routed
1459 // to a device not relevant to this client because of other active use cases.
1460 if (mState != STATE_ACTIVE) {
1461 return;
1462 }
1463 if (mOutput != AUDIO_IO_HANDLE_NONE) {
1464 audio_port_handle_t deviceId = AudioSystem::getDeviceIdForIo(mOutput);
1465 if (deviceId != AUDIO_PORT_HANDLE_NONE) {
1466 mRoutedDeviceId = deviceId;
1467 }
1468 }
1469}
1470
Eric Laurent296fb132015-05-01 11:38:42 -07001471audio_port_handle_t AudioTrack::getRoutedDeviceId() {
1472 AutoMutex lock(mLock);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001473 updateRoutedDeviceId_l();
1474 return mRoutedDeviceId;
Eric Laurent296fb132015-05-01 11:38:42 -07001475}
1476
Eric Laurentbe916aa2010-06-01 23:49:17 -07001477status_t AudioTrack::attachAuxEffect(int effectId)
1478{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001479 AutoMutex lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001480 status_t status = mAudioTrack->attachAuxEffect(effectId);
1481 if (status == NO_ERROR) {
1482 mAuxEffectId = effectId;
1483 }
1484 return status;
Eric Laurentbe916aa2010-06-01 23:49:17 -07001485}
1486
Eric Laurente83b55d2014-11-14 10:06:21 -08001487audio_stream_type_t AudioTrack::streamType() const
1488{
1489 if (mStreamType == AUDIO_STREAM_DEFAULT) {
François Gaffie58d4be52018-11-06 15:30:12 +01001490 return AudioSystem::attributesToStreamType(mAttributes);
Eric Laurente83b55d2014-11-14 10:06:21 -08001491 }
1492 return mStreamType;
1493}
1494
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001495uint32_t AudioTrack::latency()
1496{
1497 AutoMutex lock(mLock);
1498 updateLatency_l();
1499 return mLatency;
1500}
1501
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001502// -------------------------------------------------------------------------
1503
Eric Laurent1703cdf2011-03-07 14:52:59 -08001504// must be called with mLock held
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001505void AudioTrack::updateLatency_l()
1506{
1507 status_t status = AudioSystem::getLatency(mOutput, &mAfLatency);
1508 if (status != NO_ERROR) {
Eric Laurent973db022018-11-20 14:54:31 -08001509 ALOGW("%s(%d): getLatency(%d) failed status %d", __func__, mPortId, mOutput, status);
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001510 } else {
1511 // FIXME don't believe this lie
Andy Hung13969262017-09-11 17:24:21 -07001512 mLatency = mAfLatency + (1000LL * mFrameCount) / mSampleRate;
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07001513 }
1514}
1515
Phil Burkadbb75a2017-06-16 12:19:42 -07001516// TODO Move this macro to a common header file for enum to string conversion in audio framework.
1517#define MEDIA_CASE_ENUM(name) case name: return #name
1518const char * AudioTrack::convertTransferToText(transfer_type transferType) {
1519 switch (transferType) {
1520 MEDIA_CASE_ENUM(TRANSFER_DEFAULT);
1521 MEDIA_CASE_ENUM(TRANSFER_CALLBACK);
1522 MEDIA_CASE_ENUM(TRANSFER_OBTAIN);
1523 MEDIA_CASE_ENUM(TRANSFER_SYNC);
1524 MEDIA_CASE_ENUM(TRANSFER_SHARED);
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07001525 MEDIA_CASE_ENUM(TRANSFER_SYNC_NOTIF_CALLBACK);
Phil Burkadbb75a2017-06-16 12:19:42 -07001526 default:
1527 return "UNRECOGNIZED";
1528 }
1529}
1530
Glenn Kasten200092b2014-08-15 15:13:30 -07001531status_t AudioTrack::createTrack_l()
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001532{
Eric Laurentf32d7812017-11-30 14:44:07 -08001533 status_t status;
1534 bool callbackAdded = false;
1535
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001536 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
1537 if (audioFlinger == 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001538 ALOGE("%s(%d): Could not get audioflinger",
Eric Laurent973db022018-11-20 14:54:31 -08001539 __func__, mPortId);
Eric Laurentf32d7812017-11-30 14:44:07 -08001540 status = NO_INIT;
1541 goto exit;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001542 }
1543
Eric Laurent21da6472017-11-09 16:29:26 -08001544 {
Haynes Mathew Georgeae34ed22016-01-28 11:58:39 -08001545 // mFlags (not mOrigFlags) is modified depending on whether fast request is accepted.
1546 // After fast request is denied, we will request again if IAudioTrack is re-created.
Glenn Kastend79072e2016-01-06 08:41:20 -08001547 // Client can only express a preference for FAST. Server will perform additional tests.
Phil Burk33ff89b2015-11-30 11:16:01 -08001548 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Phil Burkadbb75a2017-06-16 12:19:42 -07001549 // either of these use cases:
1550 // use case 1: shared buffer
1551 bool sharedBuffer = mSharedBuffer != 0;
1552 bool transferAllowed =
Glenn Kastenc6ba8232014-02-27 13:34:29 -08001553 // use case 2: callback transfer mode
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001554 (mTransfer == TRANSFER_CALLBACK) ||
1555 // use case 3: obtain/release mode
Phil Burk33ff89b2015-11-30 11:16:01 -08001556 (mTransfer == TRANSFER_OBTAIN) ||
1557 // use case 4: synchronous write
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07001558 ((mTransfer == TRANSFER_SYNC || mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK)
1559 && mThreadCanCallJava);
Phil Burkadbb75a2017-06-16 12:19:42 -07001560
Eric Laurent21da6472017-11-09 16:29:26 -08001561 bool fastAllowed = sharedBuffer || transferAllowed;
1562 if (!fastAllowed) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001563 ALOGW("%s(%d): AUDIO_OUTPUT_FLAG_FAST denied by client,"
1564 " not shared buffer and transfer = %s",
Eric Laurent973db022018-11-20 14:54:31 -08001565 __func__, mPortId,
Phil Burkadbb75a2017-06-16 12:19:42 -07001566 convertTransferToText(mTransfer));
Phil Burk33ff89b2015-11-30 11:16:01 -08001567 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1568 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001569 }
1570
Eric Laurent21da6472017-11-09 16:29:26 -08001571 IAudioFlinger::CreateTrackInput input;
1572 if (mStreamType != AUDIO_STREAM_DEFAULT) {
François Gaffie58d4be52018-11-06 15:30:12 +01001573 input.attr = AudioSystem::streamTypeToAttributes(mStreamType);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001574 } else {
Eric Laurent21da6472017-11-09 16:29:26 -08001575 input.attr = mAttributes;
Eric Laurentd1b449a2010-05-14 03:26:45 -07001576 }
Eric Laurent21da6472017-11-09 16:29:26 -08001577 input.config = AUDIO_CONFIG_INITIALIZER;
1578 input.config.sample_rate = mSampleRate;
1579 input.config.channel_mask = mChannelMask;
1580 input.config.format = mFormat;
1581 input.config.offload_info = mOffloadInfoCopy;
1582 input.clientInfo.clientUid = mClientUid;
1583 input.clientInfo.clientPid = mClientPid;
1584 input.clientInfo.clientTid = -1;
Glenn Kasten363fb752014-01-15 12:27:31 -08001585 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Glenn Kasten47d55172017-05-23 11:19:30 -07001586 // It is currently meaningless to request SCHED_FIFO for a Java thread. Even if the
1587 // application-level code follows all non-blocking design rules, the language runtime
1588 // doesn't also follow those rules, so the thread will not benefit overall.
Phil Burk33ff89b2015-11-30 11:16:01 -08001589 if (mAudioTrackThread != 0 && !mThreadCanCallJava) {
Eric Laurent21da6472017-11-09 16:29:26 -08001590 input.clientInfo.clientTid = mAudioTrackThread->getTid();
Glenn Kasten3acbd052012-02-28 10:39:56 -08001591 }
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001592 }
Eric Laurent21da6472017-11-09 16:29:26 -08001593 input.sharedBuffer = mSharedBuffer;
1594 input.notificationsPerBuffer = mNotificationsPerBufferReq;
1595 input.speed = 1.0;
1596 if (audio_has_proportional_frames(mFormat) && mSharedBuffer == 0 &&
1597 (mFlags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1598 input.speed = !isPurePcmData_l() || isOffloadedOrDirect_l() ? 1.0f :
1599 max(mMaxRequiredSpeed, mPlaybackRate.mSpeed);
1600 }
1601 input.flags = mFlags;
1602 input.frameCount = mReqFrameCount;
1603 input.notificationFrameCount = mNotificationFramesReq;
1604 input.selectedDeviceId = mSelectedDeviceId;
1605 input.sessionId = mSessionId;
jiabinf6eb4c32020-02-25 14:06:25 -08001606 input.audioTrackCallback = mAudioTrackCallback;
Colin Crossb8a9dbb2020-08-27 04:12:26 +00001607 input.opPackageName = mOpPackageName;
Glenn Kasten4a4a0952012-03-19 11:38:14 -07001608
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08001609 media::CreateTrackResponse response;
1610 sp<IAudioTrack> track = audioFlinger->createTrack(VALUE_OR_FATAL(input.toAidl()),
1611 response,
Eric Laurent21da6472017-11-09 16:29:26 -08001612 &status);
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08001613 IAudioFlinger::CreateTrackOutput output = VALUE_OR_FATAL(
1614 IAudioFlinger::CreateTrackOutput::fromAidl(
1615 response));
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001616
Eric Laurent21da6472017-11-09 16:29:26 -08001617 if (status != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001618 ALOGE("%s(%d): AudioFlinger could not create track, status: %d output %d",
Eric Laurent973db022018-11-20 14:54:31 -08001619 __func__, mPortId, status, output.outputId);
Eric Laurentf32d7812017-11-30 14:44:07 -08001620 if (status == NO_ERROR) {
1621 status = NO_INIT;
1622 }
1623 goto exit;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001624 }
Glenn Kastenc08d20b2014-02-24 15:21:10 -08001625 ALOG_ASSERT(track != 0);
1626
Eric Laurent21da6472017-11-09 16:29:26 -08001627 mFrameCount = output.frameCount;
1628 mNotificationFramesAct = (uint32_t)output.notificationFrameCount;
1629 mRoutedDeviceId = output.selectedDeviceId;
1630 mSessionId = output.sessionId;
1631
1632 mSampleRate = output.sampleRate;
1633 if (mOriginalSampleRate == 0) {
1634 mOriginalSampleRate = mSampleRate;
1635 }
1636
1637 mAfFrameCount = output.afFrameCount;
1638 mAfSampleRate = output.afSampleRate;
1639 mAfLatency = output.afLatencyMs;
1640
1641 mLatency = mAfLatency + (1000LL * mFrameCount) / mSampleRate;
1642
Glenn Kasten38e905b2014-01-13 10:21:48 -08001643 // AudioFlinger now owns the reference to the I/O handle,
1644 // so we are no longer responsible for releasing it.
1645
Glenn Kasten7fd04222016-02-02 12:38:16 -08001646 // FIXME compare to AudioRecord
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001647 sp<IMemory> iMem = track->getCblk();
1648 if (iMem == 0) {
Eric Laurent973db022018-11-20 14:54:31 -08001649 ALOGE("%s(%d): Could not get control block", __func__, mPortId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001650 status = NO_INIT;
Eric Laurentf32d7812017-11-30 14:44:07 -08001651 goto exit;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001652 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07001653 // TODO: Using unsecurePointer() has some associated security pitfalls
1654 // (see declaration for details).
1655 // Either document why it is safe in this case or address the
1656 // issue (e.g. by copying).
1657 void *iMemPointer = iMem->unsecurePointer();
Glenn Kasten0cde0762014-01-16 15:06:36 -08001658 if (iMemPointer == NULL) {
Eric Laurent973db022018-11-20 14:54:31 -08001659 ALOGE("%s(%d): Could not get control block pointer", __func__, mPortId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001660 status = NO_INIT;
Eric Laurentf32d7812017-11-30 14:44:07 -08001661 goto exit;
Glenn Kasten0cde0762014-01-16 15:06:36 -08001662 }
Glenn Kasten53cec222013-08-29 09:01:02 -07001663 // invariant that mAudioTrack != 0 is true only after set() returns successfully
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001664 if (mAudioTrack != 0) {
Marco Nelissenf8880202014-11-14 07:58:25 -08001665 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001666 mDeathNotifier.clear();
1667 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001668 mAudioTrack = track;
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001669 mCblkMemory = iMem;
Eric Laurent3bcffa12014-06-12 18:38:45 -07001670 IPCThreadState::self()->flushCommands();
1671
Glenn Kasten0cde0762014-01-16 15:06:36 -08001672 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
Glenn Kastend2c38fc2012-11-01 14:58:02 -07001673 mCblk = cblk;
Glenn Kasten5f631512014-02-24 15:16:07 -08001674
Glenn Kastena07f17c2013-04-23 12:39:37 -07001675 mAwaitBoost = false;
Glenn Kasten363fb752014-01-15 12:27:31 -08001676 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent21da6472017-11-09 16:29:26 -08001677 if (output.flags & AUDIO_OUTPUT_FLAG_FAST) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001678 ALOGI("%s(%d): AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu -> %zu",
Eric Laurent973db022018-11-20 14:54:31 -08001679 __func__, mPortId, mReqFrameCount, mFrameCount);
Phil Burk33ff89b2015-11-30 11:16:01 -08001680 if (!mThreadCanCallJava) {
1681 mAwaitBoost = true;
1682 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001683 } else {
Phil Burkcc6ed2d2020-05-18 13:06:54 -07001684 ALOGD("%s(%d): AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu -> %zu",
Eric Laurent973db022018-11-20 14:54:31 -08001685 __func__, mPortId, mReqFrameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001686 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001687 }
Eric Laurent21da6472017-11-09 16:29:26 -08001688 mFlags = output.flags;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001689
Eric Laurentad2e7b92017-09-14 20:06:42 -07001690 //mOutput != output includes the case where mOutput == AUDIO_IO_HANDLE_NONE for first creation
Eric Laurent09f1ed22019-04-24 17:45:17 -07001691 if (mDeviceCallback != 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001692 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent09f1ed22019-04-24 17:45:17 -07001693 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001694 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07001695 AudioSystem::addAudioDeviceCallback(this, output.outputId, output.portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001696 callbackAdded = true;
1697 }
1698
Eric Laurent09f1ed22019-04-24 17:45:17 -07001699 mPortId = output.portId;
Glenn Kasten38e905b2014-01-13 10:21:48 -08001700 // We retain a copy of the I/O handle, but don't own the reference
Eric Laurent21da6472017-11-09 16:29:26 -08001701 mOutput = output.outputId;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001702 mRefreshRemaining = true;
1703
1704 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1705 // is the value of pointer() for the shared buffer, otherwise buffers points
1706 // immediately after the control block. This address is for the mapping within client
1707 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1708 void* buffers;
Glenn Kasten363fb752014-01-15 12:27:31 -08001709 if (mSharedBuffer == 0) {
Glenn Kasten138d6f92015-03-20 10:54:51 -07001710 buffers = cblk + 1;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001711 } else {
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07001712 // TODO: Using unsecurePointer() has some associated security pitfalls
1713 // (see declaration for details).
1714 // Either document why it is safe in this case or address the
1715 // issue (e.g. by copying).
1716 buffers = mSharedBuffer->unsecurePointer();
Glenn Kasten138d6f92015-03-20 10:54:51 -07001717 if (buffers == NULL) {
Eric Laurent973db022018-11-20 14:54:31 -08001718 ALOGE("%s(%d): Could not get buffer pointer", __func__, mPortId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001719 status = NO_INIT;
Eric Laurentf32d7812017-11-30 14:44:07 -08001720 goto exit;
Glenn Kasten138d6f92015-03-20 10:54:51 -07001721 }
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001722 }
1723
Eric Laurent2beeb502010-07-16 07:43:46 -07001724 mAudioTrack->attachAuxEffect(mAuxEffectId);
Glenn Kasten5f631512014-02-24 15:16:07 -08001725
Glenn Kasten093000f2012-05-03 09:35:36 -07001726 // If IAudioTrack is re-created, don't let the requested frameCount
1727 // decrease. This can confuse clients that cache frameCount().
Eric Laurent21da6472017-11-09 16:29:26 -08001728 if (mFrameCount > mReqFrameCount) {
1729 mReqFrameCount = mFrameCount;
Glenn Kasten093000f2012-05-03 09:35:36 -07001730 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001731
Andy Hungd7bd69e2015-07-24 07:52:41 -07001732 // reset server position to 0 as we have new cblk.
1733 mServer = 0;
1734
Glenn Kastene3aa6592012-12-04 12:22:46 -08001735 // update proxy
Glenn Kasten363fb752014-01-15 12:27:31 -08001736 if (mSharedBuffer == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001737 mStaticProxy.clear();
Eric Laurent21da6472017-11-09 16:29:26 -08001738 mProxy = new AudioTrackClientProxy(cblk, buffers, mFrameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001739 } else {
Eric Laurent21da6472017-11-09 16:29:26 -08001740 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, mFrameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001741 mProxy = mStaticProxy;
1742 }
seunghak.hane6a9d6582014-11-22 15:22:35 +09001743
1744 mProxy->setVolumeLR(gain_minifloat_pack(
1745 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1746 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1747
Glenn Kastene3aa6592012-12-04 12:22:46 -08001748 mProxy->setSendLevel(mSendLevel);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001749 const uint32_t effectiveSampleRate = adjustSampleRate(mSampleRate, mPlaybackRate.mPitch);
1750 const float effectiveSpeed = adjustSpeed(mPlaybackRate.mSpeed, mPlaybackRate.mPitch);
1751 const float effectivePitch = adjustPitch(mPlaybackRate.mPitch);
Andy Hung26145642015-04-15 21:56:53 -07001752 mProxy->setSampleRate(effectiveSampleRate);
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001753
1754 AudioPlaybackRate playbackRateTemp = mPlaybackRate;
1755 playbackRateTemp.mSpeed = effectiveSpeed;
1756 playbackRateTemp.mPitch = effectivePitch;
1757 mProxy->setPlaybackRate(playbackRateTemp);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001758 mProxy->setMinimum(mNotificationFramesAct);
1759
1760 mDeathNotifier = new DeathNotifier(this);
Marco Nelissenf8880202014-11-14 07:58:25 -08001761 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001762
Andy Hungb68f5eb2019-12-03 16:49:17 -08001763 // This is the first log sent from the AudioTrack client.
1764 // The creation of the audio track by AudioFlinger (in the code above)
1765 // is the first log of the AudioTrack and must be present before
1766 // any AudioTrack client logs will be accepted.
Andy Hungea840382020-05-05 21:50:17 -07001767
Andy Hungb68f5eb2019-12-03 16:49:17 -08001768 mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_TRACK) + std::to_string(mPortId);
1769 mediametrics::LogItem(mMetricsId)
1770 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CREATE)
1771 // the following are immutable
Andy Hunga629bd12020-06-05 16:03:53 -07001772 .set(AMEDIAMETRICS_PROP_FLAGS, toString(mFlags).c_str())
1773 .set(AMEDIAMETRICS_PROP_ORIGINALFLAGS, toString(mOrigFlags).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08001774 .set(AMEDIAMETRICS_PROP_SESSIONID, (int32_t)mSessionId)
1775 .set(AMEDIAMETRICS_PROP_TRACKID, mPortId) // dup from key
Andy Hungb68f5eb2019-12-03 16:49:17 -08001776 .set(AMEDIAMETRICS_PROP_CONTENTTYPE, toString(mAttributes.content_type).c_str())
1777 .set(AMEDIAMETRICS_PROP_USAGE, toString(mAttributes.usage).c_str())
1778 .set(AMEDIAMETRICS_PROP_THREADID, (int32_t)output.outputId)
1779 .set(AMEDIAMETRICS_PROP_SELECTEDDEVICEID, (int32_t)mSelectedDeviceId)
1780 .set(AMEDIAMETRICS_PROP_ROUTEDDEVICEID, (int32_t)mRoutedDeviceId)
1781 .set(AMEDIAMETRICS_PROP_ENCODING, toString(mFormat).c_str())
1782 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
1783 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
1784 // the following are NOT immutable
1785 .set(AMEDIAMETRICS_PROP_VOLUME_LEFT, (double)mVolume[AUDIO_INTERLEAVE_LEFT])
1786 .set(AMEDIAMETRICS_PROP_VOLUME_RIGHT, (double)mVolume[AUDIO_INTERLEAVE_RIGHT])
1787 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
1788 .set(AMEDIAMETRICS_PROP_AUXEFFECTID, (int32_t)mAuxEffectId)
1789 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
1790 .set(AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)mPlaybackRate.mSpeed)
1791 .set(AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)mPlaybackRate.mPitch)
1792 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1793 AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)effectiveSampleRate)
1794 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1795 AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)effectiveSpeed)
1796 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1797 AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)effectivePitch)
1798 .record();
1799
1800 // mSendLevel
1801 // mReqFrameCount?
1802 // mNotificationFramesAct, mNotificationFramesReq, mNotificationsPerBufferReq
1803 // mLatency, mAfLatency, mAfFrameCount, mAfSampleRate
1804
Glenn Kasten38e905b2014-01-13 10:21:48 -08001805 }
1806
Eric Laurentf32d7812017-11-30 14:44:07 -08001807exit:
1808 if (status != NO_ERROR && callbackAdded) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001809 // note: mOutput is always valid is callbackAdded is true
Eric Laurent09f1ed22019-04-24 17:45:17 -07001810 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001811 }
Eric Laurentf32d7812017-11-30 14:44:07 -08001812
1813 mStatus = status;
Eric Laurent21da6472017-11-09 16:29:26 -08001814
1815 // sp<IAudioTrack> track destructor will cause releaseOutput() to be called by AudioFlinger
Glenn Kasten38e905b2014-01-13 10:21:48 -08001816 return status;
Eric Laurent34f1d8e2009-11-04 08:27:26 -08001817}
1818
Glenn Kastenb46f3942015-03-09 12:00:30 -07001819status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001820{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001821 if (audioBuffer == NULL) {
Glenn Kasten551b5352015-03-20 11:30:28 -07001822 if (nonContig != NULL) {
1823 *nonContig = 0;
1824 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001825 return BAD_VALUE;
Eric Laurent9b7d9502011-03-21 11:49:00 -07001826 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001827 if (mTransfer != TRANSFER_OBTAIN) {
1828 audioBuffer->frameCount = 0;
1829 audioBuffer->size = 0;
1830 audioBuffer->raw = NULL;
Glenn Kasten551b5352015-03-20 11:30:28 -07001831 if (nonContig != NULL) {
1832 *nonContig = 0;
1833 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001834 return INVALID_OPERATION;
1835 }
Eric Laurent9b7d9502011-03-21 11:49:00 -07001836
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001837 const struct timespec *requested;
Eric Laurentdf576992014-01-27 18:13:39 -08001838 struct timespec timeout;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001839 if (waitCount == -1) {
1840 requested = &ClientProxy::kForever;
1841 } else if (waitCount == 0) {
1842 requested = &ClientProxy::kNonBlocking;
1843 } else if (waitCount > 0) {
Chih-Hung Hsiehbca74292018-08-10 16:06:07 -07001844 time_t ms = WAIT_PERIOD_MS * (time_t) waitCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001845 timeout.tv_sec = ms / 1000;
Andy Hung06a730b2020-04-09 13:28:31 -07001846 timeout.tv_nsec = (ms % 1000) * 1000000;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001847 requested = &timeout;
1848 } else {
Eric Laurent973db022018-11-20 14:54:31 -08001849 ALOGE("%s(%d): invalid waitCount %d", __func__, mPortId, waitCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001850 requested = NULL;
1851 }
Glenn Kastenb46f3942015-03-09 12:00:30 -07001852 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001853}
Eric Laurent1703cdf2011-03-07 14:52:59 -08001854
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001855status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1856 struct timespec *elapsed, size_t *nonContig)
1857{
1858 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1859 uint32_t oldSequence = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001860
1861 Proxy::Buffer buffer;
1862 status_t status = NO_ERROR;
1863
1864 static const int32_t kMaxTries = 5;
1865 int32_t tryCounter = kMaxTries;
1866
1867 do {
1868 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1869 // keep them from going away if another thread re-creates the track during obtainBuffer()
1870 sp<AudioTrackClientProxy> proxy;
1871 sp<IMemory> iMem;
1872
1873 { // start of lock scope
1874 AutoMutex lock(mLock);
1875
Glenn Kasten305996c2020-01-27 08:03:37 -08001876 uint32_t newSequence = mSequence;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001877 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1878 if (status == DEAD_OBJECT) {
1879 // re-create track, unless someone else has already done so
1880 if (newSequence == oldSequence) {
1881 status = restoreTrack_l("obtainBuffer");
1882 if (status != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001883 buffer.mFrameCount = 0;
1884 buffer.mRaw = NULL;
1885 buffer.mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001886 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001887 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001888 }
1889 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001890 oldSequence = newSequence;
1891
Eric Laurent4d231dc2016-03-11 18:38:23 -08001892 if (status == NOT_ENOUGH_DATA) {
1893 restartIfDisabled();
1894 }
1895
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001896 // Keep the extra references
1897 proxy = mProxy;
1898 iMem = mCblkMemory;
1899
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01001900 if (mState == STATE_STOPPING) {
1901 status = -EINTR;
1902 buffer.mFrameCount = 0;
1903 buffer.mRaw = NULL;
1904 buffer.mNonContig = 0;
1905 break;
1906 }
1907
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001908 // Non-blocking if track is stopped or paused
1909 if (mState != STATE_ACTIVE) {
1910 requested = &ClientProxy::kNonBlocking;
1911 }
1912
1913 } // end of lock scope
1914
1915 buffer.mFrameCount = audioBuffer->frameCount;
1916 // FIXME starts the requested timeout and elapsed over from scratch
1917 status = proxy->obtainBuffer(&buffer, requested, elapsed);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001918 } while (((status == DEAD_OBJECT) || (status == NOT_ENOUGH_DATA)) && (tryCounter-- > 0));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001919
1920 audioBuffer->frameCount = buffer.mFrameCount;
Andy Hungabdb9902015-01-12 15:08:22 -08001921 audioBuffer->size = buffer.mFrameCount * mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001922 audioBuffer->raw = buffer.mRaw;
Glenn Kasten305996c2020-01-27 08:03:37 -08001923 audioBuffer->sequence = oldSequence;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001924 if (nonContig != NULL) {
1925 *nonContig = buffer.mNonContig;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001926 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001927 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001928}
1929
Glenn Kasten54a8a452015-03-09 12:03:00 -07001930void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001931{
Glenn Kasten3f02be22015-03-09 11:59:04 -07001932 // FIXME add error checking on mode, by adding an internal version
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001933 if (mTransfer == TRANSFER_SHARED) {
1934 return;
1935 }
1936
Andy Hungabdb9902015-01-12 15:08:22 -08001937 size_t stepCount = audioBuffer->size / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001938 if (stepCount == 0) {
1939 return;
1940 }
1941
1942 Proxy::Buffer buffer;
1943 buffer.mFrameCount = stepCount;
1944 buffer.mRaw = audioBuffer->raw;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001945
Eric Laurent1703cdf2011-03-07 14:52:59 -08001946 AutoMutex lock(mLock);
Glenn Kasten305996c2020-01-27 08:03:37 -08001947 if (audioBuffer->sequence != mSequence) {
1948 // This Buffer came from a different IAudioTrack instance, so ignore the releaseBuffer
1949 ALOGD("%s is no-op due to IAudioTrack sequence mismatch %u != %u",
1950 __func__, audioBuffer->sequence, mSequence);
1951 return;
1952 }
Glenn Kasten200092b2014-08-15 15:13:30 -07001953 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001954 mInUnderrun = false;
1955 mProxy->releaseBuffer(&buffer);
1956
1957 // restart track if it was disabled by audioflinger due to previous underrun
Eric Laurent4d231dc2016-03-11 18:38:23 -08001958 restartIfDisabled();
1959}
1960
1961void AudioTrack::restartIfDisabled()
1962{
1963 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1964 if ((mState == STATE_ACTIVE) && (flags & CBLK_DISABLED)) {
Andy Hungfb8ede22018-09-12 19:03:24 -07001965 ALOGW("%s(%d): releaseBuffer() track %p disabled due to previous underrun, restarting",
Eric Laurent973db022018-11-20 14:54:31 -08001966 __func__, mPortId, this);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001967 // FIXME ignoring status
1968 mAudioTrack->start();
Eric Laurentdf839842012-05-31 14:27:14 -07001969 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001970}
1971
1972// -------------------------------------------------------------------------
1973
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08001974ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001975{
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07001976 if (mTransfer != TRANSFER_SYNC && mTransfer != TRANSFER_SYNC_NOTIF_CALLBACK) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07001977 return INVALID_OPERATION;
1978 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001979
Eric Laurentab5cdba2014-06-09 17:22:27 -07001980 if (isDirect()) {
1981 AutoMutex lock(mLock);
1982 int32_t flags = android_atomic_and(
1983 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1984 &mCblk->mFlags);
1985 if (flags & CBLK_INVALID) {
1986 return DEAD_OBJECT;
1987 }
1988 }
1989
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001990 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
Jiabin Huang447cea72020-07-28 22:35:18 +00001991 // Validation: user is most-likely passing an error code, and it would
Glenn Kasten99e53b82012-01-19 08:59:58 -08001992 // make the return value ambiguous (actualSize vs error).
Andy Hungfb8ede22018-09-12 19:03:24 -07001993 ALOGE("%s(%d): AudioTrack::write(buffer=%p, size=%zu (%zd)",
Eric Laurent973db022018-11-20 14:54:31 -08001994 __func__, mPortId, buffer, userSize, userSize);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001995 return BAD_VALUE;
1996 }
1997
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001998 size_t written = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001999 Buffer audioBuffer;
2000
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002001 while (userSize >= mFrameSize) {
2002 audioBuffer.frameCount = userSize / mFrameSize;
Eric Laurentc2f1f072009-07-17 12:17:14 -07002003
Jean-Michel Trivi720ad9d2014-02-04 11:00:59 -08002004 status_t err = obtainBuffer(&audioBuffer,
2005 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002006 if (err < 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002007 if (written > 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002008 break;
Glenn Kastend65d73c2012-06-22 17:21:07 -07002009 }
Glenn Kasten0a2f1512016-07-22 08:06:37 -07002010 if (err == TIMED_OUT || err == -EINTR) {
2011 err = WOULD_BLOCK;
2012 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002013 return ssize_t(err);
2014 }
2015
Glenn Kastenae4b8792015-03-20 09:04:21 -07002016 size_t toWrite = audioBuffer.size;
Andy Hungabdb9902015-01-12 15:08:22 -08002017 memcpy(audioBuffer.i8, buffer, toWrite);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002018 buffer = ((const char *) buffer) + toWrite;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002019 userSize -= toWrite;
2020 written += toWrite;
2021
2022 releaseBuffer(&audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002023 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002024
Andy Hungea2b9c02016-02-12 17:06:53 -08002025 if (written > 0) {
2026 mFramesWritten += written / mFrameSize;
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07002027
2028 if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
2029 const sp<AudioTrackThread> t = mAudioTrackThread;
2030 if (t != 0) {
2031 // causes wake up of the playback thread, that will callback the client for
2032 // more data (with EVENT_CAN_WRITE_MORE_DATA) in processAudioBuffer()
2033 t->wake();
2034 }
2035 }
Andy Hungea2b9c02016-02-12 17:06:53 -08002036 }
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07002037
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002038 return written;
2039}
2040
2041// -------------------------------------------------------------------------
2042
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08002043nsecs_t AudioTrack::processAudioBuffer()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002044{
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07002045 // Currently the AudioTrack thread is not created if there are no callbacks.
2046 // Would it ever make sense to run the thread, even without callbacks?
2047 // If so, then replace this by checks at each use for mCbf != NULL.
2048 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
2049
Eric Laurent1703cdf2011-03-07 14:52:59 -08002050 mLock.lock();
Glenn Kastena07f17c2013-04-23 12:39:37 -07002051 if (mAwaitBoost) {
2052 mAwaitBoost = false;
2053 mLock.unlock();
2054 static const int32_t kMaxTries = 5;
2055 int32_t tryCounter = kMaxTries;
2056 uint32_t pollUs = 10000;
2057 do {
Glenn Kasten8255ba72016-08-23 13:54:23 -07002058 int policy = sched_getscheduler(0) & ~SCHED_RESET_ON_FORK;
Glenn Kastena07f17c2013-04-23 12:39:37 -07002059 if (policy == SCHED_FIFO || policy == SCHED_RR) {
2060 break;
2061 }
2062 usleep(pollUs);
2063 pollUs <<= 1;
2064 } while (tryCounter-- > 0);
2065 if (tryCounter < 0) {
Andy Hungfb8ede22018-09-12 19:03:24 -07002066 ALOGE("%s(%d): did not receive expected priority boost on time",
Eric Laurent973db022018-11-20 14:54:31 -08002067 __func__, mPortId);
Glenn Kastena07f17c2013-04-23 12:39:37 -07002068 }
Glenn Kastenb0dfd462013-07-10 16:52:47 -07002069 // Run again immediately
2070 return 0;
Glenn Kastena07f17c2013-04-23 12:39:37 -07002071 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002072
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002073 // Can only reference mCblk while locked
2074 int32_t flags = android_atomic_and(
Glenn Kasten96f60d82013-07-12 10:21:18 -07002075 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
Glenn Kastena47f3162012-11-07 10:13:08 -08002076
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002077 // Check for track invalidation
2078 if (flags & CBLK_INVALID) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002079 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
2080 // AudioSystem cache. We should not exit here but after calling the callback so
2081 // that the upper layers can recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07002082 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
Lajos Molnarf1063e22015-04-17 15:19:42 -07002083 status_t status __unused = restoreTrack_l("processAudioBuffer");
2084 // FIXME unused status
Andy Hung53c3b5f2014-12-15 16:42:05 -08002085 // after restoration, continue below to make sure that the loop and buffer events
2086 // are notified because they have been cleared from mCblk->mFlags above.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002087 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002088 }
2089
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002090 bool waitStreamEnd = mState == STATE_STOPPING;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002091 bool active = mState == STATE_ACTIVE;
2092
2093 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
2094 bool newUnderrun = false;
2095 if (flags & CBLK_UNDERRUN) {
2096#if 0
2097 // Currently in shared buffer mode, when the server reaches the end of buffer,
2098 // the track stays active in continuous underrun state. It's up to the application
2099 // to pause or stop the track, or set the position to a new offset within buffer.
2100 // This was some experimental code to auto-pause on underrun. Keeping it here
2101 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
2102 if (mTransfer == TRANSFER_SHARED) {
2103 mState = STATE_PAUSED;
2104 active = false;
2105 }
2106#endif
2107 if (!mInUnderrun) {
2108 mInUnderrun = true;
2109 newUnderrun = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002110 }
2111 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07002112
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002113 // Get current position of server
Andy Hung90e8a972015-11-09 16:42:40 -08002114 Modulo<uint32_t> position(updateAndGetPosition_l());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002115
2116 // Manage marker callback
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002117 bool markerReached = false;
Andy Hung90e8a972015-11-09 16:42:40 -08002118 Modulo<uint32_t> markerPosition(mMarkerPosition);
2119 // uses 32 bit wraparound for comparison with position.
2120 if (!mMarkerReached && markerPosition.value() > 0 && position >= markerPosition) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002121 mMarkerReached = markerReached = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002122 }
2123
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002124 // Determine number of new position callback(s) that will be needed, while locked
2125 size_t newPosCount = 0;
Andy Hung90e8a972015-11-09 16:42:40 -08002126 Modulo<uint32_t> newPosition(mNewPosition);
2127 uint32_t updatePeriod = mUpdatePeriod;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002128 // FIXME fails for wraparound, need 64 bits
2129 if (updatePeriod > 0 && position >= newPosition) {
Andy Hung90e8a972015-11-09 16:42:40 -08002130 newPosCount = ((position - newPosition).value() / updatePeriod) + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002131 mNewPosition += updatePeriod * newPosCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002132 }
2133
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002134 // Cache other fields that will be needed soon
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002135 uint32_t sampleRate = mSampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002136 float speed = mPlaybackRate.mSpeed;
Andy Hunga7f03352015-05-31 21:54:49 -07002137 const uint32_t notificationFrames = mNotificationFramesAct;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002138 if (mRefreshRemaining) {
2139 mRefreshRemaining = false;
2140 mRemainingFrames = notificationFrames;
2141 mRetryOnPartialBuffer = false;
2142 }
2143 size_t misalignment = mProxy->getMisalignment();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002144 uint32_t sequence = mSequence;
Glenn Kasten96f04882013-09-20 09:28:56 -07002145 sp<AudioTrackClientProxy> proxy = mProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002146
Andy Hung53c3b5f2014-12-15 16:42:05 -08002147 // Determine the number of new loop callback(s) that will be needed, while locked.
2148 int loopCountNotifications = 0;
2149 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
2150
2151 if (mLoopCount > 0) {
2152 int loopCount;
2153 size_t bufferPosition;
2154 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
2155 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
2156 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
2157 mLoopCountNotified = loopCount; // discard any excess notifications
2158 } else if (mLoopCount < 0) {
2159 // FIXME: We're not accurate with notification count and position with infinite looping
2160 // since loopCount from server side will always return -1 (we could decrement it).
2161 size_t bufferPosition = mStaticProxy->getBufferPosition();
2162 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
2163 loopPeriod = mLoopEnd - bufferPosition;
2164 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
2165 size_t bufferPosition = mStaticProxy->getBufferPosition();
2166 loopPeriod = mFrameCount - bufferPosition;
2167 }
2168
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002169 // These fields don't need to be cached, because they are assigned only by set():
Andy Hungabdb9902015-01-12 15:08:22 -08002170 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002171 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
2172
2173 mLock.unlock();
2174
Andy Hunga7f03352015-05-31 21:54:49 -07002175 // get anchor time to account for callbacks.
2176 const nsecs_t timeBeforeCallbacks = systemTime();
2177
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002178 if (waitStreamEnd) {
Andy Hunga7f03352015-05-31 21:54:49 -07002179 // FIXME: Instead of blocking in proxy->waitStreamEndDone(), Callback thread
2180 // should wait on proxy futex and handle CBLK_STREAM_END_DONE within this function
2181 // (and make sure we don't callback for more data while we're stopping).
2182 // This helps with position, marker notifications, and track invalidation.
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002183 struct timespec timeout;
2184 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
2185 timeout.tv_nsec = 0;
2186
Glenn Kasten96f04882013-09-20 09:28:56 -07002187 status_t status = proxy->waitStreamEndDone(&timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002188 switch (status) {
2189 case NO_ERROR:
2190 case DEAD_OBJECT:
2191 case TIMED_OUT:
Andy Hung39609a02015-09-03 16:38:38 -07002192 if (status != DEAD_OBJECT) {
2193 // for DEAD_OBJECT, we do not send a EVENT_STREAM_END after stop();
2194 // instead, the application should handle the EVENT_NEW_IAUDIOTRACK.
2195 mCbf(EVENT_STREAM_END, mUserData, NULL);
2196 }
Glenn Kasten96f04882013-09-20 09:28:56 -07002197 {
2198 AutoMutex lock(mLock);
2199 // The previously assigned value of waitStreamEnd is no longer valid,
2200 // since the mutex has been unlocked and either the callback handler
2201 // or another thread could have re-started the AudioTrack during that time.
2202 waitStreamEnd = mState == STATE_STOPPING;
2203 if (waitStreamEnd) {
2204 mState = STATE_STOPPED;
Andy Hungc2813e52014-10-16 17:54:34 -07002205 mReleased = 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002206 }
2207 }
Glenn Kasten96f04882013-09-20 09:28:56 -07002208 if (waitStreamEnd && status != DEAD_OBJECT) {
2209 return NS_INACTIVE;
2210 }
2211 break;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002212 }
Glenn Kasten96f04882013-09-20 09:28:56 -07002213 return 0;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002214 }
2215
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002216 // perform callbacks while unlocked
2217 if (newUnderrun) {
2218 mCbf(EVENT_UNDERRUN, mUserData, NULL);
2219 }
Andy Hung53c3b5f2014-12-15 16:42:05 -08002220 while (loopCountNotifications > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002221 mCbf(EVENT_LOOP_END, mUserData, NULL);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002222 --loopCountNotifications;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002223 }
2224 if (flags & CBLK_BUFFER_END) {
2225 mCbf(EVENT_BUFFER_END, mUserData, NULL);
2226 }
2227 if (markerReached) {
2228 mCbf(EVENT_MARKER, mUserData, &markerPosition);
2229 }
2230 while (newPosCount > 0) {
Andy Hung90e8a972015-11-09 16:42:40 -08002231 size_t temp = newPosition.value(); // FIXME size_t != uint32_t
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002232 mCbf(EVENT_NEW_POS, mUserData, &temp);
2233 newPosition += updatePeriod;
2234 newPosCount--;
2235 }
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002236
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002237 if (mObservedSequence != sequence) {
2238 mObservedSequence = sequence;
2239 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002240 // for offloaded tracks, just wait for the upper layers to recreate the track
Eric Laurentab5cdba2014-06-09 17:22:27 -07002241 if (isOffloadedOrDirect()) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002242 return NS_INACTIVE;
2243 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002244 }
2245
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002246 // if inactive, then don't run me again until re-started
2247 if (!active) {
2248 return NS_INACTIVE;
Eric Laurent2267ba12011-09-07 11:13:23 -07002249 }
2250
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002251 // Compute the estimated time until the next timed event (position, markers, loops)
2252 // FIXME only for non-compressed audio
2253 uint32_t minFrames = ~0;
2254 if (!markerReached && position < markerPosition) {
Andy Hung90e8a972015-11-09 16:42:40 -08002255 minFrames = (markerPosition - position).value();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002256 }
2257 if (loopPeriod > 0 && loopPeriod < minFrames) {
Andy Hung2d85f092015-01-07 12:45:13 -08002258 // loopPeriod is already adjusted for actual position.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002259 minFrames = loopPeriod;
2260 }
Andy Hung2d85f092015-01-07 12:45:13 -08002261 if (updatePeriod > 0) {
Andy Hung90e8a972015-11-09 16:42:40 -08002262 minFrames = min(minFrames, (newPosition - position).value());
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002263 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002264
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002265 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
2266 static const uint32_t kPoll = 0;
2267 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
2268 minFrames = kPoll * notificationFrames;
2269 }
Eric Laurentc2f1f072009-07-17 12:17:14 -07002270
Andy Hunga7f03352015-05-31 21:54:49 -07002271 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
2272 static const nsecs_t kWaitPeriodNs = WAIT_PERIOD_MS * 1000000LL;
2273 const nsecs_t timeAfterCallbacks = systemTime();
2274
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002275 // Convert frame units to time units
2276 nsecs_t ns = NS_WHENEVER;
2277 if (minFrames != (uint32_t) ~0) {
jiabinc7bb8322017-09-06 18:20:11 -07002278 // AudioFlinger consumption of client data may be irregular when coming out of device
2279 // standby since the kernel buffers require filling. This is throttled to no more than 2x
2280 // the expected rate in the MixerThread. Hence, we reduce the estimated time to wait by one
2281 // half (but no more than half a second) to improve callback accuracy during these temporary
2282 // data surges.
2283 const nsecs_t estimatedNs = framesToNanoseconds(minFrames, sampleRate, speed);
2284 constexpr nsecs_t maxThrottleCompensationNs = 500000000LL;
2285 ns = estimatedNs - min(estimatedNs / 2, maxThrottleCompensationNs) + kWaitPeriodNs;
Andy Hunga7f03352015-05-31 21:54:49 -07002286 ns -= (timeAfterCallbacks - timeBeforeCallbacks); // account for callback time
2287 // TODO: Should we warn if the callback time is too long?
2288 if (ns < 0) ns = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002289 }
2290
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07002291 // If not supplying data by EVENT_MORE_DATA or EVENT_CAN_WRITE_MORE_DATA, then we're done
2292 if (mTransfer != TRANSFER_CALLBACK && mTransfer != TRANSFER_SYNC_NOTIF_CALLBACK) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002293 return ns;
2294 }
2295
Andy Hunga7f03352015-05-31 21:54:49 -07002296 // EVENT_MORE_DATA callback handling.
2297 // Timing for linear pcm audio data formats can be derived directly from the
2298 // buffer fill level.
2299 // Timing for compressed data is not directly available from the buffer fill level,
2300 // rather indirectly from waiting for blocking mode callbacks or waiting for obtain()
2301 // to return a certain fill level.
2302
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002303 struct timespec timeout;
2304 const struct timespec *requested = &ClientProxy::kForever;
2305 if (ns != NS_WHENEVER) {
2306 timeout.tv_sec = ns / 1000000000LL;
2307 timeout.tv_nsec = ns % 1000000000LL;
Andy Hungfb8ede22018-09-12 19:03:24 -07002308 ALOGV("%s(%d): timeout %ld.%03d",
Eric Laurent973db022018-11-20 14:54:31 -08002309 __func__, mPortId, timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002310 requested = &timeout;
2311 }
2312
Andy Hungea2b9c02016-02-12 17:06:53 -08002313 size_t writtenFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002314 while (mRemainingFrames > 0) {
2315
2316 Buffer audioBuffer;
2317 audioBuffer.frameCount = mRemainingFrames;
2318 size_t nonContig;
2319 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
2320 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
Andy Hungfb8ede22018-09-12 19:03:24 -07002321 "%s(%d): obtainBuffer() err=%d frameCount=%zu",
Eric Laurent973db022018-11-20 14:54:31 -08002322 __func__, mPortId, err, audioBuffer.frameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002323 requested = &ClientProxy::kNonBlocking;
2324 size_t avail = audioBuffer.frameCount + nonContig;
Andy Hungfb8ede22018-09-12 19:03:24 -07002325 ALOGV("%s(%d): obtainBuffer(%u) returned %zu = %zu + %zu err %d",
Eric Laurent973db022018-11-20 14:54:31 -08002326 __func__, mPortId, mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002327 if (err != NO_ERROR) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002328 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
2329 (isOffloaded() && (err == DEAD_OBJECT))) {
Glenn Kasten606fbc12015-10-22 15:28:15 -07002330 // FIXME bug 25195759
2331 return 1000000;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002332 }
Andy Hungfb8ede22018-09-12 19:03:24 -07002333 ALOGE("%s(%d): Error %d obtaining an audio buffer, giving up.",
Eric Laurent973db022018-11-20 14:54:31 -08002334 __func__, mPortId, err);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002335 return NS_NEVER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002336 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002337
Phil Burkfdb3c072016-02-09 10:47:02 -08002338 if (mRetryOnPartialBuffer && audio_has_proportional_frames(mFormat)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002339 mRetryOnPartialBuffer = false;
2340 if (avail < mRemainingFrames) {
Andy Hunga7f03352015-05-31 21:54:49 -07002341 if (ns > 0) { // account for obtain time
2342 const nsecs_t timeNow = systemTime();
2343 ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2344 }
Andy Hungeb6e6502019-04-29 13:47:40 -07002345
2346 // delayNs is first computed by the additional frames required in the buffer.
2347 nsecs_t delayNs = framesToNanoseconds(
2348 mRemainingFrames - avail, sampleRate, speed);
2349
2350 // afNs is the AudioFlinger mixer period in ns.
2351 const nsecs_t afNs = framesToNanoseconds(mAfFrameCount, mAfSampleRate, speed);
2352
2353 // If the AudioTrack is double buffered based on the AudioFlinger mixer period,
2354 // we may have a race if we wait based on the number of frames desired.
2355 // This is a possible issue with resampling and AAudio.
2356 //
2357 // The granularity of audioflinger processing is one mixer period; if
2358 // our wait time is less than one mixer period, wait at most half the period.
2359 if (delayNs < afNs) {
2360 delayNs = std::min(delayNs, afNs / 2);
2361 }
2362
2363 // adjust our ns wait by delayNs.
2364 if (ns < 0 /* NS_WHENEVER */ || delayNs < ns) {
2365 ns = delayNs;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002366 }
2367 return ns;
2368 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07002369 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002370
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002371 size_t reqSize = audioBuffer.size;
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07002372 if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
2373 // when notifying client it can write more data, pass the total size that can be
2374 // written in the next write() call, since it's not passed through the callback
2375 audioBuffer.size += nonContig;
2376 }
2377 mCbf(mTransfer == TRANSFER_CALLBACK ? EVENT_MORE_DATA : EVENT_CAN_WRITE_MORE_DATA,
2378 mUserData, &audioBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002379 size_t writtenSize = audioBuffer.size;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002380
Jiabin Huang447cea72020-07-28 22:35:18 +00002381 // Validate on returned size
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002382 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
Andy Hungfb8ede22018-09-12 19:03:24 -07002383 ALOGE("%s(%d): EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
Eric Laurent973db022018-11-20 14:54:31 -08002384 __func__, mPortId, reqSize, ssize_t(writtenSize));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002385 return NS_NEVER;
2386 }
2387
2388 if (writtenSize == 0) {
Jean-Michel Trivif4158d82018-09-25 12:43:58 -07002389 if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
2390 // The callback EVENT_CAN_WRITE_MORE_DATA was processed in the JNI of
2391 // android.media.AudioTrack. The JNI is not using the callback to provide data,
2392 // it only signals to the Java client that it can provide more data, which
2393 // this track is read to accept now.
2394 // The playback thread will be awaken at the next ::write()
2395 return NS_WHENEVER;
2396 }
The Android Open Source Project8555d082009-03-05 14:34:35 -08002397 // The callback is done filling buffers
2398 // Keep this thread going to handle timed events and
2399 // still try to get more data in intervals of WAIT_PERIOD_MS
2400 // but don't just loop and block the CPU, so wait
Andy Hunga7f03352015-05-31 21:54:49 -07002401
2402 // mCbf(EVENT_MORE_DATA, ...) might either
2403 // (1) Block until it can fill the buffer, returning 0 size on EOS.
2404 // (2) Block until it can fill the buffer, returning 0 data (silence) on EOS.
2405 // (3) Return 0 size when no data is available, does not wait for more data.
2406 //
2407 // (1) and (2) occurs with AudioPlayer/AwesomePlayer; (3) occurs with NuPlayer.
2408 // We try to compute the wait time to avoid a tight sleep-wait cycle,
2409 // especially for case (3).
2410 //
2411 // The decision to support (1) and (2) affect the sizing of mRemainingFrames
2412 // and this loop; whereas for case (3) we could simply check once with the full
2413 // buffer size and skip the loop entirely.
2414
2415 nsecs_t myns;
Phil Burkfdb3c072016-02-09 10:47:02 -08002416 if (audio_has_proportional_frames(mFormat)) {
Andy Hunga7f03352015-05-31 21:54:49 -07002417 // time to wait based on buffer occupancy
2418 const nsecs_t datans = mRemainingFrames <= avail ? 0 :
2419 framesToNanoseconds(mRemainingFrames - avail, sampleRate, speed);
2420 // audio flinger thread buffer size (TODO: adjust for fast tracks)
Glenn Kastenea38ee72016-04-18 11:08:01 -07002421 // FIXME: use mAfFrameCountHAL instead of mAfFrameCount below for fast tracks.
Andy Hunga7f03352015-05-31 21:54:49 -07002422 const nsecs_t afns = framesToNanoseconds(mAfFrameCount, mAfSampleRate, speed);
2423 // add a half the AudioFlinger buffer time to avoid soaking CPU if datans is 0.
2424 myns = datans + (afns / 2);
2425 } else {
2426 // FIXME: This could ping quite a bit if the buffer isn't full.
2427 // Note that when mState is stopping we waitStreamEnd, so it never gets here.
2428 myns = kWaitPeriodNs;
2429 }
2430 if (ns > 0) { // account for obtain and callback time
2431 const nsecs_t timeNow = systemTime();
2432 ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2433 }
2434 if (ns < 0 /* NS_WHENEVER */ || myns < ns) {
2435 ns = myns;
2436 }
2437 return ns;
Glenn Kastend65d73c2012-06-22 17:21:07 -07002438 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002439
Glenn Kasten138d6f92015-03-20 10:54:51 -07002440 size_t releasedFrames = writtenSize / mFrameSize;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002441 audioBuffer.frameCount = releasedFrames;
2442 mRemainingFrames -= releasedFrames;
2443 if (misalignment >= releasedFrames) {
2444 misalignment -= releasedFrames;
2445 } else {
2446 misalignment = 0;
2447 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002448
2449 releaseBuffer(&audioBuffer);
Andy Hungea2b9c02016-02-12 17:06:53 -08002450 writtenFrames += releasedFrames;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002451
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002452 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
2453 // if callback doesn't like to accept the full chunk
2454 if (writtenSize < reqSize) {
2455 continue;
2456 }
2457
2458 // There could be enough non-contiguous frames available to satisfy the remaining request
2459 if (mRemainingFrames <= nonContig) {
2460 continue;
2461 }
2462
2463#if 0
2464 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
2465 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
2466 // that total to a sum == notificationFrames.
2467 if (0 < misalignment && misalignment <= mRemainingFrames) {
2468 mRemainingFrames = misalignment;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002469 return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002470 }
2471#endif
2472
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002473 }
Andy Hungea2b9c02016-02-12 17:06:53 -08002474 if (writtenFrames > 0) {
2475 AutoMutex lock(mLock);
2476 mFramesWritten += writtenFrames;
2477 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002478 mRemainingFrames = notificationFrames;
2479 mRetryOnPartialBuffer = true;
2480
2481 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
2482 return 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002483}
2484
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002485status_t AudioTrack::restoreTrack_l(const char *from)
Eric Laurent1703cdf2011-03-07 14:52:59 -08002486{
Andy Hungb68f5eb2019-12-03 16:49:17 -08002487 status_t result = NO_ERROR; // logged: make sure to set this before returning.
2488 const int64_t beginNs = systemTime();
Andy Hunga6b27032020-04-27 10:34:24 -07002489 mediametrics::Defer defer([&] {
Andy Hungb68f5eb2019-12-03 16:49:17 -08002490 mediametrics::LogItem(mMetricsId)
2491 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_RESTORE)
Andy Hungea840382020-05-05 21:50:17 -07002492 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
Andy Hungb68f5eb2019-12-03 16:49:17 -08002493 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
2494 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
2495 .set(AMEDIAMETRICS_PROP_WHERE, from)
2496 .record(); });
2497
Andy Hungfb8ede22018-09-12 19:03:24 -07002498 ALOGW("%s(%d): dead IAudioTrack, %s, creating a new one from %s()",
Eric Laurent973db022018-11-20 14:54:31 -08002499 __func__, mPortId, isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002500 ++mSequence;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002501
Glenn Kastena47f3162012-11-07 10:13:08 -08002502 // refresh the audio configuration cache in this process to make sure we get new
Glenn Kastend2d089f2014-11-05 11:48:12 -08002503 // output parameters and new IAudioFlinger in createTrack_l()
Glenn Kastena47f3162012-11-07 10:13:08 -08002504 AudioSystem::clearAudioConfigCache();
Eric Laurent9f6530f2011-08-30 10:18:54 -07002505
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002506 if (isOffloadedOrDirect_l() || mDoNotReconnect) {
Andy Hung1f1db832015-06-08 13:26:10 -07002507 // FIXME re-creation of offloaded and direct tracks is not yet implemented;
2508 // reconsider enabling for linear PCM encodings when position can be preserved.
Andy Hungb68f5eb2019-12-03 16:49:17 -08002509 result = DEAD_OBJECT;
2510 return result;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01002511 }
2512
Phil Burk2812d9e2016-01-04 10:34:30 -08002513 // Save so we can return count since creation.
2514 mUnderrunCountOffset = getUnderrunCount_l();
2515
Glenn Kasten200092b2014-08-15 15:13:30 -07002516 // save the old static buffer position
Andy Hungf20a4e92016-08-15 19:10:34 -07002517 uint32_t staticPosition = 0;
Andy Hung4ede21d2014-12-12 15:37:34 -08002518 size_t bufferPosition = 0;
2519 int loopCount = 0;
2520 if (mStaticProxy != 0) {
2521 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
Andy Hungf20a4e92016-08-15 19:10:34 -07002522 staticPosition = mStaticProxy->getPosition().unsignedValue();
Andy Hung4ede21d2014-12-12 15:37:34 -08002523 }
Glenn Kasten200092b2014-08-15 15:13:30 -07002524
Mikhail Naganovb13b35d2018-03-30 17:21:14 -07002525 // See b/74409267. Connecting to a BT A2DP device supporting multiple codecs
2526 // causes a lot of churn on the service side, and it can reject starting
2527 // playback of a previously created track. May also apply to other cases.
2528 const int INITIAL_RETRIES = 3;
2529 int retries = INITIAL_RETRIES;
2530retry:
2531 if (retries < INITIAL_RETRIES) {
2532 // See the comment for clearAudioConfigCache at the start of the function.
2533 AudioSystem::clearAudioConfigCache();
2534 }
Haynes Mathew Georgeae34ed22016-01-28 11:58:39 -08002535 mFlags = mOrigFlags;
2536
Glenn Kasten200092b2014-08-15 15:13:30 -07002537 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
Glenn Kastena47f3162012-11-07 10:13:08 -08002538 // following member variables: mAudioTrack, mCblkMemory and mCblk.
Glenn Kasten200092b2014-08-15 15:13:30 -07002539 // It will also delete the strong references on previous IAudioTrack and IMemory.
2540 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
Andy Hungb68f5eb2019-12-03 16:49:17 -08002541 result = createTrack_l();
Eric Laurentcc21e4f2013-10-16 15:12:32 -07002542
Eric Laurent6ec546d2018-10-10 16:52:14 -07002543 if (result == NO_ERROR) {
Andy Hungd7bd69e2015-07-24 07:52:41 -07002544 // take the frames that will be lost by track recreation into account in saved position
2545 // For streaming tracks, this is the amount we obtained from the user/client
2546 // (not the number actually consumed at the server - those are already lost).
2547 if (mStaticProxy == 0) {
2548 mPosition = mReleased;
2549 }
Andy Hung4ede21d2014-12-12 15:37:34 -08002550 // Continue playback from last known position and restore loop.
2551 if (mStaticProxy != 0) {
2552 if (loopCount != 0) {
2553 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
2554 mLoopStart, mLoopEnd, loopCount);
2555 } else {
2556 mStaticProxy->setBufferPosition(bufferPosition);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002557 if (bufferPosition == mFrameCount) {
Eric Laurent973db022018-11-20 14:54:31 -08002558 ALOGD("%s(%d): restoring track at end of static buffer", __func__, mPortId);
Andy Hung53c3b5f2014-12-15 16:42:05 -08002559 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002560 }
2561 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002562 // restore volume handler
Andy Hung39399b62017-04-21 15:07:45 -07002563 mVolumeHandler->forall([this](const VolumeShaper &shaper) -> VolumeShaper::Status {
2564 sp<VolumeShaper::Operation> operationToEnd =
2565 new VolumeShaper::Operation(shaper.mOperation);
Andy Hung4ef88d72017-02-21 19:47:53 -08002566 // TODO: Ideally we would restore to the exact xOffset position
2567 // as returned by getVolumeShaperState(), but we don't have that
2568 // information when restoring at the client unless we periodically poll
2569 // the server or create shared memory state.
2570 //
Andy Hung39399b62017-04-21 15:07:45 -07002571 // For now, we simply advance to the end of the VolumeShaper effect
2572 // if it has been started.
2573 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002574 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002575 }
2576 return mAudioTrack->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002577 });
2578
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002579 if (mState == STATE_ACTIVE) {
Glenn Kastena47f3162012-11-07 10:13:08 -08002580 result = mAudioTrack->start();
Eric Laurent1703cdf2011-03-07 14:52:59 -08002581 }
Andy Hungf20a4e92016-08-15 19:10:34 -07002582 // server resets to zero so we offset
2583 mFramesWrittenServerOffset =
2584 mStaticProxy.get() != nullptr ? staticPosition : mFramesWritten;
2585 mFramesWrittenAtRestore = mFramesWrittenServerOffset;
Eric Laurent1703cdf2011-03-07 14:52:59 -08002586 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002587 if (result != NO_ERROR) {
Eric Laurent973db022018-11-20 14:54:31 -08002588 ALOGW("%s(%d): failed status %d, retries %d", __func__, mPortId, result, retries);
Mikhail Naganovb13b35d2018-03-30 17:21:14 -07002589 if (--retries > 0) {
Eric Laurent6ec546d2018-10-10 16:52:14 -07002590 // leave time for an eventual race condition to clear before retrying
2591 usleep(500000);
Mikhail Naganovb13b35d2018-03-30 17:21:14 -07002592 goto retry;
2593 }
Eric Laurent6ec546d2018-10-10 16:52:14 -07002594 // if no retries left, set invalid bit to force restoring at next occasion
2595 // and avoid inconsistent active state on client and server sides
2596 if (mCblk != nullptr) {
2597 android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
2598 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002599 }
Eric Laurent1703cdf2011-03-07 14:52:59 -08002600 return result;
2601}
2602
Andy Hung90e8a972015-11-09 16:42:40 -08002603Modulo<uint32_t> AudioTrack::updateAndGetPosition_l()
Glenn Kasten200092b2014-08-15 15:13:30 -07002604{
2605 // This is the sole place to read server consumed frames
Andy Hung90e8a972015-11-09 16:42:40 -08002606 Modulo<uint32_t> newServer(mProxy->getPosition());
2607 const int32_t delta = (newServer - mServer).signedValue();
Glenn Kasten200092b2014-08-15 15:13:30 -07002608 // TODO There is controversy about whether there can be "negative jitter" in server position.
2609 // This should be investigated further, and if possible, it should be addressed.
2610 // A more definite failure mode is infrequent polling by client.
2611 // One could call (void)getPosition_l() in releaseBuffer(),
2612 // so mReleased and mPosition are always lock-step as best possible.
2613 // That should ensure delta never goes negative for infrequent polling
2614 // unless the server has more than 2^31 frames in its buffer,
2615 // in which case the use of uint32_t for these counters has bigger issues.
Andy Hung90e8a972015-11-09 16:42:40 -08002616 ALOGE_IF(delta < 0,
Andy Hungfb8ede22018-09-12 19:03:24 -07002617 "%s(%d): detected illegal retrograde motion by the server: mServer advanced by %d",
Eric Laurent973db022018-11-20 14:54:31 -08002618 __func__, mPortId, delta);
Chad Brubaker039c27a2015-09-23 15:17:29 -07002619 mServer = newServer;
Andy Hung90e8a972015-11-09 16:42:40 -08002620 if (delta > 0) { // avoid retrograde
2621 mPosition += delta;
2622 }
2623 return mPosition;
Glenn Kasten200092b2014-08-15 15:13:30 -07002624}
2625
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002626bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed)
Andy Hung8edb8dc2015-03-26 19:13:55 -07002627{
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002628 updateLatency_l();
Andy Hung8edb8dc2015-03-26 19:13:55 -07002629 // applicable for mixing tracks only (not offloaded or direct)
2630 if (mStaticProxy != 0) {
2631 return true; // static tracks do not have issues with buffer sizing.
2632 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07002633 const size_t minFrameCount =
Eric Laurent21da6472017-11-09 16:29:26 -08002634 AudioSystem::calculateMinFrameCount(mAfLatency, mAfFrameCount, mAfSampleRate,
2635 sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002636 const bool allowed = mFrameCount >= minFrameCount;
2637 ALOGD_IF(!allowed,
Andy Hungfb8ede22018-09-12 19:03:24 -07002638 "%s(%d): denied "
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002639 "mAfLatency:%u mAfFrameCount:%zu mAfSampleRate:%u sampleRate:%u speed:%f "
2640 "mFrameCount:%zu < minFrameCount:%zu",
Eric Laurent973db022018-11-20 14:54:31 -08002641 __func__, mPortId,
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002642 mAfLatency, mAfFrameCount, mAfSampleRate, sampleRate, speed,
Andy Hung8edb8dc2015-03-26 19:13:55 -07002643 mFrameCount, minFrameCount);
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002644 return allowed;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002645}
2646
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002647status_t AudioTrack::setParameters(const String8& keyValuePairs)
2648{
2649 AutoMutex lock(mLock);
Glenn Kasten53cec222013-08-29 09:01:02 -07002650 return mAudioTrack->setParameters(keyValuePairs);
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002651}
2652
Dean Wheatleya70eef72018-01-04 14:23:50 +11002653status_t AudioTrack::selectPresentation(int presentationId, int programId)
2654{
2655 AutoMutex lock(mLock);
Eric Laurent973db022018-11-20 14:54:31 -08002656 AudioParameter param = AudioParameter();
2657 param.addInt(String8(AudioParameter::keyPresentationId), presentationId);
2658 param.addInt(String8(AudioParameter::keyProgramId), programId);
2659 ALOGV("%s(%d): PresentationId/ProgramId[%s]",
2660 __func__, mPortId, param.toString().string());
2661
2662 return mAudioTrack->setParameters(param.toString());
Dean Wheatleya70eef72018-01-04 14:23:50 +11002663}
2664
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002665VolumeShaper::Status AudioTrack::applyVolumeShaper(
2666 const sp<VolumeShaper::Configuration>& configuration,
2667 const sp<VolumeShaper::Operation>& operation)
2668{
2669 AutoMutex lock(mLock);
Andy Hung4ef88d72017-02-21 19:47:53 -08002670 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002671 VolumeShaper::Status status = mAudioTrack->applyVolumeShaper(configuration, operation);
Andy Hung39399b62017-04-21 15:07:45 -07002672
2673 if (status == DEAD_OBJECT) {
2674 if (restoreTrack_l("applyVolumeShaper") == OK) {
2675 status = mAudioTrack->applyVolumeShaper(configuration, operation);
2676 }
2677 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002678 if (status >= 0) {
2679 // save VolumeShaper for restore
2680 mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung39399b62017-04-21 15:07:45 -07002681 if (mState == STATE_ACTIVE || mState == STATE_STOPPING) {
2682 mVolumeHandler->setStarted();
2683 }
2684 } else {
2685 // warn only if not an expected restore failure.
2686 ALOGW_IF(!((isOffloadedOrDirect_l() || mDoNotReconnect) && status == DEAD_OBJECT),
Eric Laurent973db022018-11-20 14:54:31 -08002687 "%s(%d): applyVolumeShaper failed: %d", __func__, mPortId, status);
Andy Hung4ef88d72017-02-21 19:47:53 -08002688 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002689 return status;
2690}
2691
2692sp<VolumeShaper::State> AudioTrack::getVolumeShaperState(int id)
2693{
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002694 AutoMutex lock(mLock);
Andy Hung39399b62017-04-21 15:07:45 -07002695 sp<VolumeShaper::State> state = mAudioTrack->getVolumeShaperState(id);
2696 if (state.get() == nullptr && (mCblk->mFlags & CBLK_INVALID) != 0) {
2697 if (restoreTrack_l("getVolumeShaperState") == OK) {
2698 state = mAudioTrack->getVolumeShaperState(id);
2699 }
2700 }
2701 return state;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002702}
2703
Andy Hungea2b9c02016-02-12 17:06:53 -08002704status_t AudioTrack::getTimestamp(ExtendedTimestamp *timestamp)
2705{
2706 if (timestamp == nullptr) {
2707 return BAD_VALUE;
2708 }
2709 AutoMutex lock(mLock);
Andy Hunge13f8a62016-03-30 14:20:42 -07002710 return getTimestamp_l(timestamp);
2711}
2712
2713status_t AudioTrack::getTimestamp_l(ExtendedTimestamp *timestamp)
2714{
Andy Hungea2b9c02016-02-12 17:06:53 -08002715 if (mCblk->mFlags & CBLK_INVALID) {
2716 const status_t status = restoreTrack_l("getTimestampExtended");
2717 if (status != OK) {
2718 // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
2719 // recommending that the track be recreated.
2720 return DEAD_OBJECT;
2721 }
2722 }
2723 // check for offloaded/direct here in case restoring somehow changed those flags.
2724 if (isOffloadedOrDirect_l()) {
2725 return INVALID_OPERATION; // not supported
2726 }
2727 status_t status = mProxy->getTimestamp(timestamp);
Andy Hungfb8ede22018-09-12 19:03:24 -07002728 LOG_ALWAYS_FATAL_IF(status != OK, "%s(%d): status %d not allowed from proxy getTimestamp",
Eric Laurent973db022018-11-20 14:54:31 -08002729 __func__, mPortId, status);
Andy Hungea2b9c02016-02-12 17:06:53 -08002730 bool found = false;
Andy Hunge1e98462016-04-12 10:18:51 -07002731 timestamp->mPosition[ExtendedTimestamp::LOCATION_CLIENT] = mFramesWritten;
2732 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_CLIENT] = 0;
2733 // server side frame offset in case AudioTrack has been restored.
2734 for (int i = ExtendedTimestamp::LOCATION_SERVER;
2735 i < ExtendedTimestamp::LOCATION_MAX; ++i) {
2736 if (timestamp->mTimeNs[i] >= 0) {
2737 // apply server offset (frames flushed is ignored
2738 // so we don't report the jump when the flush occurs).
2739 timestamp->mPosition[i] += mFramesWrittenServerOffset;
2740 found = true;
Andy Hungea2b9c02016-02-12 17:06:53 -08002741 }
2742 }
2743 return found ? OK : WOULD_BLOCK;
2744}
2745
Glenn Kastence703742013-07-19 16:33:58 -07002746status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
2747{
Glenn Kasten53cec222013-08-29 09:01:02 -07002748 AutoMutex lock(mLock);
Andy Hung65ffdfc2016-10-10 15:52:11 -07002749 return getTimestamp_l(timestamp);
2750}
Phil Burk1b420972015-04-22 10:52:21 -07002751
Andy Hung65ffdfc2016-10-10 15:52:11 -07002752status_t AudioTrack::getTimestamp_l(AudioTimestamp& timestamp)
2753{
Phil Burk1b420972015-04-22 10:52:21 -07002754 bool previousTimestampValid = mPreviousTimestampValid;
2755 // Set false here to cover all the error return cases.
2756 mPreviousTimestampValid = false;
2757
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002758 switch (mState) {
2759 case STATE_ACTIVE:
2760 case STATE_PAUSED:
2761 break; // handle below
2762 case STATE_FLUSHED:
2763 case STATE_STOPPED:
2764 return WOULD_BLOCK;
2765 case STATE_STOPPING:
2766 case STATE_PAUSED_STOPPING:
2767 if (!isOffloaded_l()) {
2768 return INVALID_OPERATION;
2769 }
2770 break; // offloaded tracks handled below
2771 default:
Andy Hungfb8ede22018-09-12 19:03:24 -07002772 LOG_ALWAYS_FATAL("%s(%d): Invalid mState in getTimestamp(): %d",
Eric Laurent973db022018-11-20 14:54:31 -08002773 __func__, mPortId, mState);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002774 break;
Glenn Kastenfe346c72013-08-30 13:28:22 -07002775 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002776
Eric Laurent275e8e92014-11-30 15:14:47 -08002777 if (mCblk->mFlags & CBLK_INVALID) {
Andy Hung6653c932015-06-08 13:27:48 -07002778 const status_t status = restoreTrack_l("getTimestamp");
2779 if (status != OK) {
2780 // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
2781 // recommending that the track be recreated.
2782 return DEAD_OBJECT;
2783 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002784 }
2785
Glenn Kasten200092b2014-08-15 15:13:30 -07002786 // The presented frame count must always lag behind the consumed frame count.
2787 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
Andy Hung6ae58432016-02-16 18:32:24 -08002788
2789 status_t status;
Andy Hung818e7a32016-02-16 18:08:07 -08002790 if (isOffloadedOrDirect_l()) {
Andy Hung6ae58432016-02-16 18:32:24 -08002791 // use Binder to get timestamp
2792 status = mAudioTrack->getTimestamp(timestamp);
2793 } else {
2794 // read timestamp from shared memory
2795 ExtendedTimestamp ets;
2796 status = mProxy->getTimestamp(&ets);
2797 if (status == OK) {
Andy Hungb01faa32016-04-27 12:51:32 -07002798 ExtendedTimestamp::Location location;
2799 status = ets.getBestTimestamp(&timestamp, &location);
2800
2801 if (status == OK) {
Haynes Mathew Georgefb12e202017-04-06 12:24:42 -07002802 updateLatency_l();
Andy Hungb01faa32016-04-27 12:51:32 -07002803 // It is possible that the best location has moved from the kernel to the server.
2804 // In this case we adjust the position from the previous computed latency.
2805 if (location == ExtendedTimestamp::LOCATION_SERVER) {
2806 ALOGW_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_KERNEL,
Andy Hungfb8ede22018-09-12 19:03:24 -07002807 "%s(%d): location moved from kernel to server",
Eric Laurent973db022018-11-20 14:54:31 -08002808 __func__, mPortId);
Andy Hung07eee802016-06-21 16:47:16 -07002809 // check that the last kernel OK time info exists and the positions
2810 // are valid (if they predate the current track, the positions may
2811 // be zero or negative).
Andy Hungb01faa32016-04-27 12:51:32 -07002812 const int64_t frames =
Andy Hung6d7b1192016-05-07 22:59:48 -07002813 (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
Andy Hung07eee802016-06-21 16:47:16 -07002814 ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0 ||
2815 ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] <= 0 ||
2816 ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] <= 0)
Andy Hung6d7b1192016-05-07 22:59:48 -07002817 ?
2818 int64_t((double)mAfLatency * mSampleRate * mPlaybackRate.mSpeed
2819 / 1000)
2820 :
2821 (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
2822 - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK]);
Andy Hungfb8ede22018-09-12 19:03:24 -07002823 ALOGV("%s(%d): frame adjustment:%lld timestamp:%s",
Eric Laurent973db022018-11-20 14:54:31 -08002824 __func__, mPortId, (long long)frames, ets.toString().c_str());
Andy Hungb01faa32016-04-27 12:51:32 -07002825 if (frames >= ets.mPosition[location]) {
2826 timestamp.mPosition = 0;
2827 } else {
2828 timestamp.mPosition = (uint32_t)(ets.mPosition[location] - frames);
2829 }
Andy Hung69488c42016-05-16 18:43:33 -07002830 } else if (location == ExtendedTimestamp::LOCATION_KERNEL) {
2831 ALOGV_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_SERVER,
Andy Hungfb8ede22018-09-12 19:03:24 -07002832 "%s(%d): location moved from server to kernel",
Eric Laurent973db022018-11-20 14:54:31 -08002833 __func__, mPortId);
Andy Hung98731a22019-04-08 19:19:07 -07002834
2835 if (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER] ==
2836 ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL]) {
2837 // In Q, we don't return errors as an invalid time
2838 // but instead we leave the last kernel good timestamp alone.
2839 //
2840 // If server is identical to kernel, the device data pipeline is idle.
2841 // A better start time is now. The retrograde check ensures
2842 // timestamp monotonicity.
2843 const int64_t nowNs = systemTime();
Andy Hungcf3b7152019-04-19 18:29:21 -07002844 if (!mTimestampStallReported) {
2845 ALOGD("%s(%d): device stall time corrected using current time %lld",
2846 __func__, mPortId, (long long)nowNs);
2847 mTimestampStallReported = true;
2848 }
Andy Hung98731a22019-04-08 19:19:07 -07002849 timestamp.mTime = convertNsToTimespec(nowNs);
Andy Hungcf3b7152019-04-19 18:29:21 -07002850 } else {
2851 mTimestampStallReported = false;
Andy Hung98731a22019-04-08 19:19:07 -07002852 }
Andy Hungb01faa32016-04-27 12:51:32 -07002853 }
Andy Hung5d313802016-10-10 15:09:39 -07002854
2855 // We update the timestamp time even when paused.
2856 if (mState == STATE_PAUSED /* not needed: STATE_PAUSED_STOPPING */) {
2857 const int64_t now = systemTime();
Andy Hung2b01f002017-07-05 12:01:36 -07002858 const int64_t at = audio_utils_ns_from_timespec(&timestamp.mTime);
Andy Hung5d313802016-10-10 15:09:39 -07002859 const int64_t lag =
2860 (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
2861 ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0)
2862 ? int64_t(mAfLatency * 1000000LL)
2863 : (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
2864 - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK])
2865 * NANOS_PER_SECOND / mSampleRate;
2866 const int64_t limit = now - lag; // no earlier than this limit
2867 if (at < limit) {
2868 ALOGV("timestamp pause lag:%lld adjusting from %lld to %lld",
2869 (long long)lag, (long long)at, (long long)limit);
Andy Hungffa36952017-08-17 10:41:51 -07002870 timestamp.mTime = convertNsToTimespec(limit);
Andy Hung5d313802016-10-10 15:09:39 -07002871 }
2872 }
Andy Hungb01faa32016-04-27 12:51:32 -07002873 mPreviousLocation = location;
2874 } else {
2875 // right after AudioTrack is started, one may not find a timestamp
Eric Laurent973db022018-11-20 14:54:31 -08002876 ALOGV("%s(%d): getBestTimestamp did not find timestamp", __func__, mPortId);
Andy Hungb01faa32016-04-27 12:51:32 -07002877 }
Andy Hung6ae58432016-02-16 18:32:24 -08002878 }
2879 if (status == INVALID_OPERATION) {
Andy Hungf20a4e92016-08-15 19:10:34 -07002880 // INVALID_OPERATION occurs when no timestamp has been issued by the server;
2881 // other failures are signaled by a negative time.
2882 // If we come out of FLUSHED or STOPPED where the position is known
2883 // to be zero we convert this to WOULD_BLOCK (with the implicit meaning of
2884 // "zero" for NuPlayer). We don't convert for track restoration as position
2885 // does not reset.
Andy Hungfb8ede22018-09-12 19:03:24 -07002886 ALOGV("%s(%d): timestamp server offset:%lld restore frames:%lld",
Eric Laurent973db022018-11-20 14:54:31 -08002887 __func__, mPortId,
Andy Hungf20a4e92016-08-15 19:10:34 -07002888 (long long)mFramesWrittenServerOffset, (long long)mFramesWrittenAtRestore);
2889 if (mFramesWrittenServerOffset != mFramesWrittenAtRestore) {
2890 status = WOULD_BLOCK;
2891 }
Andy Hung6ae58432016-02-16 18:32:24 -08002892 }
2893 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002894 if (status != NO_ERROR) {
Eric Laurent973db022018-11-20 14:54:31 -08002895 ALOGV_IF(status != WOULD_BLOCK, "%s(%d): getTimestamp error:%#x", __func__, mPortId, status);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002896 return status;
2897 }
2898 if (isOffloadedOrDirect_l()) {
2899 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
2900 // use cached paused position in case another offloaded track is running.
2901 timestamp.mPosition = mPausedPosition;
2902 clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
Andy Hung5d313802016-10-10 15:09:39 -07002903 // TODO: adjust for delay
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002904 return NO_ERROR;
2905 }
2906
2907 // Check whether a pending flush or stop has completed, as those commands may
Andy Hungc8e09c62015-06-03 23:43:36 -07002908 // be asynchronous or return near finish or exhibit glitchy behavior.
2909 //
2910 // Originally this showed up as the first timestamp being a continuation of
2911 // the previous song under gapless playback.
2912 // However, we sometimes see zero timestamps, then a glitch of
2913 // the previous song's position, and then correct timestamps afterwards.
Andy Hungffa36952017-08-17 10:41:51 -07002914 if (mStartFromZeroUs != 0 && mSampleRate != 0) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002915 static const int kTimeJitterUs = 100000; // 100 ms
2916 static const int k1SecUs = 1000000;
2917
2918 const int64_t timeNow = getNowUs();
2919
Andy Hungffa36952017-08-17 10:41:51 -07002920 if (timeNow < mStartFromZeroUs + k1SecUs) { // within first second of starting
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002921 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
Andy Hungffa36952017-08-17 10:41:51 -07002922 if (timestampTimeUs < mStartFromZeroUs) {
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002923 return WOULD_BLOCK; // stale timestamp time, occurs before start.
2924 }
Andy Hungffa36952017-08-17 10:41:51 -07002925 const int64_t deltaTimeUs = timestampTimeUs - mStartFromZeroUs;
Andy Hung8edb8dc2015-03-26 19:13:55 -07002926 const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07002927 / ((double)mSampleRate * mPlaybackRate.mSpeed);
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002928
2929 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2930 // Verify that the counter can't count faster than the sample rate
Andy Hungc8e09c62015-06-03 23:43:36 -07002931 // since the start time. If greater, then that means we may have failed
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002932 // to completely flush or stop the previous playing track.
Andy Hungc8e09c62015-06-03 23:43:36 -07002933 ALOGW_IF(!mTimestampStartupGlitchReported,
Andy Hungfb8ede22018-09-12 19:03:24 -07002934 "%s(%d): startup glitch detected"
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002935 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
Eric Laurent973db022018-11-20 14:54:31 -08002936 __func__, mPortId,
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002937 (long long)deltaTimeUs, (long long)deltaPositionByUs,
2938 timestamp.mPosition);
Andy Hungc8e09c62015-06-03 23:43:36 -07002939 mTimestampStartupGlitchReported = true;
2940 if (previousTimestampValid
2941 && mPreviousTimestamp.mPosition == 0 /* should be true if valid */) {
2942 timestamp = mPreviousTimestamp;
2943 mPreviousTimestampValid = true;
2944 return NO_ERROR;
2945 }
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002946 return WOULD_BLOCK;
2947 }
Andy Hungc8e09c62015-06-03 23:43:36 -07002948 if (deltaPositionByUs != 0) {
Andy Hungffa36952017-08-17 10:41:51 -07002949 mStartFromZeroUs = 0; // don't check again, we got valid nonzero position.
Andy Hungc8e09c62015-06-03 23:43:36 -07002950 }
2951 } else {
Andy Hungffa36952017-08-17 10:41:51 -07002952 mStartFromZeroUs = 0; // don't check again, start time expired.
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002953 }
Andy Hungc8e09c62015-06-03 23:43:36 -07002954 mTimestampStartupGlitchReported = false;
Andy Hung7f1bc8a2014-09-12 14:43:11 -07002955 }
2956 } else {
Glenn Kasten200092b2014-08-15 15:13:30 -07002957 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2958 (void) updateAndGetPosition_l();
2959 // Server consumed (mServer) and presented both use the same server time base,
2960 // and server consumed is always >= presented.
2961 // The delta between these represents the number of frames in the buffer pipeline.
2962 // If this delta between these is greater than the client position, it means that
2963 // actually presented is still stuck at the starting line (figuratively speaking),
2964 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
Andy Hung90e8a972015-11-09 16:42:40 -08002965 // Note: We explicitly use non-Modulo comparison here - potential wrap issue when
2966 // mPosition exceeds 32 bits.
2967 // TODO Remove when timestamp is updated to contain pipeline status info.
2968 const int32_t pipelineDepthInFrames = (mServer - timestamp.mPosition).signedValue();
2969 if (pipelineDepthInFrames > 0 /* should be true, but we check anyways */
2970 && (uint32_t)pipelineDepthInFrames > mPosition.value()) {
Glenn Kasten200092b2014-08-15 15:13:30 -07002971 return INVALID_OPERATION;
2972 }
2973 // Convert timestamp position from server time base to client time base.
2974 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2975 // But if we change it to 64-bit then this could fail.
Andy Hung90e8a972015-11-09 16:42:40 -08002976 // Use Modulo computation here.
2977 timestamp.mPosition = (mPosition - mServer + timestamp.mPosition).value();
Glenn Kasten200092b2014-08-15 15:13:30 -07002978 // Immediately after a call to getPosition_l(), mPosition and
2979 // mServer both represent the same frame position. mPosition is
2980 // in client's point of view, and mServer is in server's point of
2981 // view. So the difference between them is the "fudge factor"
2982 // between client and server views due to stop() and/or new
2983 // IAudioTrack. And timestamp.mPosition is initially in server's
2984 // point of view, so we need to apply the same fudge factor to it.
Glenn Kastenfe346c72013-08-30 13:28:22 -07002985 }
Phil Burk1b420972015-04-22 10:52:21 -07002986
2987 // Prevent retrograde motion in timestamp.
2988 // This is sometimes caused by erratic reports of the available space in the ALSA drivers.
2989 if (status == NO_ERROR) {
Andy Hung3b8c6332019-04-03 19:29:36 -07002990 // Fix stale time when checking timestamp right after start().
2991 // The position is at the last reported location but the time can be stale
2992 // due to pause or standby or cold start latency.
2993 //
2994 // We keep advancing the time (but not the position) to ensure that the
2995 // stale value does not confuse the application.
2996 //
2997 // For offload compatibility, use a default lag value here.
2998 // Any time discrepancy between this update and the pause timestamp is handled
2999 // by the retrograde check afterwards.
3000 int64_t currentTimeNanos = audio_utils_ns_from_timespec(&timestamp.mTime);
3001 const int64_t lagNs = int64_t(mAfLatency * 1000000LL);
3002 const int64_t limitNs = mStartNs - lagNs;
3003 if (currentTimeNanos < limitNs) {
Andy Hungcf3b7152019-04-19 18:29:21 -07003004 if (!mTimestampStaleTimeReported) {
3005 ALOGD("%s(%d): stale timestamp time corrected, "
3006 "currentTimeNanos: %lld < limitNs: %lld < mStartNs: %lld",
3007 __func__, mPortId,
3008 (long long)currentTimeNanos, (long long)limitNs, (long long)mStartNs);
3009 mTimestampStaleTimeReported = true;
3010 }
Andy Hung3b8c6332019-04-03 19:29:36 -07003011 timestamp.mTime = convertNsToTimespec(limitNs);
3012 currentTimeNanos = limitNs;
Andy Hungcf3b7152019-04-19 18:29:21 -07003013 } else {
3014 mTimestampStaleTimeReported = false;
Andy Hung3b8c6332019-04-03 19:29:36 -07003015 }
3016
Andy Hungffa36952017-08-17 10:41:51 -07003017 // previousTimestampValid is set to false when starting after a stop or flush.
Phil Burk1b420972015-04-22 10:52:21 -07003018 if (previousTimestampValid) {
Andy Hung2b01f002017-07-05 12:01:36 -07003019 const int64_t previousTimeNanos =
3020 audio_utils_ns_from_timespec(&mPreviousTimestamp.mTime);
Andy Hungffa36952017-08-17 10:41:51 -07003021
3022 // retrograde check
Phil Burk1b420972015-04-22 10:52:21 -07003023 if (currentTimeNanos < previousTimeNanos) {
Andy Hungcf3b7152019-04-19 18:29:21 -07003024 if (!mTimestampRetrogradeTimeReported) {
3025 ALOGW("%s(%d): retrograde timestamp time corrected, %lld < %lld",
3026 __func__, mPortId,
3027 (long long)currentTimeNanos, (long long)previousTimeNanos);
3028 mTimestampRetrogradeTimeReported = true;
3029 }
Andy Hung5d313802016-10-10 15:09:39 -07003030 timestamp.mTime = mPreviousTimestamp.mTime;
Andy Hungcf3b7152019-04-19 18:29:21 -07003031 } else {
3032 mTimestampRetrogradeTimeReported = false;
Phil Burk1b420972015-04-22 10:52:21 -07003033 }
3034
3035 // Looking at signed delta will work even when the timestamps
3036 // are wrapping around.
Andy Hung90e8a972015-11-09 16:42:40 -08003037 int32_t deltaPosition = (Modulo<uint32_t>(timestamp.mPosition)
3038 - mPreviousTimestamp.mPosition).signedValue();
Phil Burk4c5a3672015-04-30 16:18:53 -07003039 if (deltaPosition < 0) {
3040 // Only report once per position instead of spamming the log.
Andy Hungcf3b7152019-04-19 18:29:21 -07003041 if (!mTimestampRetrogradePositionReported) {
Andy Hungfb8ede22018-09-12 19:03:24 -07003042 ALOGW("%s(%d): retrograde timestamp position corrected, %d = %u - %u",
Eric Laurent973db022018-11-20 14:54:31 -08003043 __func__, mPortId,
Phil Burk4c5a3672015-04-30 16:18:53 -07003044 deltaPosition,
3045 timestamp.mPosition,
3046 mPreviousTimestamp.mPosition);
Andy Hungcf3b7152019-04-19 18:29:21 -07003047 mTimestampRetrogradePositionReported = true;
Phil Burk4c5a3672015-04-30 16:18:53 -07003048 }
3049 } else {
Andy Hungcf3b7152019-04-19 18:29:21 -07003050 mTimestampRetrogradePositionReported = false;
Phil Burk4c5a3672015-04-30 16:18:53 -07003051 }
Andy Hung5d313802016-10-10 15:09:39 -07003052 if (deltaPosition < 0) {
3053 timestamp.mPosition = mPreviousTimestamp.mPosition;
3054 deltaPosition = 0;
Phil Burk1b420972015-04-22 10:52:21 -07003055 }
Andy Hung5d313802016-10-10 15:09:39 -07003056#if 0
3057 // Uncomment this to verify audio timestamp rate.
3058 const int64_t deltaTime =
Andy Hung2b01f002017-07-05 12:01:36 -07003059 audio_utils_ns_from_timespec(&timestamp.mTime) - previousTimeNanos;
Andy Hung5d313802016-10-10 15:09:39 -07003060 if (deltaTime != 0) {
3061 const int64_t computedSampleRate =
3062 deltaPosition * (long long)NANOS_PER_SECOND / deltaTime;
Andy Hungfb8ede22018-09-12 19:03:24 -07003063 ALOGD("%s(%d): computedSampleRate:%u sampleRate:%u",
Eric Laurent973db022018-11-20 14:54:31 -08003064 __func__, mPortId,
Andy Hung5d313802016-10-10 15:09:39 -07003065 (unsigned)computedSampleRate, mSampleRate);
3066 }
3067#endif
Phil Burk1b420972015-04-22 10:52:21 -07003068 }
3069 mPreviousTimestamp = timestamp;
3070 mPreviousTimestampValid = true;
3071 }
3072
Glenn Kastenfe346c72013-08-30 13:28:22 -07003073 return status;
Glenn Kastence703742013-07-19 16:33:58 -07003074}
3075
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00003076String8 AudioTrack::getParameters(const String8& keys)
3077{
Glenn Kasten2c6c5292014-01-13 10:29:08 -08003078 audio_io_handle_t output = getOutput();
Glenn Kasten142f5192014-03-25 17:44:59 -07003079 if (output != AUDIO_IO_HANDLE_NONE) {
Glenn Kasten2c6c5292014-01-13 10:29:08 -08003080 return AudioSystem::getParameters(output, keys);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +01003081 } else {
3082 return String8::empty();
3083 }
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00003084}
3085
Glenn Kasten23a75452014-01-13 10:37:17 -08003086bool AudioTrack::isOffloaded() const
3087{
3088 AutoMutex lock(mLock);
3089 return isOffloaded_l();
3090}
3091
Eric Laurentab5cdba2014-06-09 17:22:27 -07003092bool AudioTrack::isDirect() const
3093{
3094 AutoMutex lock(mLock);
3095 return isDirect_l();
3096}
3097
3098bool AudioTrack::isOffloadedOrDirect() const
3099{
3100 AutoMutex lock(mLock);
3101 return isOffloadedOrDirect_l();
3102}
3103
3104
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08003105status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003106{
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003107 String8 result;
3108
3109 result.append(" AudioTrack::dump\n");
Andy Hungfb8ede22018-09-12 19:03:24 -07003110 result.appendFormat(" id(%d) status(%d), state(%d), session Id(%d), flags(%#x)\n",
Eric Laurent973db022018-11-20 14:54:31 -08003111 mPortId, mStatus, mState, mSessionId, mFlags);
Eric Laurentd114b622017-11-27 18:37:04 -08003112 result.appendFormat(" stream type(%d), left - right volume(%f, %f)\n",
3113 (mStreamType == AUDIO_STREAM_DEFAULT) ?
François Gaffie58d4be52018-11-06 15:30:12 +01003114 AudioSystem::attributesToStreamType(mAttributes) :
3115 mStreamType,
Eric Laurentd114b622017-11-27 18:37:04 -08003116 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003117 result.appendFormat(" format(%#x), channel mask(%#x), channel count(%u)\n",
Eric Laurentd114b622017-11-27 18:37:04 -08003118 mFormat, mChannelMask, mChannelCount);
3119 result.appendFormat(" sample rate(%u), original sample rate(%u), speed(%f)\n",
3120 mSampleRate, mOriginalSampleRate, mPlaybackRate.mSpeed);
3121 result.appendFormat(" frame count(%zu), req. frame count(%zu)\n",
3122 mFrameCount, mReqFrameCount);
3123 result.appendFormat(" notif. frame count(%u), req. notif. frame count(%u),"
3124 " req. notif. per buff(%u)\n",
3125 mNotificationFramesAct, mNotificationFramesReq, mNotificationsPerBufferReq);
3126 result.appendFormat(" latency (%d), selected device Id(%d), routed device Id(%d)\n",
3127 mLatency, mSelectedDeviceId, mRoutedDeviceId);
3128 result.appendFormat(" output(%d) AF latency (%u) AF frame count(%zu) AF SampleRate(%u)\n",
3129 mOutput, mAfLatency, mAfFrameCount, mAfSampleRate);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003130 ::write(fd, result.string(), result.size());
3131 return NO_ERROR;
3132}
3133
Phil Burk2812d9e2016-01-04 10:34:30 -08003134uint32_t AudioTrack::getUnderrunCount() const
3135{
3136 AutoMutex lock(mLock);
3137 return getUnderrunCount_l();
3138}
3139
3140uint32_t AudioTrack::getUnderrunCount_l() const
3141{
3142 return mProxy->getUnderrunCount() + mUnderrunCountOffset;
3143}
3144
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003145uint32_t AudioTrack::getUnderrunFrames() const
3146{
3147 AutoMutex lock(mLock);
3148 return mProxy->getUnderrunFrames();
3149}
3150
Eric Laurent296fb132015-05-01 11:38:42 -07003151status_t AudioTrack::addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback)
3152{
Eric Laurent09f1ed22019-04-24 17:45:17 -07003153
Eric Laurent296fb132015-05-01 11:38:42 -07003154 if (callback == 0) {
Eric Laurent973db022018-11-20 14:54:31 -08003155 ALOGW("%s(%d): adding NULL callback!", __func__, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07003156 return BAD_VALUE;
3157 }
3158 AutoMutex lock(mLock);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003159 if (mDeviceCallback.unsafe_get() == callback.get()) {
Eric Laurent973db022018-11-20 14:54:31 -08003160 ALOGW("%s(%d): adding same callback!", __func__, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07003161 return INVALID_OPERATION;
3162 }
3163 status_t status = NO_ERROR;
3164 if (mOutput != AUDIO_IO_HANDLE_NONE) {
3165 if (mDeviceCallback != 0) {
Eric Laurent973db022018-11-20 14:54:31 -08003166 ALOGW("%s(%d): callback already present!", __func__, mPortId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003167 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07003168 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07003169 status = AudioSystem::addAudioDeviceCallback(this, mOutput, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07003170 }
3171 mDeviceCallback = callback;
3172 return status;
3173}
3174
3175status_t AudioTrack::removeAudioDeviceCallback(
3176 const sp<AudioSystem::AudioDeviceCallback>& callback)
3177{
3178 if (callback == 0) {
Eric Laurent973db022018-11-20 14:54:31 -08003179 ALOGW("%s(%d): removing NULL callback!", __func__, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07003180 return BAD_VALUE;
3181 }
Eric Laurent4463ff52019-02-07 13:56:09 -08003182 AutoMutex lock(mLock);
3183 if (mDeviceCallback.unsafe_get() != callback.get()) {
3184 ALOGW("%s removing different callback!", __FUNCTION__);
3185 return INVALID_OPERATION;
Eric Laurent296fb132015-05-01 11:38:42 -07003186 }
Eric Laurent4463ff52019-02-07 13:56:09 -08003187 mDeviceCallback.clear();
Eric Laurent296fb132015-05-01 11:38:42 -07003188 if (mOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurent09f1ed22019-04-24 17:45:17 -07003189 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07003190 }
Eric Laurent296fb132015-05-01 11:38:42 -07003191 return NO_ERROR;
3192}
3193
Eric Laurentad2e7b92017-09-14 20:06:42 -07003194
3195void AudioTrack::onAudioDeviceUpdate(audio_io_handle_t audioIo,
3196 audio_port_handle_t deviceId)
3197{
3198 sp<AudioSystem::AudioDeviceCallback> callback;
3199 {
3200 AutoMutex lock(mLock);
3201 if (audioIo != mOutput) {
3202 return;
3203 }
3204 callback = mDeviceCallback.promote();
3205 // only update device if the track is active as route changes due to other use cases are
3206 // irrelevant for this client
3207 if (mState == STATE_ACTIVE) {
3208 mRoutedDeviceId = deviceId;
3209 }
3210 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07003211
Eric Laurentad2e7b92017-09-14 20:06:42 -07003212 if (callback.get() != nullptr) {
3213 callback->onAudioDeviceUpdate(mOutput, mRoutedDeviceId);
3214 }
3215}
3216
Andy Hunge13f8a62016-03-30 14:20:42 -07003217status_t AudioTrack::pendingDuration(int32_t *msec, ExtendedTimestamp::Location location)
3218{
3219 if (msec == nullptr ||
3220 (location != ExtendedTimestamp::LOCATION_SERVER
3221 && location != ExtendedTimestamp::LOCATION_KERNEL)) {
3222 return BAD_VALUE;
3223 }
3224 AutoMutex lock(mLock);
3225 // inclusive of offloaded and direct tracks.
3226 //
3227 // It is possible, but not enabled, to allow duration computation for non-pcm
3228 // audio_has_proportional_frames() formats because currently they have
3229 // the drain rate equivalent to the pcm sample rate * framesize.
3230 if (!isPurePcmData_l()) {
3231 return INVALID_OPERATION;
3232 }
3233 ExtendedTimestamp ets;
3234 if (getTimestamp_l(&ets) == OK
3235 && ets.mTimeNs[location] > 0) {
3236 int64_t diff = ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT]
3237 - ets.mPosition[location];
3238 if (diff < 0) {
3239 *msec = 0;
3240 } else {
3241 // ms is the playback time by frames
3242 int64_t ms = (int64_t)((double)diff * 1000 /
3243 ((double)mSampleRate * mPlaybackRate.mSpeed));
3244 // clockdiff is the timestamp age (negative)
3245 int64_t clockdiff = (mState != STATE_ACTIVE) ? 0 :
3246 ets.mTimeNs[location]
3247 + ets.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_MONOTONIC]
3248 - systemTime(SYSTEM_TIME_MONOTONIC);
3249
3250 //ALOGV("ms: %lld clockdiff: %lld", (long long)ms, (long long)clockdiff);
3251 static const int NANOS_PER_MILLIS = 1000000;
3252 *msec = (int32_t)(ms + clockdiff / NANOS_PER_MILLIS);
3253 }
3254 return NO_ERROR;
3255 }
3256 if (location != ExtendedTimestamp::LOCATION_SERVER) {
3257 return INVALID_OPERATION; // LOCATION_KERNEL is not available
3258 }
3259 // use server position directly (offloaded and direct arrive here)
3260 updateAndGetPosition_l();
3261 int32_t diff = (Modulo<uint32_t>(mFramesWritten) - mPosition).signedValue();
3262 *msec = (diff <= 0) ? 0
3263 : (int32_t)((double)diff * 1000 / ((double)mSampleRate * mPlaybackRate.mSpeed));
3264 return NO_ERROR;
3265}
3266
Andy Hung65ffdfc2016-10-10 15:52:11 -07003267bool AudioTrack::hasStarted()
3268{
3269 AutoMutex lock(mLock);
3270 switch (mState) {
3271 case STATE_STOPPED:
3272 if (isOffloadedOrDirect_l()) {
3273 // check if we have started in the past to return true.
Andy Hungffa36952017-08-17 10:41:51 -07003274 return mStartFromZeroUs > 0;
Andy Hung65ffdfc2016-10-10 15:52:11 -07003275 }
3276 // A normal audio track may still be draining, so
3277 // check if stream has ended. This covers fasttrack position
3278 // instability and start/stop without any data written.
3279 if (mProxy->getStreamEndDone()) {
3280 return true;
3281 }
Chih-Hung Hsiehffe35582018-09-13 13:59:28 -07003282 FALLTHROUGH_INTENDED;
Andy Hung65ffdfc2016-10-10 15:52:11 -07003283 case STATE_ACTIVE:
3284 case STATE_STOPPING:
3285 break;
3286 case STATE_PAUSED:
3287 case STATE_PAUSED_STOPPING:
3288 case STATE_FLUSHED:
3289 return false; // we're not active
3290 default:
Eric Laurent973db022018-11-20 14:54:31 -08003291 LOG_ALWAYS_FATAL("%s(%d): Invalid mState in hasStarted(): %d", __func__, mPortId, mState);
Andy Hung65ffdfc2016-10-10 15:52:11 -07003292 break;
3293 }
3294
3295 // wait indicates whether we need to wait for a timestamp.
3296 // This is conservatively figured - if we encounter an unexpected error
3297 // then we will not wait.
3298 bool wait = false;
3299 if (isOffloadedOrDirect_l()) {
3300 AudioTimestamp ts;
3301 status_t status = getTimestamp_l(ts);
3302 if (status == WOULD_BLOCK) {
3303 wait = true;
3304 } else if (status == OK) {
3305 wait = (ts.mPosition == 0 || ts.mPosition == mStartTs.mPosition);
3306 }
Andy Hungfb8ede22018-09-12 19:03:24 -07003307 ALOGV("%s(%d): hasStarted wait:%d ts:%u start position:%lld",
Eric Laurent973db022018-11-20 14:54:31 -08003308 __func__, mPortId,
Andy Hung65ffdfc2016-10-10 15:52:11 -07003309 (int)wait,
3310 ts.mPosition,
3311 (long long)mStartTs.mPosition);
3312 } else {
3313 int location = ExtendedTimestamp::LOCATION_SERVER; // for ALOG
3314 ExtendedTimestamp ets;
3315 status_t status = getTimestamp_l(&ets);
3316 if (status == WOULD_BLOCK) { // no SERVER or KERNEL frame info in ets
3317 wait = true;
3318 } else if (status == OK) {
3319 for (location = ExtendedTimestamp::LOCATION_KERNEL;
3320 location >= ExtendedTimestamp::LOCATION_SERVER; --location) {
3321 if (ets.mTimeNs[location] < 0 || mStartEts.mTimeNs[location] < 0) {
3322 continue;
3323 }
3324 wait = ets.mPosition[location] == 0
3325 || ets.mPosition[location] == mStartEts.mPosition[location];
3326 break;
3327 }
3328 }
Andy Hungfb8ede22018-09-12 19:03:24 -07003329 ALOGV("%s(%d): hasStarted wait:%d ets:%lld start position:%lld",
Eric Laurent973db022018-11-20 14:54:31 -08003330 __func__, mPortId,
Andy Hung65ffdfc2016-10-10 15:52:11 -07003331 (int)wait,
3332 (long long)ets.mPosition[location],
3333 (long long)mStartEts.mPosition[location]);
3334 }
3335 return !wait;
3336}
3337
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003338// =========================================================================
3339
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08003340void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003341{
3342 sp<AudioTrack> audioTrack = mAudioTrack.promote();
3343 if (audioTrack != 0) {
3344 AutoMutex lock(audioTrack->mLock);
3345 audioTrack->mProxy->binderDied();
3346 }
3347}
3348
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003349// =========================================================================
3350
Andy Hungca353672019-03-06 11:54:38 -08003351AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver)
Andy Hungeb46cf92019-03-06 10:13:38 -08003352 : Thread(true /* bCanCallJava */) // binder recursion on restoreTrack_l() may call Java.
3353 , mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
Glenn Kasten598de6c2013-10-16 17:02:13 -07003354 mIgnoreNextPausedInt(false)
Glenn Kasten3acbd052012-02-28 10:39:56 -08003355{
3356}
3357
3358AudioTrack::AudioTrackThread::~AudioTrackThread()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003359{
3360}
3361
3362bool AudioTrack::AudioTrackThread::threadLoop()
3363{
Glenn Kasten3acbd052012-02-28 10:39:56 -08003364 {
3365 AutoMutex _l(mMyLock);
3366 if (mPaused) {
Glenn Kasten75f79032017-05-23 11:22:44 -07003367 // TODO check return value and handle or log
Glenn Kasten3acbd052012-02-28 10:39:56 -08003368 mMyCond.wait(mMyLock);
3369 // caller will check for exitPending()
3370 return true;
3371 }
Glenn Kasten598de6c2013-10-16 17:02:13 -07003372 if (mIgnoreNextPausedInt) {
3373 mIgnoreNextPausedInt = false;
3374 mPausedInt = false;
3375 }
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003376 if (mPausedInt) {
Glenn Kasten47d55172017-05-23 11:19:30 -07003377 // TODO use futex instead of condition, for event flag "or"
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003378 if (mPausedNs > 0) {
Glenn Kasten75f79032017-05-23 11:22:44 -07003379 // TODO check return value and handle or log
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003380 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
3381 } else {
Glenn Kasten75f79032017-05-23 11:22:44 -07003382 // TODO check return value and handle or log
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003383 mMyCond.wait(mMyLock);
3384 }
Eric Laurent9d2c78c2013-09-23 12:29:42 -07003385 mPausedInt = false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003386 return true;
3387 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08003388 }
Eric Laurent7985dcb2014-10-07 15:45:14 -07003389 if (exitPending()) {
3390 return false;
3391 }
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08003392 nsecs_t ns = mReceiver.processAudioBuffer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003393 switch (ns) {
3394 case 0:
3395 return true;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003396 case NS_INACTIVE:
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003397 pauseInternal();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003398 return true;
3399 case NS_NEVER:
3400 return false;
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003401 case NS_WHENEVER:
Andy Hung3c09c782014-12-29 18:39:32 -08003402 // Event driven: call wake() when callback notifications conditions change.
3403 ns = INT64_MAX;
Chih-Hung Hsiehffe35582018-09-13 13:59:28 -07003404 FALLTHROUGH_INTENDED;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003405 default:
Andy Hungfb8ede22018-09-12 19:03:24 -07003406 LOG_ALWAYS_FATAL_IF(ns < 0, "%s(%d): processAudioBuffer() returned %lld",
Eric Laurent973db022018-11-20 14:54:31 -08003407 __func__, mReceiver.mPortId, (long long)ns);
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003408 pauseInternal(ns);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003409 return true;
Glenn Kastenca8b2802012-04-23 13:58:16 -07003410 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08003411}
3412
Glenn Kasten3acbd052012-02-28 10:39:56 -08003413void AudioTrack::AudioTrackThread::requestExit()
3414{
3415 // must be in this order to avoid a race condition
3416 Thread::requestExit();
Glenn Kasten598de6c2013-10-16 17:02:13 -07003417 resume();
Glenn Kasten3acbd052012-02-28 10:39:56 -08003418}
3419
3420void AudioTrack::AudioTrackThread::pause()
3421{
3422 AutoMutex _l(mMyLock);
3423 mPaused = true;
3424}
3425
3426void AudioTrack::AudioTrackThread::resume()
3427{
3428 AutoMutex _l(mMyLock);
Glenn Kasten598de6c2013-10-16 17:02:13 -07003429 mIgnoreNextPausedInt = true;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07003430 if (mPaused || mPausedInt) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08003431 mPaused = false;
Eric Laurent9d2c78c2013-09-23 12:29:42 -07003432 mPausedInt = false;
Glenn Kasten3acbd052012-02-28 10:39:56 -08003433 mMyCond.signal();
3434 }
3435}
3436
Andy Hung3c09c782014-12-29 18:39:32 -08003437void AudioTrack::AudioTrackThread::wake()
3438{
3439 AutoMutex _l(mMyLock);
Andy Hunga8d08902015-07-22 11:52:13 -07003440 if (!mPaused) {
3441 // wake() might be called while servicing a callback - ignore the next
3442 // pause time and call processAudioBuffer.
Andy Hung3c09c782014-12-29 18:39:32 -08003443 mIgnoreNextPausedInt = true;
Andy Hunga8d08902015-07-22 11:52:13 -07003444 if (mPausedInt && mPausedNs > 0) {
3445 // audio track is active and internally paused with timeout.
3446 mPausedInt = false;
3447 mMyCond.signal();
3448 }
Andy Hung3c09c782014-12-29 18:39:32 -08003449 }
3450}
3451
Glenn Kasten5a6cd222013-09-20 09:20:45 -07003452void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
3453{
3454 AutoMutex _l(mMyLock);
3455 mPausedInt = true;
3456 mPausedNs = ns;
3457}
3458
jiabinf6eb4c32020-02-25 14:06:25 -08003459binder::Status AudioTrack::AudioTrackCallback::onCodecFormatChanged(
3460 const std::vector<uint8_t>& audioMetadata)
3461{
3462 AutoMutex _l(mAudioTrackCbLock);
3463 sp<media::IAudioTrackCallback> callback = mCallback.promote();
3464 if (callback.get() != nullptr) {
3465 callback->onCodecFormatChanged(audioMetadata);
3466 } else {
3467 mCallback.clear();
3468 }
3469 return binder::Status::ok();
3470}
3471
3472void AudioTrack::AudioTrackCallback::setAudioTrackCallback(
3473 const sp<media::IAudioTrackCallback> &callback) {
3474 AutoMutex lock(mAudioTrackCbLock);
3475 mCallback = callback;
3476}
3477
Glenn Kasten40bc9062015-03-20 09:09:33 -07003478} // namespace android