1 /* 2 ** 3 ** Copyright 2012, 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 #ifndef INCLUDING_FROM_AUDIOFLINGER_H 19 #error This header file should only be included from AudioFlinger.h 20 #endif 21 22 #include <math.h> 23 24 // Checks and monitors OP_PLAY_AUDIO 25 class OpPlayAudioMonitor : public RefBase { 26 public: 27 ~OpPlayAudioMonitor() override; 28 bool hasOpPlayAudio() const; 29 30 static sp<OpPlayAudioMonitor> createIfNeeded( 31 const AttributionSourceState& attributionSource, 32 const audio_attributes_t& attr, int id, 33 audio_stream_type_t streamType); 34 35 private: 36 OpPlayAudioMonitor(const AttributionSourceState& attributionSource, 37 audio_usage_t usage, int id); 38 void onFirstRef() override; 39 static void getPackagesForUid(uid_t uid, Vector<String16>& packages); 40 41 AppOpsManager mAppOpsManager; 42 43 class PlayAudioOpCallback : public BnAppOpsCallback { 44 public: 45 explicit PlayAudioOpCallback(const wp<OpPlayAudioMonitor>& monitor); 46 void opChanged(int32_t op, const String16& packageName) override; 47 48 private: 49 const wp<OpPlayAudioMonitor> mMonitor; 50 }; 51 52 sp<PlayAudioOpCallback> mOpCallback; 53 // called by PlayAudioOpCallback when OP_PLAY_AUDIO is updated in AppOp callback 54 void checkPlayAudioForUsage(); 55 56 std::atomic_bool mHasOpPlayAudio; 57 const AttributionSourceState mAttributionSource; 58 const int32_t mUsage; // on purpose not audio_usage_t because always checked in appOps as int32_t 59 const int mId; // for logging purposes only 60 }; 61 62 // playback track 63 class Track : public TrackBase, public VolumeProvider { 64 public: 65 Track( PlaybackThread *thread, 66 const sp<Client>& client, 67 audio_stream_type_t streamType, 68 const audio_attributes_t& attr, 69 uint32_t sampleRate, 70 audio_format_t format, 71 audio_channel_mask_t channelMask, 72 size_t frameCount, 73 void *buffer, 74 size_t bufferSize, 75 const sp<IMemory>& sharedBuffer, 76 audio_session_t sessionId, 77 pid_t creatorPid, 78 const AttributionSourceState& attributionSource, 79 audio_output_flags_t flags, 80 track_type type, 81 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE, 82 /** default behaviour is to start when there are as many frames 83 * ready as possible (aka. Buffer is full). */ 84 size_t frameCountToBeReady = SIZE_MAX, 85 float speed = 1.0f, 86 bool isSpatialized = false); 87 virtual ~Track(); 88 virtual status_t initCheck() const; 89 90 void appendDumpHeader(String8& result); 91 void appendDump(String8& result, bool active); 92 virtual status_t start(AudioSystem::sync_event_t event = AudioSystem::SYNC_EVENT_NONE, 93 audio_session_t triggerSession = AUDIO_SESSION_NONE); 94 virtual void stop(); 95 void pause(); 96 97 void flush(); 98 void destroy(); 99 100 virtual uint32_t sampleRate() const; 101 streamType()102 audio_stream_type_t streamType() const { 103 return mStreamType; 104 } isOffloaded()105 bool isOffloaded() const 106 { return (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0; } isDirect()107 bool isDirect() const override 108 { return (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0; } isOffloadedOrDirect()109 bool isOffloadedOrDirect() const { return (mFlags 110 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD 111 | AUDIO_OUTPUT_FLAG_DIRECT)) != 0; } isStatic()112 bool isStatic() const { return mSharedBuffer.get() != nullptr; } 113 114 status_t setParameters(const String8& keyValuePairs); 115 status_t selectPresentation(int presentationId, int programId); 116 status_t attachAuxEffect(int EffectId); 117 void setAuxBuffer(int EffectId, int32_t *buffer); auxBuffer()118 int32_t *auxBuffer() const { return mAuxBuffer; } setMainBuffer(effect_buffer_t * buffer)119 void setMainBuffer(effect_buffer_t *buffer) { mMainBuffer = buffer; } mainBuffer()120 effect_buffer_t *mainBuffer() const { return mMainBuffer; } auxEffectId()121 int auxEffectId() const { return mAuxEffectId; } 122 virtual status_t getTimestamp(AudioTimestamp& timestamp); 123 void signal(); 124 status_t getDualMonoMode(audio_dual_mono_mode_t* mode); 125 status_t setDualMonoMode(audio_dual_mono_mode_t mode); 126 status_t getAudioDescriptionMixLevel(float* leveldB); 127 status_t setAudioDescriptionMixLevel(float leveldB); 128 status_t getPlaybackRateParameters(audio_playback_rate_t* playbackRate); 129 status_t setPlaybackRateParameters(const audio_playback_rate_t& playbackRate); 130 131 // implement FastMixerState::VolumeProvider interface 132 virtual gain_minifloat_packed_t getVolumeLR(); 133 134 virtual status_t setSyncEvent(const sp<SyncEvent>& event); 135 isFastTrack()136 virtual bool isFastTrack() const { return (mFlags & AUDIO_OUTPUT_FLAG_FAST) != 0; } 137 bufferLatencyMs()138 double bufferLatencyMs() const override { 139 return isStatic() ? 0. : TrackBase::bufferLatencyMs(); 140 } 141 142 // implement volume handling. 143 media::VolumeShaper::Status applyVolumeShaper( 144 const sp<media::VolumeShaper::Configuration>& configuration, 145 const sp<media::VolumeShaper::Operation>& operation); 146 sp<media::VolumeShaper::State> getVolumeShaperState(int id); getVolumeHandler()147 sp<media::VolumeHandler> getVolumeHandler() { return mVolumeHandler; } 148 /** Set the computed normalized final volume of the track. 149 * !masterMute * masterVolume * streamVolume * averageLRVolume */ 150 void setFinalVolume(float volume); getFinalVolume()151 float getFinalVolume() const { return mFinalVolume; } 152 153 using SourceMetadatas = std::vector<playback_track_metadata_v7_t>; 154 using MetadataInserter = std::back_insert_iterator<SourceMetadatas>; 155 /** Copy the track metadata in the provided iterator. Thread safe. */ 156 virtual void copyMetadataTo(MetadataInserter& backInserter) const; 157 158 /** Return haptic playback of the track is enabled or not, used in mixer. */ getHapticPlaybackEnabled()159 bool getHapticPlaybackEnabled() const { return mHapticPlaybackEnabled; } 160 /** Set haptic playback of the track is enabled or not, should be 161 * set after query or get callback from vibrator service */ setHapticPlaybackEnabled(bool hapticPlaybackEnabled)162 void setHapticPlaybackEnabled(bool hapticPlaybackEnabled) { 163 mHapticPlaybackEnabled = hapticPlaybackEnabled; 164 } 165 /** Return at what intensity to play haptics, used in mixer. */ getHapticIntensity()166 os::HapticScale getHapticIntensity() const { return mHapticIntensity; } 167 /** Return the maximum amplitude allowed for haptics data, used in mixer. */ getHapticMaxAmplitude()168 float getHapticMaxAmplitude() const { return mHapticMaxAmplitude; } 169 /** Set intensity of haptic playback, should be set after querying vibrator service. */ setHapticIntensity(os::HapticScale hapticIntensity)170 void setHapticIntensity(os::HapticScale hapticIntensity) { 171 if (os::isValidHapticScale(hapticIntensity)) { 172 mHapticIntensity = hapticIntensity; 173 setHapticPlaybackEnabled(mHapticIntensity != os::HapticScale::MUTE); 174 } 175 } 176 /** Set maximum amplitude allowed for haptic data, should be set after querying 177 * vibrator service. 178 */ setHapticMaxAmplitude(float maxAmplitude)179 void setHapticMaxAmplitude(float maxAmplitude) { 180 mHapticMaxAmplitude = maxAmplitude; 181 } getExternalVibration()182 sp<os::ExternalVibration> getExternalVibration() const { return mExternalVibration; } 183 184 void setTeePatches(TeePatches teePatches); 185 tallyUnderrunFrames(size_t frames)186 void tallyUnderrunFrames(size_t frames) override { 187 if (isOut()) { // we expect this from output tracks only 188 mAudioTrackServerProxy->tallyUnderrunFrames(frames); 189 // Fetch absolute numbers from AudioTrackShared as it counts 190 // contiguous underruns as a one -- we want a consistent number. 191 // TODO: isolate this counting into a class. 192 mTrackMetrics.logUnderruns(mAudioTrackServerProxy->getUnderrunCount(), 193 mAudioTrackServerProxy->getUnderrunFrames()); 194 } 195 } 196 checkServerLatencySupported(audio_format_t format,audio_output_flags_t flags)197 static bool checkServerLatencySupported( 198 audio_format_t format, audio_output_flags_t flags) { 199 return audio_is_linear_pcm(format) 200 && (flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) == 0; 201 } 202 getOutputFlags()203 audio_output_flags_t getOutputFlags() const { return mFlags; } getSpeed()204 float getSpeed() const { return mSpeed; } isSpatialized()205 bool isSpatialized() const override { return mIsSpatialized; } 206 207 protected: 208 // for numerous 209 friend class PlaybackThread; 210 friend class MixerThread; 211 friend class DirectOutputThread; 212 friend class OffloadThread; 213 214 DISALLOW_COPY_AND_ASSIGN(Track); 215 216 // AudioBufferProvider interface 217 status_t getNextBuffer(AudioBufferProvider::Buffer* buffer) override; 218 void releaseBuffer(AudioBufferProvider::Buffer* buffer) override; 219 220 // ExtendedAudioBufferProvider interface 221 virtual size_t framesReady() const; 222 virtual int64_t framesReleased() const; 223 virtual void onTimestamp(const ExtendedTimestamp ×tamp); 224 isPausing()225 bool isPausing() const { return mState == PAUSING; } isPaused()226 bool isPaused() const { return mState == PAUSED; } isResuming()227 bool isResuming() const { return mState == RESUMING; } 228 bool isReady() const; setPaused()229 void setPaused() { mState = PAUSED; } 230 void reset(); isFlushPending()231 bool isFlushPending() const { return mFlushHwPending; } 232 void flushAck(); 233 bool isResumePending(); 234 void resumeAck(); 235 // For direct or offloaded tracks ensure that the pause state is acknowledged 236 // by the playback thread in case of an immediate flush. isPausePending()237 bool isPausePending() const { return mPauseHwPending; } 238 void pauseAck(); 239 void updateTrackFrameInfo(int64_t trackFramesReleased, int64_t sinkFramesWritten, 240 uint32_t halSampleRate, const ExtendedTimestamp &timeStamp); 241 sharedBuffer()242 sp<IMemory> sharedBuffer() const { return mSharedBuffer; } 243 244 // presentationComplete checked by frames. (Mixed Tracks). 245 // framesWritten is cumulative, never reset, and is shared all tracks 246 // audioHalFrames is derived from output latency 247 bool presentationComplete(int64_t framesWritten, size_t audioHalFrames); 248 249 // presentationComplete checked by time. (Direct Tracks). 250 bool presentationComplete(uint32_t latencyMs); 251 resetPresentationComplete()252 void resetPresentationComplete() { 253 mPresentationCompleteFrames = 0; 254 mPresentationCompleteTimeNs = 0; 255 } 256 257 // notifyPresentationComplete is called when presentationComplete() detects 258 // that the track is finished stopping. 259 void notifyPresentationComplete(); 260 261 void signalClientFlag(int32_t flag); 262 263 public: 264 void triggerEvents(AudioSystem::sync_event_t type); 265 virtual void invalidate(); 266 void disable(); 267 fastIndex()268 int fastIndex() const { return mFastIndex; } 269 isPlaybackRestricted()270 bool isPlaybackRestricted() const { 271 // The monitor is only created for tracks that can be silenced. 272 return mOpPlayAudioMonitor ? !mOpPlayAudioMonitor->hasOpPlayAudio() : false; } 273 274 protected: 275 276 // FILLED state is used for suppressing volume ramp at begin of playing 277 enum {FS_INVALID, FS_FILLING, FS_FILLED, FS_ACTIVE}; 278 mutable uint8_t mFillingUpStatus; 279 int8_t mRetryCount; 280 281 // see comment at AudioFlinger::PlaybackThread::Track::~Track for why this can't be const 282 sp<IMemory> mSharedBuffer; 283 284 bool mResetDone; 285 const audio_stream_type_t mStreamType; 286 effect_buffer_t *mMainBuffer; 287 288 int32_t *mAuxBuffer; 289 int mAuxEffectId; 290 bool mHasVolumeController; 291 292 // access these three variables only when holding thread lock. 293 LinearMap<int64_t> mFrameMap; // track frame to server frame mapping 294 295 ExtendedTimestamp mSinkTimestamp; 296 297 sp<media::VolumeHandler> mVolumeHandler; // handles multiple VolumeShaper configs and operations 298 299 sp<OpPlayAudioMonitor> mOpPlayAudioMonitor; 300 301 bool mHapticPlaybackEnabled = false; // indicates haptic playback enabled or not 302 // intensity to play haptic data 303 os::HapticScale mHapticIntensity = os::HapticScale::MUTE; 304 // max amplitude allowed for haptic data 305 float mHapticMaxAmplitude = NAN; 306 class AudioVibrationController : public os::BnExternalVibrationController { 307 public: AudioVibrationController(Track * track)308 explicit AudioVibrationController(Track* track) : mTrack(track) {} 309 binder::Status mute(/*out*/ bool *ret) override; 310 binder::Status unmute(/*out*/ bool *ret) override; 311 private: 312 Track* const mTrack; 313 }; 314 sp<AudioVibrationController> mAudioVibrationController; 315 sp<os::ExternalVibration> mExternalVibration; 316 317 audio_dual_mono_mode_t mDualMonoMode = AUDIO_DUAL_MONO_MODE_OFF; 318 float mAudioDescriptionMixLevel = -std::numeric_limits<float>::infinity(); 319 audio_playback_rate_t mPlaybackRateParameters = AUDIO_PLAYBACK_RATE_INITIALIZER; 320 321 private: 322 void interceptBuffer(const AudioBufferProvider::Buffer& buffer); 323 template <class F> forEachTeePatchTrack(F f)324 void forEachTeePatchTrack(F f) { 325 for (auto& tp : mTeePatches) { f(tp.patchTrack); } 326 }; 327 328 size_t mPresentationCompleteFrames = 0; // (Used for Mixed tracks) 329 // The number of frames written to the 330 // audio HAL when this track is considered fully rendered. 331 // Zero means not monitoring. 332 int64_t mPresentationCompleteTimeNs = 0; // (Used for Direct tracks) 333 // The time when this track is considered fully rendered. 334 // Zero means not monitoring. 335 336 // The following fields are only for fast tracks, and should be in a subclass 337 int mFastIndex; // index within FastMixerState::mFastTracks[]; 338 // either mFastIndex == -1 if not isFastTrack() 339 // or 0 < mFastIndex < FastMixerState::kMaxFast because 340 // index 0 is reserved for normal mixer's submix; 341 // index is allocated statically at track creation time 342 // but the slot is only used if track is active 343 FastTrackUnderruns mObservedUnderruns; // Most recently observed value of 344 // mFastMixerDumpState.mTracks[mFastIndex].mUnderruns 345 volatile float mCachedVolume; // combined master volume and stream type volume; 346 // 'volatile' means accessed without lock or 347 // barrier, but is read/written atomically 348 float mFinalVolume; // combine master volume, stream type volume and track volume 349 sp<AudioTrackServerProxy> mAudioTrackServerProxy; 350 bool mResumeToStopping; // track was paused in stopping state. 351 bool mFlushHwPending; // track requests for thread flush 352 bool mPauseHwPending = false; // direct/offload track request for thread pause 353 audio_output_flags_t mFlags; 354 TeePatches mTeePatches; 355 const float mSpeed; 356 const bool mIsSpatialized; 357 }; // end of Track 358 359 360 // playback track, used by DuplicatingThread 361 class OutputTrack : public Track { 362 public: 363 364 class Buffer : public AudioBufferProvider::Buffer { 365 public: 366 void *mBuffer; 367 }; 368 369 OutputTrack(PlaybackThread *thread, 370 DuplicatingThread *sourceThread, 371 uint32_t sampleRate, 372 audio_format_t format, 373 audio_channel_mask_t channelMask, 374 size_t frameCount, 375 const AttributionSourceState& attributionSource); 376 virtual ~OutputTrack(); 377 378 virtual status_t start(AudioSystem::sync_event_t event = 379 AudioSystem::SYNC_EVENT_NONE, 380 audio_session_t triggerSession = AUDIO_SESSION_NONE); 381 virtual void stop(); 382 ssize_t write(void* data, uint32_t frames); bufferQueueEmpty()383 bool bufferQueueEmpty() const { return mBufferQueue.size() == 0; } isActive()384 bool isActive() const { return mActive; } thread()385 const wp<ThreadBase>& thread() const { return mThread; } 386 387 void copyMetadataTo(MetadataInserter& backInserter) const override; 388 /** Set the metadatas of the upstream tracks. Thread safe. */ 389 void setMetadatas(const SourceMetadatas& metadatas); 390 /** returns client timestamp to the upstream duplicating thread. */ getClientProxyTimestamp()391 ExtendedTimestamp getClientProxyTimestamp() const { 392 // server - kernel difference is not true latency when drained 393 // i.e. mServerProxy->isDrained(). 394 ExtendedTimestamp timestamp; 395 (void) mClientProxy->getTimestamp(×tamp); 396 // On success, the timestamp LOCATION_SERVER and LOCATION_KERNEL 397 // entries will be properly filled. If getTimestamp() 398 // is unsuccessful, then a default initialized timestamp 399 // (with mTimeNs[] filled with -1's) is returned. 400 return timestamp; 401 } 402 403 private: 404 status_t obtainBuffer(AudioBufferProvider::Buffer* buffer, 405 uint32_t waitTimeMs); 406 void clearBufferQueue(); 407 408 void restartIfDisabled(); 409 410 // Maximum number of pending buffers allocated by OutputTrack::write() 411 static const uint8_t kMaxOverFlowBuffers = 10; 412 413 Vector < Buffer* > mBufferQueue; 414 AudioBufferProvider::Buffer mOutBuffer; 415 bool mActive; 416 DuplicatingThread* const mSourceThread; // for waitTimeMs() in write() 417 sp<AudioTrackClientProxy> mClientProxy; 418 419 /** Attributes of the source tracks. 420 * 421 * This member must be accessed with mTrackMetadatasMutex taken. 422 * There is one writer (duplicating thread) and one reader (downstream mixer). 423 * 424 * That means that the duplicating thread can block the downstream mixer 425 * thread and vice versa for the time of the copy. 426 * If this becomes an issue, the metadata could be stored in an atomic raw pointer, 427 * and a exchange with nullptr and delete can be used. 428 * Alternatively a read-copy-update might be implemented. 429 */ 430 SourceMetadatas mTrackMetadatas; 431 /** Protects mTrackMetadatas against concurrent access. */ 432 mutable std::mutex mTrackMetadatasMutex; 433 }; // end of OutputTrack 434 435 // playback track, used by PatchPanel 436 class PatchTrack : public Track, public PatchTrackBase { 437 public: 438 439 PatchTrack(PlaybackThread *playbackThread, 440 audio_stream_type_t streamType, 441 uint32_t sampleRate, 442 audio_channel_mask_t channelMask, 443 audio_format_t format, 444 size_t frameCount, 445 void *buffer, 446 size_t bufferSize, 447 audio_output_flags_t flags, 448 const Timeout& timeout = {}, 449 size_t frameCountToBeReady = 1 /** Default behaviour is to start 450 * as soon as possible to have 451 * the lowest possible latency 452 * even if it might glitch. */); 453 virtual ~PatchTrack(); 454 455 size_t framesReady() const override; 456 457 virtual status_t start(AudioSystem::sync_event_t event = 458 AudioSystem::SYNC_EVENT_NONE, 459 audio_session_t triggerSession = AUDIO_SESSION_NONE); 460 461 // AudioBufferProvider interface 462 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer); 463 virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer); 464 465 // PatchProxyBufferProvider interface 466 virtual status_t obtainBuffer(Proxy::Buffer* buffer, 467 const struct timespec *timeOut = NULL); 468 virtual void releaseBuffer(Proxy::Buffer* buffer); 469 470 private: 471 void restartIfDisabled(); 472 }; // end of PatchTrack 473