Coverage Report

Created: 2026-12-01 06:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ogre/PlugIns/STBICodec/src/OgreSTBICodec.cpp
Line
Count
Source
1
/*
2
-----------------------------------------------------------------------------
3
This source file is part of OGRE
4
(Object-oriented Graphics Rendering Engine)
5
For the latest info, see http://www.ogre3d.org/
6
7
Copyright (c) 2000-2014 Torus Knot Software Ltd
8
9
Permission is hereby granted, free of charge, to any person obtaining a copy
10
of this software and associated documentation files (the "Software"), to deal
11
in the Software without restriction, including without limitation the rights
12
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
copies of the Software, and to permit persons to whom the Software is
14
furnished to do so, subject to the following conditions:
15
16
The above copyright notice and this permission notice shall be included in
17
all copies or substantial portions of the Software.
18
19
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25
THE SOFTWARE.
26
-----------------------------------------------------------------------------
27
*/
28
29
#include "OgreSTBICodec.h"
30
#include "OgreLogManager.h"
31
#include "OgreDataStream.h"
32
#include "OgreImage.h"
33
34
#include "OgrePlatformInformation.h"
35
#include "OgreString.h"
36
#include "OgreRoot.h"
37
38
#include <vector>
39
40
#if __OGRE_HAVE_NEON
41
#define STBI_NEON
42
#endif
43
44
#define STBI_NO_STDIO
45
#define STB_IMAGE_IMPLEMENTATION
46
#define STB_IMAGE_STATIC
47
// guard against wrong image headers, limits to 16K x 16K
48
13.8k
#define STBI_MAX_DIMENSIONS 16384
49
#include "stbi/stb_image.h"
50
51
#ifdef HAVE_ZLIB
52
#include <zlib.h>
53
static Ogre::uchar* custom_zlib_compress(Ogre::uchar* data, int data_len, int* out_len, int /*quality*/)
54
{
55
    unsigned long destLen = compressBound(data_len);
56
    Ogre::uchar* dest = (Ogre::uchar*)malloc(destLen);
57
    int ret = compress(dest, &destLen, data, data_len); // use default quality
58
    if (ret != Z_OK)
59
    {
60
        free(dest);
61
        OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, "compress failed");
62
    }
63
64
    *out_len = destLen;
65
    return dest;
66
}
67
#define STBIW_ZLIB_COMPRESS custom_zlib_compress
68
#endif
69
70
#define STB_IMAGE_WRITE_IMPLEMENTATION
71
#define STBI_WRITE_NO_STDIO
72
#include "stbi/stb_image_write.h"
73
74
namespace Ogre {
75
76
    namespace
77
    {
78
        void appendToVector(void* context, void* data, int size)
79
0
        {
80
0
            auto* out = static_cast<std::vector<uchar>*>(context);
81
0
            auto* bytes = static_cast<uchar*>(data);
82
0
            out->insert(out->end(), bytes, bytes + size);
83
0
        }
84
    }
85
86
    STBIImageCodec::RegisteredCodecList STBIImageCodec::msCodecList;
87
    //---------------------------------------------------------------------
88
    void STBIImageCodec::startup(void)
89
6.62k
    {
90
6.62k
        stbi_convert_iphone_png_to_rgb(1);
91
6.62k
        stbi_set_unpremultiply_on_load(1);
92
93
6.62k
        LogManager::getSingleton().logMessage("stb_image - v2.30 - public domain image loader");
94
        
95
        // Register codecs
96
6.62k
        String exts = "jpeg,jpg,png,bmp,psd,tga,gif,pic,ppm,pgm,hdr";
97
6.62k
        StringVector extsVector = StringUtil::split(exts, ",");
98
6.62k
        for (auto & v : extsVector)
99
72.8k
        {
100
72.8k
            ImageCodec* codec = OGRE_NEW STBIImageCodec(v);
101
72.8k
            msCodecList.push_back(codec);
102
72.8k
            Codec::registerCodec(codec);
103
72.8k
        }
104
105
6.62k
        LogManager::getSingleton().logMessage("Supported formats: " + exts);
106
6.62k
    }
107
    //---------------------------------------------------------------------
108
    void STBIImageCodec::shutdown(void)
109
6.62k
    {
110
6.62k
        for (auto & i : msCodecList)
111
72.8k
        {
112
72.8k
            Codec::unregisterCodec(i);
113
72.8k
            OGRE_DELETE i;
114
72.8k
        }
115
6.62k
        msCodecList.clear();
116
6.62k
    }
117
    //---------------------------------------------------------------------
118
    STBIImageCodec::STBIImageCodec(const String &type):
119
72.8k
        mType(type)
120
72.8k
    { 
121
72.8k
    }
122
    //---------------------------------------------------------------------
123
    DataStreamPtr STBIImageCodec::encode(const Any& input) const
124
1.37k
    {
125
1.37k
        if(mType != "png" && mType != "jpeg" && mType != "jpg") {
126
0
            OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
127
0
                        "currently only encoding to PNG and JPEG supported",
128
0
                        "STBIImageCodec::encode" ) ;
129
0
        }
130
131
1.37k
        Image* image = any_cast<Image*>(input);
132
133
        // Convert image data to ABGR format for STBI (unless it's already compatible)
134
1.37k
        Image converted;
135
1.37k
        const Image* source = image;
136
1.37k
        if (image->getFormat() != Ogre::PF_A8B8G8R8 && image->getFormat() != PF_B8G8R8 &&
137
498
            image->getFormat() != PF_BYTE_LA && image->getFormat() != PF_L8 &&
138
152
            image->getFormat() != PF_R8)
139
152
        {
140
152
            converted.create(PF_A8B8G8R8, image->getWidth(), image->getHeight());
141
152
            PixelUtil::bulkPixelConversion(image->getPixelBox(), converted.getPixelBox());
142
152
            source = &converted;
143
152
        }
144
145
1.37k
        const int channels = PixelUtil::getComponentCount(source->getFormat());
146
147
1.37k
        if (mType == "png")
148
1.37k
        {
149
1.37k
            int len;
150
1.37k
            uchar* data = stbi_write_png_to_mem(source->getData(), source->getRowSpan(),
151
1.37k
                                                source->getWidth(), source->getHeight(), channels,
152
1.37k
                                                &len);
153
154
1.37k
            if (!data) {
155
0
                OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
156
0
                    "Error encoding image: " + String(stbi_failure_reason()),
157
0
                    "STBIImageCodec::encode");
158
0
            }
159
160
1.37k
            return DataStreamPtr(new MemoryDataStream(data, len, true));
161
1.37k
        }
