1 /* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef OHOS_NAPI_ASYNC_WORK_H 17 #define OHOS_NAPI_ASYNC_WORK_H 18 19 #include <functional> 20 #include <memory> 21 #include <string> 22 23 #include "napi/native_api.h" 24 #include "napi/native_common.h" 25 #include "napi/native_node_api.h" 26 27 namespace OHOS::AVSession { 28 using NapiCbInfoParser = std::function<void(size_t argc, napi_value* argv)>; 29 using NapiAsyncExecute = std::function<void(void)>; 30 using NapiAsyncComplete = std::function<void(napi_value&)>; 31 32 struct ContextBase { 33 virtual ~ContextBase(); 34 void GetCbInfo(napi_env env, napi_callback_info info, NapiCbInfoParser parse = NapiCbInfoParser(), 35 bool sync = false); 36 37 napi_env env = nullptr; 38 napi_value output = nullptr; 39 napi_status status = napi_invalid_arg; 40 std::string errMessage; 41 int32_t errCode; 42 napi_value self = nullptr; 43 void* native = nullptr; 44 int32_t taskId = -1; 45 std::string taskName; 46 47 private: 48 napi_deferred deferred = nullptr; 49 napi_async_work work = nullptr; 50 napi_ref callbackRef = nullptr; 51 napi_ref selfRef = nullptr; 52 53 NapiAsyncExecute execute = nullptr; 54 NapiAsyncComplete complete = nullptr; 55 std::shared_ptr<ContextBase> hold; /* cross thread data */ 56 57 static constexpr size_t ARGC_MAX = 6; 58 59 friend class NapiAsyncWork; 60 }; 61 62 class NapiAsyncWork { 63 public: 64 static napi_value Enqueue(napi_env env, std::shared_ptr<ContextBase> ctxt, const std::string& name, 65 NapiAsyncExecute execute = NapiAsyncExecute(), 66 NapiAsyncComplete complete = NapiAsyncComplete()); 67 68 private: 69 enum { 70 /* AsyncCallback / Promise output result index */ 71 RESULT_ERROR = 0, 72 RESULT_DATA = 1, 73 RESULT_ALL = 2 74 }; 75 static void GenerateOutput(ContextBase* ctxt); 76 }; 77 } // namespace OHOS::AVSession 78 #endif // OHOS_NAPI_ASYNC_WORK_H