Debian Codegraph @

src/brotlicffi/_api.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 import math
3 import enum
4 import threading
5
6 from ._brotlicffi import ffi, lib
7
8
9 class error(Exception):
10 """
11 Raised whenever an error is encountered with compressing or decompressing
12 data using brotlicffi.
13
14 .. versionadded:: 0.5.1
15 """
16 pass
17
18
19 #: An alias of :class:`error <brotli.error>` that
20 #: exists for compatibility with the original CFFI brotli module.
21 #:
22 #: .. versionadded: 0.8.0
23 Error = error
24
25
26 class BrotliEncoderMode(enum.IntEnum):
27 """
28 Compression modes for the Brotli encoder.
29
30 .. versionadded:: 0.5.0
31 """
32 #: Default compression mode. The compressor does not know anything in
33 #: advance about the properties of the input.
34 GENERIC = lib.BROTLI_MODE_GENERIC
35
36 #: Compression mode for UTF-8 format text input.
37 TEXT = lib.BROTLI_MODE_TEXT
38
39 #: Compression mode used in WOFF 2.0
40 FONT = lib.BROTLI_MODE_FONT
41
42
43 # Define some names for compatibility with the C module.
44
45 #: The default compression mode for brotli.
46 DEFAULT_MODE = BrotliEncoderMode(lib.BROTLI_DEFAULT_MODE)
47
48
49 #: A compression mode where the compressor does not know anything in advance
50 #: about the properties of the input.
51 #:
52 #: .. note:: This name is defined for compatibility with the Brotli C
53 #: extension. If you're not interested in that compatibility, it is
54 #: recommended that you use :class:`BrotliEncoderMode
55 #: <brotlicffi.BrotliEncoderMode>` instead.
56 #:
57 #: .. versionadded:: 0.5.0
58 MODE_GENERIC = BrotliEncoderMode.GENERIC
59
60
61 #: A compression mode for UTF-8 format text input.
62 #:
63 #: .. note:: This name is defined for compatibility with the Brotli C
64 #: extension. If you're not interested in that compatibility, it is
65 #: recommended that you use :class:`BrotliEncoderMode
66 #: <brotlicffi.BrotliEncoderMode>` instead.
67 #:
68 #: .. versionadded:: 0.5.0
69 MODE_TEXT = BrotliEncoderMode.TEXT
70
71
72 #: The compression mode used in WOFF 2.0.
73 #:
74 #: .. note:: This name is defined for compatibility with the Brotli C
75 #: extension. If you're not interested in that compatibility, it is
76 #: recommended that you use :class:`BrotliEncoderMode
77 #: <brotlicffi.BrotliEncoderMode>` instead.
78 #:
79 #: .. versionadded:: 0.5.0
80 MODE_FONT = BrotliEncoderMode.FONT
81
82
83 def decompress(data):
84 """
85 Decompress a complete Brotli-compressed string.
86
87 :param data: A bytestring containing Brotli-compressed data.
88 """
89 d = Decompressor()
90 data = d.decompress(data)
91 d.finish()
92 return data
93
94
95 def compress(data,
96 mode=DEFAULT_MODE,
97 quality=lib.BROTLI_DEFAULT_QUALITY,
98 lgwin=lib.BROTLI_DEFAULT_WINDOW,
99 lgblock=0):
100 """
101 Compress a string using Brotli.
102
103 .. versionchanged:: 0.5.0
104 Added ``mode``, ``quality``, `lgwin``, ``lgblock``, and ``dictionary``
105 parameters.
106
107 :param data: A bytestring containing the data to compress.
108 :type data: ``bytes``
109
110 :param mode: The encoder mode.
111 :type mode: :class:`BrotliEncoderMode` or ``int``
112
113 :param quality: Controls the compression-speed vs compression-density
114 tradeoffs. The higher the quality, the slower the compression. The
115 range of this value is 0 to 11.
116 :type quality: ``int``
117
118 :param lgwin: The base-2 logarithm of the sliding window size. The range of
119 this value is 10 to 24.
120 :type lgwin: ``int``
121
122 :param lgblock: The base-2 logarithm of the maximum input block size. The
123 range of this value is 16 to 24. If set to 0, the value will be set
124 based on ``quality``.
125 :type lgblock: ``int``
126
127 :returns: The compressed bytestring.
128 :rtype: ``bytes``
129 """
130 # This method uses private variables on the Compressor object, and
131 # generally does a whole lot of stuff that's not supported by the public
132 # API. The goal here is to minimise the number of allocations and copies
133 # we have to do. Users should prefer this method over the Compressor if
134 # they know they have single-shot data.
135 compressor = Compressor(
136 mode=mode,
137 quality=quality,
138 lgwin=lgwin,
139 lgblock=lgblock
140 )
141 compressed_data = compressor._compress(data, lib.BROTLI_OPERATION_FINISH)
142 assert lib.BrotliEncoderIsFinished(compressor._encoder) == lib.BROTLI_TRUE
143 assert (
144 lib.BrotliEncoderHasMoreOutput(compressor._encoder) == lib.BROTLI_FALSE
145 )
146 return compressed_data
147
148
149 def _validate_mode(val):
150 """
151 Validate that the mode is valid.
152 """
153 try:
154 val = BrotliEncoderMode(val)
155 except ValueError:
156 raise error("%s is not a valid encoder mode" % val)
157
158
159 def _validate_quality(val):
160 """
161 Validate that the quality setting is valid.
162 """
163 if not (0 <= val <= 11):
164 raise error(
165 "%d is not a valid quality, must be between 0 and 11" % val
166 )
167
168
169 def _validate_lgwin(val):
170 """
171 Validate that the lgwin setting is valid.
172 """
173 if not (10 <= val <= 24):
174 raise error("%d is not a valid lgwin, must be between 10 and 24" % val)
175
176
177 def _validate_lgblock(val):
178 """
179 Validate that the lgblock setting is valid.
180 """
181 if (val != 0) and not (16 <= val <= 24):
182 raise error(
183 "%d is not a valid lgblock, must be either 0 or between 16 and 24"
184 % val
185 )
186
187
188 def _set_parameter(encoder, parameter, parameter_name, val):
189 """
190 This helper function sets a specific Brotli encoder parameter, checking
191 the return code and raising :class:`Error <brotlicffi.Error>` if it is
192 invalid.
193 """
194 rc = lib.BrotliEncoderSetParameter(encoder, parameter, val)
195
196 if parameter == lib.BROTLI_PARAM_MODE:
197 _validate_mode(val)
198 elif parameter == lib.BROTLI_PARAM_QUALITY:
199 _validate_quality(val)
200 elif parameter == lib.BROTLI_PARAM_LGWIN:
201 _validate_lgwin(val)
202 elif parameter == lib.BROTLI_PARAM_LGBLOCK:
203 _validate_lgblock(val)
204 else: # pragma: no cover
205 raise RuntimeError("Unexpected parameter!")
206
207 # This block is defensive: I see no way to hit it, but as long as the
208 # function returns a value we can live in hope that the brotli folks will
209 # enforce their own constraints.
210 if rc != lib.BROTLI_TRUE: # pragma: no cover
211 raise error(
212 "Error setting parameter %s: %d" % (parameter_name, val)
213 )
214
215
216 class Compressor(object):
217 """
218 An object that allows for streaming compression of data using the Brotli
219 compression algorithm.
220
221 .. versionadded:: 0.5.0
222
223 :param mode: The encoder mode.
224 :type mode: :class:`BrotliEncoderMode` or ``int``
225
226 :param quality: Controls the compression-speed vs compression-density
227 tradeoffs. The higher the quality, the slower the compression. The
228 range of this value is 0 to 11.
229 :type quality: ``int``
230
231 :param lgwin: The base-2 logarithm of the sliding window size. The range of
232 this value is 10 to 24.
233 :type lgwin: ``int``
234
235 :param lgblock: The base-2 logarithm of the maximum input block size. The
236 range of this value is 16 to 24. If set to 0, the value will be set
237 based on ``quality``.
238 :type lgblock: ``int``
239
240 :param dictionary: A pre-set dictionary for LZ77. Please use this with
241 caution: if a dictionary is used for compression, the same dictionary
242 **must** be used for decompression!
243 :type dictionary: ``bytes``
244 """
245 _dictionary = None
246 _dictionary_size = None
247
248 def __init__(self,
249 mode=DEFAULT_MODE,
250 quality=lib.BROTLI_DEFAULT_QUALITY,
251 lgwin=lib.BROTLI_DEFAULT_WINDOW,
252 lgblock=0):
253 self.lock = threading.RLock()
254 enc = lib.BrotliEncoderCreateInstance(
255 ffi.NULL, ffi.NULL, ffi.NULL
256 )
257 if not enc: # pragma: no cover
258 raise RuntimeError("Unable to allocate Brotli encoder!")
259
260 enc = ffi.gc(enc, lib.BrotliEncoderDestroyInstance)
261
262 # Configure the encoder appropriately.
263 _set_parameter(enc, lib.BROTLI_PARAM_MODE, "mode", mode)
264 _set_parameter(enc, lib.BROTLI_PARAM_QUALITY, "quality", quality)
265 _set_parameter(enc, lib.BROTLI_PARAM_LGWIN, "lgwin", lgwin)
266 _set_parameter(enc, lib.BROTLI_PARAM_LGBLOCK, "lgblock", lgblock)
267
268 self._encoder = enc
269
270 def _compress(self, data, operation):
271 """
272 This private method compresses some data in a given mode. This is used
273 because almost all of the code uses the exact same setup. It wouldn't
274 have to, but it doesn't hurt at all.
275 """
276 if not self.lock.acquire(blocking=False):
277 raise error(
278 "Concurrently sharing Compressor objects is not allowed")
279 try:
280 # The 'algorithm' for working out how big to make this buffer is
281 # from the Brotli source code, brotlimodule.cc.
282 original_output_size = int(
283 math.ceil(len(data) + (len(data) >> 2) + 10240)
284 )
285 available_out = ffi.new("size_t *")
286 available_out[0] = original_output_size
287 output_buffer = ffi.new("uint8_t []", available_out[0])
288 ptr_to_output_buffer = ffi.new("uint8_t **", output_buffer)
289 input_size = ffi.new("size_t *", len(data))
290 input_buffer = ffi.new("uint8_t []", data)
291 ptr_to_input_buffer = ffi.new("uint8_t **", input_buffer)
292
293 rc = lib.BrotliEncoderCompressStream(
294 self._encoder,
295 operation,
296 input_size,
297 ptr_to_input_buffer,
298 available_out,
299 ptr_to_output_buffer,
300 ffi.NULL
301 )
302 finally:
303 self.lock.release()
304 if rc != lib.BROTLI_TRUE: # pragma: no cover
305 raise error("Error encountered compressing data.")
306
307 assert not input_size[0]
308
309 size_of_output = original_output_size - available_out[0]
310 return ffi.buffer(output_buffer, size_of_output)[:]
311
312 def compress(self, data):
313 """
314 Incrementally compress more data.
315
316 :param data: A bytestring containing data to compress.
317 :returns: A bytestring containing some compressed data. May return the
318 empty bytestring if not enough data has been inserted into the
319 compressor to create the output yet.
320 """
321 return self._compress(data, lib.BROTLI_OPERATION_PROCESS)
322
323 process = compress
324
325 def flush(self):
326 """
327 Flush the compressor. This will emit the remaining output data, but
328 will not destroy the compressor. It can be used, for example, to ensure
329 that given chunks of content will decompress immediately.
330 """
331 if not self.lock.acquire(blocking=False):
332 raise error(
333 "Concurrently sharing Compressor objects is not allowed")
334 try:
335 chunks = [self._compress(b'', lib.BROTLI_OPERATION_FLUSH)]
336
337 while ((lib.BrotliEncoderHasMoreOutput(self._encoder) ==
338 lib.BROTLI_TRUE)):
339 chunks.append(self._compress(b'', lib.BROTLI_OPERATION_FLUSH))
340 finally:
341 self.lock.release()
342 return b''.join(chunks)
343
344 def finish(self):
345 """
346 Finish the compressor. This will emit the remaining output data and
347 transition the compressor to a completed state. The compressor cannot
348 be used again after this point, and must be replaced.
349 """
350 if not self.lock.acquire(blocking=False):
351 raise error(
352 "Concurrently sharing Compressor objects is not allowed")
353 try:
354 chunks = []
355 while ((lib.BrotliEncoderIsFinished(self._encoder) ==
356 lib.BROTLI_FALSE)):
357 chunks.append(self._compress(b'', lib.BROTLI_OPERATION_FINISH))
358 finally:
359 self.lock.release()
360 return b''.join(chunks)
361
362
363 class Decompressor(object):
364 """
365 An object that allows for streaming decompression of Brotli-compressed
366 data.
367
368 .. versionchanged:: 0.5.0
369 Added ``dictionary`` parameter.
370
371 .. versionchanged:: 1.2.0
372 Added ``can_accept_more_data()`` method and optional
373 ``output_buffer_limit`` parameter to ``process()``/``decompress()``.
374
375 :param dictionary: A pre-set dictionary for LZ77. Please use this with
376 caution: if a dictionary is used for compression, the same dictionary
377 **must** be used for decompression!
378 :type dictionary: ``bytes``
379 """
380 _dictionary = None
381 _dictionary_size = None
382 _unconsumed_data = None
383
384 def __init__(self, dictionary=b''):
385 self.lock = threading.Lock()
386 dec = lib.BrotliDecoderCreateInstance(ffi.NULL, ffi.NULL, ffi.NULL)
387 self._decoder = ffi.gc(dec, lib.BrotliDecoderDestroyInstance)
388 self._unconsumed_data = b''
389
390 if dictionary:
391 self._dictionary = ffi.new("uint8_t []", dictionary)
392 self._dictionary_size = len(dictionary)
393 lib.BrotliDecoderSetCustomDictionary(
394 self._decoder,
395 self._dictionary_size,
396 self._dictionary
397 )
398
399 @staticmethod
400 def _calculate_buffer_size(
401 input_data_len, output_buffer_limit, chunks_len, chunks_num
402 ):
403 if output_buffer_limit is not None:
404 return output_buffer_limit - chunks_len
405 # When `decompress(b'')` is called without `output_buffer_limit`.
406 elif input_data_len == 0:
407 # libbrotli would use 32 KB as a starting buffer size and double it
408 # each time, capped at 16 MB.
409 # https://github.com/google/brotli/blob/028fb5a23661f123017c060daa546b55cf4bde29/python/_brotli.c#L291-L292
410 return 1 << min(chunks_num + 15, 24)
411 else:
412 # Allocate a buffer that's hopefully overlarge, but if it's not we
413 # don't mind: we'll spin around again.
414 return 5 * input_data_len
415
416 def decompress(self, data, output_buffer_limit=None):
417 """
418 Decompress part of a complete Brotli-compressed string.
419
420 .. versionchanged:: 1.2.0
421 Added ``output_buffer_limit`` parameter.
422
423 :param data: A bytestring containing Brotli-compressed data.
424 :param output_buffer_limit: Optional maximum size for the output
425 buffer. If set, the output buffer will not grow once its size
426 equals or exceeds this value. If the limit is reached, further
427 calls to process (potentially with empty input) will continue to
428 yield more data. Following process() calls must only be called
429 with empty input until can_accept_more_data() returns True.
430 :type output_buffer_limit: ``int`` or ``None``
431 :returns: A bytestring containing the decompressed data.
432 """
433 if not self.lock.acquire(blocking=False):
434 raise error(
435 "Concurrently sharing Decompressor instances is not allowed")
436 try:
437 chunks = self._decompress(data, output_buffer_limit)
438 finally:
439 self.lock.release()
440 return b''.join(chunks)
441
442 def _decompress(self, data, output_buffer_limit):
443 if self._unconsumed_data and data:
444 raise error(
445 "brotli: decoder process called with data when "
446 "'can_accept_more_data()' is False"
447 )
448
449 # We should avoid operations on the `self._unconsumed_data` if no data
450 # is to be processed.
451 if output_buffer_limit is not None and output_buffer_limit <= 0:
452 return b''
453
454 # Use unconsumed data if available, use new data otherwise.
455 if self._unconsumed_data:
456 input_data = self._unconsumed_data
457 self._unconsumed_data = b''
458 else:
459 input_data = data
460
461 chunks = []
462 chunks_len = 0
463
464 available_in = ffi.new("size_t *", len(input_data))
465 in_buffer = ffi.new("uint8_t[]", input_data)
466 next_in = ffi.new("uint8_t **", in_buffer)
467
468 while True:
469 buffer_size = self._calculate_buffer_size(
470 input_data_len=len(input_data),
471 output_buffer_limit=output_buffer_limit,
472 chunks_len=chunks_len,
473 chunks_num=len(chunks),
474 )
475
476 available_out = ffi.new("size_t *", buffer_size)
477 out_buffer = ffi.new("uint8_t[]", buffer_size)
478 next_out = ffi.new("uint8_t **", out_buffer)
479
480 rc = lib.BrotliDecoderDecompressStream(self._decoder,
481 available_in,
482 next_in,
483 available_out,
484 next_out,
485 ffi.NULL)
486
487 # First, check for errors.
488 if rc == lib.BROTLI_DECODER_RESULT_ERROR:
489 error_code = lib.BrotliDecoderGetErrorCode(self._decoder)
490 error_message = lib.BrotliDecoderErrorString(error_code)
491 raise error(
492 b"Decompression error: %s" % ffi.string(error_message)
493 )
494
495 # Next, copy the result out.
496 chunk = ffi.buffer(out_buffer, buffer_size - available_out[0])[:]
497 chunks.append(chunk)
498 chunks_len += len(chunk)
499
500 # Save any unconsumed input for the next call.
501 if available_in[0] > 0:
502 remaining_input = ffi.buffer(next_in[0], available_in[0])[:]
503 self._unconsumed_data = remaining_input
504
505 # Check if we've reached the output limit.
506 if (
507 output_buffer_limit is not None
508 and chunks_len >= output_buffer_limit
509 ):
510 break
511
512 if rc == lib.BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:
513 assert available_in[0] == 0
514 break
515 elif rc == lib.BROTLI_DECODER_RESULT_SUCCESS:
516 break
517 else:
518 # It's cool if we need more output, we just loop again.
519 assert rc == lib.BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT
520 return chunks
521
522 process = decompress
523
524 def flush(self):
525 """
526 Complete the decompression, return whatever data is remaining to be
527 decompressed.
528
529 .. deprecated:: 0.4.0
530
531 This method is no longer required, as decompress() will now
532 decompress eagerly.
533
534 :returns: A bytestring containing the remaining decompressed data.
535 """
536 return b''
537
538 def finish(self):
539 """
540 Finish the decompressor. As the decompressor decompresses eagerly, this
541 will never actually emit any data. However, it will potentially throw
542 errors if a truncated or damaged data stream has been used.
543
544 Note that, once this method is called, the decompressor is no longer
545 safe for further use and must be thrown away.
546 """
547 assert (
548 lib.BrotliDecoderHasMoreOutput(self._decoder) == lib.BROTLI_FALSE
549 )
550 if not self.is_finished():
551 raise error("Decompression error: incomplete compressed stream.")
552
553 return b''
554
555 def is_finished(self):
556 """
557 Returns ``True`` if the decompression stream
558 is complete, ``False`` otherwise
559 """
560 if not self.lock.acquire(blocking=False):
561 raise error(
562 "Concurrently sharing Decompressor instances is not allowed")
563 try:
564 ret = (
565 lib.BrotliDecoderIsFinished(self._decoder) == lib.BROTLI_TRUE)
566 finally:
567 self.lock.release()
568 return ret
569
570 def can_accept_more_data(self):
571 """
572 Checks if the decompressor can accept more compressed data.
573
574 If the ``output_buffer_limit`` parameter was used with
575 ``decompress()`` or ``process()``, this method should be checked to
576 determine if the decompressor is ready to accept new input. When the
577 output buffer limit is reached, the decompressor may still have
578 unconsumed input data or internal buffered output, and calling
579 ``decompress(b'')`` repeatedly will continue producing output until
580 this method returns ``True``.
581
582 .. versionadded:: 1.2.0
583
584 :returns: ``True`` if the decompressor is ready to accept more
585 compressed data via ``decompress()`` or ``process()``, ``False``
586 if the decompressor needs to output some data via
587 ``decompress(b'')``/``process(b'')`` before being provided any
588 more compressed data.
589 :rtype: ``bool``
590 """
591 if not self.lock.acquire(blocking=False):
592 raise error(
593 "Concurrently sharing Decompressor instances is not allowed")
594 try:
595 ret = True
596 if len(self._unconsumed_data) > 0:
597 ret = False
598 if ((lib.BrotliDecoderHasMoreOutput(self._decoder) ==
599 lib.BROTLI_TRUE)):
600 ret = False
601 finally:
602 self.lock.release()
603 return ret