1 /* 2 * Copyright 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef AAUDIO_AUDIOSTREAM_H 18 #define AAUDIO_AUDIOSTREAM_H 19 20 #include <atomic> 21 #include <mutex> 22 #include <set> 23 #include <stdint.h> 24 25 #include <android-base/thread_annotations.h> 26 #include <binder/IServiceManager.h> 27 #include <binder/Status.h> 28 #include <utils/StrongPointer.h> 29 30 #include <aaudio/AAudio.h> 31 #include <media/AudioContainers.h> 32 #include <media/AudioSystem.h> 33 #include <media/PlayerBase.h> 34 #include <media/VolumeShaper.h> 35 36 #include "utility/AAudioUtilities.h" 37 #include "utility/MonotonicCounter.h" 38 39 // Cannot get android::media::VolumeShaper to compile! 40 #define AAUDIO_USE_VOLUME_SHAPER 0 41 42 namespace aaudio { 43 44 typedef void *(*aaudio_audio_thread_proc_t)(void *); 45 typedef uint32_t aaudio_stream_id_t; 46 47 class AudioStreamBuilder; 48 49 constexpr pid_t CALLBACK_THREAD_NONE = 0; 50 51 /** 52 * AAudio audio stream. 53 */ 54 // By extending AudioDeviceCallback, we also inherit from RefBase. 55 class AudioStream : public android::AudioSystem::AudioDeviceCallback { 56 public: 57 58 AudioStream(); 59 60 virtual ~AudioStream(); 61 62 protected: 63 64 /** 65 * Check the state to see if Pause is currently legal. 66 * 67 * @param result pointer to return code 68 * @return true if OK to continue, if false then return result 69 */ 70 bool checkPauseStateTransition(aaudio_result_t *result); 71 isFlushSupported()72 virtual bool isFlushSupported() const { 73 // Only implement FLUSH for OUTPUT streams. 74 return false; 75 } 76 isPauseSupported()77 virtual bool isPauseSupported() const { 78 // Only implement PAUSE for OUTPUT streams. 79 return false; 80 } 81 82 /* Asynchronous requests. 83 * Use waitForStateChange() to wait for completion. 84 */ 85 virtual aaudio_result_t requestStart_l() REQUIRES(mStreamLock) = 0; 86 requestPause_l()87 virtual aaudio_result_t requestPause_l() REQUIRES(mStreamLock) { 88 // Only implement this for OUTPUT streams. 89 return AAUDIO_ERROR_UNIMPLEMENTED; 90 } 91 requestFlush_l()92 virtual aaudio_result_t requestFlush_l() REQUIRES(mStreamLock) { 93 // Only implement this for OUTPUT streams. 94 return AAUDIO_ERROR_UNIMPLEMENTED; 95 } 96 97 virtual aaudio_result_t requestStop_l() REQUIRES(mStreamLock) = 0; 98 99 public: 100 virtual aaudio_result_t getTimestamp(clockid_t clockId, 101 int64_t *framePosition, 102 int64_t *timeNanoseconds) = 0; 103 104 /** 105 * Update state machine. 106 * @return result of the operation. 107 */ updateStateMachine()108 aaudio_result_t updateStateMachine() { 109 if (isDataCallbackActive()) { 110 return AAUDIO_OK; // state is getting updated by the callback thread read/write call 111 } 112 return processCommands(); 113 }; 114 115 virtual aaudio_result_t processCommands() = 0; 116 117 // =========== End ABSTRACT methods =========================== 118 119 virtual aaudio_result_t waitForStateChange(aaudio_stream_state_t currentState, 120 aaudio_stream_state_t *nextState, 121 int64_t timeoutNanoseconds); 122 123 /** 124 * Open the stream using the parameters in the builder. 125 * Allocate the necessary resources. 126 */ 127 virtual aaudio_result_t open(const AudioStreamBuilder& builder); 128 129 // log to MediaMetrics 130 virtual void logOpenActual(); 131 void logReleaseBufferState(); 132 133 /* Note about naming for "release" and "close" related methods. 134 * 135 * These names are intended to match the public AAudio API. 136 * The original AAudio API had an AAudioStream_close() function that 137 * released the hardware and deleted the stream. That made it difficult 138 * because apps want to release the HW ASAP but are not in a rush to delete 139 * the stream object. So in R we added an AAudioStream_release() function 140 * that just released the hardware. 141 * The AAudioStream_close() method releases if needed and then closes. 142 */ 143 144 protected: 145 /** 146 * Free any hardware or system resources from the open() call. 147 * It is safe to call release_l() multiple times. 148 */ release_l()149 virtual aaudio_result_t release_l() REQUIRES(mStreamLock) { 150 setState(AAUDIO_STREAM_STATE_CLOSING); 151 return AAUDIO_OK; 152 } 153 154 /** 155 * Free any resources not already freed by release_l(). 156 * Assume release_l() already called. 157 */ 158 virtual void close_l() REQUIRES(mStreamLock); 159 160 public: 161 // This is only used to identify a stream in the logs without 162 // revealing any pointers. getId()163 aaudio_stream_id_t getId() { 164 return mStreamId; 165 } 166 167 virtual aaudio_result_t setBufferSize(int32_t requestedFrames) = 0; 168 createThread(int64_t periodNanoseconds,aaudio_audio_thread_proc_t threadProc,void * threadArg)169 aaudio_result_t createThread(int64_t periodNanoseconds, 170 aaudio_audio_thread_proc_t threadProc, 171 void *threadArg) 172 EXCLUDES(mStreamLock) { 173 std::lock_guard<std::mutex> lock(mStreamLock); 174 return createThread_l(periodNanoseconds, threadProc, threadArg); 175 } 176 177 aaudio_result_t joinThread(void **returnArg) EXCLUDES(mStreamLock); 178 registerThread()179 virtual aaudio_result_t registerThread() { 180 return AAUDIO_OK; 181 } 182 unregisterThread()183 virtual aaudio_result_t unregisterThread() { 184 return AAUDIO_OK; 185 } 186 187 /** 188 * Internal function used to call the audio thread passed by the user. 189 * It is unfortunately public because it needs to be called by a static 'C' function. 190 */ 191 void* wrapUserThread(); 192 193 // ============== Queries =========================== 194 getState()195 aaudio_stream_state_t getState() const { 196 return mState.load(); 197 } 198 199 aaudio_stream_state_t getStateExternal() const; 200 getBufferSize()201 virtual int32_t getBufferSize() const { 202 return AAUDIO_ERROR_UNIMPLEMENTED; 203 } 204 getBufferCapacity()205 virtual int32_t getBufferCapacity() const { 206 return mBufferCapacity; 207 } 208 getDeviceBufferCapacity()209 virtual int32_t getDeviceBufferCapacity() const { 210 return mDeviceBufferCapacity; 211 } 212 getFramesPerBurst()213 virtual int32_t getFramesPerBurst() const { 214 return mFramesPerBurst; 215 } 216 getDeviceFramesPerBurst()217 virtual int32_t getDeviceFramesPerBurst() const { 218 return mDeviceFramesPerBurst; 219 } 220 getXRunCount()221 virtual int32_t getXRunCount() const { 222 return AAUDIO_ERROR_UNIMPLEMENTED; 223 } 224 isActive()225 bool isActive() const { 226 return mState == AAUDIO_STREAM_STATE_STARTING || mState == AAUDIO_STREAM_STATE_STARTED; 227 } 228 isMMap()229 virtual bool isMMap() { 230 return false; 231 } 232 getSampleRate()233 aaudio_result_t getSampleRate() const { 234 return mSampleRate; 235 } 236 getDeviceSampleRate()237 aaudio_result_t getDeviceSampleRate() const { 238 return mDeviceSampleRate; 239 } 240 getHardwareSampleRate()241 aaudio_result_t getHardwareSampleRate() const { 242 return mHardwareSampleRate; 243 } 244 getFormat()245 audio_format_t getFormat() const { 246 return mFormat; 247 } 248 getHardwareFormat()249 audio_format_t getHardwareFormat() const { 250 return mHardwareFormat; 251 } 252 getSamplesPerFrame()253 aaudio_result_t getSamplesPerFrame() const { 254 return mSamplesPerFrame; 255 } 256 getDeviceSamplesPerFrame()257 aaudio_result_t getDeviceSamplesPerFrame() const { 258 return mDeviceSamplesPerFrame; 259 } 260 getHardwareSamplesPerFrame()261 aaudio_result_t getHardwareSamplesPerFrame() const { 262 return mHardwareSamplesPerFrame; 263 } 264 getPerformanceMode()265 virtual int32_t getPerformanceMode() const { 266 return mPerformanceMode; 267 } 268 setPerformanceMode(aaudio_performance_mode_t performanceMode)269 void setPerformanceMode(aaudio_performance_mode_t performanceMode) { 270 mPerformanceMode = performanceMode; 271 } 272 getDeviceIds()273 android::DeviceIdVector getDeviceIds() const { 274 return mDeviceIds; 275 } 276 getSharingMode()277 aaudio_sharing_mode_t getSharingMode() const { 278 return mSharingMode; 279 } 280 isSharingModeMatchRequired()281 bool isSharingModeMatchRequired() const { 282 return mSharingModeMatchRequired; 283 } 284 285 virtual aaudio_direction_t getDirection() const = 0; 286 getUsage()287 aaudio_usage_t getUsage() const { 288 return mUsage; 289 } 290 getContentType()291 aaudio_content_type_t getContentType() const { 292 return mContentType; 293 } 294 getTags()295 const std::set<std::string>& getTags() const { 296 return mTags; 297 } 298 getSpatializationBehavior()299 aaudio_spatialization_behavior_t getSpatializationBehavior() const { 300 return mSpatializationBehavior; 301 } 302 isContentSpatialized()303 bool isContentSpatialized() const { 304 return mIsContentSpatialized; 305 } 306 getInputPreset()307 aaudio_input_preset_t getInputPreset() const { 308 return mInputPreset; 309 } 310 getAllowedCapturePolicy()311 aaudio_allowed_capture_policy_t getAllowedCapturePolicy() const { 312 return mAllowedCapturePolicy; 313 } 314 getSessionId()315 int32_t getSessionId() const { 316 return mSessionId; 317 } 318 isPrivacySensitive()319 bool isPrivacySensitive() const { 320 return mIsPrivacySensitive; 321 } 322 getRequireMonoBlend()323 bool getRequireMonoBlend() const { 324 return mRequireMonoBlend; 325 } 326 getAudioBalance()327 float getAudioBalance() const { 328 return mAudioBalance; 329 } 330 331 /** 332 * This is only valid after setChannelMask() and setFormat() 333 * have been called. 334 */ getBytesPerFrame()335 int32_t getBytesPerFrame() const { 336 return audio_bytes_per_frame(mSamplesPerFrame, mFormat); 337 } 338 339 /** 340 * This is only valid after setFormat() has been called. 341 */ getBytesPerSample()342 int32_t getBytesPerSample() const { 343 return audio_bytes_per_sample(mFormat); 344 } 345 346 /** 347 * This is only valid after setDeviceSamplesPerFrame() and setDeviceFormat() have been called. 348 */ getBytesPerDeviceFrame()349 int32_t getBytesPerDeviceFrame() const { 350 return audio_bytes_per_frame(getDeviceSamplesPerFrame(), getDeviceFormat()); 351 } 352 353 virtual int64_t getFramesWritten() = 0; 354 355 virtual int64_t getFramesRead() = 0; 356 getDataCallbackProc()357 AAudioStream_dataCallback getDataCallbackProc() const { 358 return mDataCallbackProc; 359 } 360 getErrorCallbackProc()361 AAudioStream_errorCallback getErrorCallbackProc() const { 362 return mErrorCallbackProc; 363 } 364 365 aaudio_data_callback_result_t maybeCallDataCallback(void *audioData, int32_t numFrames); 366 367 void maybeCallErrorCallback(aaudio_result_t result); 368 getDataCallbackUserData()369 void *getDataCallbackUserData() const { 370 return mDataCallbackUserData; 371 } 372 getErrorCallbackUserData()373 void *getErrorCallbackUserData() const { 374 return mErrorCallbackUserData; 375 } 376 getFramesPerDataCallback()377 int32_t getFramesPerDataCallback() const { 378 return mFramesPerDataCallback; 379 } 380 getChannelMask()381 aaudio_channel_mask_t getChannelMask() const { 382 return mChannelMask; 383 } 384 setChannelMask(aaudio_channel_mask_t channelMask)385 void setChannelMask(aaudio_channel_mask_t channelMask) { 386 mChannelMask = channelMask; 387 mSamplesPerFrame = AAudioConvert_channelMaskToCount(channelMask); 388 } 389 setDeviceSamplesPerFrame(int32_t deviceSamplesPerFrame)390 void setDeviceSamplesPerFrame(int32_t deviceSamplesPerFrame) { 391 mDeviceSamplesPerFrame = deviceSamplesPerFrame; 392 } 393 setOffloadDelayPadding(int32_t delayInFrames,int32_t paddingInFrames)394 virtual aaudio_result_t setOffloadDelayPadding(int32_t delayInFrames, int32_t paddingInFrames) { 395 return AAUDIO_ERROR_UNIMPLEMENTED; 396 } 397 getOffloadDelay()398 virtual int32_t getOffloadDelay() { 399 return AAUDIO_ERROR_UNIMPLEMENTED; 400 } 401 getOffloadPadding()402 virtual int32_t getOffloadPadding() { 403 return AAUDIO_ERROR_UNIMPLEMENTED; 404 } 405 setOffloadEndOfStream()406 virtual aaudio_result_t setOffloadEndOfStream() EXCLUDES(mStreamLock) { 407 return AAUDIO_ERROR_UNIMPLEMENTED; 408 } 409 setPresentationEndCallbackProc(AAudioStream_presentationEndCallback proc)410 virtual void setPresentationEndCallbackProc(AAudioStream_presentationEndCallback proc) { } setPresentationEndCallbackUserData(void * userData)411 virtual void setPresentationEndCallbackUserData(void* userData) { } 412 413 /** 414 * @return true if data callback has been specified 415 */ isDataCallbackSet()416 bool isDataCallbackSet() const { 417 return mDataCallbackProc != nullptr; 418 } 419 420 /** 421 * @return true if data callback has been specified and stream is running 422 */ isDataCallbackActive()423 bool isDataCallbackActive() const { 424 return isDataCallbackSet() && isActive(); 425 } 426 427 /** 428 * @return true if called from the same thread as the callback 429 */ 430 virtual bool collidesWithCallback() const; 431 432 // Implement AudioDeviceCallback onAudioDeviceUpdate(audio_io_handle_t audioIo,const android::DeviceIdVector & deviceIds)433 void onAudioDeviceUpdate(audio_io_handle_t audioIo, 434 const android::DeviceIdVector& deviceIds) override {}; 435 436 // ============== I/O =========================== 437 // A Stream will only implement read() or write() depending on its direction. write(const void * buffer __unused,int32_t numFrames __unused,int64_t timeoutNanoseconds __unused)438 virtual aaudio_result_t write(const void *buffer __unused, 439 int32_t numFrames __unused, 440 int64_t timeoutNanoseconds __unused) { 441 return AAUDIO_ERROR_UNIMPLEMENTED; 442 } 443 read(void * buffer __unused,int32_t numFrames __unused,int64_t timeoutNanoseconds __unused)444 virtual aaudio_result_t read(void *buffer __unused, 445 int32_t numFrames __unused, 446 int64_t timeoutNanoseconds __unused) { 447 return AAUDIO_ERROR_UNIMPLEMENTED; 448 } 449 450 // This is used by the AudioManager to duck and mute the stream when changing audio focus. 451 void setDuckAndMuteVolume(float duckAndMuteVolume) EXCLUDES(mStreamLock); 452 getDuckAndMuteVolume()453 float getDuckAndMuteVolume() const { 454 return mDuckAndMuteVolume; 455 } 456 457 // Implement this in the output subclasses. doSetVolume()458 virtual android::status_t doSetVolume() { return android::NO_ERROR; } 459 460 #if AAUDIO_USE_VOLUME_SHAPER 461 virtual ::android::binder::Status applyVolumeShaper( 462 const ::android::media::VolumeShaper::Configuration& configuration __unused, 463 const ::android::media::VolumeShaper::Operation& operation __unused); 464 #endif 465 466 /** 467 * Register this stream's PlayerBase with the AudioManager if needed. 468 * Only register output streams. 469 * This should only be called for client streams and not for streams 470 * that run in the service. 471 */ registerPlayerBase()472 virtual void registerPlayerBase() { 473 if (getDirection() == AAUDIO_DIRECTION_OUTPUT) { 474 mPlayerBase->registerWithAudioManager(this); 475 } 476 } 477 478 /** 479 * Unregister this stream's PlayerBase with the AudioManager. 480 * This will only unregister if already registered. 481 */ unregisterPlayerBase()482 void unregisterPlayerBase() { 483 mPlayerBase->unregisterWithAudioManager(); 484 } 485 486 aaudio_result_t systemStart() EXCLUDES(mStreamLock); 487 488 aaudio_result_t systemPause() EXCLUDES(mStreamLock); 489 490 aaudio_result_t safeFlush() EXCLUDES(mStreamLock); 491 492 /** 493 * This is called when an app calls AAudioStream_requestStop(); 494 * It prevents calls from a callback. 495 */ 496 aaudio_result_t systemStopFromApp(); 497 498 /** 499 * This is called internally when an app callback returns AAUDIO_CALLBACK_RESULT_STOP. 500 */ 501 aaudio_result_t systemStopInternal() EXCLUDES(mStreamLock); 502 503 /** 504 * Safely RELEASE a stream after taking mStreamLock and checking 505 * to make sure we are not being called from a callback. 506 * @return AAUDIO_OK or a negative error 507 */ 508 aaudio_result_t safeRelease() EXCLUDES(mStreamLock); 509 510 /** 511 * Safely RELEASE and CLOSE a stream after taking mStreamLock and checking 512 * to make sure we are not being called from a callback. 513 * @return AAUDIO_OK or a negative error 514 */ 515 aaudio_result_t safeReleaseClose(); 516 517 aaudio_result_t safeReleaseCloseInternal() EXCLUDES(mStreamLock); 518 519 protected: 520 521 // PlayerBase allows the system to control the stream volume. 522 class MyPlayerBase : public android::PlayerBase { 523 public: 524 MyPlayerBase() = default; 525 526 virtual ~MyPlayerBase() = default; 527 528 /** 529 * Register for volume changes and remote control. 530 */ 531 void registerWithAudioManager(const android::sp<AudioStream>& parent); 532 533 /** 534 * UnRegister. 535 */ 536 void unregisterWithAudioManager(); 537 538 /** 539 * Just calls unregisterWithAudioManager(). 540 */ 541 void destroy() override; 542 543 // Just a stub. The ability to start audio through PlayerBase is being deprecated. playerStart()544 android::status_t playerStart() override { 545 return android::NO_ERROR; 546 } 547 548 // Just a stub. The ability to pause audio through PlayerBase is being deprecated. playerPause()549 android::status_t playerPause() override { 550 return android::NO_ERROR; 551 } 552 553 // Just a stub. The ability to stop audio through PlayerBase is being deprecated. playerStop()554 android::status_t playerStop() override { 555 return android::NO_ERROR; 556 } 557 558 android::status_t playerSetVolume() override; 559 560 #if AAUDIO_USE_VOLUME_SHAPER 561 ::android::binder::Status applyVolumeShaper(); 562 #endif 563 getResult()564 aaudio_result_t getResult() { 565 return mResult; 566 } 567 568 // Returns the playerIId if registered, -1 otherwise. getPlayerIId()569 int32_t getPlayerIId() const { 570 return mPIId; 571 } 572 573 private: 574 // Use a weak pointer so the AudioStream can be deleted. 575 std::mutex mParentLock; 576 android::wp<AudioStream> mParent GUARDED_BY(mParentLock); 577 aaudio_result_t mResult = AAUDIO_OK; 578 bool mRegistered = false; 579 }; 580 581 /** 582 * This should not be called after the open() call. 583 * TODO for multiple setters: assert(mState == AAUDIO_STREAM_STATE_UNINITIALIZED) 584 */ setSampleRate(int32_t sampleRate)585 void setSampleRate(int32_t sampleRate) { 586 mSampleRate = sampleRate; 587 } 588 589 // This should not be called after the open() call. setDeviceSampleRate(int32_t deviceSampleRate)590 void setDeviceSampleRate(int32_t deviceSampleRate) { 591 mDeviceSampleRate = deviceSampleRate; 592 } 593 594 // This should not be called after the open() call. setHardwareSampleRate(int32_t hardwareSampleRate)595 void setHardwareSampleRate(int32_t hardwareSampleRate) { 596 mHardwareSampleRate = hardwareSampleRate; 597 } 598 599 // This should not be called after the open() call. setFramesPerBurst(int32_t framesPerBurst)600 void setFramesPerBurst(int32_t framesPerBurst) { 601 mFramesPerBurst = framesPerBurst; 602 } 603 604 // This should not be called after the open() call. setDeviceFramesPerBurst(int32_t deviceFramesPerBurst)605 void setDeviceFramesPerBurst(int32_t deviceFramesPerBurst) { 606 mDeviceFramesPerBurst = deviceFramesPerBurst; 607 } 608 609 // This should not be called after the open() call. setBufferCapacity(int32_t bufferCapacity)610 void setBufferCapacity(int32_t bufferCapacity) { 611 mBufferCapacity = bufferCapacity; 612 } 613 614 // This should not be called after the open() call. setDeviceBufferCapacity(int32_t deviceBufferCapacity)615 void setDeviceBufferCapacity(int32_t deviceBufferCapacity) { 616 mDeviceBufferCapacity = deviceBufferCapacity; 617 } 618 619 // This should not be called after the open() call. setSharingMode(aaudio_sharing_mode_t sharingMode)620 void setSharingMode(aaudio_sharing_mode_t sharingMode) { 621 mSharingMode = sharingMode; 622 } 623 624 // This should not be called after the open() call. setFormat(audio_format_t format)625 void setFormat(audio_format_t format) { 626 mFormat = format; 627 } 628 629 // This should not be called after the open() call. setHardwareFormat(audio_format_t format)630 void setHardwareFormat(audio_format_t format) { 631 mHardwareFormat = format; 632 } 633 634 // This should not be called after the open() call. setHardwareSamplesPerFrame(int32_t hardwareSamplesPerFrame)635 void setHardwareSamplesPerFrame(int32_t hardwareSamplesPerFrame) { 636 mHardwareSamplesPerFrame = hardwareSamplesPerFrame; 637 } 638 639 // This should not be called after the open() call. setDeviceFormat(audio_format_t format)640 void setDeviceFormat(audio_format_t format) { 641 mDeviceFormat = format; 642 } 643 getDeviceFormat()644 audio_format_t getDeviceFormat() const { 645 return mDeviceFormat; 646 } 647 648 void setState(aaudio_stream_state_t state); 649 isDisconnected()650 bool isDisconnected() const { 651 return mDisconnected.load(); 652 } 653 void setDisconnected(); 654 setDeviceIds(const android::DeviceIdVector & deviceIds)655 void setDeviceIds(const android::DeviceIdVector& deviceIds) { 656 mDeviceIds = deviceIds; 657 } 658 659 // This should not be called after the open() call. setSessionId(int32_t sessionId)660 void setSessionId(int32_t sessionId) { 661 mSessionId = sessionId; 662 } 663 664 aaudio_result_t createThread_l(int64_t periodNanoseconds, 665 aaudio_audio_thread_proc_t threadProc, 666 void *threadArg) 667 REQUIRES(mStreamLock); 668 669 aaudio_result_t joinThread_l(void **returnArg) REQUIRES(mStreamLock); 670 671 virtual aaudio_result_t systemStopInternal_l() REQUIRES(mStreamLock); 672 673 std::atomic<bool> mCallbackEnabled{false}; 674 675 float mDuckAndMuteVolume = 1.0f; 676 677 protected: 678 679 /** 680 * Either convert the data from device format to app format and return a pointer 681 * to the conversion buffer, 682 * OR just pass back the original pointer. 683 * 684 * Note that this is only used for the INPUT path. 685 * 686 * @param audioData 687 * @param numFrames 688 * @return original pointer or the conversion buffer 689 */ maybeConvertDeviceData(const void * audioData,int32_t)690 virtual const void * maybeConvertDeviceData(const void *audioData, int32_t /*numFrames*/) { 691 return audioData; 692 } 693 setPeriodNanoseconds(int64_t periodNanoseconds)694 void setPeriodNanoseconds(int64_t periodNanoseconds) { 695 mPeriodNanoseconds.store(periodNanoseconds, std::memory_order_release); 696 } 697 getPeriodNanoseconds()698 int64_t getPeriodNanoseconds() { 699 return mPeriodNanoseconds.load(std::memory_order_acquire); 700 } 701 702 /** 703 * This should not be called after the open() call. 704 */ setUsage(aaudio_usage_t usage)705 void setUsage(aaudio_usage_t usage) { 706 mUsage = usage; 707 } 708 709 /** 710 * This should not be called after the open() call. 711 */ setContentType(aaudio_content_type_t contentType)712 void setContentType(aaudio_content_type_t contentType) { 713 mContentType = contentType; 714 } 715 716 /** 717 * This should not be called after the open() call. 718 */ setTags(const std::set<std::string> & tags)719 void setTags(const std::set<std::string> &tags) { 720 mTags = tags; 721 } 722 723 std::string getTagsAsString() const; 724 setSpatializationBehavior(aaudio_spatialization_behavior_t spatializationBehavior)725 void setSpatializationBehavior(aaudio_spatialization_behavior_t spatializationBehavior) { 726 mSpatializationBehavior = spatializationBehavior; 727 } 728 setIsContentSpatialized(bool isContentSpatialized)729 void setIsContentSpatialized(bool isContentSpatialized) { 730 mIsContentSpatialized = isContentSpatialized; 731 } 732 733 /** 734 * This should not be called after the open() call. 735 */ setInputPreset(aaudio_input_preset_t inputPreset)736 void setInputPreset(aaudio_input_preset_t inputPreset) { 737 mInputPreset = inputPreset; 738 } 739 740 /** 741 * This should not be called after the open() call. 742 */ setAllowedCapturePolicy(aaudio_allowed_capture_policy_t policy)743 void setAllowedCapturePolicy(aaudio_allowed_capture_policy_t policy) { 744 mAllowedCapturePolicy = policy; 745 } 746 747 /** 748 * This should not be called after the open() call. 749 */ setPrivacySensitive(bool privacySensitive)750 void setPrivacySensitive(bool privacySensitive) { 751 mIsPrivacySensitive = privacySensitive; 752 } 753 754 /** 755 * This should not be called after the open() call. 756 */ setRequireMonoBlend(bool requireMonoBlend)757 void setRequireMonoBlend(bool requireMonoBlend) { 758 mRequireMonoBlend = requireMonoBlend; 759 } 760 761 /** 762 * This should not be called after the open() call. 763 */ setAudioBalance(float audioBalance)764 void setAudioBalance(float audioBalance) { 765 mAudioBalance = audioBalance; 766 } 767 768 aaudio_result_t safeStop_l() REQUIRES(mStreamLock); 769 770 std::string mMetricsId; // set once during open() 771 772 std::mutex mStreamLock; 773 774 const android::sp<MyPlayerBase> mPlayerBase; 775 776 private: 777 778 /** 779 * Release then close the stream. 780 */ releaseCloseFinal_l()781 void releaseCloseFinal_l() REQUIRES(mStreamLock) { 782 if (getState() != AAUDIO_STREAM_STATE_CLOSING) { // not already released? 783 // Ignore result and keep closing. 784 (void) release_l(); 785 } 786 close_l(); 787 } 788 789 std::atomic<aaudio_stream_state_t> mState{AAUDIO_STREAM_STATE_UNINITIALIZED}; 790 791 std::atomic_bool mDisconnected{false}; 792 793 // These do not change after open(). 794 int32_t mSamplesPerFrame = AAUDIO_UNSPECIFIED; 795 int32_t mDeviceSamplesPerFrame = AAUDIO_UNSPECIFIED; 796 int32_t mHardwareSamplesPerFrame = AAUDIO_UNSPECIFIED; 797 aaudio_channel_mask_t mChannelMask = AAUDIO_UNSPECIFIED; 798 int32_t mSampleRate = AAUDIO_UNSPECIFIED; 799 int32_t mDeviceSampleRate = AAUDIO_UNSPECIFIED; 800 int32_t mHardwareSampleRate = AAUDIO_UNSPECIFIED; 801 android::DeviceIdVector mDeviceIds; 802 aaudio_sharing_mode_t mSharingMode = AAUDIO_SHARING_MODE_SHARED; 803 bool mSharingModeMatchRequired = false; // must match sharing mode requested 804 audio_format_t mFormat = AUDIO_FORMAT_DEFAULT; 805 audio_format_t mHardwareFormat = AUDIO_FORMAT_DEFAULT; 806 aaudio_performance_mode_t mPerformanceMode = AAUDIO_PERFORMANCE_MODE_NONE; 807 int32_t mFramesPerBurst = 0; 808 int32_t mDeviceFramesPerBurst = 0; 809 int32_t mBufferCapacity = 0; 810 int32_t mDeviceBufferCapacity = 0; 811 812 aaudio_usage_t mUsage = AAUDIO_UNSPECIFIED; 813 aaudio_content_type_t mContentType = AAUDIO_UNSPECIFIED; 814 std::set<std::string> mTags; 815 aaudio_spatialization_behavior_t mSpatializationBehavior = AAUDIO_UNSPECIFIED; 816 bool mIsContentSpatialized = false; 817 aaudio_input_preset_t mInputPreset = AAUDIO_UNSPECIFIED; 818 aaudio_allowed_capture_policy_t mAllowedCapturePolicy = AAUDIO_ALLOW_CAPTURE_BY_ALL; 819 bool mIsPrivacySensitive = false; 820 bool mRequireMonoBlend = false; 821 float mAudioBalance = 0; 822 823 int32_t mSessionId = AAUDIO_UNSPECIFIED; 824 825 // Sometimes the hardware is operating with a different format from the app. 826 // Then we require conversion in AAudio. 827 audio_format_t mDeviceFormat = AUDIO_FORMAT_INVALID; 828 829 // callback ---------------------------------- 830 831 AAudioStream_dataCallback mDataCallbackProc = nullptr; // external callback functions 832 void *mDataCallbackUserData = nullptr; 833 int32_t mFramesPerDataCallback = AAUDIO_UNSPECIFIED; // frames 834 std::atomic<pid_t> mDataCallbackThread{CALLBACK_THREAD_NONE}; 835 836 AAudioStream_errorCallback mErrorCallbackProc = nullptr; 837 void *mErrorCallbackUserData = nullptr; 838 std::atomic<pid_t> mErrorCallbackThread{CALLBACK_THREAD_NONE}; 839 840 // background thread ---------------------------------- 841 // Use mHasThread to prevent joining twice, which has undefined behavior. 842 bool mHasThread GUARDED_BY(mStreamLock) = false; 843 pthread_t mThread GUARDED_BY(mStreamLock) = {}; 844 845 // These are set by the application thread and then read by the audio pthread. 846 std::atomic<int64_t> mPeriodNanoseconds; // for tuning SCHED_FIFO threads 847 // TODO make atomic? 848 aaudio_audio_thread_proc_t mThreadProc = nullptr; 849 void *mThreadArg = nullptr; 850 aaudio_result_t mThreadRegistrationResult = AAUDIO_OK; 851 852 const aaudio_stream_id_t mStreamId; 853 854 }; 855 856 } /* namespace aaudio */ 857 858 #endif /* AAUDIO_AUDIOSTREAM_H */ 859