• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <memory>
17 
18 #include "avsession_trace.h"
19 #include "napi_utils.h"
20 #include "napi_async_callback.h"
21 
22 namespace OHOS::AVSession {
NapiAsyncCallback(napi_env env)23 NapiAsyncCallback::NapiAsyncCallback(napi_env env) : env_(env)
24 {
25     if (env != nullptr) {
26         napi_get_uv_event_loop(env, &loop_);
27     }
28 }
29 
~NapiAsyncCallback()30 NapiAsyncCallback::~NapiAsyncCallback()
31 {
32     SLOGD("no memory leak for queue-callback");
33     env_ = nullptr;
34 }
35 
GetEnv() const36 napi_env NapiAsyncCallback::GetEnv() const
37 {
38     return env_;
39 }
40 
AfterWorkCallback(uv_work_t * work,int aStatus)41 void NapiAsyncCallback::AfterWorkCallback(uv_work_t* work, int aStatus)
42 {
43     AVSESSION_TRACE_SYNC_START("NapiAsyncCallback::AfterWorkCallback");
44     std::shared_ptr<DataContext> context(static_cast<DataContext*>(work->data), [work](DataContext* ptr) {
45         delete ptr;
46         delete work;
47     });
48 
49     int argc = 0;
50     napi_value argv[ARGC_MAX] = { nullptr };
51     if (context->getter) {
52         argc = ARGC_MAX;
53         context->getter(context->env, argc, argv);
54     }
55 
56     SLOGI("queue uv_after_work_cb");
57     napi_value global {};
58     napi_get_global(context->env, &global);
59     napi_value function {};
60     napi_get_reference_value(context->env, context->method, &function);
61     napi_value result;
62     napi_status status = napi_call_function(context->env, global, function, argc, argv, &result);
63     if (status != napi_ok) {
64         SLOGE("call function failed status=%{public}d.", status);
65     }
66 }
67 
Call(napi_ref method,NapiArgsGetter getter)68 void NapiAsyncCallback::Call(napi_ref method, NapiArgsGetter getter)
69 {
70     CHECK_RETURN_VOID(loop_ != nullptr, "loop_ is nullptr");
71     CHECK_RETURN_VOID(method != nullptr, "method is nullptr");
72 
73     auto* work = new (std::nothrow) uv_work_t;
74     CHECK_RETURN_VOID(work != nullptr, "no memory for uv_work_t");
75 
76     work->data = new DataContext{env_, method, std::move(getter)};
77     int res = uv_queue_work(loop_, work, [](uv_work_t* work) {}, AfterWorkCallback);
78     CHECK_RETURN_VOID(res == 0, "uv queue work failed");
79 }
80 }