1 /* 2 * Copyright (C) 2020 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 ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_COMMON_RESILIENT_BUFFER_H 18 #define ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_COMMON_RESILIENT_BUFFER_H 19 20 #include <android-base/thread_annotations.h> 21 #include <nnapi/IBuffer.h> 22 #include <nnapi/Result.h> 23 #include <nnapi/Types.h> 24 25 #include <functional> 26 #include <memory> 27 #include <mutex> 28 #include <utility> 29 #include <vector> 30 31 namespace android::hardware::neuralnetworks::utils { 32 33 class ResilientBuffer final : public nn::IBuffer { 34 struct PrivateConstructorTag {}; 35 36 public: 37 using Factory = std::function<nn::GeneralResult<nn::SharedBuffer>()>; 38 39 static nn::GeneralResult<std::shared_ptr<const ResilientBuffer>> create(Factory makeBuffer); 40 41 explicit ResilientBuffer(PrivateConstructorTag tag, Factory makeBuffer, 42 nn::SharedBuffer buffer); 43 44 nn::SharedBuffer getBuffer() const; 45 nn::GeneralResult<nn::SharedBuffer> recover(const nn::IBuffer* failingBuffer) const; 46 47 nn::Request::MemoryDomainToken getToken() const override; 48 49 nn::GeneralResult<void> copyTo(const nn::SharedMemory& dst) const override; 50 51 nn::GeneralResult<void> copyFrom(const nn::SharedMemory& src, 52 const nn::Dimensions& dimensions) const override; 53 54 private: 55 const Factory kMakeBuffer; 56 mutable std::mutex mMutex; 57 mutable nn::SharedBuffer mBuffer GUARDED_BY(mMutex); 58 }; 59 60 } // namespace android::hardware::neuralnetworks::utils 61 62 #endif // ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_COMMON_RESILIENT_BUFFER_H 63