1 /*
2 * Copyright (C) 2021 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 #include "Buffer.h"
18
19 #include <nnapi/IPreparedModel.h>
20 #include <nnapi/Result.h>
21 #include <nnapi/Types.h>
22
23 #include "Conversions.h"
24 #include "Utils.h"
25
26 #include <memory>
27 #include <utility>
28
29 // See hardware/interfaces/neuralnetworks/utils/README.md for more information on AIDL interface
30 // lifetimes across processes.
31
32 namespace aidl::android::hardware::neuralnetworks::utils {
33
create(std::shared_ptr<aidl_hal::IBuffer> buffer,nn::Request::MemoryDomainToken token)34 nn::GeneralResult<std::shared_ptr<const Buffer>> Buffer::create(
35 std::shared_ptr<aidl_hal::IBuffer> buffer, nn::Request::MemoryDomainToken token) {
36 if (buffer == nullptr) {
37 return NN_ERROR() << "aidl_hal::utils::Buffer::create must have non-null buffer";
38 }
39 if (token == static_cast<nn::Request::MemoryDomainToken>(0)) {
40 return NN_ERROR() << "aidl_hal::utils::Buffer::create must have non-zero token";
41 }
42
43 return std::make_shared<const Buffer>(PrivateConstructorTag{}, std::move(buffer), token);
44 }
45
Buffer(PrivateConstructorTag,std::shared_ptr<aidl_hal::IBuffer> buffer,nn::Request::MemoryDomainToken token)46 Buffer::Buffer(PrivateConstructorTag /*tag*/, std::shared_ptr<aidl_hal::IBuffer> buffer,
47 nn::Request::MemoryDomainToken token)
48 : kBuffer(std::move(buffer)), kToken(token) {
49 CHECK(kBuffer != nullptr);
50 CHECK(kToken != static_cast<nn::Request::MemoryDomainToken>(0));
51 }
52
getToken() const53 nn::Request::MemoryDomainToken Buffer::getToken() const {
54 return kToken;
55 }
56
copyTo(const nn::SharedMemory & dst) const57 nn::GeneralResult<void> Buffer::copyTo(const nn::SharedMemory& dst) const {
58 const auto aidlDst = NN_TRY(convert(dst));
59
60 const auto ret = kBuffer->copyTo(aidlDst);
61 HANDLE_ASTATUS(ret) << "IBuffer::copyTo failed";
62
63 return {};
64 }
65
copyFrom(const nn::SharedMemory & src,const nn::Dimensions & dimensions) const66 nn::GeneralResult<void> Buffer::copyFrom(const nn::SharedMemory& src,
67 const nn::Dimensions& dimensions) const {
68 const auto aidlSrc = NN_TRY(convert(src));
69 const auto aidlDimensions = NN_TRY(toSigned(dimensions));
70
71 const auto ret = kBuffer->copyFrom(aidlSrc, aidlDimensions);
72 HANDLE_ASTATUS(ret) << "IBuffer::copyFrom failed";
73
74 return {};
75 }
76
77 } // namespace aidl::android::hardware::neuralnetworks::utils
78