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 "av_virtual_memory.h"
17 #include "av_virtual_allocator.h"
18 #include "avbuffer_utils.h"
19 #include "buffer/avallocator.h"
20 #include "common/log.h"
21 #include "common/status.h"
22 #include "message_parcel.h"
23
24 namespace OHOS {
25 namespace Media {
CreateVirtualAllocator()26 std::shared_ptr<AVAllocator> AVAllocatorFactory::CreateVirtualAllocator()
27 {
28 auto allocator = std::shared_ptr<AVVirtualAllocator>(new AVVirtualAllocator());
29 FALSE_RETURN_V_MSG_E(allocator != nullptr, nullptr, "Create AVVirtualAllocator failed, no memory");
30 return allocator;
31 }
32
AVVirtualAllocator()33 AVVirtualAllocator::AVVirtualAllocator(){};
34
Alloc(int32_t capacity)35 void *AVVirtualAllocator::Alloc(int32_t capacity)
36 {
37 uint8_t *ptr = new uint8_t[capacity];
38 FALSE_RETURN_V_MSG_E(ptr != nullptr, nullptr, "Alloc memory failed, no memory");
39
40 return static_cast<void *>(ptr);
41 }
42
Free(void * ptr)43 bool AVVirtualAllocator::Free(void *ptr)
44 {
45 uint8_t *dataPtr = static_cast<uint8_t *>(ptr);
46 FALSE_RETURN_V_MSG_E(dataPtr != nullptr, false, "Invalid ptr, ptr = 0x%{public}06" PRIXPTR, FAKE_POINTER(dataPtr));
47 delete dataPtr;
48 return true;
49 }
50
GetMemoryType()51 MemoryType AVVirtualAllocator::GetMemoryType()
52 {
53 return MemoryType::VIRTUAL_MEMORY;
54 }
55
AVVirtualMemory()56 AVVirtualMemory::AVVirtualMemory() {}
57
~AVVirtualMemory()58 AVVirtualMemory::~AVVirtualMemory()
59 {
60 if (allocator_ == nullptr) {
61 return;
62 }
63 bool ret = allocator_->Free(static_cast<void *>(base_));
64 FALSE_RETURN_MSG(ret, "Free memory failed, instance: 0x%{public}06" PRIXPTR, FAKE_POINTER(this));
65 base_ = nullptr;
66 }
67
Init()68 Status AVVirtualMemory::Init()
69 {
70 int32_t allocSize = align_ ? (capacity_ + align_ - 1) : capacity_;
71 base_ = static_cast<uint8_t *>(allocator_->Alloc(allocSize));
72 FALSE_RETURN_V_MSG_E(base_ != nullptr, Status::ERROR_NO_MEMORY, "Alloc AVVirtualMemory failed");
73
74 uintptr_t addrBase = reinterpret_cast<uintptr_t>(base_);
75 offset_ = static_cast<size_t>(AlignUp(addrBase, static_cast<uintptr_t>(offset_)) - addrBase);
76 return Status::OK;
77 }
78
GetMemoryType()79 MemoryType AVVirtualMemory::GetMemoryType()
80 {
81 return MemoryType::VIRTUAL_MEMORY;
82 }
83 } // namespace Media
84 } // namespace OHOS