1 /* 2 * Copyright (C) 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 OBOE_STREAM_BUFFERED_H 18 #define OBOE_STREAM_BUFFERED_H 19 20 #include <cstring> 21 #include <cassert> 22 #include "common/OboeDebug.h" 23 #include "oboe/AudioStream.h" 24 #include "oboe/AudioStreamCallback.h" 25 #include "fifo/FifoBuffer.h" 26 27 namespace oboe { 28 29 // A stream that contains a FIFO buffer. 30 // This is used to implement blocking reads and writes. 31 class AudioStreamBuffered : public AudioStream { 32 public: 33 34 AudioStreamBuffered(); 35 explicit AudioStreamBuffered(const AudioStreamBuilder &builder); 36 37 void allocateFifo(); 38 39 40 ResultWithValue<int32_t> write(const void *buffer, 41 int32_t numFrames, 42 int64_t timeoutNanoseconds) override; 43 44 ResultWithValue<int32_t> read(void *buffer, 45 int32_t numFrames, 46 int64_t timeoutNanoseconds) override; 47 48 ResultWithValue<int32_t> setBufferSizeInFrames(int32_t requestedFrames) override; 49 50 int32_t getBufferCapacityInFrames() const override; 51 getXRunCount()52 ResultWithValue<int32_t> getXRunCount() const override { 53 return ResultWithValue<int32_t>(mXRunCount); 54 } 55 56 bool isXRunCountSupported() const override; 57 58 protected: 59 60 DataCallbackResult onDefaultCallback(void *audioData, int numFrames) override; 61 62 // If there is no callback then we need a FIFO between the App and OpenSL ES. usingFIFO()63 bool usingFIFO() const { return getCallback() == nullptr; } 64 65 virtual Result updateServiceFrameCounter() = 0; 66 67 void updateFramesRead() override; 68 void updateFramesWritten() override; 69 70 private: 71 72 int64_t predictNextCallbackTime(); 73 74 void markCallbackTime(int32_t numFrames); 75 76 // Read or write to the FIFO. 77 ResultWithValue<int32_t> transfer(void *buffer, int32_t numFrames, int64_t timeoutNanoseconds); 78 incrementXRunCount()79 void incrementXRunCount() { 80 ++mXRunCount; 81 } 82 83 std::unique_ptr<FifoBuffer> mFifoBuffer{}; 84 85 int64_t mBackgroundRanAtNanoseconds = 0; 86 int32_t mLastBackgroundSize = 0; 87 int32_t mXRunCount = 0; 88 }; 89 90 } // namespace oboe 91 92 #endif //OBOE_STREAM_BUFFERED_H 93