1 /*
2  * Copyright (C) 2018 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 #define LOG_TAG "Callbacks"
18 
19 #include "1.0/Callbacks.h"
20 
21 #include <android-base/logging.h>
22 
23 namespace android::hardware::neuralnetworks::V1_0::implementation {
24 
25 // PreparedModelCallback methods begin here
26 
notify(ErrorStatus errorStatus,const sp<IPreparedModel> & preparedModel)27 Return<void> PreparedModelCallback::notify(ErrorStatus errorStatus,
28                                            const sp<IPreparedModel>& preparedModel) {
29     {
30         std::lock_guard<std::mutex> hold(mMutex);
31 
32         // quick-return if object has already been notified
33         if (mNotified) {
34             return Void();
35         }
36 
37         // store results and mark as notified
38         mErrorStatus = errorStatus;
39         mPreparedModel = preparedModel;
40         mNotified = true;
41     }
42 
43     mCondition.notify_all();
44     return Void();
45 }
46 
wait() const47 void PreparedModelCallback::wait() const {
48     std::unique_lock<std::mutex> lock(mMutex);
49     mCondition.wait(lock, [this] { return mNotified; });
50 }
51 
getStatus() const52 ErrorStatus PreparedModelCallback::getStatus() const {
53     wait();
54     return mErrorStatus;
55 }
56 
getPreparedModel() const57 sp<IPreparedModel> PreparedModelCallback::getPreparedModel() const {
58     wait();
59     return mPreparedModel;
60 }
61 
62 // ExecutionCallback methods begin here
63 
notify(ErrorStatus errorStatus)64 Return<void> ExecutionCallback::notify(ErrorStatus errorStatus) {
65     {
66         std::lock_guard<std::mutex> hold(mMutex);
67 
68         // quick-return if object has already been notified
69         if (mNotified) {
70             return Void();
71         }
72 
73         mErrorStatus = errorStatus;
74         mNotified = true;
75     }
76     mCondition.notify_all();
77 
78     return Void();
79 }
80 
wait() const81 void ExecutionCallback::wait() const {
82     std::unique_lock<std::mutex> lock(mMutex);
83     mCondition.wait(lock, [this] { return mNotified; });
84 }
85 
getStatus() const86 ErrorStatus ExecutionCallback::getStatus() const {
87     wait();
88     return mErrorStatus;
89 }
90 
91 }  // namespace android::hardware::neuralnetworks::V1_0::implementation
92