1 /*
2  * Copyright (C) 2023 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 "media_data_source_callback.h"
17 #include "buffer/avsharedmemory.h"
18 #include "media_dfx.h"
19 #include "media_log.h"
20 #include "media_errors.h"
21 #include "scope_guard.h"
22 
23 namespace {
24 constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, LOG_DOMAIN_PLAYER, "MediaDataSourceCallback"};
25 }
26 
27 namespace OHOS {
28 namespace Media {
~MediaDataSourceJsCallback()29 MediaDataSourceJsCallback::~MediaDataSourceJsCallback()
30 {
31     isExit_ = true;
32     cond_.notify_all();
33     memory_ = nullptr;
34 }
35 
WaitResult()36 void MediaDataSourceJsCallback::WaitResult()
37 {
38     std::unique_lock<std::mutex> lock(mutexCond_);
39     if (!setResult_) {
40         static constexpr int32_t timeout = 100;
41         cond_.wait_for(lock, std::chrono::milliseconds(timeout), [this]() { return setResult_ || isExit_; });
42         if (!setResult_) {
43             readSize_ = 0;
44             if (isExit_) {
45                 MEDIA_LOGW("Reset, ReadAt has been cancel!");
46             } else {
47                 MEDIA_LOGW("timeout 100ms!");
48             }
49         }
50     }
51     setResult_ = false;
52 }
53 
MediaDataSourceCallback(napi_env env,int64_t fileSize)54 MediaDataSourceCallback::MediaDataSourceCallback(napi_env env, int64_t fileSize)
55     : env_(env),
56       size_(fileSize)
57 {
58     MEDIA_LOGD("0x%{public}06" PRIXPTR " Instances create", FAKE_POINTER(this));
59 }
60 
~MediaDataSourceCallback()61 MediaDataSourceCallback::~MediaDataSourceCallback()
62 {
63     MEDIA_LOGD("0x%{public}06" PRIXPTR " Instances destroy", FAKE_POINTER(this));
64     env_ = nullptr;
65 }
66 
ReadAt(const std::shared_ptr<AVSharedMemory> & mem,uint32_t length,int64_t pos)67 int32_t MediaDataSourceCallback::ReadAt(const std::shared_ptr<AVSharedMemory> &mem, uint32_t length, int64_t pos)
68 {
69     MEDIA_LOGD("MediaDataSourceCallback ReadAt in");
70     {
71         std::lock_guard<std::mutex> lock(mutex_);
72         if (refMap_.find(READAT_CALLBACK_NAME) == refMap_.end()) {
73             return SOURCE_ERROR_IO;
74         }
75         cb_ = std::make_shared<MediaDataSourceJsCallback>(READAT_CALLBACK_NAME, mem, length, pos);
76         CHECK_AND_RETURN_RET_LOG(cb_ != nullptr, 0, "Failed to Create MediaDataSourceJsCallback");
77         cb_->callback_ = refMap_.at(READAT_CALLBACK_NAME);
78     }
79     ON_SCOPE_EXIT(0) {
80         cb_ = nullptr;
81     };
82 
83     uv_loop_s *loop = nullptr;
84     napi_get_uv_event_loop(env_, &loop);
85     CHECK_AND_RETURN_RET_LOG(loop != nullptr, 0, "Failed to get uv event loop");
86     uv_work_t *work = new(std::nothrow) uv_work_t;
87     CHECK_AND_RETURN_RET_LOG(work != nullptr, 0, "Failed to new uv_work_t");
88     ON_SCOPE_EXIT(1) {
89         delete work;
90     };
91 
92     MediaDataSourceJsCallbackWraper *cbWrap = new(std::nothrow) MediaDataSourceJsCallbackWraper();
93     CHECK_AND_RETURN_RET_LOG(cbWrap != nullptr, 0, "Failed to new MediaDataSourceJsCallbackWraper");
94     cbWrap->cb_ = cb_;
95     work->data = reinterpret_cast<void *>(cbWrap);
96     // async callback, jsWork and jsWork->data should be heap object.
97     int ret = UvWork(loop, work);
98     CHECK_AND_RETURN_RET_LOG(ret == 0, SOURCE_ERROR_IO, "Failed to execute uv queue work");
99     CANCEL_SCOPE_EXIT_GUARD(1);
100     cb_->WaitResult();
101     MEDIA_LOGD("ReadAt out");
102     return cb_->readSize_;
103 }
104 
UvWork(uv_loop_s * loop,uv_work_t * work)105 int32_t MediaDataSourceCallback::UvWork(uv_loop_s *loop, uv_work_t *work)
106 {
107     MEDIA_LOGD("begin UvWork");
108     return uv_queue_work_with_qos(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) {
109         // Js Thread
110         CHECK_AND_RETURN_LOG(work != nullptr && work->data != nullptr, "work is nullptr");
111         MediaDataSourceJsCallbackWraper *wrap = reinterpret_cast<MediaDataSourceJsCallbackWraper *>(work->data);
112         std::shared_ptr<MediaDataSourceJsCallback> event = wrap->cb_.lock();
113         CHECK_AND_RETURN_LOG(event != nullptr, "MediaDataSourceJsCallback is nullptr");
114         MEDIA_LOGD("length is %{public}u", event->length_);
115         do {
116             CHECK_AND_BREAK(status != UV_ECANCELED);
117             std::shared_ptr<AutoRef> ref = event->callback_.lock();
118             CHECK_AND_BREAK_LOG(ref != nullptr, "%{public}s AutoRef is nullptr", event->callbackName_.c_str());
119 
120             napi_handle_scope scope = nullptr;
121             napi_open_handle_scope(ref->env_, &scope);
122             CHECK_AND_BREAK_LOG(scope != nullptr, "%{public}s scope is nullptr", event->callbackName_.c_str());
123             ON_SCOPE_EXIT(0) {
124                 napi_close_handle_scope(ref->env_, scope);
125             };
126 
127             napi_value jsCallback = nullptr;
128             napi_status nstatus = napi_get_reference_value(ref->env_, ref->cb_, &jsCallback);
129             CHECK_AND_BREAK(nstatus == napi_ok && jsCallback != nullptr);
130 
131             // noseek mode don't need pos, so noseek mode need 2 parameters and seekable mode need 3 parameters
132             int32_t paramNum;
133             napi_value args[3] = { nullptr };
134             CHECK_AND_BREAK_LOG(event->memory_ != nullptr, "failed to checkout memory");
135             nstatus = napi_create_external_arraybuffer(ref->env_, event->memory_->GetBase(),
136                 static_cast<size_t>(event->length_), [](napi_env env, void *data, void *hint) {}, nullptr, &args[0]);
137             CHECK_AND_BREAK_LOG(nstatus == napi_ok, "create napi arraybuffer failed");
138             CHECK_AND_BREAK_LOG(napi_create_uint32(ref->env_, event->length_, &args[1]) == napi_ok,
139                 "set length failed");
140             if (event->pos_ != -1) {
141                 paramNum = 3;  // 3 parameters
142                 CHECK_AND_BREAK_LOG(napi_create_int64(ref->env_, event->pos_, &args[2]) == napi_ok,  // 2 parameters
143                     "set pos failed");
144             } else {
145                 paramNum = 2;  // 2 parameters
146             }
147 
148             napi_value size;
149             MEDIA_LOGD("call JS function");
150             nstatus = napi_call_function(ref->env_, nullptr, jsCallback, paramNum, args, &size);
151             CHECK_AND_BREAK(nstatus == napi_ok);
152             nstatus = napi_get_value_int32(ref->env_, size, &event->readSize_);
153             CHECK_AND_BREAK_LOG(nstatus == napi_ok, "get size failed");
154             std::unique_lock<std::mutex> lock(event->mutexCond_);
155             event->setResult_ = true;
156             event->cond_.notify_all();
157         } while (0);
158         delete work;
159     }, uv_qos_user_initiated);
160 }
161 
ReadAt(int64_t pos,uint32_t length,const std::shared_ptr<AVSharedMemory> & mem)162 int32_t MediaDataSourceCallback::ReadAt(int64_t pos, uint32_t length, const std::shared_ptr<AVSharedMemory> &mem)
163 {
164     (void)pos;
165     (void)length;
166     (void)mem;
167     return MSERR_OK;
168 }
169 
ReadAt(uint32_t length,const std::shared_ptr<AVSharedMemory> & mem)170 int32_t MediaDataSourceCallback::ReadAt(uint32_t length, const std::shared_ptr<AVSharedMemory> &mem)
171 {
172     (void)length;
173     (void)mem;
174     return MSERR_OK;
175 }
176 
GetSize(int64_t & size)177 int32_t MediaDataSourceCallback::GetSize(int64_t &size)
178 {
179     size = size_;
180     return MSERR_OK;
181 }
182 
SaveCallbackReference(const std::string & name,std::shared_ptr<AutoRef> ref)183 void MediaDataSourceCallback::SaveCallbackReference(const std::string &name, std::shared_ptr<AutoRef> ref)
184 {
185     MEDIA_LOGD("Add Callback: %{public}s", name.c_str());
186     std::lock_guard<std::mutex> lock(mutex_);
187     refMap_[name] = ref;
188 }
189 
GetCallback(const std::string & name,napi_value * callback)190 int32_t MediaDataSourceCallback::GetCallback(const std::string &name, napi_value *callback)
191 {
192     (void)name;
193     if (refMap_.find(READAT_CALLBACK_NAME) == refMap_.end()) {
194         return MSERR_INVALID_VAL;
195     }
196     auto ref = refMap_.at(READAT_CALLBACK_NAME);
197     napi_status nstatus = napi_get_reference_value(ref->env_, ref->cb_, callback);
198     CHECK_AND_RETURN_RET(nstatus == napi_ok && callback != nullptr, MSERR_INVALID_OPERATION);
199     return MSERR_OK;
200 }
201 
ClearCallbackReference()202 void MediaDataSourceCallback::ClearCallbackReference()
203 {
204     std::lock_guard<std::mutex> lock(mutex_);
205     std::map<std::string, std::shared_ptr<AutoRef>> temp;
206     temp.swap(refMap_);
207     MEDIA_LOGD("callback has been clear");
208     if (cb_) {
209         cb_->isExit_ = true;
210         cb_->cond_.notify_all();
211     }
212 }
213 
AddNapiValueProp(napi_env env,napi_value obj,const std::string & key,napi_value value)214 bool MediaDataSourceCallback::AddNapiValueProp(napi_env env, napi_value obj, const std::string &key, napi_value value)
215 {
216     CHECK_AND_RETURN_RET(obj != nullptr, false);
217 
218     napi_value keyNapi = nullptr;
219     napi_status status = napi_create_string_utf8(env, key.c_str(), NAPI_AUTO_LENGTH, &keyNapi);
220     CHECK_AND_RETURN_RET(status == napi_ok, false);
221 
222     status = napi_set_property(env, obj, keyNapi, value);
223     CHECK_AND_RETURN_RET_LOG(status == napi_ok, false, "Failed to set property");
224 
225     return true;
226 }
227 } // namespace Media
228 } // namespace OHOS
229