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