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 "Callbacks.h"
18 
19 #include "Conversions.h"
20 #include "PreparedModel.h"
21 #include "ProtectCallback.h"
22 #include "Utils.h"
23 
24 #include <nnapi/IPreparedModel.h>
25 #include <nnapi/Result.h>
26 #include <nnapi/Types.h>
27 
28 #include <utility>
29 
30 // See hardware/interfaces/neuralnetworks/utils/README.md for more information on AIDL interface
31 // lifetimes across processes and for protecting asynchronous calls across AIDL.
32 
33 namespace aidl::android::hardware::neuralnetworks::utils {
34 namespace {
35 
36 // Converts the results of IDevice::prepareModel* to the NN canonical format. On success, this
37 // function returns with a non-null nn::SharedPreparedModel with a feature level of
38 // nn::kVersionFeatureLevel5. On failure, this function returns with the appropriate
39 // nn::GeneralError.
prepareModelCallback(ErrorStatus status,const std::shared_ptr<IPreparedModel> & preparedModel,nn::Version featureLevel)40 nn::GeneralResult<nn::SharedPreparedModel> prepareModelCallback(
41         ErrorStatus status, const std::shared_ptr<IPreparedModel>& preparedModel,
42         nn::Version featureLevel) {
43     HANDLE_STATUS_AIDL(status) << "model preparation failed with " << toString(status);
44     return NN_TRY(PreparedModel::create(preparedModel, featureLevel));
45 }
46 
47 }  // namespace
48 
notify(ErrorStatus status,const std::shared_ptr<IPreparedModel> & preparedModel)49 ndk::ScopedAStatus PreparedModelCallback::notify(
50         ErrorStatus status, const std::shared_ptr<IPreparedModel>& preparedModel) {
51     mData.put(prepareModelCallback(status, preparedModel, kFeatureLevel));
52     return ndk::ScopedAStatus::ok();
53 }
54 
notifyAsDeadObject()55 void PreparedModelCallback::notifyAsDeadObject() {
56     mData.put(NN_ERROR(nn::ErrorStatus::DEAD_OBJECT) << "Dead object");
57 }
58 
get()59 PreparedModelCallback::Data PreparedModelCallback::get() {
60     return mData.take();
61 }
62 
63 }  // namespace aidl::android::hardware::neuralnetworks::utils
64