summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibGfx/QOILoader.h
blob: b5df791830a8990597be9f8a073aa8f0d92e56c4 (plain)
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
/*
 * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/Forward.h>
#include <LibGfx/Forward.h>
#include <LibGfx/ImageDecoder.h>

namespace Gfx {

// Decoder for the "Quite OK Image" format (v1.0).
// https://qoiformat.org/qoi-specification.pdf

struct [[gnu::packed]] QOIHeader {
    char magic[4];
    u32 width;
    u32 height;
    u8 channels;
    u8 colorspace;
};

struct QOILoadingContext {
    enum class State {
        NotDecoded = 0,
        HeaderDecoded,
        ImageDecoded,
        Error,
    };
    State state { State::NotDecoded };
    u8 const* data { nullptr };
    size_t data_size { 0 };
    QOIHeader header {};
    RefPtr<Bitmap> bitmap;
    Optional<Error> error;
};

class QOIImageDecoderPlugin final : public ImageDecoderPlugin {
public:
    static ErrorOr<bool> sniff(ReadonlyBytes);
    static ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> create(ReadonlyBytes);

    virtual ~QOIImageDecoderPlugin() override = default;

    virtual IntSize size() override;
    virtual void set_volatile() override;
    [[nodiscard]] virtual bool set_nonvolatile(bool& was_purged) override;
    virtual bool initialize() override;
    virtual bool is_animated() override { return false; }
    virtual size_t loop_count() override { return 0; }
    virtual size_t frame_count() override { return 1; }
    virtual ErrorOr<ImageFrameDescriptor> frame(size_t index) override;

private:
    ErrorOr<void> decode_header_and_update_context(InputMemoryStream&);
    ErrorOr<void> decode_image_and_update_context(InputMemoryStream&);

    QOIImageDecoderPlugin(u8 const*, size_t);

    OwnPtr<QOILoadingContext> m_context;
};

}