aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/streams/brotli/brotli.cpp
blob: 4e6ce64531e75042beab0be50bc048fe87b3358d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#include "brotli.h"

#include <contrib/libs/brotli/include/brotli/decode.h>
#include <contrib/libs/brotli/include/brotli/encode.h>

#include <util/generic/yexception.h>
#include <util/memory/addstorage.h>

namespace {
    struct TAllocator {
        static void* Allocate(void* /* opaque */, size_t size) {
            return ::operator new(size);
        }

        static void Deallocate(void* /* opaque */, void* ptr) noexcept {
            ::operator delete(ptr);
        }
    };

}

class TBrotliCompress::TImpl {
public:
    TImpl(IOutputStream* slave, int quality)
        : Slave_(slave)
        , EncoderState_(BrotliEncoderCreateInstance(&TAllocator::Allocate, &TAllocator::Deallocate, nullptr))
    {
        if (!EncoderState_) {
            ythrow yexception() << "Brotli encoder initialization failed";
        }

        auto res = BrotliEncoderSetParameter(
            EncoderState_,
            BROTLI_PARAM_QUALITY,
            quality);

        if (!res) {
            BrotliEncoderDestroyInstance(EncoderState_);
            ythrow yexception() << "Failed to set brotli encoder quality to " << quality;
        }
    }

    ~TImpl() {
        BrotliEncoderDestroyInstance(EncoderState_);
    }

    void Write(const void* buffer, size_t size) {
        DoWrite(buffer, size, BROTLI_OPERATION_PROCESS);
    }

    void Flush() {
        DoWrite(nullptr, 0, BROTLI_OPERATION_FLUSH);
    }

    void Finish() {
        Flush();
        DoWrite(nullptr, 0, BROTLI_OPERATION_FINISH);
        Y_ABORT_UNLESS(BrotliEncoderIsFinished(EncoderState_));
    }

private:
    IOutputStream* Slave_;
    BrotliEncoderState* EncoderState_;

    void DoWrite(const void* buffer, size_t size, BrotliEncoderOperation operation) {
        size_t availableOut = 0;
        ui8* outputBuffer = nullptr;

        const ui8* uBuffer = static_cast<const ui8*>(buffer);

        do {
            auto result = BrotliEncoderCompressStream(
                EncoderState_,
                operation,
                &size,
                &uBuffer,
                &availableOut,
                &outputBuffer,
                nullptr);

            if (result == BROTLI_FALSE) {
                ythrow yexception() << "Brotli encoder failed to process buffer";
            }

            size_t outputLength = 0;
            const ui8* output = BrotliEncoderTakeOutput(EncoderState_, &outputLength);
            if (outputLength > 0) {
                Slave_->Write(output, outputLength);
            }
        } while (size > 0 || BrotliEncoderHasMoreOutput(EncoderState_));
    }
};

TBrotliCompress::TBrotliCompress(IOutputStream* slave, int quality) {
    Impl_.Reset(new TImpl(slave, quality));
}

TBrotliCompress::~TBrotliCompress() {
    try {
        Finish();
    } catch (...) {
    }
}

void TBrotliCompress::DoWrite(const void* buffer, size_t size) {
    Impl_->Write(buffer, size);
}

void TBrotliCompress::DoFlush() {
    if (Impl_) {
        Impl_->Flush();
    }
}

void TBrotliCompress::DoFinish() {
    THolder<TImpl> impl(Impl_.Release());

    if (impl) {
        impl->Finish();
    }
}

////////////////////////////////////////////////////////////////////////////////

class TBrotliDecompress::TImpl: public TAdditionalStorage<TImpl> {
public:
    TImpl(IInputStream* slave)
        : Slave_(slave)
    {
        InitDecoder();
    }

    ~TImpl() {
        FreeDecoder();
    }

    size_t Read(void* buffer, size_t size) {
        Y_ASSERT(size > 0);

        ui8* outBuffer = static_cast<ui8*>(buffer);
        size_t availableOut = size;
        size_t decompressedSize = 0;

        BrotliDecoderResult result;
        do {
            if (InputAvailable_ == 0 && !InputExhausted_) {
                InputBuffer_ = TmpBuf();
                InputAvailable_ = Slave_->Read((void*)InputBuffer_, TmpBufLen());
                if (InputAvailable_ == 0) {
                    InputExhausted_ = true;
                }
            }

            if (SubstreamFinished_ && !InputExhausted_) {
                ResetState();
            }

            result = BrotliDecoderDecompressStream(
                DecoderState_,
                &InputAvailable_,
                &InputBuffer_,
                &availableOut,
                &outBuffer,
                nullptr);

            decompressedSize = size - availableOut;
            SubstreamFinished_ = (result == BROTLI_DECODER_RESULT_SUCCESS);

            if (result == BROTLI_DECODER_RESULT_ERROR) {
                BrotliDecoderErrorCode code = BrotliDecoderGetErrorCode(DecoderState_);
                ythrow yexception() << "Brotli decoder failed to decompress buffer: "
                                    << BrotliDecoderErrorString(code);
            } else if (result == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
                Y_ABORT_UNLESS(availableOut != size,
                         "Buffer passed to read in Brotli decoder is too small");
                break;
            }
        } while (decompressedSize == 0 && result == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT && !InputExhausted_);

        if (!SubstreamFinished_ && decompressedSize == 0) {
            ythrow yexception() << "Input stream is incomplete";
        }

        return decompressedSize;
    }

private:
    IInputStream* Slave_;
    BrotliDecoderState* DecoderState_;

    bool SubstreamFinished_ = false;
    bool InputExhausted_ = false;
    const ui8* InputBuffer_ = nullptr;
    size_t InputAvailable_ = 0;

    unsigned char* TmpBuf() noexcept {
        return static_cast<unsigned char*>(AdditionalData());
    }

    size_t TmpBufLen() const noexcept {
        return AdditionalDataLength();
    }

    void InitDecoder() {
        DecoderState_ = BrotliDecoderCreateInstance(&TAllocator::Allocate, &TAllocator::Deallocate, nullptr);
        if (!DecoderState_) {
            ythrow yexception() << "Brotli decoder initialization failed";
        }
    }

    void FreeDecoder() {
        BrotliDecoderDestroyInstance(DecoderState_);
    }

    void ResetState() {
        Y_ABORT_UNLESS(BrotliDecoderIsFinished(DecoderState_));
        FreeDecoder();
        InitDecoder();
    }
};

TBrotliDecompress::TBrotliDecompress(IInputStream* slave, size_t bufferSize)
    : Impl_(new (bufferSize) TImpl(slave))
{
}

TBrotliDecompress::~TBrotliDecompress() = default;

size_t TBrotliDecompress::DoRead(void* buffer, size_t size) {
    return Impl_->Read(buffer, size);
}