ClientConnection.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <ImageDecoder/ClientConnection.h>
  8. #include <ImageDecoder/ImageDecoderClientEndpoint.h>
  9. #include <LibGfx/Bitmap.h>
  10. #include <LibGfx/ImageDecoder.h>
  11. namespace ImageDecoder {
  12. static HashMap<int, RefPtr<ClientConnection>> s_connections;
  13. ClientConnection::ClientConnection(NonnullRefPtr<Core::LocalSocket> socket, int client_id)
  14. : IPC::ClientConnection<ImageDecoderClientEndpoint, ImageDecoderServerEndpoint>(*this, move(socket), client_id)
  15. {
  16. s_connections.set(client_id, *this);
  17. }
  18. ClientConnection::~ClientConnection()
  19. {
  20. }
  21. void ClientConnection::die()
  22. {
  23. s_connections.remove(client_id());
  24. exit(0);
  25. }
  26. Messages::ImageDecoderServer::DecodeImageResponse ClientConnection::decode_image(Core::AnonymousBuffer const& encoded_buffer)
  27. {
  28. if (!encoded_buffer.is_valid()) {
  29. dbgln_if(IMAGE_DECODER_DEBUG, "Encoded data is invalid");
  30. return nullptr;
  31. }
  32. auto decoder = Gfx::ImageDecoder::try_create(ReadonlyBytes { encoded_buffer.data<u8>(), encoded_buffer.size() });
  33. if (!decoder) {
  34. dbgln_if(IMAGE_DECODER_DEBUG, "Could not find suitable image decoder plugin for data");
  35. return { false, 0, Vector<Gfx::ShareableBitmap> {}, Vector<u32> {} };
  36. }
  37. if (!decoder->frame_count()) {
  38. dbgln_if(IMAGE_DECODER_DEBUG, "Could not decode image from encoded data");
  39. return { false, 0, Vector<Gfx::ShareableBitmap> {}, Vector<u32> {} };
  40. }
  41. Vector<Gfx::ShareableBitmap> bitmaps;
  42. Vector<u32> durations;
  43. for (size_t i = 0; i < decoder->frame_count(); ++i) {
  44. auto frame_or_error = decoder->frame(i);
  45. if (frame_or_error.is_error()) {
  46. bitmaps.append(Gfx::ShareableBitmap {});
  47. durations.append(0);
  48. } else {
  49. auto frame = frame_or_error.release_value();
  50. bitmaps.append(frame.image->to_shareable_bitmap());
  51. durations.append(frame.duration);
  52. }
  53. }
  54. return { decoder->is_animated(), static_cast<u32>(decoder->loop_count()), bitmaps, durations };
  55. }
  56. }