162
163
        // Save to JPEG. JPEG has no alpha channel, so it is discarded by stb_image_write.
164
0
        static const int quality = 90;
165
0
        std::vector<uchar> data;
166
0
        const bool success = stbi_write_jpg_to_func(appendToVector, &data, source->getWidth(),
167
0
                                                    source->getHeight(), channels, source->getData(),
168
0
                                                    quality);
169
170
0
        if (!success)
171
0
        {
172
0
            OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Error encoding image as JPEG",
173
0
                        "STBIImageCodec::encode");
174
0
        }
175
176
0
        auto stream = std::make_shared<MemoryDataStream>(data.size());
177
0
        memcpy(stream->getPtr(), data.data(), data.size());
178
0
        return stream;
179
0
    }
180
    //---------------------------------------------------------------------
181
    void STBIImageCodec::encodeToFile(const Any& input, const String& outFileName) const
182
1.37k
    {
183
1.37k
#if OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN
184
1.37k
        MemoryDataStreamPtr data = static_pointer_cast<MemoryDataStream>(encode(input));
185
1.37k
        DataStreamPtr f = Root::createFileStream(outFileName, "", true);
186
187
1.37k
        f->write(data->getPtr(), data->size());
188
1.37k
        f->close();
189
1.37k
#endif
190
1.37k
    }
191
    //---------------------------------------------------------------------
192
    void STBIImageCodec::decode(const DataStreamPtr& input, const Any& output) const
193
6.62k
    {
194
6.62k
        auto image = any_cast<Image*>(output);
195
6.62k
        String contents = input->getAsString();
196
197
6.62k
        int width, height, components;
198
6.62k
        const int size = static_cast<int>(contents.size());
199
6.62k
        const bool is16Bit = stbi_is_16_bit_from_memory((const uchar*)contents.data(), size) != 0;
200
201
        // stb_image always decodes to 8 bits unless explicitly asked for 16 bits
202
6.62k
        void* pixelData = is16Bit
203
6.62k
            ? static_cast<void*>(stbi_load_16_from_memory((const uchar*)contents.data(), size,
204
378
                                                          &width, &height, &components, 0))
205
6.62k
            : static_cast<void*>(stbi_load_from_memory((const uchar*)contents.data(), size,
206
6.24k
                                                       &width, &height, &components, 0));
207
208
6.62k
        if (!pixelData)
209
3.95k
        {
210
3.95k
            const char* reason = stbi_failure_reason();
211
3.95k
            OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
212
3.95k
                        "Error decoding image: " + String(reason ? reason : "no reason"));
213
3.95k
        }
214
215
2.66k
        if (width <= 0 || height <= 0)
216
116
        {
217
116
            stbi_image_free(pixelData);
218
116
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
219
116
                        StringUtil::format("Image has invalid dimensions: %dx%d", width, height));
220
116
        }
221
222
2.55k
        PixelFormat format = PF_UNKNOWN;
223
2.55k
        switch( components )
224
2.55k
        {
225
637
            case 1:
226
637
                format = is16Bit ? PF_L16 : PF_BYTE_L;
227
637
                break;
228
50
            case 2:
229
                // no dedicated 16-bit luminance-alpha format, use the 2-channel short format
230
50
                format = is16Bit ? PF_SHORT_GR : PF_BYTE_LA;
231
50
                break;
232
1.15k
            case 3:
233
1.15k
                format = is16Bit ? PF_SHORT_RGB : PF_BYTE_RGB;
234
1.15k
                break;
235
715
            case 4:
236
715
                format = is16Bit ? PF_SHORT_RGBA : PF_BYTE_RGBA;
237
715
                break;
238
0
            default:
239
0
                stbi_image_free(pixelData);
240
0
                OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Only 1..4 channels supported");
241
0
                break;
242
2.55k
        }
243
        
244
2.55k
        image->loadDynamicImage(static_cast<uchar*>(pixelData), width, height, 1, format, true);
245
2.55k
    }
246
    //---------------------------------------------------------------------    
247
    String STBIImageCodec::getType() const
248
145k
    {
249
145k
        return mType;
250
145k
    }
251
252
#ifndef OGRE_STATIC_LIB
253
    extern "C" void _OgreSTBICodecExport dllStartPlugin();
254
    extern "C" void _OgreSTBICodecExport dllStopPlugin();
255
256
    extern "C" void _OgreSTBICodecExport dllStartPlugin()
257
    {
258
        STBIImageCodec::startup();
259
    }
260
    extern "C" void _OgreSTBICodecExport dllStopPlugin()
261
    {
262
        STBIImageCodec::shutdown();
263
    }
264
#endif
265
}