1 /*
2 * Copyright (c) 2021-2021 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 "bit_reader.h"
17
18 namespace OHOS {
19 namespace Media {
20 namespace Plugin {
21 namespace Ffmpeg {
BitReader()22 BitReader::BitReader() : begin_(nullptr), cur_(nullptr), end_(nullptr)
23 {
24 }
25
BitReader(const uint8_t * buffer,size_t bufferSize)26 BitReader::BitReader(const uint8_t* buffer, size_t bufferSize) : begin_(buffer), cur_(buffer), end_(buffer + bufferSize)
27 {
28 }
29
BitReader(const uint8_t * begin,const uint8_t * end)30 BitReader::BitReader(const uint8_t* begin, const uint8_t* end) : begin_(begin), cur_(begin), end_(end)
31 {
32 }
33
~BitReader()34 BitReader::~BitReader()
35 {
36 begin_ = nullptr;
37 cur_ = nullptr;
38 end_ = nullptr;
39 availBits_ = 8; // 8
40 }
41
GetAvailableBits() const42 size_t BitReader::GetAvailableBits() const
43 {
44 return (cur_ != end_) ? static_cast<std::size_t>(((end_ - cur_ - 1) * 8) + availBits_) : 0; // 8
45 }
46
GetCurrentPtr() const47 const uint8_t* BitReader::GetCurrentPtr() const
48 {
49 return cur_;
50 }
51
SkipBits(size_t bits)52 void BitReader::SkipBits(size_t bits)
53 {
54 if (bits <= availBits_) {
55 availBits_ -= static_cast<uint8_t>(bits);
56 return;
57 }
58 auto skipBits = bits;
59 cur_ += (1 + (skipBits -= availBits_) / 8); // 8
60 if (cur_ >= end_) {
61 cur_ = end_;
62 availBits_ = 0;
63 } else {
64 availBits_ = 8 - skipBits % 8; // 8
65 }
66 }
67
SeekTo(size_t bitPos)68 bool BitReader::SeekTo(size_t bitPos)
69 {
70 size_t bytePos = bitPos / 8; // 8
71 if (begin_ + bytePos >= end_) {
72 return false;
73 }
74 cur_ = begin_ + bytePos;
75 uint8_t skipBits = bitPos % 8; // 8
76 availBits_ = 8 - skipBits; // 8
77 SkipBits(skipBits);
78 return true;
79 }
80
Reset(const uint8_t * begin,const uint8_t * end)81 void BitReader::Reset(const uint8_t* begin, const uint8_t* end)
82 {
83 begin_ = begin;
84 cur_ = begin;
85 end_ = end;
86 availBits_ = 8; // 8
87 }
88 } // namespace Ffmpeg
89 } // namespace Plugin
90 } // namespace Media
91 } // namespace OHOS
92