CompressionStream.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. /*
  2. * Copyright (c) 2024, Tim Flynn <trflynn89@ladybird.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibCompress/Deflate.h>
  7. #include <LibCompress/Gzip.h>
  8. #include <LibCompress/Zlib.h>
  9. #include <LibJS/Runtime/ArrayBuffer.h>
  10. #include <LibJS/Runtime/Realm.h>
  11. #include <LibJS/Runtime/TypedArray.h>
  12. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  13. #include <LibWeb/Bindings/Intrinsics.h>
  14. #include <LibWeb/Compression/CompressionStream.h>
  15. #include <LibWeb/Streams/AbstractOperations.h>
  16. #include <LibWeb/Streams/TransformStream.h>
  17. #include <LibWeb/WebIDL/AbstractOperations.h>
  18. namespace Web::Compression {
  19. GC_DEFINE_ALLOCATOR(CompressionStream);
  20. // https://compression.spec.whatwg.org/#dom-compressionstream-compressionstream
  21. WebIDL::ExceptionOr<GC::Ref<CompressionStream>> CompressionStream::construct_impl(JS::Realm& realm, Bindings::CompressionFormat format)
  22. {
  23. // 1. If format is unsupported in CompressionStream, then throw a TypeError.
  24. // 2. Set this's format to format.
  25. auto input_stream = make<AllocatingMemoryStream>();
  26. auto compressor = [&, input_stream = MaybeOwned<Stream> { *input_stream }]() mutable -> ErrorOr<Compressor> {
  27. switch (format) {
  28. case Bindings::CompressionFormat::Deflate:
  29. return TRY(Compress::ZlibCompressor::construct(move(input_stream)));
  30. case Bindings::CompressionFormat::DeflateRaw:
  31. return TRY(Compress::DeflateCompressor::construct(make<LittleEndianInputBitStream>(move(input_stream))));
  32. case Bindings::CompressionFormat::Gzip:
  33. return TRY(Compress::GzipCompressor::create(move(input_stream)));
  34. }
  35. VERIFY_NOT_REACHED();
  36. }();
  37. if (compressor.is_error())
  38. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, MUST(String::formatted("Unable to create compressor: {}", compressor.error())) };
  39. // 5. Set this's transform to a new TransformStream.
  40. // NOTE: We do this first so that we may store it as nonnull in the GenericTransformStream.
  41. auto stream = realm.create<CompressionStream>(realm, realm.create<Streams::TransformStream>(realm), compressor.release_value(), move(input_stream));
  42. // 3. Let transformAlgorithm be an algorithm which takes a chunk argument and runs the compress and enqueue a chunk
  43. // algorithm with this and chunk.
  44. auto transform_algorithm = GC::create_function(realm.heap(), [stream](JS::Value chunk) -> GC::Ref<WebIDL::Promise> {
  45. auto& realm = stream->realm();
  46. auto& vm = realm.vm();
  47. if (auto result = stream->compress_and_enqueue_chunk(chunk); result.is_error()) {
  48. auto throw_completion = Bindings::exception_to_throw_completion(vm, result.exception());
  49. return WebIDL::create_rejected_promise(realm, *throw_completion.release_value());
  50. }
  51. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  52. });
  53. // 4. Let flushAlgorithm be an algorithm which takes no argument and runs the compress flush and enqueue algorithm with this.
  54. auto flush_algorithm = GC::create_function(realm.heap(), [stream]() -> GC::Ref<WebIDL::Promise> {
  55. auto& realm = stream->realm();
  56. auto& vm = realm.vm();
  57. if (auto result = stream->compress_flush_and_enqueue(); result.is_error()) {
  58. auto throw_completion = Bindings::exception_to_throw_completion(vm, result.exception());
  59. return WebIDL::create_rejected_promise(realm, *throw_completion.release_value());
  60. }
  61. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  62. });
  63. // 6. Set up this's transform with transformAlgorithm set to transformAlgorithm and flushAlgorithm set to flushAlgorithm.
  64. stream->m_transform->set_up(transform_algorithm, flush_algorithm);
  65. return stream;
  66. }
  67. CompressionStream::CompressionStream(JS::Realm& realm, GC::Ref<Streams::TransformStream> transform, Compressor compressor, NonnullOwnPtr<AllocatingMemoryStream> input_stream)
  68. : Bindings::PlatformObject(realm)
  69. , Streams::GenericTransformStreamMixin(transform)
  70. , m_compressor(move(compressor))
  71. , m_output_stream(move(input_stream))
  72. {
  73. }
  74. CompressionStream::~CompressionStream() = default;
  75. void CompressionStream::initialize(JS::Realm& realm)
  76. {
  77. Base::initialize(realm);
  78. WEB_SET_PROTOTYPE_FOR_INTERFACE(CompressionStream);
  79. }
  80. void CompressionStream::visit_edges(JS::Cell::Visitor& visitor)
  81. {
  82. Base::visit_edges(visitor);
  83. Streams::GenericTransformStreamMixin::visit_edges(visitor);
  84. }
  85. // https://compression.spec.whatwg.org/#compress-and-enqueue-a-chunk
  86. WebIDL::ExceptionOr<void> CompressionStream::compress_and_enqueue_chunk(JS::Value chunk)
  87. {
  88. auto& realm = this->realm();
  89. // 1. If chunk is not a BufferSource type, then throw a TypeError.
  90. if (!WebIDL::is_buffer_source_type(chunk))
  91. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Chunk is not a BufferSource type"sv };
  92. // 2. Let buffer be the result of compressing chunk with cs's format and context.
  93. auto buffer = [&]() -> ErrorOr<ByteBuffer> {
  94. if (auto buffer = WebIDL::underlying_buffer_source(chunk.as_object()))
  95. return compress(buffer->buffer(), Finish::No);
  96. return ByteBuffer {};
  97. }();
  98. if (buffer.is_error())
  99. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, MUST(String::formatted("Unable to compress chunk: {}", buffer.error())) };
  100. // 3. If buffer is empty, return.
  101. if (buffer.value().is_empty())
  102. return {};
  103. // 4. Split buffer into one or more non-empty pieces and convert them into Uint8Arrays.
  104. auto array_buffer = JS::ArrayBuffer::create(realm, buffer.release_value());
  105. auto array = JS::Uint8Array::create(realm, array_buffer->byte_length(), *array_buffer);
  106. // 5. For each Uint8Array array, enqueue array in cs's transform.
  107. TRY(Streams::transform_stream_default_controller_enqueue(*m_transform->controller(), array));
  108. return {};
  109. }
  110. // https://compression.spec.whatwg.org/#compress-flush-and-enqueue
  111. WebIDL::ExceptionOr<void> CompressionStream::compress_flush_and_enqueue()
  112. {
  113. auto& realm = this->realm();
  114. // 1. Let buffer be the result of compressing an empty input with cs's format and context, with the finish flag.
  115. auto buffer = compress({}, Finish::Yes);
  116. if (buffer.is_error())
  117. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, MUST(String::formatted("Unable to compress flush: {}", buffer.error())) };
  118. // 2. If buffer is empty, return.
  119. if (buffer.value().is_empty())
  120. return {};
  121. // 3. Split buffer into one or more non-empty pieces and convert them into Uint8Arrays.
  122. auto array_buffer = JS::ArrayBuffer::create(realm, buffer.release_value());
  123. auto array = JS::Uint8Array::create(realm, array_buffer->byte_length(), *array_buffer);
  124. // 4. For each Uint8Array array, enqueue array in cs's transform.
  125. TRY(Streams::transform_stream_default_controller_enqueue(*m_transform->controller(), array));
  126. return {};
  127. }
  128. ErrorOr<ByteBuffer> CompressionStream::compress(ReadonlyBytes bytes, Finish finish)
  129. {
  130. TRY(m_compressor.visit([&](auto const& compressor) {
  131. return compressor->write_until_depleted(bytes);
  132. }));
  133. if (finish == Finish::Yes) {
  134. TRY(m_compressor.visit(
  135. [&](NonnullOwnPtr<Compress::ZlibCompressor> const& compressor) {
  136. return compressor->finish();
  137. },
  138. [&](NonnullOwnPtr<Compress::DeflateCompressor> const& compressor) {
  139. return compressor->final_flush();
  140. },
  141. [&](NonnullOwnPtr<Compress::GzipCompressor> const& compressor) {
  142. return compressor->finish();
  143. }));
  144. }
  145. auto buffer = TRY(ByteBuffer::create_uninitialized(m_output_stream->used_buffer_size()));
  146. TRY(m_output_stream->read_until_filled(buffer.bytes()));
  147. return buffer;
  148. }
  149. }