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 "native_avmemory.h"
17 #include "buffer/avsharedmemorybase.h"
18 #include "common/log.h"
19 #include "common/native_mfmagic.h"
20 #include "common/status.h"
21 
22 namespace {
23 constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, LOG_DOMAIN_FOUNDATION, "NativeAVMemory" };
24 }
25 
26 using namespace OHOS::Media;
27 
OH_AVMemory_Create(int32_t size)28 struct OH_AVMemory *OH_AVMemory_Create(int32_t size)
29 {
30     FALSE_RETURN_V_MSG_E(size >= 0, nullptr, "size %{public}d is error!", size);
31     std::shared_ptr<AVSharedMemoryBase> sharedMemory =
32         std::make_shared<AVSharedMemoryBase>(size, AVSharedMemory::FLAGS_READ_WRITE, "userBuffer");
33     FALSE_RETURN_V_MSG_E(sharedMemory->Init() == static_cast<int32_t>(Status::OK), nullptr,
34                          "create OH_AVMemory failed");
35 
36     struct OH_AVMemory *mem = new (std::nothrow) OH_AVMemory(sharedMemory);
37     FALSE_RETURN_V_MSG_E(mem != nullptr, nullptr, "failed to new OH_AVMemory");
38     mem->isUserCreated = true;
39 
40     return mem;
41 }
42 
OH_AVMemory_GetAddr(struct OH_AVMemory * mem)43 uint8_t *OH_AVMemory_GetAddr(struct OH_AVMemory *mem)
44 {
45     FALSE_RETURN_V_MSG_E(mem != nullptr, nullptr, "input mem is nullptr!");
46     FALSE_RETURN_V_MSG_E(mem->magic_ == MFMagic::MFMAGIC_SHARED_MEMORY, nullptr, "magic error!");
47     FALSE_RETURN_V_MSG_E(mem->memory_ != nullptr, nullptr, "memory is nullptr!");
48     return mem->memory_->GetBase();
49 }
50 
OH_AVMemory_GetSize(struct OH_AVMemory * mem)51 int32_t OH_AVMemory_GetSize(struct OH_AVMemory *mem)
52 {
53     FALSE_RETURN_V_MSG_E(mem != nullptr, -1, "input mem is nullptr!");
54     FALSE_RETURN_V_MSG_E(mem->magic_ == MFMagic::MFMAGIC_SHARED_MEMORY, -1, "magic error!");
55     FALSE_RETURN_V_MSG_E(mem->memory_ != nullptr, -1, "memory is nullptr!");
56     return mem->memory_->GetSize();
57 }
58 
OH_AVMemory_Destroy(struct OH_AVMemory * mem)59 OH_AVErrCode OH_AVMemory_Destroy(struct OH_AVMemory *mem)
60 {
61     FALSE_RETURN_V_MSG_E(mem != nullptr, AV_ERR_INVALID_VAL, "input mem is nullptr!");
62     FALSE_RETURN_V_MSG_E(mem->magic_ == MFMagic::MFMAGIC_SHARED_MEMORY, AV_ERR_INVALID_VAL, "magic error!");
63     FALSE_RETURN_V_MSG_E(mem->isUserCreated, AV_ERR_INVALID_VAL, "input mem is not user created!");
64     delete mem;
65     return AV_ERR_OK;
66 }