1 /*
2 **
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
18 //#define LOG_NDEBUG 0
19 #define LOG_TAG "AudioTrack"
20
21 #include <inttypes.h>
22 #include <math.h>
23 #include <sys/resource.h>
24 #include <thread>
25
26 #include <android/media/IAudioPolicyService.h>
27 #include <android-base/macros.h>
28 #include <android-base/stringprintf.h>
29 #include <audio_utils/clock.h>
30 #include <audio_utils/primitives.h>
31 #include <binder/IPCThreadState.h>
32 #include <media/AudioTrack.h>
33 #include <utils/Log.h>
34 #include <private/media/AudioTrackShared.h>
35 #include <processgroup/sched_policy.h>
36 #include <media/IAudioFlinger.h>
37 #include <media/AudioParameter.h>
38 #include <media/AudioResamplerPublic.h>
39 #include <media/AudioSystem.h>
40 #include <media/MediaMetricsItem.h>
41 #include <media/TypeConverter.h>
42
43 #define WAIT_PERIOD_MS 10
44 #define WAIT_STREAM_END_TIMEOUT_SEC 120
45 static const int kMaxLoopCountNotifications = 32;
46
47 using ::android::aidl_utils::statusTFromBinderStatus;
48 using ::android::base::StringPrintf;
49
50 namespace android {
51 // ---------------------------------------------------------------------------
52
53 using media::VolumeShaper;
54 using android::content::AttributionSourceState;
55
56 // TODO: Move to a separate .h
57
58 template <typename T>
min(const T & x,const T & y)59 static inline const T &min(const T &x, const T &y) {
60 return x < y ? x : y;
61 }
62
63 template <typename T>
max(const T & x,const T & y)64 static inline const T &max(const T &x, const T &y) {
65 return x > y ? x : y;
66 }
67
framesToNanoseconds(ssize_t frames,uint32_t sampleRate,float speed)68 static inline nsecs_t framesToNanoseconds(ssize_t frames, uint32_t sampleRate, float speed)
69 {
70 return ((double)frames * 1000000000) / ((double)sampleRate * speed);
71 }
72
convertTimespecToUs(const struct timespec & tv)73 static int64_t convertTimespecToUs(const struct timespec &tv)
74 {
75 return tv.tv_sec * 1000000LL + tv.tv_nsec / 1000;
76 }
77
78 // TODO move to audio_utils.
convertNsToTimespec(int64_t ns)79 static inline struct timespec convertNsToTimespec(int64_t ns) {
80 struct timespec tv;
81 tv.tv_sec = static_cast<time_t>(ns / NANOS_PER_SECOND);
82 tv.tv_nsec = static_cast<int64_t>(ns % NANOS_PER_SECOND);
83 return tv;
84 }
85
86 // current monotonic time in microseconds.
getNowUs()87 static int64_t getNowUs()
88 {
89 struct timespec tv;
90 (void) clock_gettime(CLOCK_MONOTONIC, &tv);
91 return convertTimespecToUs(tv);
92 }
93
94 // FIXME: we don't use the pitch setting in the time stretcher (not working);
95 // instead we emulate it using our sample rate converter.
96 static const bool kFixPitch = true; // enable pitch fix
adjustSampleRate(uint32_t sampleRate,float pitch)97 static inline uint32_t adjustSampleRate(uint32_t sampleRate, float pitch)
98 {
99 return kFixPitch ? (sampleRate * pitch + 0.5) : sampleRate;
100 }
101
adjustSpeed(float speed,float pitch)102 static inline float adjustSpeed(float speed, float pitch)
103 {
104 return kFixPitch ? speed / max(pitch, AUDIO_TIMESTRETCH_PITCH_MIN_DELTA) : speed;
105 }
106
adjustPitch(float pitch)107 static inline float adjustPitch(float pitch)
108 {
109 return kFixPitch ? AUDIO_TIMESTRETCH_PITCH_NORMAL : pitch;
110 }
111
112 // static
getMinFrameCount(size_t * frameCount,audio_stream_type_t streamType,uint32_t sampleRate)113 status_t AudioTrack::getMinFrameCount(
114 size_t* frameCount,
115 audio_stream_type_t streamType,
116 uint32_t sampleRate)
117 {
118 if (frameCount == NULL) {
119 return BAD_VALUE;
120 }
121
122 // FIXME handle in server, like createTrack_l(), possible missing info:
123 // audio_io_handle_t output
124 // audio_format_t format
125 // audio_channel_mask_t channelMask
126 // audio_output_flags_t flags (FAST)
127 uint32_t afSampleRate;
128 status_t status;
129 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
130 if (status != NO_ERROR) {
131 ALOGE("%s(): Unable to query output sample rate for stream type %d; status %d",
132 __func__, streamType, status);
133 return status;
134 }
135 size_t afFrameCount;
136 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
137 if (status != NO_ERROR) {
138 ALOGE("%s(): Unable to query output frame count for stream type %d; status %d",
139 __func__, streamType, status);
140 return status;
141 }
142 uint32_t afLatency;
143 status = AudioSystem::getOutputLatency(&afLatency, streamType);
144 if (status != NO_ERROR) {
145 ALOGE("%s(): Unable to query output latency for stream type %d; status %d",
146 __func__, streamType, status);
147 return status;
148 }
149
150 // When called from createTrack, speed is 1.0f (normal speed).
151 // This is rechecked again on setting playback rate (TODO: on setting sample rate, too).
152 *frameCount = AudioSystem::calculateMinFrameCount(afLatency, afFrameCount, afSampleRate,
153 sampleRate, 1.0f /*, 0 notificationsPerBufferReq*/);
154
155 // The formula above should always produce a non-zero value under normal circumstances:
156 // AudioTrack.SAMPLE_RATE_HZ_MIN <= sampleRate <= AudioTrack.SAMPLE_RATE_HZ_MAX.
157 // Return error in the unlikely event that it does not, as that's part of the API contract.
158 if (*frameCount == 0) {
159 ALOGE("%s(): failed for streamType %d, sampleRate %u",
160 __func__, streamType, sampleRate);
161 return BAD_VALUE;
162 }
163 ALOGV("%s(): getMinFrameCount=%zu: afFrameCount=%zu, afSampleRate=%u, afLatency=%u",
164 __func__, *frameCount, afFrameCount, afSampleRate, afLatency);
165 return NO_ERROR;
166 }
167
168 // static
isDirectOutputSupported(const audio_config_base_t & config,const audio_attributes_t & attributes)169 bool AudioTrack::isDirectOutputSupported(const audio_config_base_t& config,
170 const audio_attributes_t& attributes) {
171 ALOGV("%s()", __FUNCTION__);
172 const sp<media::IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
173 if (aps == 0) return false;
174
175 auto result = [&]() -> ConversionResult<bool> {
176 media::AudioConfigBase configAidl = VALUE_OR_RETURN(
177 legacy2aidl_audio_config_base_t_AudioConfigBase(config));
178 media::AudioAttributesInternal attributesAidl = VALUE_OR_RETURN(
179 legacy2aidl_audio_attributes_t_AudioAttributesInternal(attributes));
180 bool retAidl;
181 RETURN_IF_ERROR(aidl_utils::statusTFromBinderStatus(
182 aps->isDirectOutputSupported(configAidl, attributesAidl, &retAidl)));
183 return retAidl;
184 }();
185 return result.value_or(false);
186 }
187
188 // ---------------------------------------------------------------------------
189
gather(const AudioTrack * track)190 void AudioTrack::MediaMetrics::gather(const AudioTrack *track)
191 {
192 // only if we're in a good state...
193 // XXX: shall we gather alternative info if failing?
194 const status_t lstatus = track->initCheck();
195 if (lstatus != NO_ERROR) {
196 ALOGD("%s(): no metrics gathered, track status=%d", __func__, (int) lstatus);
197 return;
198 }
199
200 #define MM_PREFIX "android.media.audiotrack." // avoid cut-n-paste errors.
201
202 // Do not change this without changing the MediaMetricsService side.
203 // Java API 28 entries, do not change.
204 mMetricsItem->setCString(MM_PREFIX "streamtype", toString(track->streamType()).c_str());
205 mMetricsItem->setCString(MM_PREFIX "type",
206 toString(track->mAttributes.content_type).c_str());
207 mMetricsItem->setCString(MM_PREFIX "usage", toString(track->mAttributes.usage).c_str());
208
209 // Non-API entries, these can change due to a Java string mistake.
210 mMetricsItem->setInt32(MM_PREFIX "sampleRate", (int32_t)track->mSampleRate);
211 mMetricsItem->setInt64(MM_PREFIX "channelMask", (int64_t)track->mChannelMask);
212 // Non-API entries, these can change.
213 mMetricsItem->setInt32(MM_PREFIX "portId", (int32_t)track->mPortId);
214 mMetricsItem->setCString(MM_PREFIX "encoding", toString(track->mFormat).c_str());
215 mMetricsItem->setInt32(MM_PREFIX "frameCount", (int32_t)track->mFrameCount);
216 mMetricsItem->setCString(MM_PREFIX "attributes", toString(track->mAttributes).c_str());
217 mMetricsItem->setCString(MM_PREFIX "logSessionId", track->mLogSessionId.c_str());
218 mMetricsItem->setInt32(MM_PREFIX "underrunFrames", (int32_t)track->getUnderrunFrames());
219 }
220
221 // hand the user a snapshot of the metrics.
getMetrics(mediametrics::Item * & item)222 status_t AudioTrack::getMetrics(mediametrics::Item * &item)
223 {
224 mMediaMetrics.gather(this);
225 mediametrics::Item *tmp = mMediaMetrics.dup();
226 if (tmp == nullptr) {
227 return BAD_VALUE;
228 }
229 item = tmp;
230 return NO_ERROR;
231 }
232
AudioTrack()233 AudioTrack::AudioTrack() : AudioTrack(AttributionSourceState())
234 {
235 }
236
AudioTrack(const AttributionSourceState & attributionSource)237 AudioTrack::AudioTrack(const AttributionSourceState& attributionSource)
238 : mStatus(NO_INIT),
239 mState(STATE_STOPPED),
240 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
241 mPreviousSchedulingGroup(SP_DEFAULT),
242 mPausedPosition(0),
243 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
244 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
245 mClientAttributionSource(attributionSource),
246 mAudioTrackCallback(new AudioTrackCallback())
247 {
248 mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
249 mAttributes.usage = AUDIO_USAGE_UNKNOWN;
250 mAttributes.flags = AUDIO_FLAG_NONE;
251 strcpy(mAttributes.tags, "");
252 }
253
AudioTrack(audio_stream_type_t streamType,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t frameCount,audio_output_flags_t flags,callback_t cbf,void * user,int32_t notificationFrames,audio_session_t sessionId,transfer_type transferType,const audio_offload_info_t * offloadInfo,const AttributionSourceState & attributionSource,const audio_attributes_t * pAttributes,bool doNotReconnect,float maxRequiredSpeed,audio_port_handle_t selectedDeviceId)254 AudioTrack::AudioTrack(
255 audio_stream_type_t streamType,
256 uint32_t sampleRate,
257 audio_format_t format,
258 audio_channel_mask_t channelMask,
259 size_t frameCount,
260 audio_output_flags_t flags,
261 callback_t cbf,
262 void* user,
263 int32_t notificationFrames,
264 audio_session_t sessionId,
265 transfer_type transferType,
266 const audio_offload_info_t *offloadInfo,
267 const AttributionSourceState& attributionSource,
268 const audio_attributes_t* pAttributes,
269 bool doNotReconnect,
270 float maxRequiredSpeed,
271 audio_port_handle_t selectedDeviceId)
272 : mStatus(NO_INIT),
273 mState(STATE_STOPPED),
274 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
275 mPreviousSchedulingGroup(SP_DEFAULT),
276 mPausedPosition(0),
277 mAudioTrackCallback(new AudioTrackCallback())
278 {
279 mAttributes = AUDIO_ATTRIBUTES_INITIALIZER;
280
281 (void)set(streamType, sampleRate, format, channelMask,
282 frameCount, flags, cbf, user, notificationFrames,
283 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
284 attributionSource, pAttributes, doNotReconnect, maxRequiredSpeed, selectedDeviceId);
285 }
286
AudioTrack(audio_stream_type_t streamType,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,const sp<IMemory> & sharedBuffer,audio_output_flags_t flags,callback_t cbf,void * user,int32_t notificationFrames,audio_session_t sessionId,transfer_type transferType,const audio_offload_info_t * offloadInfo,const AttributionSourceState & attributionSource,const audio_attributes_t * pAttributes,bool doNotReconnect,float maxRequiredSpeed)287 AudioTrack::AudioTrack(
288 audio_stream_type_t streamType,
289 uint32_t sampleRate,
290 audio_format_t format,
291 audio_channel_mask_t channelMask,
292 const sp<IMemory>& sharedBuffer,
293 audio_output_flags_t flags,
294 callback_t cbf,
295 void* user,
296 int32_t notificationFrames,
297 audio_session_t sessionId,
298 transfer_type transferType,
299 const audio_offload_info_t *offloadInfo,
300 const AttributionSourceState& attributionSource,
301 const audio_attributes_t* pAttributes,
302 bool doNotReconnect,
303 float maxRequiredSpeed)
304 : mStatus(NO_INIT),
305 mState(STATE_STOPPED),
306 mPreviousPriority(ANDROID_PRIORITY_NORMAL),
307 mPreviousSchedulingGroup(SP_DEFAULT),
308 mPausedPosition(0),
309 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
310 mAudioTrackCallback(new AudioTrackCallback())
311 {
312 mAttributes = AUDIO_ATTRIBUTES_INITIALIZER;
313
314 (void)set(streamType, sampleRate, format, channelMask,
315 0 /*frameCount*/, flags, cbf, user, notificationFrames,
316 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
317 attributionSource, pAttributes, doNotReconnect, maxRequiredSpeed);
318 }
319
~AudioTrack()320 AudioTrack::~AudioTrack()
321 {
322 // pull together the numbers, before we clean up our structures
323 mMediaMetrics.gather(this);
324
325 mediametrics::LogItem(mMetricsId)
326 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DTOR)
327 .set(AMEDIAMETRICS_PROP_CALLERNAME,
328 mCallerName.empty()
329 ? AMEDIAMETRICS_PROP_CALLERNAME_VALUE_UNKNOWN
330 : mCallerName.c_str())
331 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
332 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)mStatus)
333 .record();
334
335 stopAndJoinCallbacks(); // checks mStatus
336
337 if (mStatus == NO_ERROR) {
338 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
339 mAudioTrack.clear();
340 mCblkMemory.clear();
341 mSharedBuffer.clear();
342 IPCThreadState::self()->flushCommands();
343 pid_t clientPid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mClientAttributionSource.pid));
344 ALOGV("%s(%d), releasing session id %d from %d on behalf of %d",
345 __func__, mPortId,
346 mSessionId, IPCThreadState::self()->getCallingPid(), clientPid);
347 AudioSystem::releaseAudioSessionId(mSessionId, clientPid);
348 }
349 }
350
stopAndJoinCallbacks()351 void AudioTrack::stopAndJoinCallbacks() {
352 // Prevent nullptr crash if it did not open properly.
353 if (mStatus != NO_ERROR) return;
354
355 // Make sure that callback function exits in the case where
356 // it is looping on buffer full condition in obtainBuffer().
357 // Otherwise the callback thread will never exit.
358 stop();
359 if (mAudioTrackThread != 0) { // not thread safe
360 mProxy->interrupt();
361 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
362 mAudioTrackThread->requestExitAndWait();
363 mAudioTrackThread.clear();
364 }
365 // No lock here: worst case we remove a NULL callback which will be a nop
366 if (mDeviceCallback != 0 && mOutput != AUDIO_IO_HANDLE_NONE) {
367 // This may not stop all of these device callbacks!
368 // TODO: Add some sort of protection.
369 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
370 mDeviceCallback.clear();
371 }
372 }
373
set(audio_stream_type_t streamType,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t frameCount,audio_output_flags_t flags,callback_t cbf,void * user,int32_t notificationFrames,const sp<IMemory> & sharedBuffer,bool threadCanCallJava,audio_session_t sessionId,transfer_type transferType,const audio_offload_info_t * offloadInfo,const AttributionSourceState & attributionSource,const audio_attributes_t * pAttributes,bool doNotReconnect,float maxRequiredSpeed,audio_port_handle_t selectedDeviceId)374 status_t AudioTrack::set(
375 audio_stream_type_t streamType,
376 uint32_t sampleRate,
377 audio_format_t format,
378 audio_channel_mask_t channelMask,
379 size_t frameCount,
380 audio_output_flags_t flags,
381 callback_t cbf,
382 void* user,
383 int32_t notificationFrames,
384 const sp<IMemory>& sharedBuffer,
385 bool threadCanCallJava,
386 audio_session_t sessionId,
387 transfer_type transferType,
388 const audio_offload_info_t *offloadInfo,
389 const AttributionSourceState& attributionSource,
390 const audio_attributes_t* pAttributes,
391 bool doNotReconnect,
392 float maxRequiredSpeed,
393 audio_port_handle_t selectedDeviceId)
394 {
395 status_t status;
396 uint32_t channelCount;
397 pid_t callingPid;
398 pid_t myPid;
399 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
400 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
401 std::string errorMessage;
402
403 // Note mPortId is not valid until the track is created, so omit mPortId in ALOG for set.
404 ALOGV("%s(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
405 "flags #%x, notificationFrames %d, sessionId %d, transferType %d, uid %d, pid %d",
406 __func__,
407 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
408 sessionId, transferType, attributionSource.uid, attributionSource.pid);
409
410 mThreadCanCallJava = threadCanCallJava;
411
412 // These variables are pulled in an error report, so we initialize them early.
413 mSelectedDeviceId = selectedDeviceId;
414 mSessionId = sessionId;
415 mChannelMask = channelMask;
416 mReqFrameCount = mFrameCount = frameCount;
417 mSampleRate = sampleRate;
418 mOriginalSampleRate = sampleRate;
419 mAttributes = pAttributes != nullptr ? *pAttributes : AUDIO_ATTRIBUTES_INITIALIZER;
420 mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT;
421
422 // update format and flags before storing them in mFormat, mOrigFlags and mFlags
423 if (pAttributes != NULL) {
424 // stream type shouldn't be looked at, this track has audio attributes
425 ALOGV("%s(): Building AudioTrack with attributes:"
426 " usage=%d content=%d flags=0x%x tags=[%s]",
427 __func__,
428 mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
429 audio_flags_to_audio_output_flags(mAttributes.flags, &flags);
430 }
431
432 // these below should probably come from the audioFlinger too...
433 if (format == AUDIO_FORMAT_DEFAULT) {
434 format = AUDIO_FORMAT_PCM_16_BIT;
435 } else if (format == AUDIO_FORMAT_IEC61937) { // HDMI pass-through?
436 flags = static_cast<audio_output_flags_t>(flags | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
437 }
438
439 // force direct flag if format is not linear PCM
440 // or offload was requested
441 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
442 || !audio_is_linear_pcm(format)) {
443 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
444 ? "%s(): Offload request, forcing to Direct Output"
445 : "%s(): Not linear PCM, forcing to Direct Output",
446 __func__);
447 flags = (audio_output_flags_t)
448 // FIXME why can't we allow direct AND fast?
449 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
450 }
451
452 // force direct flag if HW A/V sync requested
453 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
454 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
455 }
456
457 mFormat = format;
458 mOrigFlags = mFlags = flags;
459
460 switch (transferType) {
461 case TRANSFER_DEFAULT:
462 if (sharedBuffer != 0) {
463 transferType = TRANSFER_SHARED;
464 } else if (cbf == NULL || threadCanCallJava) {
465 transferType = TRANSFER_SYNC;
466 } else {
467 transferType = TRANSFER_CALLBACK;
468 }
469 break;
470 case TRANSFER_CALLBACK:
471 case TRANSFER_SYNC_NOTIF_CALLBACK:
472 if (cbf == NULL || sharedBuffer != 0) {
473 errorMessage = StringPrintf(
474 "%s: Transfer type %s but cbf == NULL || sharedBuffer != 0",
475 convertTransferToText(transferType), __func__);
476 status = BAD_VALUE;
477 goto error;
478 }
479 break;
480 case TRANSFER_OBTAIN:
481 case TRANSFER_SYNC:
482 if (sharedBuffer != 0) {
483 errorMessage = StringPrintf(
484 "%s: Transfer type TRANSFER_OBTAIN but sharedBuffer != 0", __func__);
485 status = BAD_VALUE;
486 goto error;
487 }
488 break;
489 case TRANSFER_SHARED:
490 if (sharedBuffer == 0) {
491 errorMessage = StringPrintf(
492 "%s: Transfer type TRANSFER_SHARED but sharedBuffer == 0", __func__);
493 status = BAD_VALUE;
494 goto error;
495 }
496 break;
497 default:
498 errorMessage = StringPrintf("%s: Invalid transfer type %d", __func__, transferType);
499 status = BAD_VALUE;
500 goto error;
501 }
502 mSharedBuffer = sharedBuffer;
503 mTransfer = transferType;
504 mDoNotReconnect = doNotReconnect;
505
506 ALOGV_IF(sharedBuffer != 0, "%s(): sharedBuffer: %p, size: %zu",
507 __func__, sharedBuffer->unsecurePointer(), sharedBuffer->size());
508
509 // invariant that mAudioTrack != 0 is true only after set() returns successfully
510 if (mAudioTrack != 0) {
511 errorMessage = StringPrintf("%s: Track already in use", __func__);
512 status = INVALID_OPERATION;
513 goto error;
514 }
515
516 // handle default values first.
517 if (streamType == AUDIO_STREAM_DEFAULT) {
518 streamType = AUDIO_STREAM_MUSIC;
519 }
520 if (pAttributes == NULL) {
521 if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
522 errorMessage = StringPrintf("%s: Invalid stream type %d", __func__, streamType);
523 status = BAD_VALUE;
524 goto error;
525 }
526 mOriginalStreamType = streamType;
527 } else {
528 mOriginalStreamType = AUDIO_STREAM_DEFAULT;
529 }
530
531 // validate parameters
532 if (!audio_is_valid_format(format)) {
533 errorMessage = StringPrintf("%s: Invalid format %#x", __func__, format);
534 status = BAD_VALUE;
535 goto error;
536 }
537
538 if (!audio_is_output_channel(channelMask)) {
539 errorMessage = StringPrintf("%s: Invalid channel mask %#x", __func__, channelMask);
540 status = BAD_VALUE;
541 goto error;
542 }
543 channelCount = audio_channel_count_from_out_mask(channelMask);
544 mChannelCount = channelCount;
545
546 if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
547 if (audio_has_proportional_frames(format)) {
548 mFrameSize = channelCount * audio_bytes_per_sample(format);
549 } else {
550 mFrameSize = sizeof(uint8_t);
551 }
552 } else {
553 ALOG_ASSERT(audio_has_proportional_frames(format));
554 mFrameSize = channelCount * audio_bytes_per_sample(format);
555 // createTrack will return an error if PCM format is not supported by server,
556 // so no need to check for specific PCM formats here
557 }
558
559 // sampling rate must be specified for direct outputs
560 if (sampleRate == 0 && (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
561 errorMessage = StringPrintf(
562 "%s: sample rate must be specified for direct outputs", __func__);
563 status = BAD_VALUE;
564 goto error;
565 }
566 // 1.0 <= mMaxRequiredSpeed <= AUDIO_TIMESTRETCH_SPEED_MAX
567 mMaxRequiredSpeed = min(max(maxRequiredSpeed, 1.0f), AUDIO_TIMESTRETCH_SPEED_MAX);
568
569 // Make copy of input parameter offloadInfo so that in the future:
570 // (a) createTrack_l doesn't need it as an input parameter
571 // (b) we can support re-creation of offloaded tracks
572 if (offloadInfo != NULL) {
573 mOffloadInfoCopy = *offloadInfo;
574 mOffloadInfo = &mOffloadInfoCopy;
575 } else {
576 mOffloadInfo = NULL;
577 memset(&mOffloadInfoCopy, 0, sizeof(audio_offload_info_t));
578 mOffloadInfoCopy = AUDIO_INFO_INITIALIZER;
579 }
580
581 mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
582 mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
583 mSendLevel = 0.0f;
584 // mFrameCount is initialized in createTrack_l
585 if (notificationFrames >= 0) {
586 mNotificationFramesReq = notificationFrames;
587 mNotificationsPerBufferReq = 0;
588 } else {
589 if (!(mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
590 errorMessage = StringPrintf(
591 "%s: notificationFrames=%d not permitted for non-fast track",
592 __func__, notificationFrames);
593 status = BAD_VALUE;
594 goto error;
595 }
596 if (frameCount > 0) {
597 ALOGE("%s(): notificationFrames=%d not permitted with non-zero frameCount=%zu",
598 __func__, notificationFrames, frameCount);
599 status = BAD_VALUE;
600 goto error;
601 }
602 mNotificationFramesReq = 0;
603 const uint32_t minNotificationsPerBuffer = 1;
604 const uint32_t maxNotificationsPerBuffer = 8;
605 mNotificationsPerBufferReq = min(maxNotificationsPerBuffer,
606 max((uint32_t) -notificationFrames, minNotificationsPerBuffer));
607 ALOGW_IF(mNotificationsPerBufferReq != (uint32_t) -notificationFrames,
608 "%s(): notificationFrames=%d clamped to the range -%u to -%u",
609 __func__,
610 notificationFrames, minNotificationsPerBuffer, maxNotificationsPerBuffer);
611 }
612 mNotificationFramesAct = 0;
613 // TODO b/182392553: refactor or remove
614 mClientAttributionSource = AttributionSourceState(attributionSource);
615 callingPid = IPCThreadState::self()->getCallingPid();
616 myPid = getpid();
617 if (uid == -1 || (callingPid != myPid)) {
618 mClientAttributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
619 IPCThreadState::self()->getCallingUid()));
620 }
621 if (pid == (pid_t)-1 || (callingPid != myPid)) {
622 mClientAttributionSource.pid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(callingPid));
623 }
624 mAuxEffectId = 0;
625 mCbf = cbf;
626
627 if (cbf != NULL) {
628 mAudioTrackThread = new AudioTrackThread(*this);
629 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
630 // thread begins in paused state, and will not reference us until start()
631 }
632
633 // create the IAudioTrack
634 {
635 AutoMutex lock(mLock);
636 status = createTrack_l();
637 }
638 if (status != NO_ERROR) {
639 if (mAudioTrackThread != 0) {
640 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h
641 mAudioTrackThread->requestExitAndWait();
642 mAudioTrackThread.clear();
643 }
644 // We do not goto error to prevent double-logging errors.
645 goto exit;
646 }
647
648 mUserData = user;
649 mLoopCount = 0;
650 mLoopStart = 0;
651 mLoopEnd = 0;
652 mLoopCountNotified = 0;
653 mMarkerPosition = 0;
654 mMarkerReached = false;
655 mNewPosition = 0;
656 mUpdatePeriod = 0;
657 mPosition = 0;
658 mReleased = 0;
659 mStartNs = 0;
660 mStartFromZeroUs = 0;
661 AudioSystem::acquireAudioSessionId(mSessionId, pid, uid);
662 mSequence = 1;
663 mObservedSequence = mSequence;
664 mInUnderrun = false;
665 mPreviousTimestampValid = false;
666 mTimestampStartupGlitchReported = false;
667 mTimestampRetrogradePositionReported = false;
668 mTimestampRetrogradeTimeReported = false;
669 mTimestampStallReported = false;
670 mTimestampStaleTimeReported = false;
671 mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
672 mStartTs.mPosition = 0;
673 mUnderrunCountOffset = 0;
674 mFramesWritten = 0;
675 mFramesWrittenServerOffset = 0;
676 mFramesWrittenAtRestore = -1; // -1 is a unique initializer.
677 mVolumeHandler = new media::VolumeHandler();
678
679 error:
680 if (status != NO_ERROR) {
681 ALOGE_IF(!errorMessage.empty(), "%s", errorMessage.c_str());
682 reportError(status, AMEDIAMETRICS_PROP_EVENT_VALUE_CREATE, errorMessage.c_str());
683 }
684 // fall through
685 exit:
686 mStatus = status;
687 return status;
688 }
689
690
set(audio_stream_type_t streamType,uint32_t sampleRate,audio_format_t format,uint32_t channelMask,size_t frameCount,audio_output_flags_t flags,callback_t cbf,void * user,int32_t notificationFrames,const sp<IMemory> & sharedBuffer,bool threadCanCallJava,audio_session_t sessionId,transfer_type transferType,const audio_offload_info_t * offloadInfo,uid_t uid,pid_t pid,const audio_attributes_t * pAttributes,bool doNotReconnect,float maxRequiredSpeed,audio_port_handle_t selectedDeviceId)691 status_t AudioTrack::set(
692 audio_stream_type_t streamType,
693 uint32_t sampleRate,
694 audio_format_t format,
695 uint32_t channelMask,
696 size_t frameCount,
697 audio_output_flags_t flags,
698 callback_t cbf,
699 void* user,
700 int32_t notificationFrames,
701 const sp<IMemory>& sharedBuffer,
702 bool threadCanCallJava,
703 audio_session_t sessionId,
704 transfer_type transferType,
705 const audio_offload_info_t *offloadInfo,
706 uid_t uid,
707 pid_t pid,
708 const audio_attributes_t* pAttributes,
709 bool doNotReconnect,
710 float maxRequiredSpeed,
711 audio_port_handle_t selectedDeviceId)
712 {
713 AttributionSourceState attributionSource;
714 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(uid));
715 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(pid));
716 attributionSource.token = sp<BBinder>::make();
717 return set(streamType, sampleRate, format,
718 static_cast<audio_channel_mask_t>(channelMask),
719 frameCount, flags, cbf, user, notificationFrames, sharedBuffer,
720 threadCanCallJava, sessionId, transferType, offloadInfo, attributionSource,
721 pAttributes, doNotReconnect, maxRequiredSpeed, selectedDeviceId);
722 }
723
724 // -------------------------------------------------------------------------
725
start()726 status_t AudioTrack::start()
727 {
728 AutoMutex lock(mLock);
729
730 if (mState == STATE_ACTIVE) {
731 return INVALID_OPERATION;
732 }
733
734 ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
735
736 // Defer logging here due to OpenSL ES repeated start calls.
737 // TODO(b/154868033) after fix, restore this logging back to the beginning of start().
738 const int64_t beginNs = systemTime();
739 status_t status = NO_ERROR; // logged: make sure to set this before returning.
740 mediametrics::Defer defer([&] {
741 mediametrics::LogItem(mMetricsId)
742 .set(AMEDIAMETRICS_PROP_CALLERNAME,
743 mCallerName.empty()
744 ? AMEDIAMETRICS_PROP_CALLERNAME_VALUE_UNKNOWN
745 : mCallerName.c_str())
746 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_START)
747 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
748 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
749 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)status)
750 .record(); });
751
752
753 mInUnderrun = true;
754
755 State previousState = mState;
756 if (previousState == STATE_PAUSED_STOPPING) {
757 mState = STATE_STOPPING;
758 } else {
759 mState = STATE_ACTIVE;
760 }
761 (void) updateAndGetPosition_l();
762
763 // save start timestamp
764 if (isOffloadedOrDirect_l()) {
765 if (getTimestamp_l(mStartTs) != OK) {
766 mStartTs.mPosition = 0;
767 }
768 } else {
769 if (getTimestamp_l(&mStartEts) != OK) {
770 mStartEts.clear();
771 }
772 }
773 mStartNs = systemTime(); // save this for timestamp adjustment after starting.
774 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
775 // reset current position as seen by client to 0
776 mPosition = 0;
777 mPreviousTimestampValid = false;
778 mTimestampStartupGlitchReported = false;
779 mTimestampRetrogradePositionReported = false;
780 mTimestampRetrogradeTimeReported = false;
781 mTimestampStallReported = false;
782 mTimestampStaleTimeReported = false;
783 mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
784
785 if (!isOffloadedOrDirect_l()
786 && mStartEts.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] > 0) {
787 // Server side has consumed something, but is it finished consuming?
788 // It is possible since flush and stop are asynchronous that the server
789 // is still active at this point.
790 ALOGV("%s(%d): server read:%lld cumulative flushed:%lld client written:%lld",
791 __func__, mPortId,
792 (long long)(mFramesWrittenServerOffset
793 + mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER]),
794 (long long)mStartEts.mFlushed,
795 (long long)mFramesWritten);
796 // mStartEts is already adjusted by mFramesWrittenServerOffset, so we delta adjust.
797 mFramesWrittenServerOffset -= mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER];
798 }
799 mFramesWritten = 0;
800 mProxy->clearTimestamp(); // need new server push for valid timestamp
801 mMarkerReached = false;
802
803 // For offloaded tracks, we don't know if the hardware counters are really zero here,
804 // since the flush is asynchronous and stop may not fully drain.
805 // We save the time when the track is started to later verify whether
806 // the counters are realistic (i.e. start from zero after this time).
807 mStartFromZeroUs = mStartNs / 1000;
808
809 // force refresh of remaining frames by processAudioBuffer() as last
810 // write before stop could be partial.
811 mRefreshRemaining = true;
812
813 // for static track, clear the old flags when starting from stopped state
814 if (mSharedBuffer != 0) {
815 android_atomic_and(
816 ~(CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
817 &mCblk->mFlags);
818 }
819 }
820 mNewPosition = mPosition + mUpdatePeriod;
821 int32_t flags = android_atomic_and(~(CBLK_STREAM_END_DONE | CBLK_DISABLED), &mCblk->mFlags);
822
823 if (!(flags & CBLK_INVALID)) {
824 mAudioTrack->start(&status);
825 if (status == DEAD_OBJECT) {
826 flags |= CBLK_INVALID;
827 }
828 }
829 if (flags & CBLK_INVALID) {
830 status = restoreTrack_l("start");
831 }
832
833 // resume or pause the callback thread as needed.
834 sp<AudioTrackThread> t = mAudioTrackThread;
835 if (status == NO_ERROR) {
836 if (t != 0) {
837 if (previousState == STATE_STOPPING) {
838 mProxy->interrupt();
839 } else {
840 t->resume();
841 }
842 } else {
843 mPreviousPriority = getpriority(PRIO_PROCESS, 0);
844 get_sched_policy(0, &mPreviousSchedulingGroup);
845 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
846 }
847
848 // Start our local VolumeHandler for restoration purposes.
849 mVolumeHandler->setStarted();
850 } else {
851 ALOGE("%s(%d): status %d", __func__, mPortId, status);
852 mState = previousState;
853 if (t != 0) {
854 if (previousState != STATE_STOPPING) {
855 t->pause();
856 }
857 } else {
858 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
859 set_sched_policy(0, mPreviousSchedulingGroup);
860 }
861 }
862
863 return status;
864 }
865
stop()866 void AudioTrack::stop()
867 {
868 const int64_t beginNs = systemTime();
869
870 AutoMutex lock(mLock);
871 mediametrics::Defer defer([&]() {
872 mediametrics::LogItem(mMetricsId)
873 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_STOP)
874 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
875 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
876 .set(AMEDIAMETRICS_PROP_BUFFERSIZEFRAMES, (int32_t)mProxy->getBufferSizeInFrames())
877 .set(AMEDIAMETRICS_PROP_UNDERRUN, (int32_t) getUnderrunCount_l())
878 .record();
879 });
880
881 ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
882
883 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
884 return;
885 }
886
887 if (isOffloaded_l()) {
888 mState = STATE_STOPPING;
889 } else {
890 mState = STATE_STOPPED;
891 ALOGD_IF(mSharedBuffer == nullptr,
892 "%s(%d): called with %u frames delivered", __func__, mPortId, mReleased.value());
893 mReleased = 0;
894 }
895
896 mProxy->stop(); // notify server not to read beyond current client position until start().
897 mProxy->interrupt();
898 mAudioTrack->stop();
899
900 // Note: legacy handling - stop does not clear playback marker
901 // and periodic update counter, but flush does for streaming tracks.
902
903 if (mSharedBuffer != 0) {
904 // clear buffer position and loop count.
905 mStaticProxy->setBufferPositionAndLoop(0 /* position */,
906 0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
907 }
908
909 sp<AudioTrackThread> t = mAudioTrackThread;
910 if (t != 0) {
911 if (!isOffloaded_l()) {
912 t->pause();
913 } else if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
914 // causes wake up of the playback thread, that will callback the client for
915 // EVENT_STREAM_END in processAudioBuffer()
916 t->wake();
917 }
918 } else {
919 setpriority(PRIO_PROCESS, 0, mPreviousPriority);
920 set_sched_policy(0, mPreviousSchedulingGroup);
921 }
922 }
923
stopped() const924 bool AudioTrack::stopped() const
925 {
926 AutoMutex lock(mLock);
927 return mState != STATE_ACTIVE;
928 }
929
flush()930 void AudioTrack::flush()
931 {
932 const int64_t beginNs = systemTime();
933 AutoMutex lock(mLock);
934 mediametrics::Defer defer([&]() {
935 mediametrics::LogItem(mMetricsId)
936 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_FLUSH)
937 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
938 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
939 .record(); });
940
941 ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
942
943 if (mSharedBuffer != 0) {
944 return;
945 }
946 if (mState == STATE_ACTIVE) {
947 return;
948 }
949 flush_l();
950 }
951
flush_l()952 void AudioTrack::flush_l()
953 {
954 ALOG_ASSERT(mState != STATE_ACTIVE);
955
956 // clear playback marker and periodic update counter
957 mMarkerPosition = 0;
958 mMarkerReached = false;
959 mUpdatePeriod = 0;
960 mRefreshRemaining = true;
961
962 mState = STATE_FLUSHED;
963 mReleased = 0;
964 if (isOffloaded_l()) {
965 mProxy->interrupt();
966 }
967 mProxy->flush();
968 mAudioTrack->flush();
969 }
970
pauseAndWait(const std::chrono::milliseconds & timeout)971 bool AudioTrack::pauseAndWait(const std::chrono::milliseconds& timeout)
972 {
973 using namespace std::chrono_literals;
974
975 // We use atomic access here for state variables - these are used as hints
976 // to ensure we have ramped down audio.
977 const int priorState = mProxy->getState();
978 const uint32_t priorPosition = mProxy->getPosition().unsignedValue();
979
980 pause();
981
982 // Only if we were previously active, do we wait to ramp down the audio.
983 if (priorState != CBLK_STATE_ACTIVE) return true;
984
985 AutoMutex lock(mLock);
986 // offload and direct tracks do not wait because pause volume ramp is handled by hardware.
987 if (isOffloadedOrDirect_l()) return true;
988
989 // Wait for the track state to be anything besides pausing.
990 // This ensures that the volume has ramped down.
991 constexpr auto SLEEP_INTERVAL_MS = 10ms;
992 constexpr auto POSITION_TIMEOUT_MS = 40ms; // don't wait longer than this for position change.
993 auto begin = std::chrono::steady_clock::now();
994 while (true) {
995 // Wait for state and position to change.
996 // After pause() the server state should be PAUSING, but that may immediately
997 // convert to PAUSED by prepareTracks before data is read into the mixer.
998 // Hence we check that the state is not PAUSING and that the server position
999 // has advanced to be a more reliable estimate that the volume ramp has completed.
1000 const int state = mProxy->getState();
1001 const uint32_t position = mProxy->getPosition().unsignedValue();
1002
1003 mLock.unlock(); // only local variables accessed until lock.
1004 auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
1005 std::chrono::steady_clock::now() - begin);
1006 if (state != CBLK_STATE_PAUSING &&
1007 (elapsed >= POSITION_TIMEOUT_MS || position != priorPosition)) {
1008 ALOGV("%s: success state:%d, position:%u after %lld ms"
1009 " (prior state:%d prior position:%u)",
1010 __func__, state, position, elapsed.count(), priorState, priorPosition);
1011 return true;
1012 }
1013 std::chrono::milliseconds remaining = timeout - elapsed;
1014 if (remaining.count() <= 0) {
1015 ALOGW("%s: timeout expired state:%d still pausing:%d after %lld ms",
1016 __func__, state, CBLK_STATE_PAUSING, elapsed.count());
1017 return false;
1018 }
1019 // It is conceivable that the track is restored while sleeping;
1020 // as this logic is advisory, we allow that.
1021 std::this_thread::sleep_for(std::min(remaining, SLEEP_INTERVAL_MS));
1022 mLock.lock();
1023 }
1024 }
1025
pause()1026 void AudioTrack::pause()
1027 {
1028 const int64_t beginNs = systemTime();
1029 AutoMutex lock(mLock);
1030 mediametrics::Defer defer([&]() {
1031 mediametrics::LogItem(mMetricsId)
1032 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_PAUSE)
1033 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
1034 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
1035 .record(); });
1036
1037 ALOGV("%s(%d): prior state:%s", __func__, mPortId, stateToString(mState));
1038
1039 if (mState == STATE_ACTIVE) {
1040 mState = STATE_PAUSED;
1041 } else if (mState == STATE_STOPPING) {
1042 mState = STATE_PAUSED_STOPPING;
1043 } else {
1044 return;
1045 }
1046 mProxy->interrupt();
1047 mAudioTrack->pause();
1048
1049 if (isOffloaded_l()) {
1050 if (mOutput != AUDIO_IO_HANDLE_NONE) {
1051 // An offload output can be re-used between two audio tracks having
1052 // the same configuration. A timestamp query for a paused track
1053 // while the other is running would return an incorrect time.
1054 // To fix this, cache the playback position on a pause() and return
1055 // this time when requested until the track is resumed.
1056
1057 // OffloadThread sends HAL pause in its threadLoop. Time saved
1058 // here can be slightly off.
1059
1060 // TODO: check return code for getRenderPosition.
1061
1062 uint32_t halFrames;
1063 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
1064 ALOGV("%s(%d): for offload, cache current position %u",
1065 __func__, mPortId, mPausedPosition);
1066 }
1067 }
1068 }
1069
setVolume(float left,float right)1070 status_t AudioTrack::setVolume(float left, float right)
1071 {
1072 // This duplicates a test by AudioTrack JNI, but that is not the only caller
1073 if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
1074 isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
1075 return BAD_VALUE;
1076 }
1077
1078 mediametrics::LogItem(mMetricsId)
1079 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETVOLUME)
1080 .set(AMEDIAMETRICS_PROP_VOLUME_LEFT, (double)left)
1081 .set(AMEDIAMETRICS_PROP_VOLUME_RIGHT, (double)right)
1082 .record();
1083
1084 AutoMutex lock(mLock);
1085 mVolume[AUDIO_INTERLEAVE_LEFT] = left;
1086 mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
1087
1088 mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
1089
1090 if (isOffloaded_l()) {
1091 mAudioTrack->signal();
1092 }
1093 return NO_ERROR;
1094 }
1095
setVolume(float volume)1096 status_t AudioTrack::setVolume(float volume)
1097 {
1098 return setVolume(volume, volume);
1099 }
1100
setAuxEffectSendLevel(float level)1101 status_t AudioTrack::setAuxEffectSendLevel(float level)
1102 {
1103 // This duplicates a test by AudioTrack JNI, but that is not the only caller
1104 if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
1105 return BAD_VALUE;
1106 }
1107
1108 AutoMutex lock(mLock);
1109 mSendLevel = level;
1110 mProxy->setSendLevel(level);
1111
1112 return NO_ERROR;
1113 }
1114
getAuxEffectSendLevel(float * level) const1115 void AudioTrack::getAuxEffectSendLevel(float* level) const
1116 {
1117 if (level != NULL) {
1118 *level = mSendLevel;
1119 }
1120 }
1121
setSampleRate(uint32_t rate)1122 status_t AudioTrack::setSampleRate(uint32_t rate)
1123 {
1124 AutoMutex lock(mLock);
1125 ALOGV("%s(%d): prior state:%s rate:%u", __func__, mPortId, stateToString(mState), rate);
1126
1127 if (rate == mSampleRate) {
1128 return NO_ERROR;
1129 }
1130 if (isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)
1131 || (mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL)) {
1132 return INVALID_OPERATION;
1133 }
1134 if (mOutput == AUDIO_IO_HANDLE_NONE) {
1135 return NO_INIT;
1136 }
1137 // NOTE: it is theoretically possible, but highly unlikely, that a device change
1138 // could mean a previously allowed sampling rate is no longer allowed.
1139 uint32_t afSamplingRate;
1140 if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
1141 return NO_INIT;
1142 }
1143 // pitch is emulated by adjusting speed and sampleRate
1144 const uint32_t effectiveSampleRate = adjustSampleRate(rate, mPlaybackRate.mPitch);
1145 if (rate == 0 || effectiveSampleRate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
1146 return BAD_VALUE;
1147 }
1148 // TODO: Should we also check if the buffer size is compatible?
1149
1150 mSampleRate = rate;
1151 mProxy->setSampleRate(effectiveSampleRate);
1152
1153 return NO_ERROR;
1154 }
1155
getSampleRate() const1156 uint32_t AudioTrack::getSampleRate() const
1157 {
1158 AutoMutex lock(mLock);
1159
1160 // sample rate can be updated during playback by the offloaded decoder so we need to
1161 // query the HAL and update if needed.
1162 // FIXME use Proxy return channel to update the rate from server and avoid polling here
1163 if (isOffloadedOrDirect_l()) {
1164 if (mOutput != AUDIO_IO_HANDLE_NONE) {
1165 uint32_t sampleRate = 0;
1166 status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
1167 if (status == NO_ERROR) {
1168 mSampleRate = sampleRate;
1169 }
1170 }
1171 }
1172 return mSampleRate;
1173 }
1174
getOriginalSampleRate() const1175 uint32_t AudioTrack::getOriginalSampleRate() const
1176 {
1177 return mOriginalSampleRate;
1178 }
1179
setDualMonoMode(audio_dual_mono_mode_t mode)1180 status_t AudioTrack::setDualMonoMode(audio_dual_mono_mode_t mode)
1181 {
1182 AutoMutex lock(mLock);
1183 return setDualMonoMode_l(mode);
1184 }
1185
setDualMonoMode_l(audio_dual_mono_mode_t mode)1186 status_t AudioTrack::setDualMonoMode_l(audio_dual_mono_mode_t mode)
1187 {
1188 const status_t status = statusTFromBinderStatus(
1189 mAudioTrack->setDualMonoMode(VALUE_OR_RETURN_STATUS(
1190 legacy2aidl_audio_dual_mono_mode_t_AudioDualMonoMode(mode))));
1191 if (status == NO_ERROR) mDualMonoMode = mode;
1192 return status;
1193 }
1194
getDualMonoMode(audio_dual_mono_mode_t * mode) const1195 status_t AudioTrack::getDualMonoMode(audio_dual_mono_mode_t* mode) const
1196 {
1197 AutoMutex lock(mLock);
1198 media::AudioDualMonoMode mediaMode;
1199 const status_t status = statusTFromBinderStatus(mAudioTrack->getDualMonoMode(&mediaMode));
1200 if (status == NO_ERROR) {
1201 *mode = VALUE_OR_RETURN_STATUS(
1202 aidl2legacy_AudioDualMonoMode_audio_dual_mono_mode_t(mediaMode));
1203 }
1204 return status;
1205 }
1206
setAudioDescriptionMixLevel(float leveldB)1207 status_t AudioTrack::setAudioDescriptionMixLevel(float leveldB)
1208 {
1209 AutoMutex lock(mLock);
1210 return setAudioDescriptionMixLevel_l(leveldB);
1211 }
1212
setAudioDescriptionMixLevel_l(float leveldB)1213 status_t AudioTrack::setAudioDescriptionMixLevel_l(float leveldB)
1214 {
1215 const status_t status = statusTFromBinderStatus(
1216 mAudioTrack->setAudioDescriptionMixLevel(leveldB));
1217 if (status == NO_ERROR) mAudioDescriptionMixLeveldB = leveldB;
1218 return status;
1219 }
1220
getAudioDescriptionMixLevel(float * leveldB) const1221 status_t AudioTrack::getAudioDescriptionMixLevel(float* leveldB) const
1222 {
1223 AutoMutex lock(mLock);
1224 return statusTFromBinderStatus(mAudioTrack->getAudioDescriptionMixLevel(leveldB));
1225 }
1226
setPlaybackRate(const AudioPlaybackRate & playbackRate)1227 status_t AudioTrack::setPlaybackRate(const AudioPlaybackRate &playbackRate)
1228 {
1229 AutoMutex lock(mLock);
1230 if (isAudioPlaybackRateEqual(playbackRate, mPlaybackRate)) {
1231 return NO_ERROR;
1232 }
1233 if (isOffloadedOrDirect_l()) {
1234 const status_t status = statusTFromBinderStatus(mAudioTrack->setPlaybackRateParameters(
1235 VALUE_OR_RETURN_STATUS(
1236 legacy2aidl_audio_playback_rate_t_AudioPlaybackRate(playbackRate))));
1237 if (status == NO_ERROR) {
1238 mPlaybackRate = playbackRate;
1239 }
1240 return status;
1241 }
1242 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1243 return INVALID_OPERATION;
1244 }
1245
1246 ALOGV("%s(%d): mSampleRate:%u mSpeed:%f mPitch:%f",
1247 __func__, mPortId, mSampleRate, playbackRate.mSpeed, playbackRate.mPitch);
1248 // pitch is emulated by adjusting speed and sampleRate
1249 const uint32_t effectiveRate = adjustSampleRate(mSampleRate, playbackRate.mPitch);
1250 const float effectiveSpeed = adjustSpeed(playbackRate.mSpeed, playbackRate.mPitch);
1251 const float effectivePitch = adjustPitch(playbackRate.mPitch);
1252 AudioPlaybackRate playbackRateTemp = playbackRate;
1253 playbackRateTemp.mSpeed = effectiveSpeed;
1254 playbackRateTemp.mPitch = effectivePitch;
1255
1256 ALOGV("%s(%d) (effective) mSampleRate:%u mSpeed:%f mPitch:%f",
1257 __func__, mPortId, effectiveRate, effectiveSpeed, effectivePitch);
1258
1259 if (!isAudioPlaybackRateValid(playbackRateTemp)) {
1260 ALOGW("%s(%d) (%f, %f) failed (effective rate out of bounds)",
1261 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
1262 return BAD_VALUE;
1263 }
1264 // Check if the buffer size is compatible.
1265 if (!isSampleRateSpeedAllowed_l(effectiveRate, effectiveSpeed)) {
1266 ALOGW("%s(%d) (%f, %f) failed (buffer size)",
1267 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
1268 return BAD_VALUE;
1269 }
1270
1271 // Check resampler ratios are within bounds
1272 if ((uint64_t)effectiveRate > (uint64_t)mSampleRate *
1273 (uint64_t)AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
1274 ALOGW("%s(%d) (%f, %f) failed. Resample rate exceeds max accepted value",
1275 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
1276 return BAD_VALUE;
1277 }
1278
1279 if ((uint64_t)effectiveRate * (uint64_t)AUDIO_RESAMPLER_UP_RATIO_MAX < (uint64_t)mSampleRate) {
1280 ALOGW("%s(%d) (%f, %f) failed. Resample rate below min accepted value",
1281 __func__, mPortId, playbackRate.mSpeed, playbackRate.mPitch);
1282 return BAD_VALUE;
1283 }
1284 mPlaybackRate = playbackRate;
1285 //set effective rates
1286 mProxy->setPlaybackRate(playbackRateTemp);
1287 mProxy->setSampleRate(effectiveRate); // FIXME: not quite "atomic" with setPlaybackRate
1288
1289 mediametrics::LogItem(mMetricsId)
1290 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETPLAYBACKPARAM)
1291 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
1292 .set(AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)mPlaybackRate.mSpeed)
1293 .set(AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)mPlaybackRate.mPitch)
1294 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1295 AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)effectiveRate)
1296 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1297 AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)playbackRateTemp.mSpeed)
1298 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
1299 AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)playbackRateTemp.mPitch)
1300 .record();
1301
1302 return NO_ERROR;
1303 }
1304
getPlaybackRate()1305 const AudioPlaybackRate& AudioTrack::getPlaybackRate()
1306 {
1307 AutoMutex lock(mLock);
1308 if (isOffloadedOrDirect_l()) {
1309 media::AudioPlaybackRate playbackRateTemp;
1310 const status_t status = statusTFromBinderStatus(
1311 mAudioTrack->getPlaybackRateParameters(&playbackRateTemp));
1312 if (status == NO_ERROR) { // update local version if changed.
1313 mPlaybackRate =
1314 aidl2legacy_AudioPlaybackRate_audio_playback_rate_t(playbackRateTemp).value();
1315 }
1316 }
1317 return mPlaybackRate;
1318 }
1319
getBufferSizeInFrames()1320 ssize_t AudioTrack::getBufferSizeInFrames()
1321 {
1322 AutoMutex lock(mLock);
1323 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1324 return NO_INIT;
1325 }
1326
1327 return (ssize_t) mProxy->getBufferSizeInFrames();
1328 }
1329
getBufferDurationInUs(int64_t * duration)1330 status_t AudioTrack::getBufferDurationInUs(int64_t *duration)
1331 {
1332 if (duration == nullptr) {
1333 return BAD_VALUE;
1334 }
1335 AutoMutex lock(mLock);
1336 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1337 return NO_INIT;
1338 }
1339 ssize_t bufferSizeInFrames = (ssize_t) mProxy->getBufferSizeInFrames();
1340 if (bufferSizeInFrames < 0) {
1341 return (status_t)bufferSizeInFrames;
1342 }
1343 *duration = (int64_t)((double)bufferSizeInFrames * 1000000
1344 / ((double)mSampleRate * mPlaybackRate.mSpeed));
1345 return NO_ERROR;
1346 }
1347
setBufferSizeInFrames(size_t bufferSizeInFrames)1348 ssize_t AudioTrack::setBufferSizeInFrames(size_t bufferSizeInFrames)
1349 {
1350 AutoMutex lock(mLock);
1351 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1352 return NO_INIT;
1353 }
1354 // Reject if timed track or compressed audio.
1355 if (!audio_is_linear_pcm(mFormat)) {
1356 return INVALID_OPERATION;
1357 }
1358
1359 ssize_t originalBufferSize = mProxy->getBufferSizeInFrames();
1360 ssize_t finalBufferSize = mProxy->setBufferSizeInFrames((uint32_t) bufferSizeInFrames);
1361 if (originalBufferSize != finalBufferSize) {
1362 android::mediametrics::LogItem(mMetricsId)
1363 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETBUFFERSIZE)
1364 .set(AMEDIAMETRICS_PROP_BUFFERSIZEFRAMES, (int32_t)mProxy->getBufferSizeInFrames())
1365 .set(AMEDIAMETRICS_PROP_UNDERRUN, (int32_t)getUnderrunCount_l())
1366 .record();
1367 }
1368 return finalBufferSize;
1369 }
1370
getStartThresholdInFrames() const1371 ssize_t AudioTrack::getStartThresholdInFrames() const
1372 {
1373 AutoMutex lock(mLock);
1374 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1375 return NO_INIT;
1376 }
1377 return (ssize_t) mProxy->getStartThresholdInFrames();
1378 }
1379
setStartThresholdInFrames(size_t startThresholdInFrames)1380 ssize_t AudioTrack::setStartThresholdInFrames(size_t startThresholdInFrames)
1381 {
1382 if (startThresholdInFrames > INT32_MAX || startThresholdInFrames == 0) {
1383 // contractually we could simply return the current threshold in frames
1384 // to indicate the request was ignored, but we return an error here.
1385 return BAD_VALUE;
1386 }
1387 AutoMutex lock(mLock);
1388 // We do not permit calling setStartThresholdInFrames() between the AudioTrack
1389 // default ctor AudioTrack() and set(...) but rather fail such an attempt.
1390 // (To do so would require a cached mOrigStartThresholdInFrames and we may
1391 // not have proper validation for the actual set value).
1392 if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
1393 return NO_INIT;
1394 }
1395 const uint32_t original = mProxy->getStartThresholdInFrames();
1396 const uint32_t final = mProxy->setStartThresholdInFrames(startThresholdInFrames);
1397 if (original != final) {
1398 android::mediametrics::LogItem(mMetricsId)
1399 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETSTARTTHRESHOLD)
1400 .set(AMEDIAMETRICS_PROP_STARTTHRESHOLDFRAMES, (int32_t)final)
1401 .record();
1402 if (original > final) {
1403 // restart track if it was disabled by audioflinger due to previous underrun
1404 // and we reduced the number of frames for the threshold.
1405 restartIfDisabled();
1406 }
1407 }
1408 return final;
1409 }
1410
setLoop(uint32_t loopStart,uint32_t loopEnd,int loopCount)1411 status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
1412 {
1413 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
1414 return INVALID_OPERATION;
1415 }
1416
1417 if (loopCount == 0) {
1418 ;
1419 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
1420 loopEnd - loopStart >= MIN_LOOP) {
1421 ;
1422 } else {
1423 return BAD_VALUE;
1424 }
1425
1426 AutoMutex lock(mLock);
1427 // See setPosition() regarding setting parameters such as loop points or position while active
1428 if (mState == STATE_ACTIVE) {
1429 return INVALID_OPERATION;
1430 }
1431 setLoop_l(loopStart, loopEnd, loopCount);
1432 return NO_ERROR;
1433 }
1434
setLoop_l(uint32_t loopStart,uint32_t loopEnd,int loopCount)1435 void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
1436 {
1437 // We do not update the periodic notification point.
1438 // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
1439 mLoopCount = loopCount;
1440 mLoopEnd = loopEnd;
1441 mLoopStart = loopStart;
1442 mLoopCountNotified = loopCount;
1443 mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
1444
1445 // Waking the AudioTrackThread is not needed as this cannot be called when active.
1446 }
1447
setMarkerPosition(uint32_t marker)1448 status_t AudioTrack::setMarkerPosition(uint32_t marker)
1449 {
1450 // The only purpose of setting marker position is to get a callback
1451 if (mCbf == NULL || isOffloadedOrDirect()) {
1452 return INVALID_OPERATION;
1453 }
1454
1455 AutoMutex lock(mLock);
1456 mMarkerPosition = marker;
1457 mMarkerReached = false;
1458
1459 sp<AudioTrackThread> t = mAudioTrackThread;
1460 if (t != 0) {
1461 t->wake();
1462 }
1463 return NO_ERROR;
1464 }
1465
getMarkerPosition(uint32_t * marker) const1466 status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
1467 {
1468 if (isOffloadedOrDirect()) {
1469 return INVALID_OPERATION;
1470 }
1471 if (marker == NULL) {
1472 return BAD_VALUE;
1473 }
1474
1475 AutoMutex lock(mLock);
1476 mMarkerPosition.getValue(marker);
1477
1478 return NO_ERROR;
1479 }
1480
setPositionUpdatePeriod(uint32_t updatePeriod)1481 status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
1482 {
1483 // The only purpose of setting position update period is to get a callback
1484 if (mCbf == NULL || isOffloadedOrDirect()) {
1485 return INVALID_OPERATION;
1486 }
1487
1488 AutoMutex lock(mLock);
1489 mNewPosition = updateAndGetPosition_l() + updatePeriod;
1490 mUpdatePeriod = updatePeriod;
1491
1492 sp<AudioTrackThread> t = mAudioTrackThread;
1493 if (t != 0) {
1494 t->wake();
1495 }
1496 return NO_ERROR;
1497 }
1498
getPositionUpdatePeriod(uint32_t * updatePeriod) const1499 status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
1500 {
1501 if (isOffloadedOrDirect()) {
1502 return INVALID_OPERATION;
1503 }
1504 if (updatePeriod == NULL) {
1505 return BAD_VALUE;
1506 }
1507
1508 AutoMutex lock(mLock);
1509 *updatePeriod = mUpdatePeriod;
1510
1511 return NO_ERROR;
1512 }
1513
setPosition(uint32_t position)1514 status_t AudioTrack::setPosition(uint32_t position)
1515 {
1516 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
1517 return INVALID_OPERATION;
1518 }
1519 if (position > mFrameCount) {
1520 return BAD_VALUE;
1521 }
1522
1523 AutoMutex lock(mLock);
1524 // Currently we require that the player is inactive before setting parameters such as position
1525 // or loop points. Otherwise, there could be a race condition: the application could read the
1526 // current position, compute a new position or loop parameters, and then set that position or
1527 // loop parameters but it would do the "wrong" thing since the position has continued to advance
1528 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app
1529 // to specify how it wants to handle such scenarios.
1530 if (mState == STATE_ACTIVE) {
1531 return INVALID_OPERATION;
1532 }
1533 // After setting the position, use full update period before notification.
1534 mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
1535 mStaticProxy->setBufferPosition(position);
1536
1537 // Waking the AudioTrackThread is not needed as this cannot be called when active.
1538 return NO_ERROR;
1539 }
1540
getPosition(uint32_t * position)1541 status_t AudioTrack::getPosition(uint32_t *position)
1542 {
1543 if (position == NULL) {
1544 return BAD_VALUE;
1545 }
1546
1547 AutoMutex lock(mLock);
1548 // FIXME: offloaded and direct tracks call into the HAL for render positions
1549 // for compressed/synced data; however, we use proxy position for pure linear pcm data
1550 // as we do not know the capability of the HAL for pcm position support and standby.
1551 // There may be some latency differences between the HAL position and the proxy position.
1552 if (isOffloadedOrDirect_l() && !isPurePcmData_l()) {
1553 uint32_t dspFrames = 0;
1554
1555 if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
1556 ALOGV("%s(%d): called in paused state, return cached position %u",
1557 __func__, mPortId, mPausedPosition);
1558 *position = mPausedPosition;
1559 return NO_ERROR;
1560 }
1561
1562 if (mOutput != AUDIO_IO_HANDLE_NONE) {
1563 uint32_t halFrames; // actually unused
1564 (void) AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
1565 // FIXME: on getRenderPosition() error, we return OK with frame position 0.
1566 }
1567 // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
1568 // due to hardware latency. We leave this behavior for now.
1569 *position = dspFrames;
1570 } else {
1571 if (mCblk->mFlags & CBLK_INVALID) {
1572 (void) restoreTrack_l("getPosition");
1573 // FIXME: for compatibility with the Java API we ignore the restoreTrack_l()
1574 // error here (e.g. DEAD_OBJECT) and return OK with the last recorded server position.
1575 }
1576
1577 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
1578 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
1579 0 : updateAndGetPosition_l().value();
1580 }
1581 return NO_ERROR;
1582 }
1583
getBufferPosition(uint32_t * position)1584 status_t AudioTrack::getBufferPosition(uint32_t *position)
1585 {
1586 if (mSharedBuffer == 0) {
1587 return INVALID_OPERATION;
1588 }
1589 if (position == NULL) {
1590 return BAD_VALUE;
1591 }
1592
1593 AutoMutex lock(mLock);
1594 *position = mStaticProxy->getBufferPosition();
1595 return NO_ERROR;
1596 }
1597
reload()1598 status_t AudioTrack::reload()
1599 {
1600 if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
1601 return INVALID_OPERATION;
1602 }
1603
1604 AutoMutex lock(mLock);
1605 // See setPosition() regarding setting parameters such as loop points or position while active
1606 if (mState == STATE_ACTIVE) {
1607 return INVALID_OPERATION;
1608 }
1609 mNewPosition = mUpdatePeriod;
1610 (void) updateAndGetPosition_l();
1611 mPosition = 0;
1612 mPreviousTimestampValid = false;
1613 #if 0
1614 // The documentation is not clear on the behavior of reload() and the restoration
1615 // of loop count. Historically we have not restored loop count, start, end,
1616 // but it makes sense if one desires to repeat playing a particular sound.
1617 if (mLoopCount != 0) {
1618 mLoopCountNotified = mLoopCount;
1619 mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
1620 }
1621 #endif
1622 mStaticProxy->setBufferPosition(0);
1623 return NO_ERROR;
1624 }
1625
getOutput() const1626 audio_io_handle_t AudioTrack::getOutput() const
1627 {
1628 AutoMutex lock(mLock);
1629 return mOutput;
1630 }
1631
setOutputDevice(audio_port_handle_t deviceId)1632 status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
1633 AutoMutex lock(mLock);
1634 if (mSelectedDeviceId != deviceId) {
1635 mSelectedDeviceId = deviceId;
1636 if (mStatus == NO_ERROR) {
1637 android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
1638 mProxy->interrupt();
1639 }
1640 }
1641 return NO_ERROR;
1642 }
1643
getOutputDevice()1644 audio_port_handle_t AudioTrack::getOutputDevice() {
1645 AutoMutex lock(mLock);
1646 return mSelectedDeviceId;
1647 }
1648
1649 // must be called with mLock held
updateRoutedDeviceId_l()1650 void AudioTrack::updateRoutedDeviceId_l()
1651 {
1652 // if the track is inactive, do not update actual device as the output stream maybe routed
1653 // to a device not relevant to this client because of other active use cases.
1654 if (mState != STATE_ACTIVE) {
1655 return;
1656 }
1657 if (mOutput != AUDIO_IO_HANDLE_NONE) {
1658 audio_port_handle_t deviceId = AudioSystem::getDeviceIdForIo(mOutput);
1659 if (deviceId != AUDIO_PORT_HANDLE_NONE) {
1660 mRoutedDeviceId = deviceId;
1661 }
1662 }
1663 }
1664
getRoutedDeviceId()1665 audio_port_handle_t AudioTrack::getRoutedDeviceId() {
1666 AutoMutex lock(mLock);
1667 updateRoutedDeviceId_l();
1668 return mRoutedDeviceId;
1669 }
1670
attachAuxEffect(int effectId)1671 status_t AudioTrack::attachAuxEffect(int effectId)
1672 {
1673 AutoMutex lock(mLock);
1674 status_t status;
1675 mAudioTrack->attachAuxEffect(effectId, &status);
1676 if (status == NO_ERROR) {
1677 mAuxEffectId = effectId;
1678 }
1679 return status;
1680 }
1681
streamType() const1682 audio_stream_type_t AudioTrack::streamType() const
1683 {
1684 return mStreamType;
1685 }
1686
latency()1687 uint32_t AudioTrack::latency()
1688 {
1689 AutoMutex lock(mLock);
1690 updateLatency_l();
1691 return mLatency;
1692 }
1693
1694 // -------------------------------------------------------------------------
1695
1696 // must be called with mLock held
updateLatency_l()1697 void AudioTrack::updateLatency_l()
1698 {
1699 status_t status = AudioSystem::getLatency(mOutput, &mAfLatency);
1700 if (status != NO_ERROR) {
1701 ALOGW("%s(%d): getLatency(%d) failed status %d", __func__, mPortId, mOutput, status);
1702 } else {
1703 // FIXME don't believe this lie
1704 mLatency = mAfLatency + (1000LL * mFrameCount) / mSampleRate;
1705 }
1706 }
1707
1708 // TODO Move this macro to a common header file for enum to string conversion in audio framework.
1709 #define MEDIA_CASE_ENUM(name) case name: return #name
convertTransferToText(transfer_type transferType)1710 const char * AudioTrack::convertTransferToText(transfer_type transferType) {
1711 switch (transferType) {
1712 MEDIA_CASE_ENUM(TRANSFER_DEFAULT);
1713 MEDIA_CASE_ENUM(TRANSFER_CALLBACK);
1714 MEDIA_CASE_ENUM(TRANSFER_OBTAIN);
1715 MEDIA_CASE_ENUM(TRANSFER_SYNC);
1716 MEDIA_CASE_ENUM(TRANSFER_SHARED);
1717 MEDIA_CASE_ENUM(TRANSFER_SYNC_NOTIF_CALLBACK);
1718 default:
1719 return "UNRECOGNIZED";
1720 }
1721 }
1722
createTrack_l()1723 status_t AudioTrack::createTrack_l()
1724 {
1725 status_t status;
1726 bool callbackAdded = false;
1727 std::string errorMessage;
1728
1729 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
1730 if (audioFlinger == 0) {
1731 errorMessage = StringPrintf("%s(%d): Could not get audioflinger",
1732 __func__, mPortId);
1733 status = DEAD_OBJECT;
1734 goto exit;
1735 }
1736
1737 {
1738 // mFlags (not mOrigFlags) is modified depending on whether fast request is accepted.
1739 // After fast request is denied, we will request again if IAudioTrack is re-created.
1740 // Client can only express a preference for FAST. Server will perform additional tests.
1741 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1742 // either of these use cases:
1743 // use case 1: shared buffer
1744 bool sharedBuffer = mSharedBuffer != 0;
1745 bool transferAllowed =
1746 // use case 2: callback transfer mode
1747 (mTransfer == TRANSFER_CALLBACK) ||
1748 // use case 3: obtain/release mode
1749 (mTransfer == TRANSFER_OBTAIN) ||
1750 // use case 4: synchronous write
1751 ((mTransfer == TRANSFER_SYNC || mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK)
1752 && mThreadCanCallJava);
1753
1754 bool fastAllowed = sharedBuffer || transferAllowed;
1755 if (!fastAllowed) {
1756 ALOGW("%s(%d): AUDIO_OUTPUT_FLAG_FAST denied by client,"
1757 " not shared buffer and transfer = %s",
1758 __func__, mPortId,
1759 convertTransferToText(mTransfer));
1760 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1761 }
1762 }
1763
1764 IAudioFlinger::CreateTrackInput input;
1765 if (mOriginalStreamType != AUDIO_STREAM_DEFAULT) {
1766 // Legacy: This is based on original parameters even if the track is recreated.
1767 input.attr = AudioSystem::streamTypeToAttributes(mOriginalStreamType);
1768 } else {
1769 input.attr = mAttributes;
1770 }
1771 input.config = AUDIO_CONFIG_INITIALIZER;
1772 input.config.sample_rate = mSampleRate;
1773 input.config.channel_mask = mChannelMask;
1774 input.config.format = mFormat;
1775 input.config.offload_info = mOffloadInfoCopy;
1776 input.clientInfo.attributionSource = mClientAttributionSource;
1777 input.clientInfo.clientTid = -1;
1778 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1779 // It is currently meaningless to request SCHED_FIFO for a Java thread. Even if the
1780 // application-level code follows all non-blocking design rules, the language runtime
1781 // doesn't also follow those rules, so the thread will not benefit overall.
1782 if (mAudioTrackThread != 0 && !mThreadCanCallJava) {
1783 input.clientInfo.clientTid = mAudioTrackThread->getTid();
1784 }
1785 }
1786 input.sharedBuffer = mSharedBuffer;
1787 input.notificationsPerBuffer = mNotificationsPerBufferReq;
1788 input.speed = 1.0;
1789 if (audio_has_proportional_frames(mFormat) && mSharedBuffer == 0 &&
1790 (mFlags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1791 input.speed = !isPurePcmData_l() || isOffloadedOrDirect_l() ? 1.0f :
1792 max(mMaxRequiredSpeed, mPlaybackRate.mSpeed);
1793 }
1794 input.flags = mFlags;
1795 input.frameCount = mReqFrameCount;
1796 input.notificationFrameCount = mNotificationFramesReq;
1797 input.selectedDeviceId = mSelectedDeviceId;
1798 input.sessionId = mSessionId;
1799 input.audioTrackCallback = mAudioTrackCallback;
1800
1801 media::CreateTrackResponse response;
1802 status = audioFlinger->createTrack(VALUE_OR_FATAL(input.toAidl()), response);
1803
1804 IAudioFlinger::CreateTrackOutput output{};
1805 if (status == NO_ERROR) {
1806 output = VALUE_OR_FATAL(IAudioFlinger::CreateTrackOutput::fromAidl(response));
1807 }
1808
1809 if (status != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
1810 errorMessage = StringPrintf(
1811 "%s(%d): AudioFlinger could not create track, status: %d output %d",
1812 __func__, mPortId, status, output.outputId);
1813 if (status == NO_ERROR) {
1814 status = INVALID_OPERATION; // device not ready
1815 }
1816 goto exit;
1817 }
1818 ALOG_ASSERT(output.audioTrack != 0);
1819
1820 mFrameCount = output.frameCount;
1821 mNotificationFramesAct = (uint32_t)output.notificationFrameCount;
1822 mRoutedDeviceId = output.selectedDeviceId;
1823 mSessionId = output.sessionId;
1824 mStreamType = output.streamType;
1825
1826 mSampleRate = output.sampleRate;
1827 if (mOriginalSampleRate == 0) {
1828 mOriginalSampleRate = mSampleRate;
1829 }
1830
1831 mAfFrameCount = output.afFrameCount;
1832 mAfSampleRate = output.afSampleRate;
1833 mAfLatency = output.afLatencyMs;
1834
1835 mLatency = mAfLatency + (1000LL * mFrameCount) / mSampleRate;
1836
1837 // AudioFlinger now owns the reference to the I/O handle,
1838 // so we are no longer responsible for releasing it.
1839
1840 // FIXME compare to AudioRecord
1841 std::optional<media::SharedFileRegion> sfr;
1842 output.audioTrack->getCblk(&sfr);
1843 sp<IMemory> iMem = VALUE_OR_FATAL(aidl2legacy_NullableSharedFileRegion_IMemory(sfr));
1844 if (iMem == 0) {
1845 errorMessage = StringPrintf("%s(%d): Could not get control block", __func__, mPortId);
1846 status = FAILED_TRANSACTION;
1847 goto exit;
1848 }
1849 // TODO: Using unsecurePointer() has some associated security pitfalls
1850 // (see declaration for details).
1851 // Either document why it is safe in this case or address the
1852 // issue (e.g. by copying).
1853 void *iMemPointer = iMem->unsecurePointer();
1854 if (iMemPointer == NULL) {
1855 errorMessage = StringPrintf(
1856 "%s(%d): Could not get control block pointer", __func__, mPortId);
1857 status = FAILED_TRANSACTION;
1858 goto exit;
1859 }
1860 // invariant that mAudioTrack != 0 is true only after set() returns successfully
1861 if (mAudioTrack != 0) {
1862 IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
1863 mDeathNotifier.clear();
1864 }
1865 mAudioTrack = output.audioTrack;
1866 mCblkMemory = iMem;
1867 IPCThreadState::self()->flushCommands();
1868
1869 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
1870 mCblk = cblk;
1871
1872 mAwaitBoost = false;
1873 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1874 if (output.flags & AUDIO_OUTPUT_FLAG_FAST) {
1875 ALOGI("%s(%d): AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu -> %zu",
1876 __func__, mPortId, mReqFrameCount, mFrameCount);
1877 if (!mThreadCanCallJava) {
1878 mAwaitBoost = true;
1879 }
1880 } else {
1881 ALOGD("%s(%d): AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu -> %zu",
1882 __func__, mPortId, mReqFrameCount, mFrameCount);
1883 }
1884 }
1885 mFlags = output.flags;
1886
1887 //mOutput != output includes the case where mOutput == AUDIO_IO_HANDLE_NONE for first creation
1888 if (mDeviceCallback != 0) {
1889 if (mOutput != AUDIO_IO_HANDLE_NONE) {
1890 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
1891 }
1892 AudioSystem::addAudioDeviceCallback(this, output.outputId, output.portId);
1893 callbackAdded = true;
1894 }
1895
1896 mPortId = output.portId;
1897 // We retain a copy of the I/O handle, but don't own the reference
1898 mOutput = output.outputId;
1899 mRefreshRemaining = true;
1900
1901 // Starting address of buffers in shared memory. If there is a shared buffer, buffers
1902 // is the value of pointer() for the shared buffer, otherwise buffers points
1903 // immediately after the control block. This address is for the mapping within client
1904 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space.
1905 void* buffers;
1906 if (mSharedBuffer == 0) {
1907 buffers = cblk + 1;
1908 } else {
1909 // TODO: Using unsecurePointer() has some associated security pitfalls
1910 // (see declaration for details).
1911 // Either document why it is safe in this case or address the
1912 // issue (e.g. by copying).
1913 buffers = mSharedBuffer->unsecurePointer();
1914 if (buffers == NULL) {
1915 errorMessage = StringPrintf(
1916 "%s(%d): Could not get buffer pointer", __func__, mPortId);
1917 ALOGE("%s", errorMessage.c_str());
1918 status = FAILED_TRANSACTION;
1919 goto exit;
1920 }
1921 }
1922
1923 mAudioTrack->attachAuxEffect(mAuxEffectId, &status);
1924
1925 // If IAudioTrack is re-created, don't let the requested frameCount
1926 // decrease. This can confuse clients that cache frameCount().
1927 if (mFrameCount > mReqFrameCount) {
1928 mReqFrameCount = mFrameCount;
1929 }
1930
1931 // reset server position to 0 as we have new cblk.
1932 mServer = 0;
1933
1934 // update proxy
1935 if (mSharedBuffer == 0) {
1936 mStaticProxy.clear();
1937 mProxy = new AudioTrackClientProxy(cblk, buffers, mFrameCount, mFrameSize);
1938 } else {
1939 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, mFrameCount, mFrameSize);
1940 mProxy = mStaticProxy;
1941 }
1942
1943 mProxy->setVolumeLR(gain_minifloat_pack(
1944 gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1945 gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1946
1947 mProxy->setSendLevel(mSendLevel);
1948 const uint32_t effectiveSampleRate = adjustSampleRate(mSampleRate, mPlaybackRate.mPitch);
1949 const float effectiveSpeed = adjustSpeed(mPlaybackRate.mSpeed, mPlaybackRate.mPitch);
1950 const float effectivePitch = adjustPitch(mPlaybackRate.mPitch);
1951 mProxy->setSampleRate(effectiveSampleRate);
1952
1953 AudioPlaybackRate playbackRateTemp = mPlaybackRate;
1954 playbackRateTemp.mSpeed = effectiveSpeed;
1955 playbackRateTemp.mPitch = effectivePitch;
1956 mProxy->setPlaybackRate(playbackRateTemp);
1957 mProxy->setMinimum(mNotificationFramesAct);
1958
1959 if (mDualMonoMode != AUDIO_DUAL_MONO_MODE_OFF) {
1960 setDualMonoMode_l(mDualMonoMode);
1961 }
1962 if (mAudioDescriptionMixLeveldB != -std::numeric_limits<float>::infinity()) {
1963 setAudioDescriptionMixLevel_l(mAudioDescriptionMixLeveldB);
1964 }
1965
1966 mDeathNotifier = new DeathNotifier(this);
1967 IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
1968
1969 // This is the first log sent from the AudioTrack client.
1970 // The creation of the audio track by AudioFlinger (in the code above)
1971 // is the first log of the AudioTrack and must be present before
1972 // any AudioTrack client logs will be accepted.
1973
1974 mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_TRACK) + std::to_string(mPortId);
1975 mediametrics::LogItem(mMetricsId)
1976 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CREATE)
1977 // the following are immutable
1978 .set(AMEDIAMETRICS_PROP_FLAGS, toString(mFlags).c_str())
1979 .set(AMEDIAMETRICS_PROP_ORIGINALFLAGS, toString(mOrigFlags).c_str())
1980 .set(AMEDIAMETRICS_PROP_SESSIONID, (int32_t)mSessionId)
1981 .set(AMEDIAMETRICS_PROP_LOGSESSIONID, mLogSessionId)
1982 .set(AMEDIAMETRICS_PROP_PLAYERIID, mPlayerIId)
1983 .set(AMEDIAMETRICS_PROP_TRACKID, mPortId) // dup from key
1984 .set(AMEDIAMETRICS_PROP_CONTENTTYPE, toString(mAttributes.content_type).c_str())
1985 .set(AMEDIAMETRICS_PROP_USAGE, toString(mAttributes.usage).c_str())
1986 .set(AMEDIAMETRICS_PROP_THREADID, (int32_t)output.outputId)
1987 .set(AMEDIAMETRICS_PROP_SELECTEDDEVICEID, (int32_t)mSelectedDeviceId)
1988 .set(AMEDIAMETRICS_PROP_ROUTEDDEVICEID, (int32_t)mRoutedDeviceId)
1989 .set(AMEDIAMETRICS_PROP_ENCODING, toString(mFormat).c_str())
1990 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
1991 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
1992 // the following are NOT immutable
1993 .set(AMEDIAMETRICS_PROP_VOLUME_LEFT, (double)mVolume[AUDIO_INTERLEAVE_LEFT])
1994 .set(AMEDIAMETRICS_PROP_VOLUME_RIGHT, (double)mVolume[AUDIO_INTERLEAVE_RIGHT])
1995 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
1996 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)NO_ERROR)
1997 .set(AMEDIAMETRICS_PROP_AUXEFFECTID, (int32_t)mAuxEffectId)
1998 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
1999 .set(AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)mPlaybackRate.mSpeed)
2000 .set(AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)mPlaybackRate.mPitch)
2001 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
2002 AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)effectiveSampleRate)
2003 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
2004 AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)effectiveSpeed)
2005 .set(AMEDIAMETRICS_PROP_PREFIX_EFFECTIVE
2006 AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)effectivePitch)
2007 .record();
2008
2009 // mSendLevel
2010 // mReqFrameCount?
2011 // mNotificationFramesAct, mNotificationFramesReq, mNotificationsPerBufferReq
2012 // mLatency, mAfLatency, mAfFrameCount, mAfSampleRate
2013
2014 }
2015
2016 exit:
2017 if (status != NO_ERROR) {
2018 if (callbackAdded) {
2019 // note: mOutput is always valid is callbackAdded is true
2020 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
2021 }
2022 ALOGE_IF(!errorMessage.empty(), "%s", errorMessage.c_str());
2023 reportError(status, AMEDIAMETRICS_PROP_EVENT_VALUE_CREATE, errorMessage.c_str());
2024 }
2025 mStatus = status;
2026
2027 // sp<IAudioTrack> track destructor will cause releaseOutput() to be called by AudioFlinger
2028 return status;
2029 }
2030
reportError(status_t status,const char * event,const char * message) const2031 void AudioTrack::reportError(status_t status, const char *event, const char *message) const
2032 {
2033 if (status == NO_ERROR) return;
2034 // We report error on the native side because some callers do not come
2035 // from Java.
2036 // Ensure these variables are initialized in set().
2037 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_TRACK_ERROR)
2038 .set(AMEDIAMETRICS_PROP_EVENT, event)
2039 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)status)
2040 .set(AMEDIAMETRICS_PROP_STATUSMESSAGE, message)
2041 .set(AMEDIAMETRICS_PROP_ORIGINALFLAGS, toString(mOrigFlags).c_str())
2042 .set(AMEDIAMETRICS_PROP_SESSIONID, (int32_t)mSessionId)
2043 .set(AMEDIAMETRICS_PROP_CONTENTTYPE, toString(mAttributes.content_type).c_str())
2044 .set(AMEDIAMETRICS_PROP_USAGE, toString(mAttributes.usage).c_str())
2045 .set(AMEDIAMETRICS_PROP_SELECTEDDEVICEID, (int32_t)mSelectedDeviceId)
2046 .set(AMEDIAMETRICS_PROP_ENCODING, toString(mFormat).c_str())
2047 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
2048 // the following are NOT immutable
2049 // frame count is initially the requested frame count, but may be adjusted
2050 // by AudioFlinger after creation.
2051 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
2052 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
2053 .set(AMEDIAMETRICS_PROP_PLAYBACK_SPEED, (double)mPlaybackRate.mSpeed)
2054 .set(AMEDIAMETRICS_PROP_PLAYBACK_PITCH, (double)mPlaybackRate.mPitch)
2055 .record();
2056 }
2057
obtainBuffer(Buffer * audioBuffer,int32_t waitCount,size_t * nonContig)2058 status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
2059 {
2060 if (audioBuffer == NULL) {
2061 if (nonContig != NULL) {
2062 *nonContig = 0;
2063 }
2064 return BAD_VALUE;
2065 }
2066 if (mTransfer != TRANSFER_OBTAIN) {
2067 audioBuffer->frameCount = 0;
2068 audioBuffer->size = 0;
2069 audioBuffer->raw = NULL;
2070 if (nonContig != NULL) {
2071 *nonContig = 0;
2072 }
2073 return INVALID_OPERATION;
2074 }
2075
2076 const struct timespec *requested;
2077 struct timespec timeout;
2078 if (waitCount == -1) {
2079 requested = &ClientProxy::kForever;
2080 } else if (waitCount == 0) {
2081 requested = &ClientProxy::kNonBlocking;
2082 } else if (waitCount > 0) {
2083 time_t ms = WAIT_PERIOD_MS * (time_t) waitCount;
2084 timeout.tv_sec = ms / 1000;
2085 timeout.tv_nsec = (ms % 1000) * 1000000;
2086 requested = &timeout;
2087 } else {
2088 ALOGE("%s(%d): invalid waitCount %d", __func__, mPortId, waitCount);
2089 requested = NULL;
2090 }
2091 return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
2092 }
2093
obtainBuffer(Buffer * audioBuffer,const struct timespec * requested,struct timespec * elapsed,size_t * nonContig)2094 status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
2095 struct timespec *elapsed, size_t *nonContig)
2096 {
2097 // previous and new IAudioTrack sequence numbers are used to detect track re-creation
2098 uint32_t oldSequence = 0;
2099
2100 Proxy::Buffer buffer;
2101 status_t status = NO_ERROR;
2102
2103 static const int32_t kMaxTries = 5;
2104 int32_t tryCounter = kMaxTries;
2105
2106 do {
2107 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
2108 // keep them from going away if another thread re-creates the track during obtainBuffer()
2109 sp<AudioTrackClientProxy> proxy;
2110 sp<IMemory> iMem;
2111
2112 { // start of lock scope
2113 AutoMutex lock(mLock);
2114
2115 uint32_t newSequence = mSequence;
2116 // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
2117 if (status == DEAD_OBJECT) {
2118 // re-create track, unless someone else has already done so
2119 if (newSequence == oldSequence) {
2120 status = restoreTrack_l("obtainBuffer");
2121 if (status != NO_ERROR) {
2122 buffer.mFrameCount = 0;
2123 buffer.mRaw = NULL;
2124 buffer.mNonContig = 0;
2125 break;
2126 }
2127 }
2128 }
2129 oldSequence = newSequence;
2130
2131 if (status == NOT_ENOUGH_DATA) {
2132 restartIfDisabled();
2133 }
2134
2135 // Keep the extra references
2136 proxy = mProxy;
2137 iMem = mCblkMemory;
2138
2139 if (mState == STATE_STOPPING) {
2140 status = -EINTR;
2141 buffer.mFrameCount = 0;
2142 buffer.mRaw = NULL;
2143 buffer.mNonContig = 0;
2144 break;
2145 }
2146
2147 // Non-blocking if track is stopped or paused
2148 if (mState != STATE_ACTIVE) {
2149 requested = &ClientProxy::kNonBlocking;
2150 }
2151
2152 } // end of lock scope
2153
2154 buffer.mFrameCount = audioBuffer->frameCount;
2155 // FIXME starts the requested timeout and elapsed over from scratch
2156 status = proxy->obtainBuffer(&buffer, requested, elapsed);
2157 } while (((status == DEAD_OBJECT) || (status == NOT_ENOUGH_DATA)) && (tryCounter-- > 0));
2158
2159 audioBuffer->frameCount = buffer.mFrameCount;
2160 audioBuffer->size = buffer.mFrameCount * mFrameSize;
2161 audioBuffer->raw = buffer.mRaw;
2162 audioBuffer->sequence = oldSequence;
2163 if (nonContig != NULL) {
2164 *nonContig = buffer.mNonContig;
2165 }
2166 return status;
2167 }
2168
releaseBuffer(const Buffer * audioBuffer)2169 void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
2170 {
2171 // FIXME add error checking on mode, by adding an internal version
2172 if (mTransfer == TRANSFER_SHARED) {
2173 return;
2174 }
2175
2176 size_t stepCount = audioBuffer->size / mFrameSize;
2177 if (stepCount == 0) {
2178 return;
2179 }
2180
2181 Proxy::Buffer buffer;
2182 buffer.mFrameCount = stepCount;
2183 buffer.mRaw = audioBuffer->raw;
2184
2185 AutoMutex lock(mLock);
2186 if (audioBuffer->sequence != mSequence) {
2187 // This Buffer came from a different IAudioTrack instance, so ignore the releaseBuffer
2188 ALOGD("%s is no-op due to IAudioTrack sequence mismatch %u != %u",
2189 __func__, audioBuffer->sequence, mSequence);
2190 return;
2191 }
2192 mReleased += stepCount;
2193 mInUnderrun = false;
2194 mProxy->releaseBuffer(&buffer);
2195
2196 // restart track if it was disabled by audioflinger due to previous underrun
2197 restartIfDisabled();
2198 }
2199
restartIfDisabled()2200 void AudioTrack::restartIfDisabled()
2201 {
2202 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
2203 if ((mState == STATE_ACTIVE) && (flags & CBLK_DISABLED)) {
2204 ALOGW("%s(%d): releaseBuffer() track %p disabled due to previous underrun, restarting",
2205 __func__, mPortId, this);
2206 // FIXME ignoring status
2207 status_t status;
2208 mAudioTrack->start(&status);
2209 }
2210 }
2211
2212 // -------------------------------------------------------------------------
2213
write(const void * buffer,size_t userSize,bool blocking)2214 ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
2215 {
2216 if (mTransfer != TRANSFER_SYNC && mTransfer != TRANSFER_SYNC_NOTIF_CALLBACK) {
2217 return INVALID_OPERATION;
2218 }
2219
2220 if (isDirect()) {
2221 AutoMutex lock(mLock);
2222 int32_t flags = android_atomic_and(
2223 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
2224 &mCblk->mFlags);
2225 if (flags & CBLK_INVALID) {
2226 return DEAD_OBJECT;
2227 }
2228 }
2229
2230 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
2231 // Validation: user is most-likely passing an error code, and it would
2232 // make the return value ambiguous (actualSize vs error).
2233 ALOGE("%s(%d): AudioTrack::write(buffer=%p, size=%zu (%zd)",
2234 __func__, mPortId, buffer, userSize, userSize);
2235 return BAD_VALUE;
2236 }
2237
2238 size_t written = 0;
2239 Buffer audioBuffer;
2240
2241 while (userSize >= mFrameSize) {
2242 audioBuffer.frameCount = userSize / mFrameSize;
2243
2244 status_t err = obtainBuffer(&audioBuffer,
2245 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
2246 if (err < 0) {
2247 if (written > 0) {
2248 break;
2249 }
2250 if (err == TIMED_OUT || err == -EINTR) {
2251 err = WOULD_BLOCK;
2252 }
2253 return ssize_t(err);
2254 }
2255
2256 size_t toWrite = audioBuffer.size;
2257 memcpy(audioBuffer.i8, buffer, toWrite);
2258 buffer = ((const char *) buffer) + toWrite;
2259 userSize -= toWrite;
2260 written += toWrite;
2261
2262 releaseBuffer(&audioBuffer);
2263 }
2264
2265 if (written > 0) {
2266 mFramesWritten += written / mFrameSize;
2267
2268 if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
2269 const sp<AudioTrackThread> t = mAudioTrackThread;
2270 if (t != 0) {
2271 // causes wake up of the playback thread, that will callback the client for
2272 // more data (with EVENT_CAN_WRITE_MORE_DATA) in processAudioBuffer()
2273 t->wake();
2274 }
2275 }
2276 }
2277
2278 return written;
2279 }
2280
2281 // -------------------------------------------------------------------------
2282
processAudioBuffer()2283 nsecs_t AudioTrack::processAudioBuffer()
2284 {
2285 // Currently the AudioTrack thread is not created if there are no callbacks.
2286 // Would it ever make sense to run the thread, even without callbacks?
2287 // If so, then replace this by checks at each use for mCbf != NULL.
2288 LOG_ALWAYS_FATAL_IF(mCblk == NULL);
2289
2290 mLock.lock();
2291 if (mAwaitBoost) {
2292 mAwaitBoost = false;
2293 mLock.unlock();
2294 static const int32_t kMaxTries = 5;
2295 int32_t tryCounter = kMaxTries;
2296 uint32_t pollUs = 10000;
2297 do {
2298 int policy = sched_getscheduler(0) & ~SCHED_RESET_ON_FORK;
2299 if (policy == SCHED_FIFO || policy == SCHED_RR) {
2300 break;
2301 }
2302 usleep(pollUs);
2303 pollUs <<= 1;
2304 } while (tryCounter-- > 0);
2305 if (tryCounter < 0) {
2306 ALOGE("%s(%d): did not receive expected priority boost on time",
2307 __func__, mPortId);
2308 }
2309 // Run again immediately
2310 return 0;
2311 }
2312
2313 // Can only reference mCblk while locked
2314 int32_t flags = android_atomic_and(
2315 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
2316
2317 // Check for track invalidation
2318 if (flags & CBLK_INVALID) {
2319 // for offloaded tracks restoreTrack_l() will just update the sequence and clear
2320 // AudioSystem cache. We should not exit here but after calling the callback so
2321 // that the upper layers can recreate the track
2322 if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
2323 status_t status __unused = restoreTrack_l("processAudioBuffer");
2324 // FIXME unused status
2325 // after restoration, continue below to make sure that the loop and buffer events
2326 // are notified because they have been cleared from mCblk->mFlags above.
2327 }
2328 }
2329
2330 bool waitStreamEnd = mState == STATE_STOPPING;
2331 bool active = mState == STATE_ACTIVE;
2332
2333 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
2334 bool newUnderrun = false;
2335 if (flags & CBLK_UNDERRUN) {
2336 #if 0
2337 // Currently in shared buffer mode, when the server reaches the end of buffer,
2338 // the track stays active in continuous underrun state. It's up to the application
2339 // to pause or stop the track, or set the position to a new offset within buffer.
2340 // This was some experimental code to auto-pause on underrun. Keeping it here
2341 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
2342 if (mTransfer == TRANSFER_SHARED) {
2343 mState = STATE_PAUSED;
2344 active = false;
2345 }
2346 #endif
2347 if (!mInUnderrun) {
2348 mInUnderrun = true;
2349 newUnderrun = true;
2350 }
2351 }
2352
2353 // Get current position of server
2354 Modulo<uint32_t> position(updateAndGetPosition_l());
2355
2356 // Manage marker callback
2357 bool markerReached = false;
2358 Modulo<uint32_t> markerPosition(mMarkerPosition);
2359 // uses 32 bit wraparound for comparison with position.
2360 if (!mMarkerReached && markerPosition.value() > 0 && position >= markerPosition) {
2361 mMarkerReached = markerReached = true;
2362 }
2363
2364 // Determine number of new position callback(s) that will be needed, while locked
2365 size_t newPosCount = 0;
2366 Modulo<uint32_t> newPosition(mNewPosition);
2367 uint32_t updatePeriod = mUpdatePeriod;
2368 // FIXME fails for wraparound, need 64 bits
2369 if (updatePeriod > 0 && position >= newPosition) {
2370 newPosCount = ((position - newPosition).value() / updatePeriod) + 1;
2371 mNewPosition += updatePeriod * newPosCount;
2372 }
2373
2374 // Cache other fields that will be needed soon
2375 uint32_t sampleRate = mSampleRate;
2376 float speed = mPlaybackRate.mSpeed;
2377 const uint32_t notificationFrames = mNotificationFramesAct;
2378 if (mRefreshRemaining) {
2379 mRefreshRemaining = false;
2380 mRemainingFrames = notificationFrames;
2381 mRetryOnPartialBuffer = false;
2382 }
2383 size_t misalignment = mProxy->getMisalignment();
2384 uint32_t sequence = mSequence;
2385 sp<AudioTrackClientProxy> proxy = mProxy;
2386
2387 // Determine the number of new loop callback(s) that will be needed, while locked.
2388 int loopCountNotifications = 0;
2389 uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
2390
2391 if (mLoopCount > 0) {
2392 int loopCount;
2393 size_t bufferPosition;
2394 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
2395 loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
2396 loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
2397 mLoopCountNotified = loopCount; // discard any excess notifications
2398 } else if (mLoopCount < 0) {
2399 // FIXME: We're not accurate with notification count and position with infinite looping
2400 // since loopCount from server side will always return -1 (we could decrement it).
2401 size_t bufferPosition = mStaticProxy->getBufferPosition();
2402 loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
2403 loopPeriod = mLoopEnd - bufferPosition;
2404 } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
2405 size_t bufferPosition = mStaticProxy->getBufferPosition();
2406 loopPeriod = mFrameCount - bufferPosition;
2407 }
2408
2409 // These fields don't need to be cached, because they are assigned only by set():
2410 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
2411 // mFlags is also assigned by createTrack_l(), but not the bit we care about.
2412
2413 mLock.unlock();
2414
2415 // get anchor time to account for callbacks.
2416 const nsecs_t timeBeforeCallbacks = systemTime();
2417
2418 if (waitStreamEnd) {
2419 // FIXME: Instead of blocking in proxy->waitStreamEndDone(), Callback thread
2420 // should wait on proxy futex and handle CBLK_STREAM_END_DONE within this function
2421 // (and make sure we don't callback for more data while we're stopping).
2422 // This helps with position, marker notifications, and track invalidation.
2423 struct timespec timeout;
2424 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
2425 timeout.tv_nsec = 0;
2426
2427 status_t status = proxy->waitStreamEndDone(&timeout);
2428 switch (status) {
2429 case NO_ERROR:
2430 case DEAD_OBJECT:
2431 case TIMED_OUT:
2432 if (status != DEAD_OBJECT) {
2433 // for DEAD_OBJECT, we do not send a EVENT_STREAM_END after stop();
2434 // instead, the application should handle the EVENT_NEW_IAUDIOTRACK.
2435 mCbf(EVENT_STREAM_END, mUserData, NULL);
2436 }
2437 {
2438 AutoMutex lock(mLock);
2439 // The previously assigned value of waitStreamEnd is no longer valid,
2440 // since the mutex has been unlocked and either the callback handler
2441 // or another thread could have re-started the AudioTrack during that time.
2442 waitStreamEnd = mState == STATE_STOPPING;
2443 if (waitStreamEnd) {
2444 mState = STATE_STOPPED;
2445 mReleased = 0;
2446 }
2447 }
2448 if (waitStreamEnd && status != DEAD_OBJECT) {
2449 return NS_INACTIVE;
2450 }
2451 break;
2452 }
2453 return 0;
2454 }
2455
2456 // perform callbacks while unlocked
2457 if (newUnderrun) {
2458 mCbf(EVENT_UNDERRUN, mUserData, NULL);
2459 }
2460 while (loopCountNotifications > 0) {
2461 mCbf(EVENT_LOOP_END, mUserData, NULL);
2462 --loopCountNotifications;
2463 }
2464 if (flags & CBLK_BUFFER_END) {
2465 mCbf(EVENT_BUFFER_END, mUserData, NULL);
2466 }
2467 if (markerReached) {
2468 mCbf(EVENT_MARKER, mUserData, &markerPosition);
2469 }
2470 while (newPosCount > 0) {
2471 size_t temp = newPosition.value(); // FIXME size_t != uint32_t
2472 mCbf(EVENT_NEW_POS, mUserData, &temp);
2473 newPosition += updatePeriod;
2474 newPosCount--;
2475 }
2476
2477 if (mObservedSequence != sequence) {
2478 mObservedSequence = sequence;
2479 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
2480 // for offloaded tracks, just wait for the upper layers to recreate the track
2481 if (isOffloadedOrDirect()) {
2482 return NS_INACTIVE;
2483 }
2484 }
2485
2486 // if inactive, then don't run me again until re-started
2487 if (!active) {
2488 return NS_INACTIVE;
2489 }
2490
2491 // Compute the estimated time until the next timed event (position, markers, loops)
2492 // FIXME only for non-compressed audio
2493 uint32_t minFrames = ~0;
2494 if (!markerReached && position < markerPosition) {
2495 minFrames = (markerPosition - position).value();
2496 }
2497 if (loopPeriod > 0 && loopPeriod < minFrames) {
2498 // loopPeriod is already adjusted for actual position.
2499 minFrames = loopPeriod;
2500 }
2501 if (updatePeriod > 0) {
2502 minFrames = min(minFrames, (newPosition - position).value());
2503 }
2504
2505 // If > 0, poll periodically to recover from a stuck server. A good value is 2.
2506 static const uint32_t kPoll = 0;
2507 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
2508 minFrames = kPoll * notificationFrames;
2509 }
2510
2511 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
2512 static const nsecs_t kWaitPeriodNs = WAIT_PERIOD_MS * 1000000LL;
2513 const nsecs_t timeAfterCallbacks = systemTime();
2514
2515 // Convert frame units to time units
2516 nsecs_t ns = NS_WHENEVER;
2517 if (minFrames != (uint32_t) ~0) {
2518 // AudioFlinger consumption of client data may be irregular when coming out of device
2519 // standby since the kernel buffers require filling. This is throttled to no more than 2x
2520 // the expected rate in the MixerThread. Hence, we reduce the estimated time to wait by one
2521 // half (but no more than half a second) to improve callback accuracy during these temporary
2522 // data surges.
2523 const nsecs_t estimatedNs = framesToNanoseconds(minFrames, sampleRate, speed);
2524 constexpr nsecs_t maxThrottleCompensationNs = 500000000LL;
2525 ns = estimatedNs - min(estimatedNs / 2, maxThrottleCompensationNs) + kWaitPeriodNs;
2526 ns -= (timeAfterCallbacks - timeBeforeCallbacks); // account for callback time
2527 // TODO: Should we warn if the callback time is too long?
2528 if (ns < 0) ns = 0;
2529 }
2530
2531 // If not supplying data by EVENT_MORE_DATA or EVENT_CAN_WRITE_MORE_DATA, then we're done
2532 if (mTransfer != TRANSFER_CALLBACK && mTransfer != TRANSFER_SYNC_NOTIF_CALLBACK) {
2533 return ns;
2534 }
2535
2536 // EVENT_MORE_DATA callback handling.
2537 // Timing for linear pcm audio data formats can be derived directly from the
2538 // buffer fill level.
2539 // Timing for compressed data is not directly available from the buffer fill level,
2540 // rather indirectly from waiting for blocking mode callbacks or waiting for obtain()
2541 // to return a certain fill level.
2542
2543 struct timespec timeout;
2544 const struct timespec *requested = &ClientProxy::kForever;
2545 if (ns != NS_WHENEVER) {
2546 timeout.tv_sec = ns / 1000000000LL;
2547 timeout.tv_nsec = ns % 1000000000LL;
2548 ALOGV("%s(%d): timeout %ld.%03d",
2549 __func__, mPortId, timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
2550 requested = &timeout;
2551 }
2552
2553 size_t writtenFrames = 0;
2554 while (mRemainingFrames > 0) {
2555
2556 Buffer audioBuffer;
2557 audioBuffer.frameCount = mRemainingFrames;
2558 size_t nonContig;
2559 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
2560 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
2561 "%s(%d): obtainBuffer() err=%d frameCount=%zu",
2562 __func__, mPortId, err, audioBuffer.frameCount);
2563 requested = &ClientProxy::kNonBlocking;
2564 size_t avail = audioBuffer.frameCount + nonContig;
2565 ALOGV("%s(%d): obtainBuffer(%u) returned %zu = %zu + %zu err %d",
2566 __func__, mPortId, mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
2567 if (err != NO_ERROR) {
2568 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
2569 (isOffloaded() && (err == DEAD_OBJECT))) {
2570 // FIXME bug 25195759
2571 return 1000000;
2572 }
2573 ALOGE("%s(%d): Error %d obtaining an audio buffer, giving up.",
2574 __func__, mPortId, err);
2575 return NS_NEVER;
2576 }
2577
2578 if (mRetryOnPartialBuffer && audio_has_proportional_frames(mFormat)) {
2579 mRetryOnPartialBuffer = false;
2580 if (avail < mRemainingFrames) {
2581 if (ns > 0) { // account for obtain time
2582 const nsecs_t timeNow = systemTime();
2583 ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2584 }
2585
2586 // delayNs is first computed by the additional frames required in the buffer.
2587 nsecs_t delayNs = framesToNanoseconds(
2588 mRemainingFrames - avail, sampleRate, speed);
2589
2590 // afNs is the AudioFlinger mixer period in ns.
2591 const nsecs_t afNs = framesToNanoseconds(mAfFrameCount, mAfSampleRate, speed);
2592
2593 // If the AudioTrack is double buffered based on the AudioFlinger mixer period,
2594 // we may have a race if we wait based on the number of frames desired.
2595 // This is a possible issue with resampling and AAudio.
2596 //
2597 // The granularity of audioflinger processing is one mixer period; if
2598 // our wait time is less than one mixer period, wait at most half the period.
2599 if (delayNs < afNs) {
2600 delayNs = std::min(delayNs, afNs / 2);
2601 }
2602
2603 // adjust our ns wait by delayNs.
2604 if (ns < 0 /* NS_WHENEVER */ || delayNs < ns) {
2605 ns = delayNs;
2606 }
2607 return ns;
2608 }
2609 }
2610
2611 size_t reqSize = audioBuffer.size;
2612 if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
2613 // when notifying client it can write more data, pass the total size that can be
2614 // written in the next write() call, since it's not passed through the callback
2615 audioBuffer.size += nonContig;
2616 }
2617 mCbf(mTransfer == TRANSFER_CALLBACK ? EVENT_MORE_DATA : EVENT_CAN_WRITE_MORE_DATA,
2618 mUserData, &audioBuffer);
2619 size_t writtenSize = audioBuffer.size;
2620
2621 // Validate on returned size
2622 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
2623 ALOGE("%s(%d): EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
2624 __func__, mPortId, reqSize, ssize_t(writtenSize));
2625 return NS_NEVER;
2626 }
2627
2628 if (writtenSize == 0) {
2629 if (mTransfer == TRANSFER_SYNC_NOTIF_CALLBACK) {
2630 // The callback EVENT_CAN_WRITE_MORE_DATA was processed in the JNI of
2631 // android.media.AudioTrack. The JNI is not using the callback to provide data,
2632 // it only signals to the Java client that it can provide more data, which
2633 // this track is read to accept now.
2634 // The playback thread will be awaken at the next ::write()
2635 return NS_WHENEVER;
2636 }
2637 // The callback is done filling buffers
2638 // Keep this thread going to handle timed events and
2639 // still try to get more data in intervals of WAIT_PERIOD_MS
2640 // but don't just loop and block the CPU, so wait
2641
2642 // mCbf(EVENT_MORE_DATA, ...) might either
2643 // (1) Block until it can fill the buffer, returning 0 size on EOS.
2644 // (2) Block until it can fill the buffer, returning 0 data (silence) on EOS.
2645 // (3) Return 0 size when no data is available, does not wait for more data.
2646 //
2647 // (1) and (2) occurs with AudioPlayer/AwesomePlayer; (3) occurs with NuPlayer.
2648 // We try to compute the wait time to avoid a tight sleep-wait cycle,
2649 // especially for case (3).
2650 //
2651 // The decision to support (1) and (2) affect the sizing of mRemainingFrames
2652 // and this loop; whereas for case (3) we could simply check once with the full
2653 // buffer size and skip the loop entirely.
2654
2655 nsecs_t myns;
2656 if (audio_has_proportional_frames(mFormat)) {
2657 // time to wait based on buffer occupancy
2658 const nsecs_t datans = mRemainingFrames <= avail ? 0 :
2659 framesToNanoseconds(mRemainingFrames - avail, sampleRate, speed);
2660 // audio flinger thread buffer size (TODO: adjust for fast tracks)
2661 // FIXME: use mAfFrameCountHAL instead of mAfFrameCount below for fast tracks.
2662 const nsecs_t afns = framesToNanoseconds(mAfFrameCount, mAfSampleRate, speed);
2663 // add a half the AudioFlinger buffer time to avoid soaking CPU if datans is 0.
2664 myns = datans + (afns / 2);
2665 } else {
2666 // FIXME: This could ping quite a bit if the buffer isn't full.
2667 // Note that when mState is stopping we waitStreamEnd, so it never gets here.
2668 myns = kWaitPeriodNs;
2669 }
2670 if (ns > 0) { // account for obtain and callback time
2671 const nsecs_t timeNow = systemTime();
2672 ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2673 }
2674 if (ns < 0 /* NS_WHENEVER */ || myns < ns) {
2675 ns = myns;
2676 }
2677 return ns;
2678 }
2679
2680 size_t releasedFrames = writtenSize / mFrameSize;
2681 audioBuffer.frameCount = releasedFrames;
2682 mRemainingFrames -= releasedFrames;
2683 if (misalignment >= releasedFrames) {
2684 misalignment -= releasedFrames;
2685 } else {
2686 misalignment = 0;
2687 }
2688
2689 releaseBuffer(&audioBuffer);
2690 writtenFrames += releasedFrames;
2691
2692 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
2693 // if callback doesn't like to accept the full chunk
2694 if (writtenSize < reqSize) {
2695 continue;
2696 }
2697
2698 // There could be enough non-contiguous frames available to satisfy the remaining request
2699 if (mRemainingFrames <= nonContig) {
2700 continue;
2701 }
2702
2703 #if 0
2704 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
2705 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA
2706 // that total to a sum == notificationFrames.
2707 if (0 < misalignment && misalignment <= mRemainingFrames) {
2708 mRemainingFrames = misalignment;
2709 return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
2710 }
2711 #endif
2712
2713 }
2714 if (writtenFrames > 0) {
2715 AutoMutex lock(mLock);
2716 mFramesWritten += writtenFrames;
2717 }
2718 mRemainingFrames = notificationFrames;
2719 mRetryOnPartialBuffer = true;
2720
2721 // A lot has transpired since ns was calculated, so run again immediately and re-calculate
2722 return 0;
2723 }
2724
restoreTrack_l(const char * from)2725 status_t AudioTrack::restoreTrack_l(const char *from)
2726 {
2727 status_t result = NO_ERROR; // logged: make sure to set this before returning.
2728 const int64_t beginNs = systemTime();
2729 mediametrics::Defer defer([&] {
2730 mediametrics::LogItem(mMetricsId)
2731 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_RESTORE)
2732 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
2733 .set(AMEDIAMETRICS_PROP_STATE, stateToString(mState))
2734 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)result)
2735 .set(AMEDIAMETRICS_PROP_WHERE, from)
2736 .record(); });
2737
2738 ALOGW("%s(%d): dead IAudioTrack, %s, creating a new one from %s()",
2739 __func__, mPortId, isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
2740 ++mSequence;
2741
2742 // refresh the audio configuration cache in this process to make sure we get new
2743 // output parameters and new IAudioFlinger in createTrack_l()
2744 AudioSystem::clearAudioConfigCache();
2745
2746 if (isOffloadedOrDirect_l() || mDoNotReconnect) {
2747 // FIXME re-creation of offloaded and direct tracks is not yet implemented;
2748 // reconsider enabling for linear PCM encodings when position can be preserved.
2749 result = DEAD_OBJECT;
2750 return result;
2751 }
2752
2753 // Save so we can return count since creation.
2754 mUnderrunCountOffset = getUnderrunCount_l();
2755
2756 // save the old static buffer position
2757 uint32_t staticPosition = 0;
2758 size_t bufferPosition = 0;
2759 int loopCount = 0;
2760 if (mStaticProxy != 0) {
2761 mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
2762 staticPosition = mStaticProxy->getPosition().unsignedValue();
2763 }
2764
2765 // save the old startThreshold and framecount
2766 const uint32_t originalStartThresholdInFrames = mProxy->getStartThresholdInFrames();
2767 const uint32_t originalFrameCount = mProxy->frameCount();
2768
2769 // See b/74409267. Connecting to a BT A2DP device supporting multiple codecs
2770 // causes a lot of churn on the service side, and it can reject starting
2771 // playback of a previously created track. May also apply to other cases.
2772 const int INITIAL_RETRIES = 3;
2773 int retries = INITIAL_RETRIES;
2774 retry:
2775 if (retries < INITIAL_RETRIES) {
2776 // See the comment for clearAudioConfigCache at the start of the function.
2777 AudioSystem::clearAudioConfigCache();
2778 }
2779 mFlags = mOrigFlags;
2780
2781 // If a new IAudioTrack is successfully created, createTrack_l() will modify the
2782 // following member variables: mAudioTrack, mCblkMemory and mCblk.
2783 // It will also delete the strong references on previous IAudioTrack and IMemory.
2784 // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
2785 result = createTrack_l();
2786
2787 if (result == NO_ERROR) {
2788 // take the frames that will be lost by track recreation into account in saved position
2789 // For streaming tracks, this is the amount we obtained from the user/client
2790 // (not the number actually consumed at the server - those are already lost).
2791 if (mStaticProxy == 0) {
2792 mPosition = mReleased;
2793 }
2794 // Continue playback from last known position and restore loop.
2795 if (mStaticProxy != 0) {
2796 if (loopCount != 0) {
2797 mStaticProxy->setBufferPositionAndLoop(bufferPosition,
2798 mLoopStart, mLoopEnd, loopCount);
2799 } else {
2800 mStaticProxy->setBufferPosition(bufferPosition);
2801 if (bufferPosition == mFrameCount) {
2802 ALOGD("%s(%d): restoring track at end of static buffer", __func__, mPortId);
2803 }
2804 }
2805 }
2806 // restore volume handler
2807 mVolumeHandler->forall([this](const VolumeShaper &shaper) -> VolumeShaper::Status {
2808 sp<VolumeShaper::Operation> operationToEnd =
2809 new VolumeShaper::Operation(shaper.mOperation);
2810 // TODO: Ideally we would restore to the exact xOffset position
2811 // as returned by getVolumeShaperState(), but we don't have that
2812 // information when restoring at the client unless we periodically poll
2813 // the server or create shared memory state.
2814 //
2815 // For now, we simply advance to the end of the VolumeShaper effect
2816 // if it has been started.
2817 if (shaper.isStarted()) {
2818 operationToEnd->setNormalizedTime(1.f);
2819 }
2820 media::VolumeShaperConfiguration config;
2821 shaper.mConfiguration->writeToParcelable(&config);
2822 media::VolumeShaperOperation operation;
2823 operationToEnd->writeToParcelable(&operation);
2824 status_t status;
2825 mAudioTrack->applyVolumeShaper(config, operation, &status);
2826 return status;
2827 });
2828
2829 // restore the original start threshold if different than frameCount.
2830 if (originalStartThresholdInFrames != originalFrameCount) {
2831 // Note: mProxy->setStartThresholdInFrames() call is in the Proxy
2832 // and does not trigger a restart.
2833 // (Also CBLK_DISABLED is not set, buffers are empty after track recreation).
2834 // Any start would be triggered on the mState == ACTIVE check below.
2835 const uint32_t currentThreshold =
2836 mProxy->setStartThresholdInFrames(originalStartThresholdInFrames);
2837 ALOGD_IF(originalStartThresholdInFrames != currentThreshold,
2838 "%s(%d) startThresholdInFrames changing from %u to %u",
2839 __func__, mPortId, originalStartThresholdInFrames, currentThreshold);
2840 }
2841 if (mState == STATE_ACTIVE) {
2842 mAudioTrack->start(&result);
2843 }
2844 // server resets to zero so we offset
2845 mFramesWrittenServerOffset =
2846 mStaticProxy.get() != nullptr ? staticPosition : mFramesWritten;
2847 mFramesWrittenAtRestore = mFramesWrittenServerOffset;
2848 }
2849 if (result != NO_ERROR) {
2850 ALOGW("%s(%d): failed status %d, retries %d", __func__, mPortId, result, retries);
2851 if (--retries > 0) {
2852 // leave time for an eventual race condition to clear before retrying
2853 usleep(500000);
2854 goto retry;
2855 }
2856 // if no retries left, set invalid bit to force restoring at next occasion
2857 // and avoid inconsistent active state on client and server sides
2858 if (mCblk != nullptr) {
2859 android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
2860 }
2861 }
2862 return result;
2863 }
2864
updateAndGetPosition_l()2865 Modulo<uint32_t> AudioTrack::updateAndGetPosition_l()
2866 {
2867 // This is the sole place to read server consumed frames
2868 Modulo<uint32_t> newServer(mProxy->getPosition());
2869 const int32_t delta = (newServer - mServer).signedValue();
2870 // TODO There is controversy about whether there can be "negative jitter" in server position.
2871 // This should be investigated further, and if possible, it should be addressed.
2872 // A more definite failure mode is infrequent polling by client.
2873 // One could call (void)getPosition_l() in releaseBuffer(),
2874 // so mReleased and mPosition are always lock-step as best possible.
2875 // That should ensure delta never goes negative for infrequent polling
2876 // unless the server has more than 2^31 frames in its buffer,
2877 // in which case the use of uint32_t for these counters has bigger issues.
2878 ALOGE_IF(delta < 0,
2879 "%s(%d): detected illegal retrograde motion by the server: mServer advanced by %d",
2880 __func__, mPortId, delta);
2881 mServer = newServer;
2882 if (delta > 0) { // avoid retrograde
2883 mPosition += delta;
2884 }
2885 return mPosition;
2886 }
2887
isSampleRateSpeedAllowed_l(uint32_t sampleRate,float speed)2888 bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed)
2889 {
2890 updateLatency_l();
2891 // applicable for mixing tracks only (not offloaded or direct)
2892 if (mStaticProxy != 0) {
2893 return true; // static tracks do not have issues with buffer sizing.
2894 }
2895 const size_t minFrameCount =
2896 AudioSystem::calculateMinFrameCount(mAfLatency, mAfFrameCount, mAfSampleRate,
2897 sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2898 const bool allowed = mFrameCount >= minFrameCount;
2899 ALOGD_IF(!allowed,
2900 "%s(%d): denied "
2901 "mAfLatency:%u mAfFrameCount:%zu mAfSampleRate:%u sampleRate:%u speed:%f "
2902 "mFrameCount:%zu < minFrameCount:%zu",
2903 __func__, mPortId,
2904 mAfLatency, mAfFrameCount, mAfSampleRate, sampleRate, speed,
2905 mFrameCount, minFrameCount);
2906 return allowed;
2907 }
2908
setParameters(const String8 & keyValuePairs)2909 status_t AudioTrack::setParameters(const String8& keyValuePairs)
2910 {
2911 AutoMutex lock(mLock);
2912 status_t status;
2913 mAudioTrack->setParameters(keyValuePairs.c_str(), &status);
2914 return status;
2915 }
2916
selectPresentation(int presentationId,int programId)2917 status_t AudioTrack::selectPresentation(int presentationId, int programId)
2918 {
2919 AutoMutex lock(mLock);
2920 AudioParameter param = AudioParameter();
2921 param.addInt(String8(AudioParameter::keyPresentationId), presentationId);
2922 param.addInt(String8(AudioParameter::keyProgramId), programId);
2923 ALOGV("%s(%d): PresentationId/ProgramId[%s]",
2924 __func__, mPortId, param.toString().string());
2925
2926 status_t status;
2927 mAudioTrack->setParameters(param.toString().c_str(), &status);
2928 return status;
2929 }
2930
applyVolumeShaper(const sp<VolumeShaper::Configuration> & configuration,const sp<VolumeShaper::Operation> & operation)2931 VolumeShaper::Status AudioTrack::applyVolumeShaper(
2932 const sp<VolumeShaper::Configuration>& configuration,
2933 const sp<VolumeShaper::Operation>& operation)
2934 {
2935 AutoMutex lock(mLock);
2936 mVolumeHandler->setIdIfNecessary(configuration);
2937 media::VolumeShaperConfiguration config;
2938 configuration->writeToParcelable(&config);
2939 media::VolumeShaperOperation op;
2940 operation->writeToParcelable(&op);
2941 VolumeShaper::Status status;
2942 mAudioTrack->applyVolumeShaper(config, op, &status);
2943
2944 if (status == DEAD_OBJECT) {
2945 if (restoreTrack_l("applyVolumeShaper") == OK) {
2946 mAudioTrack->applyVolumeShaper(config, op, &status);
2947 }
2948 }
2949 if (status >= 0) {
2950 // save VolumeShaper for restore
2951 mVolumeHandler->applyVolumeShaper(configuration, operation);
2952 if (mState == STATE_ACTIVE || mState == STATE_STOPPING) {
2953 mVolumeHandler->setStarted();
2954 }
2955 } else {
2956 // warn only if not an expected restore failure.
2957 ALOGW_IF(!((isOffloadedOrDirect_l() || mDoNotReconnect) && status == DEAD_OBJECT),
2958 "%s(%d): applyVolumeShaper failed: %d", __func__, mPortId, status);
2959 }
2960 return status;
2961 }
2962
getVolumeShaperState(int id)2963 sp<VolumeShaper::State> AudioTrack::getVolumeShaperState(int id)
2964 {
2965 AutoMutex lock(mLock);
2966 std::optional<media::VolumeShaperState> vss;
2967 mAudioTrack->getVolumeShaperState(id, &vss);
2968 sp<VolumeShaper::State> state;
2969 if (vss.has_value()) {
2970 state = new VolumeShaper::State();
2971 state->readFromParcelable(vss.value());
2972 }
2973 if (state.get() == nullptr && (mCblk->mFlags & CBLK_INVALID) != 0) {
2974 if (restoreTrack_l("getVolumeShaperState") == OK) {
2975 mAudioTrack->getVolumeShaperState(id, &vss);
2976 if (vss.has_value()) {
2977 state = new VolumeShaper::State();
2978 state->readFromParcelable(vss.value());
2979 }
2980 }
2981 }
2982 return state;
2983 }
2984
getTimestamp(ExtendedTimestamp * timestamp)2985 status_t AudioTrack::getTimestamp(ExtendedTimestamp *timestamp)
2986 {
2987 if (timestamp == nullptr) {
2988 return BAD_VALUE;
2989 }
2990 AutoMutex lock(mLock);
2991 return getTimestamp_l(timestamp);
2992 }
2993
getTimestamp_l(ExtendedTimestamp * timestamp)2994 status_t AudioTrack::getTimestamp_l(ExtendedTimestamp *timestamp)
2995 {
2996 if (mCblk->mFlags & CBLK_INVALID) {
2997 const status_t status = restoreTrack_l("getTimestampExtended");
2998 if (status != OK) {
2999 // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
3000 // recommending that the track be recreated.
3001 return DEAD_OBJECT;
3002 }
3003 }
3004 // check for offloaded/direct here in case restoring somehow changed those flags.
3005 if (isOffloadedOrDirect_l()) {
3006 return INVALID_OPERATION; // not supported
3007 }
3008 status_t status = mProxy->getTimestamp(timestamp);
3009 LOG_ALWAYS_FATAL_IF(status != OK, "%s(%d): status %d not allowed from proxy getTimestamp",
3010 __func__, mPortId, status);
3011 bool found = false;
3012 timestamp->mPosition[ExtendedTimestamp::LOCATION_CLIENT] = mFramesWritten;
3013 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_CLIENT] = 0;
3014 // server side frame offset in case AudioTrack has been restored.
3015 for (int i = ExtendedTimestamp::LOCATION_SERVER;
3016 i < ExtendedTimestamp::LOCATION_MAX; ++i) {
3017 if (timestamp->mTimeNs[i] >= 0) {
3018 // apply server offset (frames flushed is ignored
3019 // so we don't report the jump when the flush occurs).
3020 timestamp->mPosition[i] += mFramesWrittenServerOffset;
3021 found = true;
3022 }
3023 }
3024 return found ? OK : WOULD_BLOCK;
3025 }
3026
getTimestamp(AudioTimestamp & timestamp)3027 status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
3028 {
3029 AutoMutex lock(mLock);
3030 return getTimestamp_l(timestamp);
3031 }
3032
getTimestamp_l(AudioTimestamp & timestamp)3033 status_t AudioTrack::getTimestamp_l(AudioTimestamp& timestamp)
3034 {
3035 bool previousTimestampValid = mPreviousTimestampValid;
3036 // Set false here to cover all the error return cases.
3037 mPreviousTimestampValid = false;
3038
3039 switch (mState) {
3040 case STATE_ACTIVE:
3041 case STATE_PAUSED:
3042 break; // handle below
3043 case STATE_FLUSHED:
3044 case STATE_STOPPED:
3045 return WOULD_BLOCK;
3046 case STATE_STOPPING:
3047 case STATE_PAUSED_STOPPING:
3048 if (!isOffloaded_l()) {
3049 return INVALID_OPERATION;
3050 }
3051 break; // offloaded tracks handled below
3052 default:
3053 LOG_ALWAYS_FATAL("%s(%d): Invalid mState in getTimestamp(): %d",
3054 __func__, mPortId, mState);
3055 break;
3056 }
3057
3058 if (mCblk->mFlags & CBLK_INVALID) {
3059 const status_t status = restoreTrack_l("getTimestamp");
3060 if (status != OK) {
3061 // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
3062 // recommending that the track be recreated.
3063 return DEAD_OBJECT;
3064 }
3065 }
3066
3067 // The presented frame count must always lag behind the consumed frame count.
3068 // To avoid a race, read the presented frames first. This ensures that presented <= consumed.
3069
3070 status_t status;
3071 if (isOffloadedOrDirect_l()) {
3072 // use Binder to get timestamp
3073 media::AudioTimestampInternal ts;
3074 mAudioTrack->getTimestamp(&ts, &status);
3075 if (status == OK) {
3076 timestamp = VALUE_OR_FATAL(aidl2legacy_AudioTimestampInternal_AudioTimestamp(ts));
3077 }
3078 } else {
3079 // read timestamp from shared memory
3080 ExtendedTimestamp ets;
3081 status = mProxy->getTimestamp(&ets);
3082 if (status == OK) {
3083 ExtendedTimestamp::Location location;
3084 status = ets.getBestTimestamp(×tamp, &location);
3085
3086 if (status == OK) {
3087 updateLatency_l();
3088 // It is possible that the best location has moved from the kernel to the server.
3089 // In this case we adjust the position from the previous computed latency.
3090 if (location == ExtendedTimestamp::LOCATION_SERVER) {
3091 ALOGW_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_KERNEL,
3092 "%s(%d): location moved from kernel to server",
3093 __func__, mPortId);
3094 // check that the last kernel OK time info exists and the positions
3095 // are valid (if they predate the current track, the positions may
3096 // be zero or negative).
3097 const int64_t frames =
3098 (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
3099 ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0 ||
3100 ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] <= 0 ||
3101 ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] <= 0)
3102 ?
3103 int64_t((double)mAfLatency * mSampleRate * mPlaybackRate.mSpeed
3104 / 1000)
3105 :
3106 (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
3107 - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK]);
3108 ALOGV("%s(%d): frame adjustment:%lld timestamp:%s",
3109 __func__, mPortId, (long long)frames, ets.toString().c_str());
3110 if (frames >= ets.mPosition[location]) {
3111 timestamp.mPosition = 0;
3112 } else {
3113 timestamp.mPosition = (uint32_t)(ets.mPosition[location] - frames);
3114 }
3115 } else if (location == ExtendedTimestamp::LOCATION_KERNEL) {
3116 ALOGV_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_SERVER,
3117 "%s(%d): location moved from server to kernel",
3118 __func__, mPortId);
3119
3120 if (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER] ==
3121 ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL]) {
3122 // In Q, we don't return errors as an invalid time
3123 // but instead we leave the last kernel good timestamp alone.
3124 //
3125 // If server is identical to kernel, the device data pipeline is idle.
3126 // A better start time is now. The retrograde check ensures
3127 // timestamp monotonicity.
3128 const int64_t nowNs = systemTime();
3129 if (!mTimestampStallReported) {
3130 ALOGD("%s(%d): device stall time corrected using current time %lld",
3131 __func__, mPortId, (long long)nowNs);
3132 mTimestampStallReported = true;
3133 }
3134 timestamp.mTime = convertNsToTimespec(nowNs);
3135 } else {
3136 mTimestampStallReported = false;
3137 }
3138 }
3139
3140 // We update the timestamp time even when paused.
3141 if (mState == STATE_PAUSED /* not needed: STATE_PAUSED_STOPPING */) {
3142 const int64_t now = systemTime();
3143 const int64_t at = audio_utils_ns_from_timespec(×tamp.mTime);
3144 const int64_t lag =
3145 (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
3146 ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0)
3147 ? int64_t(mAfLatency * 1000000LL)
3148 : (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
3149 - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK])
3150 * NANOS_PER_SECOND / mSampleRate;
3151 const int64_t limit = now - lag; // no earlier than this limit
3152 if (at < limit) {
3153 ALOGV("timestamp pause lag:%lld adjusting from %lld to %lld",
3154 (long long)lag, (long long)at, (long long)limit);
3155 timestamp.mTime = convertNsToTimespec(limit);
3156 }
3157 }
3158 mPreviousLocation = location;
3159 } else {
3160 // right after AudioTrack is started, one may not find a timestamp
3161 ALOGV("%s(%d): getBestTimestamp did not find timestamp", __func__, mPortId);
3162 }
3163 }
3164 if (status == INVALID_OPERATION) {
3165 // INVALID_OPERATION occurs when no timestamp has been issued by the server;
3166 // other failures are signaled by a negative time.
3167 // If we come out of FLUSHED or STOPPED where the position is known
3168 // to be zero we convert this to WOULD_BLOCK (with the implicit meaning of
3169 // "zero" for NuPlayer). We don't convert for track restoration as position
3170 // does not reset.
3171 ALOGV("%s(%d): timestamp server offset:%lld restore frames:%lld",
3172 __func__, mPortId,
3173 (long long)mFramesWrittenServerOffset, (long long)mFramesWrittenAtRestore);
3174 if (mFramesWrittenServerOffset != mFramesWrittenAtRestore) {
3175 status = WOULD_BLOCK;
3176 }
3177 }
3178 }
3179 if (status != NO_ERROR) {
3180 ALOGV_IF(status != WOULD_BLOCK, "%s(%d): getTimestamp error:%#x", __func__, mPortId, status);
3181 return status;
3182 }
3183 if (isOffloadedOrDirect_l()) {
3184 if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
3185 // use cached paused position in case another offloaded track is running.
3186 timestamp.mPosition = mPausedPosition;
3187 clock_gettime(CLOCK_MONOTONIC, ×tamp.mTime);
3188 // TODO: adjust for delay
3189 return NO_ERROR;
3190 }
3191
3192 // Check whether a pending flush or stop has completed, as those commands may
3193 // be asynchronous or return near finish or exhibit glitchy behavior.
3194 //
3195 // Originally this showed up as the first timestamp being a continuation of
3196 // the previous song under gapless playback.
3197 // However, we sometimes see zero timestamps, then a glitch of
3198 // the previous song's position, and then correct timestamps afterwards.
3199 if (mStartFromZeroUs != 0 && mSampleRate != 0) {
3200 static const int kTimeJitterUs = 100000; // 100 ms
3201 static const int k1SecUs = 1000000;
3202
3203 const int64_t timeNow = getNowUs();
3204
3205 if (timeNow < mStartFromZeroUs + k1SecUs) { // within first second of starting
3206 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
3207 if (timestampTimeUs < mStartFromZeroUs) {
3208 return WOULD_BLOCK; // stale timestamp time, occurs before start.
3209 }
3210 const int64_t deltaTimeUs = timestampTimeUs - mStartFromZeroUs;
3211 const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
3212 / ((double)mSampleRate * mPlaybackRate.mSpeed);
3213
3214 if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
3215 // Verify that the counter can't count faster than the sample rate
3216 // since the start time. If greater, then that means we may have failed
3217 // to completely flush or stop the previous playing track.
3218 ALOGW_IF(!mTimestampStartupGlitchReported,
3219 "%s(%d): startup glitch detected"
3220 " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
3221 __func__, mPortId,
3222 (long long)deltaTimeUs, (long long)deltaPositionByUs,
3223 timestamp.mPosition);
3224 mTimestampStartupGlitchReported = true;
3225 if (previousTimestampValid
3226 && mPreviousTimestamp.mPosition == 0 /* should be true if valid */) {
3227 timestamp = mPreviousTimestamp;
3228 mPreviousTimestampValid = true;
3229 return NO_ERROR;
3230 }
3231 return WOULD_BLOCK;
3232 }
3233 if (deltaPositionByUs != 0) {
3234 mStartFromZeroUs = 0; // don't check again, we got valid nonzero position.
3235 }
3236 } else {
3237 mStartFromZeroUs = 0; // don't check again, start time expired.
3238 }
3239 mTimestampStartupGlitchReported = false;
3240 }
3241 } else {
3242 // Update the mapping between local consumed (mPosition) and server consumed (mServer)
3243 (void) updateAndGetPosition_l();
3244 // Server consumed (mServer) and presented both use the same server time base,
3245 // and server consumed is always >= presented.
3246 // The delta between these represents the number of frames in the buffer pipeline.
3247 // If this delta between these is greater than the client position, it means that
3248 // actually presented is still stuck at the starting line (figuratively speaking),
3249 // waiting for the first frame to go by. So we can't report a valid timestamp yet.
3250 // Note: We explicitly use non-Modulo comparison here - potential wrap issue when
3251 // mPosition exceeds 32 bits.
3252 // TODO Remove when timestamp is updated to contain pipeline status info.
3253 const int32_t pipelineDepthInFrames = (mServer - timestamp.mPosition).signedValue();
3254 if (pipelineDepthInFrames > 0 /* should be true, but we check anyways */
3255 && (uint32_t)pipelineDepthInFrames > mPosition.value()) {
3256 return INVALID_OPERATION;
3257 }
3258 // Convert timestamp position from server time base to client time base.
3259 // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
3260 // But if we change it to 64-bit then this could fail.
3261 // Use Modulo computation here.
3262 timestamp.mPosition = (mPosition - mServer + timestamp.mPosition).value();
3263 // Immediately after a call to getPosition_l(), mPosition and
3264 // mServer both represent the same frame position. mPosition is
3265 // in client's point of view, and mServer is in server's point of
3266 // view. So the difference between them is the "fudge factor"
3267 // between client and server views due to stop() and/or new
3268 // IAudioTrack. And timestamp.mPosition is initially in server's
3269 // point of view, so we need to apply the same fudge factor to it.
3270 }
3271
3272 // Prevent retrograde motion in timestamp.
3273 // This is sometimes caused by erratic reports of the available space in the ALSA drivers.
3274 if (status == NO_ERROR) {
3275 // Fix stale time when checking timestamp right after start().
3276 // The position is at the last reported location but the time can be stale
3277 // due to pause or standby or cold start latency.
3278 //
3279 // We keep advancing the time (but not the position) to ensure that the
3280 // stale value does not confuse the application.
3281 //
3282 // For offload compatibility, use a default lag value here.
3283 // Any time discrepancy between this update and the pause timestamp is handled
3284 // by the retrograde check afterwards.
3285 int64_t currentTimeNanos = audio_utils_ns_from_timespec(×tamp.mTime);
3286 const int64_t lagNs = int64_t(mAfLatency * 1000000LL);
3287 const int64_t limitNs = mStartNs - lagNs;
3288 if (currentTimeNanos < limitNs) {
3289 if (!mTimestampStaleTimeReported) {
3290 ALOGD("%s(%d): stale timestamp time corrected, "
3291 "currentTimeNanos: %lld < limitNs: %lld < mStartNs: %lld",
3292 __func__, mPortId,
3293 (long long)currentTimeNanos, (long long)limitNs, (long long)mStartNs);
3294 mTimestampStaleTimeReported = true;
3295 }
3296 timestamp.mTime = convertNsToTimespec(limitNs);
3297 currentTimeNanos = limitNs;
3298 } else {
3299 mTimestampStaleTimeReported = false;
3300 }
3301
3302 // previousTimestampValid is set to false when starting after a stop or flush.
3303 if (previousTimestampValid) {
3304 const int64_t previousTimeNanos =
3305 audio_utils_ns_from_timespec(&mPreviousTimestamp.mTime);
3306
3307 // retrograde check
3308 if (currentTimeNanos < previousTimeNanos) {
3309 if (!mTimestampRetrogradeTimeReported) {
3310 ALOGW("%s(%d): retrograde timestamp time corrected, %lld < %lld",
3311 __func__, mPortId,
3312 (long long)currentTimeNanos, (long long)previousTimeNanos);
3313 mTimestampRetrogradeTimeReported = true;
3314 }
3315 timestamp.mTime = mPreviousTimestamp.mTime;
3316 } else {
3317 mTimestampRetrogradeTimeReported = false;
3318 }
3319
3320 // Looking at signed delta will work even when the timestamps
3321 // are wrapping around.
3322 int32_t deltaPosition = (Modulo<uint32_t>(timestamp.mPosition)
3323 - mPreviousTimestamp.mPosition).signedValue();
3324 if (deltaPosition < 0) {
3325 // Only report once per position instead of spamming the log.
3326 if (!mTimestampRetrogradePositionReported) {
3327 ALOGW("%s(%d): retrograde timestamp position corrected, %d = %u - %u",
3328 __func__, mPortId,
3329 deltaPosition,
3330 timestamp.mPosition,
3331 mPreviousTimestamp.mPosition);
3332 mTimestampRetrogradePositionReported = true;
3333 }
3334 } else {
3335 mTimestampRetrogradePositionReported = false;
3336 }
3337 if (deltaPosition < 0) {
3338 timestamp.mPosition = mPreviousTimestamp.mPosition;
3339 deltaPosition = 0;
3340 }
3341 #if 0
3342 // Uncomment this to verify audio timestamp rate.
3343 const int64_t deltaTime =
3344 audio_utils_ns_from_timespec(×tamp.mTime) - previousTimeNanos;
3345 if (deltaTime != 0) {
3346 const int64_t computedSampleRate =
3347 deltaPosition * (long long)NANOS_PER_SECOND / deltaTime;
3348 ALOGD("%s(%d): computedSampleRate:%u sampleRate:%u",
3349 __func__, mPortId,
3350 (unsigned)computedSampleRate, mSampleRate);
3351 }
3352 #endif
3353 }
3354 mPreviousTimestamp = timestamp;
3355 mPreviousTimestampValid = true;
3356 }
3357
3358 return status;
3359 }
3360
getParameters(const String8 & keys)3361 String8 AudioTrack::getParameters(const String8& keys)
3362 {
3363 audio_io_handle_t output = getOutput();
3364 if (output != AUDIO_IO_HANDLE_NONE) {
3365 return AudioSystem::getParameters(output, keys);
3366 } else {
3367 return String8::empty();
3368 }
3369 }
3370
isOffloaded() const3371 bool AudioTrack::isOffloaded() const
3372 {
3373 AutoMutex lock(mLock);
3374 return isOffloaded_l();
3375 }
3376
isDirect() const3377 bool AudioTrack::isDirect() const
3378 {
3379 AutoMutex lock(mLock);
3380 return isDirect_l();
3381 }
3382
isOffloadedOrDirect() const3383 bool AudioTrack::isOffloadedOrDirect() const
3384 {
3385 AutoMutex lock(mLock);
3386 return isOffloadedOrDirect_l();
3387 }
3388
3389
dump(int fd,const Vector<String16> & args __unused) const3390 status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
3391 {
3392 String8 result;
3393
3394 result.append(" AudioTrack::dump\n");
3395 result.appendFormat(" id(%d) status(%d), state(%d), session Id(%d), flags(%#x)\n",
3396 mPortId, mStatus, mState, mSessionId, mFlags);
3397 result.appendFormat(" stream type(%d), left - right volume(%f, %f)\n",
3398 mStreamType,
3399 mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
3400 result.appendFormat(" format(%#x), channel mask(%#x), channel count(%u)\n",
3401 mFormat, mChannelMask, mChannelCount);
3402 result.appendFormat(" sample rate(%u), original sample rate(%u), speed(%f)\n",
3403 mSampleRate, mOriginalSampleRate, mPlaybackRate.mSpeed);
3404 result.appendFormat(" frame count(%zu), req. frame count(%zu)\n",
3405 mFrameCount, mReqFrameCount);
3406 result.appendFormat(" notif. frame count(%u), req. notif. frame count(%u),"
3407 " req. notif. per buff(%u)\n",
3408 mNotificationFramesAct, mNotificationFramesReq, mNotificationsPerBufferReq);
3409 result.appendFormat(" latency (%d), selected device Id(%d), routed device Id(%d)\n",
3410 mLatency, mSelectedDeviceId, mRoutedDeviceId);
3411 result.appendFormat(" output(%d) AF latency (%u) AF frame count(%zu) AF SampleRate(%u)\n",
3412 mOutput, mAfLatency, mAfFrameCount, mAfSampleRate);
3413 ::write(fd, result.string(), result.size());
3414 return NO_ERROR;
3415 }
3416
getUnderrunCount() const3417 uint32_t AudioTrack::getUnderrunCount() const
3418 {
3419 AutoMutex lock(mLock);
3420 return getUnderrunCount_l();
3421 }
3422
getUnderrunCount_l() const3423 uint32_t AudioTrack::getUnderrunCount_l() const
3424 {
3425 return mProxy->getUnderrunCount() + mUnderrunCountOffset;
3426 }
3427
getUnderrunFrames() const3428 uint32_t AudioTrack::getUnderrunFrames() const
3429 {
3430 AutoMutex lock(mLock);
3431 return mProxy->getUnderrunFrames();
3432 }
3433
setLogSessionId(const char * logSessionId)3434 void AudioTrack::setLogSessionId(const char *logSessionId)
3435 {
3436 AutoMutex lock(mLock);
3437 if (logSessionId == nullptr) logSessionId = ""; // an empty string is an unset session id.
3438 if (mLogSessionId == logSessionId) return;
3439
3440 mLogSessionId = logSessionId;
3441 mediametrics::LogItem(mMetricsId)
3442 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETLOGSESSIONID)
3443 .set(AMEDIAMETRICS_PROP_LOGSESSIONID, logSessionId)
3444 .record();
3445 }
3446
setPlayerIId(int playerIId)3447 void AudioTrack::setPlayerIId(int playerIId)
3448 {
3449 AutoMutex lock(mLock);
3450 if (mPlayerIId == playerIId) return;
3451
3452 mPlayerIId = playerIId;
3453 mediametrics::LogItem(mMetricsId)
3454 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETPLAYERIID)
3455 .set(AMEDIAMETRICS_PROP_PLAYERIID, playerIId)
3456 .record();
3457 }
3458
addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback> & callback)3459 status_t AudioTrack::addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback)
3460 {
3461
3462 if (callback == 0) {
3463 ALOGW("%s(%d): adding NULL callback!", __func__, mPortId);
3464 return BAD_VALUE;
3465 }
3466 AutoMutex lock(mLock);
3467 if (mDeviceCallback.unsafe_get() == callback.get()) {
3468 ALOGW("%s(%d): adding same callback!", __func__, mPortId);
3469 return INVALID_OPERATION;
3470 }
3471 status_t status = NO_ERROR;
3472 if (mOutput != AUDIO_IO_HANDLE_NONE) {
3473 if (mDeviceCallback != 0) {
3474 ALOGW("%s(%d): callback already present!", __func__, mPortId);
3475 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
3476 }
3477 status = AudioSystem::addAudioDeviceCallback(this, mOutput, mPortId);
3478 }
3479 mDeviceCallback = callback;
3480 return status;
3481 }
3482
removeAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback> & callback)3483 status_t AudioTrack::removeAudioDeviceCallback(
3484 const sp<AudioSystem::AudioDeviceCallback>& callback)
3485 {
3486 if (callback == 0) {
3487 ALOGW("%s(%d): removing NULL callback!", __func__, mPortId);
3488 return BAD_VALUE;
3489 }
3490 AutoMutex lock(mLock);
3491 if (mDeviceCallback.unsafe_get() != callback.get()) {
3492 ALOGW("%s removing different callback!", __FUNCTION__);
3493 return INVALID_OPERATION;
3494 }
3495 mDeviceCallback.clear();
3496 if (mOutput != AUDIO_IO_HANDLE_NONE) {
3497 AudioSystem::removeAudioDeviceCallback(this, mOutput, mPortId);
3498 }
3499 return NO_ERROR;
3500 }
3501
3502
onAudioDeviceUpdate(audio_io_handle_t audioIo,audio_port_handle_t deviceId)3503 void AudioTrack::onAudioDeviceUpdate(audio_io_handle_t audioIo,
3504 audio_port_handle_t deviceId)
3505 {
3506 sp<AudioSystem::AudioDeviceCallback> callback;
3507 {
3508 AutoMutex lock(mLock);
3509 if (audioIo != mOutput) {
3510 return;
3511 }
3512 callback = mDeviceCallback.promote();
3513 // only update device if the track is active as route changes due to other use cases are
3514 // irrelevant for this client
3515 if (mState == STATE_ACTIVE) {
3516 mRoutedDeviceId = deviceId;
3517 }
3518 }
3519
3520 if (callback.get() != nullptr) {
3521 callback->onAudioDeviceUpdate(mOutput, mRoutedDeviceId);
3522 }
3523 }
3524
pendingDuration(int32_t * msec,ExtendedTimestamp::Location location)3525 status_t AudioTrack::pendingDuration(int32_t *msec, ExtendedTimestamp::Location location)
3526 {
3527 if (msec == nullptr ||
3528 (location != ExtendedTimestamp::LOCATION_SERVER
3529 && location != ExtendedTimestamp::LOCATION_KERNEL)) {
3530 return BAD_VALUE;
3531 }
3532 AutoMutex lock(mLock);
3533 // inclusive of offloaded and direct tracks.
3534 //
3535 // It is possible, but not enabled, to allow duration computation for non-pcm
3536 // audio_has_proportional_frames() formats because currently they have
3537 // the drain rate equivalent to the pcm sample rate * framesize.
3538 if (!isPurePcmData_l()) {
3539 return INVALID_OPERATION;
3540 }
3541 ExtendedTimestamp ets;
3542 if (getTimestamp_l(&ets) == OK
3543 && ets.mTimeNs[location] > 0) {
3544 int64_t diff = ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT]
3545 - ets.mPosition[location];
3546 if (diff < 0) {
3547 *msec = 0;
3548 } else {
3549 // ms is the playback time by frames
3550 int64_t ms = (int64_t)((double)diff * 1000 /
3551 ((double)mSampleRate * mPlaybackRate.mSpeed));
3552 // clockdiff is the timestamp age (negative)
3553 int64_t clockdiff = (mState != STATE_ACTIVE) ? 0 :
3554 ets.mTimeNs[location]
3555 + ets.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_MONOTONIC]
3556 - systemTime(SYSTEM_TIME_MONOTONIC);
3557
3558 //ALOGV("ms: %lld clockdiff: %lld", (long long)ms, (long long)clockdiff);
3559 static const int NANOS_PER_MILLIS = 1000000;
3560 *msec = (int32_t)(ms + clockdiff / NANOS_PER_MILLIS);
3561 }
3562 return NO_ERROR;
3563 }
3564 if (location != ExtendedTimestamp::LOCATION_SERVER) {
3565 return INVALID_OPERATION; // LOCATION_KERNEL is not available
3566 }
3567 // use server position directly (offloaded and direct arrive here)
3568 updateAndGetPosition_l();
3569 int32_t diff = (Modulo<uint32_t>(mFramesWritten) - mPosition).signedValue();
3570 *msec = (diff <= 0) ? 0
3571 : (int32_t)((double)diff * 1000 / ((double)mSampleRate * mPlaybackRate.mSpeed));
3572 return NO_ERROR;
3573 }
3574
hasStarted()3575 bool AudioTrack::hasStarted()
3576 {
3577 AutoMutex lock(mLock);
3578 switch (mState) {
3579 case STATE_STOPPED:
3580 if (isOffloadedOrDirect_l()) {
3581 // check if we have started in the past to return true.
3582 return mStartFromZeroUs > 0;
3583 }
3584 // A normal audio track may still be draining, so
3585 // check if stream has ended. This covers fasttrack position
3586 // instability and start/stop without any data written.
3587 if (mProxy->getStreamEndDone()) {
3588 return true;
3589 }
3590 FALLTHROUGH_INTENDED;
3591 case STATE_ACTIVE:
3592 case STATE_STOPPING:
3593 break;
3594 case STATE_PAUSED:
3595 case STATE_PAUSED_STOPPING:
3596 case STATE_FLUSHED:
3597 return false; // we're not active
3598 default:
3599 LOG_ALWAYS_FATAL("%s(%d): Invalid mState in hasStarted(): %d", __func__, mPortId, mState);
3600 break;
3601 }
3602
3603 // wait indicates whether we need to wait for a timestamp.
3604 // This is conservatively figured - if we encounter an unexpected error
3605 // then we will not wait.
3606 bool wait = false;
3607 if (isOffloadedOrDirect_l()) {
3608 AudioTimestamp ts;
3609 status_t status = getTimestamp_l(ts);
3610 if (status == WOULD_BLOCK) {
3611 wait = true;
3612 } else if (status == OK) {
3613 wait = (ts.mPosition == 0 || ts.mPosition == mStartTs.mPosition);
3614 }
3615 ALOGV("%s(%d): hasStarted wait:%d ts:%u start position:%lld",
3616 __func__, mPortId,
3617 (int)wait,
3618 ts.mPosition,
3619 (long long)mStartTs.mPosition);
3620 } else {
3621 int location = ExtendedTimestamp::LOCATION_SERVER; // for ALOG
3622 ExtendedTimestamp ets;
3623 status_t status = getTimestamp_l(&ets);
3624 if (status == WOULD_BLOCK) { // no SERVER or KERNEL frame info in ets
3625 wait = true;
3626 } else if (status == OK) {
3627 for (location = ExtendedTimestamp::LOCATION_KERNEL;
3628 location >= ExtendedTimestamp::LOCATION_SERVER; --location) {
3629 if (ets.mTimeNs[location] < 0 || mStartEts.mTimeNs[location] < 0) {
3630 continue;
3631 }
3632 wait = ets.mPosition[location] == 0
3633 || ets.mPosition[location] == mStartEts.mPosition[location];
3634 break;
3635 }
3636 }
3637 ALOGV("%s(%d): hasStarted wait:%d ets:%lld start position:%lld",
3638 __func__, mPortId,
3639 (int)wait,
3640 (long long)ets.mPosition[location],
3641 (long long)mStartEts.mPosition[location]);
3642 }
3643 return !wait;
3644 }
3645
3646 // =========================================================================
3647
binderDied(const wp<IBinder> & who __unused)3648 void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
3649 {
3650 sp<AudioTrack> audioTrack = mAudioTrack.promote();
3651 if (audioTrack != 0) {
3652 AutoMutex lock(audioTrack->mLock);
3653 audioTrack->mProxy->binderDied();
3654 }
3655 }
3656
3657 // =========================================================================
3658
AudioTrackThread(AudioTrack & receiver)3659 AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver)
3660 : Thread(true /* bCanCallJava */) // binder recursion on restoreTrack_l() may call Java.
3661 , mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
3662 mIgnoreNextPausedInt(false)
3663 {
3664 }
3665
~AudioTrackThread()3666 AudioTrack::AudioTrackThread::~AudioTrackThread()
3667 {
3668 }
3669
threadLoop()3670 bool AudioTrack::AudioTrackThread::threadLoop()
3671 {
3672 {
3673 AutoMutex _l(mMyLock);
3674 if (mPaused) {
3675 // TODO check return value and handle or log
3676 mMyCond.wait(mMyLock);
3677 // caller will check for exitPending()
3678 return true;
3679 }
3680 if (mIgnoreNextPausedInt) {
3681 mIgnoreNextPausedInt = false;
3682 mPausedInt = false;
3683 }
3684 if (mPausedInt) {
3685 // TODO use futex instead of condition, for event flag "or"
3686 if (mPausedNs > 0) {
3687 // TODO check return value and handle or log
3688 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
3689 } else {
3690 // TODO check return value and handle or log
3691 mMyCond.wait(mMyLock);
3692 }
3693 mPausedInt = false;
3694 return true;
3695 }
3696 }
3697 if (exitPending()) {
3698 return false;
3699 }
3700 nsecs_t ns = mReceiver.processAudioBuffer();
3701 switch (ns) {
3702 case 0:
3703 return true;
3704 case NS_INACTIVE:
3705 pauseInternal();
3706 return true;
3707 case NS_NEVER:
3708 return false;
3709 case NS_WHENEVER:
3710 // Event driven: call wake() when callback notifications conditions change.
3711 ns = INT64_MAX;
3712 FALLTHROUGH_INTENDED;
3713 default:
3714 LOG_ALWAYS_FATAL_IF(ns < 0, "%s(%d): processAudioBuffer() returned %lld",
3715 __func__, mReceiver.mPortId, (long long)ns);
3716 pauseInternal(ns);
3717 return true;
3718 }
3719 }
3720
requestExit()3721 void AudioTrack::AudioTrackThread::requestExit()
3722 {
3723 // must be in this order to avoid a race condition
3724 Thread::requestExit();
3725 resume();
3726 }
3727
pause()3728 void AudioTrack::AudioTrackThread::pause()
3729 {
3730 AutoMutex _l(mMyLock);
3731 mPaused = true;
3732 }
3733
resume()3734 void AudioTrack::AudioTrackThread::resume()
3735 {
3736 AutoMutex _l(mMyLock);
3737 mIgnoreNextPausedInt = true;
3738 if (mPaused || mPausedInt) {
3739 mPaused = false;
3740 mPausedInt = false;
3741 mMyCond.signal();
3742 }
3743 }
3744
wake()3745 void AudioTrack::AudioTrackThread::wake()
3746 {
3747 AutoMutex _l(mMyLock);
3748 if (!mPaused) {
3749 // wake() might be called while servicing a callback - ignore the next
3750 // pause time and call processAudioBuffer.
3751 mIgnoreNextPausedInt = true;
3752 if (mPausedInt && mPausedNs > 0) {
3753 // audio track is active and internally paused with timeout.
3754 mPausedInt = false;
3755 mMyCond.signal();
3756 }
3757 }
3758 }
3759
pauseInternal(nsecs_t ns)3760 void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
3761 {
3762 AutoMutex _l(mMyLock);
3763 mPausedInt = true;
3764 mPausedNs = ns;
3765 }
3766
onCodecFormatChanged(const std::vector<uint8_t> & audioMetadata)3767 binder::Status AudioTrack::AudioTrackCallback::onCodecFormatChanged(
3768 const std::vector<uint8_t>& audioMetadata)
3769 {
3770 AutoMutex _l(mAudioTrackCbLock);
3771 sp<media::IAudioTrackCallback> callback = mCallback.promote();
3772 if (callback.get() != nullptr) {
3773 callback->onCodecFormatChanged(audioMetadata);
3774 } else {
3775 mCallback.clear();
3776 }
3777 return binder::Status::ok();
3778 }
3779
setAudioTrackCallback(const sp<media::IAudioTrackCallback> & callback)3780 void AudioTrack::AudioTrackCallback::setAudioTrackCallback(
3781 const sp<media::IAudioTrackCallback> &callback) {
3782 AutoMutex lock(mAudioTrackCbLock);
3783 mCallback = callback;
3784 }
3785
3786 } // namespace android
3787