1 /*
2  * Copyright (C) 2024 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 #ifndef BUFFER_CONVERTER_H
17 #define BUFFER_CONVERTER_H
18 #include <functional>
19 #include <shared_mutex>
20 #include "avcodec_info.h"
21 #include "buffer/avbuffer.h"
22 #include "buffer/avsharedmemorybase.h"
23 #include "meta/format.h"
24 
25 namespace OHOS {
26 namespace MediaAVCodec {
27 using AVBuffer = OHOS::Media::AVBuffer;
28 class CodecClient;
29 
30 class BufferConverter {
31 public:
32     explicit BufferConverter(bool isEncoder);
33     ~BufferConverter() = default;
34     static std::shared_ptr<BufferConverter> Create(AVCodecType type);
35     int32_t ReadFromBuffer(std::shared_ptr<AVBuffer> &buffer, std::shared_ptr<AVSharedMemory> &memory);
36     int32_t WriteToBuffer(std::shared_ptr<AVBuffer> &buffer, std::shared_ptr<AVSharedMemory> &memory);
37 
38     void NeedToResetFormatOnce();
39     void GetFormat(Format &format);
40     void SetFormat(const Format &format);
41     void SetInputBufferFormat(std::shared_ptr<AVBuffer> &buffer);
42     void SetOutputBufferFormat(std::shared_ptr<AVBuffer> &buffer);
43     typedef struct AVCodecRect {
44         int32_t wStride = 0;
45         int32_t hStride = 0;
46     } AVCodecRect;
47 
48 private:
49     void SetPixFormat(const VideoPixelFormat pixelFormat);
50     void SetWidth(const int32_t width);
51     void SetHeight(const int32_t height);
52     void SetWidthStride(const int32_t wStride);
53     void SetHeightStride(const int32_t hStride);
54 
55     bool SetBufferFormat(std::shared_ptr<AVBuffer> &buffer);
56     bool SetRectValue(const int32_t width, const int32_t height, const int32_t wStride,
57                                    const int32_t hStride);
58     int32_t GetSliceHeightFromSurfaceBuffer(sptr<SurfaceBuffer> &surfaceBuffer) const;
59 
60     static int32_t CalculateUserStride(const int32_t widthHeight);
61     std::function<int32_t(uint8_t *, uint8_t *, AVCodecRect *, int32_t)> func_;
62     AVCodecRect rect_;
63     AVCodecRect hwRect_;
64     AVCodecRect usrRect_;
65     bool isEncoder_;
66     bool isSharedMemory_;
67     bool needResetFormat_;
68     std::shared_mutex mutex_;
69 };
70 } // namespace MediaAVCodec
71 } // namespace OHOS
72 #endif // BUFFER_CONVERTER_H
73