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 "avsharedmemory_ipc.h"
17#include <unistd.h>
18#include "avcodec_errors.h"
19#include "avcodec_log.h"
20#include "buffer/avsharedmemorybase.h"
21
22namespace {
23constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, LOG_DOMAIN_FRAMEWORK, "AVSharedMemoryIPC"};
24}
25
26namespace OHOS {
27namespace MediaAVCodec {
28using namespace Media;
29int32_t WriteAVSharedMemoryToParcel(const std::shared_ptr<AVSharedMemory> &memory, MessageParcel &parcel)
30{
31    std::shared_ptr<Media::AVSharedMemoryBase> baseMem = std::static_pointer_cast<Media::AVSharedMemoryBase>(memory);
32    if (baseMem == nullptr) {
33        AVCODEC_LOGE("invalid pointer");
34        return AVCS_ERR_INVALID_VAL;
35    }
36
37    int32_t fd = baseMem->GetFd();
38    int32_t size = baseMem->GetSize();
39
40    (void)parcel.WriteFileDescriptor(fd);
41    parcel.WriteInt32(size);
42    parcel.WriteUint32(baseMem->GetFlags());
43    parcel.WriteString(baseMem->GetName());
44
45    return AVCS_ERR_OK;
46}
47
48std::shared_ptr<AVSharedMemory> ReadAVSharedMemoryFromParcel(MessageParcel &parcel)
49{
50    int32_t fd = parcel.ReadFileDescriptor();
51    int32_t size = parcel.ReadInt32();
52    uint32_t flags = parcel.ReadUint32();
53    std::string name = parcel.ReadString();
54
55    std::shared_ptr<AVSharedMemory> memory = Media::AVSharedMemoryBase::CreateFromRemote(fd, size, flags, name);
56    if (memory == nullptr || memory->GetBase() == nullptr) {
57        AVCODEC_LOGE("create remote Media::AVSharedMemoryBase failed");
58        memory = nullptr;
59    }
60
61    if (fd >= 0) {
62        (void)::close(fd);
63    }
64    return memory;
65}
66} // namespace MediaAVCodec
67} // namespace OHOS
68