Removed the DevIL backend from love.image. Replaced it with PNG and JPEG encoders/decoders via LodePNG, zlib, and libjpeg-turbo.

PNG and JPEG are now the only two supported image formats, aside from compressed DDS (DXT, etc.)

--HG--
branch : minor
This commit is contained in:
Alex Szpakowski
2014-04-22 17:11:59 -03:00
parent 1b61091aae
commit eca8c17a69
18 changed files with 8572 additions and 282 deletions
-228
View File
@@ -1,228 +0,0 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "DevilHandler.h"
// LOVE
#include "common/Exception.h"
#include "common/math.h"
// DevIL
#include <IL/il.h>
namespace love
{
namespace image
{
namespace magpie
{
static inline void ilxClearErrors()
{
while (ilGetError() != IL_NO_ERROR);
}
DevilHandler::DevilHandler()
: mutex(nullptr)
{
// There should only ever be one DevilHandler object (owned by the Image
// module), so we can use the global initialization function here.
ilInit();
ilEnable(IL_ORIGIN_SET);
ilOriginFunc(IL_ORIGIN_UPPER_LEFT);
}
DevilHandler::~DevilHandler()
{
ilShutDown();
if (mutex)
delete mutex;
}
bool DevilHandler::canDecode(love::filesystem::FileData * /*data*/)
{
// DevIL can decode a lot of formats...
return true;
}
bool DevilHandler::canEncode(ImageData::Format format)
{
switch (format)
{
case ImageData::FORMAT_BMP:
case ImageData::FORMAT_TGA:
case ImageData::FORMAT_JPG:
case ImageData::FORMAT_PNG:
return true;
default:
return false;
}
return false;
}
DevilHandler::DecodedImage DevilHandler::decode(love::filesystem::FileData *data)
{
if (!mutex)
mutex = love::thread::newMutex();
love::thread::Lock lock(mutex);
ILuint image = ilGenImage();
ilBindImage(image);
DecodedImage img;
try
{
bool success = ilLoadL(IL_TYPE_UNKNOWN, (void *)data->getData(), (ILuint) data->getSize()) == IL_TRUE;
if (!success)
throw love::Exception("Could not decode image!");
img.width = ilGetInteger(IL_IMAGE_WIDTH);
img.height = ilGetInteger(IL_IMAGE_HEIGHT);
// Make sure the image is in RGBA format.
ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
// This should always be four.
int bpp = ilGetInteger(IL_IMAGE_BPP);
if (bpp != sizeof(pixel))
throw love::Exception("Could not convert image!");
img.size = (size_t) ilGetInteger(IL_IMAGE_SIZE_OF_DATA);
try
{
img.data = new ILubyte[img.size];
}
catch (std::bad_alloc &)
{
throw love::Exception("Out of memory.");
}
memcpy(img.data, ilGetData(), img.size);
}
catch (std::exception &e)
{
// catches love and std exceptions
ilDeleteImage(image);
throw love::Exception("%s", e.what());
}
ilDeleteImage(image);
return img;
}
DevilHandler::EncodedImage DevilHandler::encode(const DecodedImage &img, ImageData::Format format)
{
if (!mutex)
mutex = love::thread::newMutex();
love::thread::Lock lock(mutex);
ILuint tempimage = ilGenImage();
ilBindImage(tempimage);
ilxClearErrors();
EncodedImage encodedimage;
try
{
bool success = ilTexImage(img.width, img.height, 1, sizeof(pixel), IL_RGBA, IL_UNSIGNED_BYTE, img.data) == IL_TRUE;
ILenum err = ilGetError();
ilxClearErrors();
if (!success)
{
if (err != IL_NO_ERROR)
{
switch (err)
{
case IL_ILLEGAL_OPERATION:
throw love::Exception("Illegal operation");
case IL_INVALID_PARAM:
throw love::Exception("Invalid parameters");
case IL_OUT_OF_MEMORY:
throw love::Exception("Out of memory");
default:
throw love::Exception("Unknown error (%d)", (int) err);
}
}
throw love::Exception("Could not create image for the encoding!");
}
ilRegisterOrigin(IL_ORIGIN_UPPER_LEFT);
ILuint ilFormat;
switch (format)
{
case ImageData::FORMAT_BMP:
ilFormat = IL_BMP;
break;
case ImageData::FORMAT_TGA:
ilFormat = IL_TGA;
break;
case ImageData::FORMAT_JPG:
ilFormat = IL_JPG;
break;
case ImageData::FORMAT_PNG:
default: // PNG is the default format
ilFormat = IL_PNG;
break;
}
encodedimage.size = ilSaveL(ilFormat, NULL, 0);
if (!encodedimage.size)
throw love::Exception("Could not encode image!");
try
{
encodedimage.data = new ILubyte[encodedimage.size];
}
catch(std::bad_alloc &)
{
throw love::Exception("Out of memory");
}
ilSaveL(ilFormat, encodedimage.data, encodedimage.size);
}
catch (std::exception &e)
{
// Catches love and std exceptions.
ilDeleteImage(tempimage);
delete[] encodedimage.data;
encodedimage.data = 0;
throw love::Exception("%s", e.what());
}
ilDeleteImage(tempimage);
return encodedimage;
}
} // magpie
} // image
} // love
@@ -57,6 +57,11 @@ FormatHandler::EncodedImage FormatHandler::encode(const DecodedImage& /*img*/, I
throw love::Exception("Image encoding is not implemented for this format backend.");
}
void FormatHandler::free(unsigned char *mem)
{
delete[] mem;
}
} // magpie
} // image
} // love
+5
View File
@@ -93,6 +93,11 @@ public:
**/
virtual EncodedImage encode(const DecodedImage &img, ImageData::Format format);
/**
* Frees memory allocated by the format handler.
**/
virtual void free(unsigned char *mem);
}; // FormatHandler
} // magpie
+4 -2
View File
@@ -23,7 +23,8 @@
#include "ImageData.h"
#include "CompressedData.h"
#include "DevilHandler.h"
#include "JPEGHandler.h"
#include "PNGHandler.h"
namespace love
{
@@ -34,7 +35,8 @@ namespace magpie
Image::Image()
{
formatHandlers.push_back(new DevilHandler);
formatHandlers.push_back(new PNGHandler);
formatHandlers.push_back(new JPEGHandler);
}
Image::~Image()
+38 -7
View File
@@ -30,6 +30,7 @@ namespace magpie
ImageData::ImageData(std::list<FormatHandler *> formats, love::filesystem::FileData *data)
: formatHandlers(formats)
, decodeHandler(nullptr)
{
for (auto it = formatHandlers.begin(); it != formatHandlers.end(); ++it)
(*it)->retain();
@@ -39,6 +40,7 @@ ImageData::ImageData(std::list<FormatHandler *> formats, love::filesystem::FileD
ImageData::ImageData(std::list<FormatHandler *> formats, int width, int height)
: formatHandlers(formats)
, decodeHandler(nullptr)
{
for (auto it = formatHandlers.begin(); it != formatHandlers.end(); ++it)
(*it)->retain();
@@ -54,6 +56,7 @@ ImageData::ImageData(std::list<FormatHandler *> formats, int width, int height)
ImageData::ImageData(std::list<FormatHandler *> formats, int width, int height, void *data, bool own)
: formatHandlers(formats)
, decodeHandler(nullptr)
{
for (auto it = formatHandlers.begin(); it != formatHandlers.end(); ++it)
(*it)->retain();
@@ -69,7 +72,10 @@ ImageData::ImageData(std::list<FormatHandler *> formats, int width, int height,
ImageData::~ImageData()
{
delete[] data;
if (decodeHandler)
decodeHandler->free(data);
else
delete[] data;
for (auto it = formatHandlers.begin(); it != formatHandlers.end(); ++it)
(*it)->release();
@@ -88,23 +94,32 @@ void ImageData::create(int width, int height, void *data)
if (data)
memcpy(this->data, data, width*height*sizeof(pixel));
decodeHandler = nullptr;
}
void ImageData::decode(love::filesystem::FileData *data)
{
FormatHandler *handler = nullptr;
FormatHandler::DecodedImage decodedimage;
for (auto it = formatHandlers.begin(); it != formatHandlers.end(); ++it)
{
if ((*it)->canDecode(data))
{
decodedimage = (*it)->decode(data);
handler = *it;
break;
}
}
if (handler)
decodedimage = handler->decode(data);
if (decodedimage.data == nullptr)
throw love::Exception("Could not decode image: unrecognized format.");
{
const char *ext = data->getExtension().c_str();
throw love::Exception("Could not decode to ImageData: unrecognized format (%s)", ext);
}
// The decoder *must* output a 32 bits-per-pixel image.
if (decodedimage.size != decodedimage.width*decodedimage.height*sizeof(pixel))
@@ -113,16 +128,22 @@ void ImageData::decode(love::filesystem::FileData *data)
throw love::Exception("Could not convert image!");
}
if (this->data)
// Clean up any old data.
if (decodeHandler)
decodeHandler->free(this->data);
else
delete[] this->data;
this->width = decodedimage.width;
this->height = decodedimage.height;
this->data = decodedimage.data;
decodeHandler = handler;
}
void ImageData::encode(love::filesystem::File *f, ImageData::Format format)
{
FormatHandler *handler = nullptr;
FormatHandler::EncodedImage encodedimage;
{
@@ -139,11 +160,14 @@ void ImageData::encode(love::filesystem::File *f, ImageData::Format format)
{
if ((*it)->canEncode(format))
{
encodedimage = (*it)->encode(rawimage, format);
handler = *it;
break;
}
}
if (handler)
handler->encode(rawimage, format);
if (encodedimage.data == nullptr)
throw love::Exception("Image format has no suitable encoder.");
}
@@ -156,11 +180,18 @@ void ImageData::encode(love::filesystem::File *f, ImageData::Format format)
}
catch (love::Exception &)
{
delete[] encodedimage.data;
if (handler)
handler->free(encodedimage.data);
else
delete[] encodedimage.data;
throw;
}
delete[] encodedimage.data;
if (handler)
handler->free(encodedimage.data);
else
delete[] encodedimage.data;
}
} // magpie
+4
View File
@@ -59,6 +59,10 @@ private:
// Image format handlers we can use for decoding and encoding.
std::list<FormatHandler *> formatHandlers;
// The format handler that was used to decode the ImageData. We need to know
// this so we can properly delete memory allocated by the decoder.
FormatHandler *decodeHandler;
}; // ImageData
} // magpie
+157
View File
@@ -0,0 +1,157 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
// LOVE
#include "JPEGHandler.h"
#include "common/Exception.h"
#include "common/math.h"
namespace love
{
namespace image
{
namespace magpie
{
JPEGHandler::JPEGHandler()
{
mutex = love::thread::newMutex();
decompressor = tjInitDecompress();
compressor = tjInitCompress();
}
JPEGHandler::~JPEGHandler()
{
delete mutex;
if (decompressor)
tjDestroy(decompressor);
if (compressor)
tjDestroy(compressor);
}
bool JPEGHandler::canDecode(love::filesystem::FileData *data)
{
if (!decompressor)
return false;
int w, h, subsamp;
int status = tjDecompressHeader2(decompressor,
(unsigned char *) data->getData(),
data->getSize(),
&w, &h, &subsamp);
return (status == 0);
}
bool JPEGHandler::canEncode(ImageData::Format format)
{
if (!compressor)
return false;
return format == ImageData::FORMAT_JPG;
}
FormatHandler::DecodedImage JPEGHandler::decode(love::filesystem::FileData *data)
{
if (!decompressor)
throw love::Exception("Could not decode jpeg image: %s", tjGetErrorStr());
DecodedImage img;
unsigned char *jpegdata = (unsigned char *) data->getData();
love::thread::Lock lock(mutex);
int unused;
int status = tjDecompressHeader2(decompressor,
jpegdata, data->getSize(),
&img.width, &img.height,
&unused);
if (status < 0)
throw love::Exception("Could not decode jpeg image: %s", tjGetErrorStr());
img.size = img.width * img.height * sizeof(pixel);
try
{
img.data = new unsigned char[img.size];
}
catch (std::bad_alloc &)
{
throw love::Exception("Out of memory.");
}
status = tjDecompress2(decompressor,
jpegdata, data->getSize(),
img.data, 0, 0, 0, TJPF_RGBA, 0);
if (status < 0)
{
delete[] img.data;
throw love::Exception("Could not decode jpeg image: %s", tjGetErrorStr());
}
return img;
}
FormatHandler::EncodedImage JPEGHandler::encode(const DecodedImage &img, ImageData::Format format)
{
if (!canEncode(format))
throw love::Exception("JPEG encoder cannot encode specified format.");
EncodedImage encodedimage;
love::thread::Lock lock(mutex);
unsigned long tjsize = tjBufSize(img.width, img.height, TJSAMP_444);
try
{
// We want to allocate the memory ourselves instead of letting
// TurboJPEG do it, so we can safely use delete[] in ImageData.cpp.
encodedimage.data = new unsigned char[tjsize];
}
catch (std::bad_alloc &)
{
throw love::Exception("Out of memory.");
}
int status = tjCompress2(compressor,
img.data,
img.width, 0, img.height,
TJPF_RGBA,
&encodedimage.data, &encodedimage.size,
TJSAMP_444, COMPRESS_QUALITY, TJFLAG_NOREALLOC);
if (status < 0)
{
delete[] encodedimage.data;
throw love::Exception("Could not encode jpeg image: %s", tjGetErrorStr());
}
return encodedimage;
}
} // magpie
} // image
} // love
+76
View File
@@ -0,0 +1,76 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#ifndef LOVE_IMAGE_MAGPIE_JPEG_HANDLER_H
#define LOVE_IMAGE_MAGPIE_JPEG_HANDLER_H
// LOVE
#include "filesystem/FileData.h"
#include "FormatHandler.h"
#include "thread/threads.h"
// libjpeg-turbo
#ifdef LOVE_MACOSX_USE_FRAMEWORKS
#include <jpeg-turbo/turbojpeg.h>
#else
#include <turbojpeg.h>
#endif
namespace love
{
namespace image
{
namespace magpie
{
/**
* Interface between ImageData and TurboJPEG.
**/
class JPEGHandler : public FormatHandler
{
public:
// Implements FormatHandler.
JPEGHandler();
virtual ~JPEGHandler();
virtual bool canDecode(love::filesystem::FileData *data);
virtual bool canEncode(ImageData::Format format);
virtual DecodedImage decode(love::filesystem::FileData *data);
virtual EncodedImage encode(const DecodedImage &img, ImageData::Format format);
private:
Mutex *mutex;
tjhandle decompressor;
tjhandle compressor;
static const int COMPRESS_QUALITY = 90;
}; // JPEGHandler
} // magpie
} // image
} // love
#endif // LOVE_IMAGE_MAGPIE_JPEG_HANDLER_H
+218
View File
@@ -0,0 +1,218 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "PNGHandler.h"
// LOVE
#include "common/Exception.h"
#include "common/math.h"
// LodePNG
#include "lodepng/lodepng.h"
// zlib
#include <zlib.h>
// C++
#include <algorithm>
namespace love
{
namespace image
{
namespace magpie
{
// Custom PNG decompression function for LodePNG, using zlib.
static unsigned zlibDecompress(unsigned char **out, size_t *outsize, const unsigned char *in,
size_t insize, const LodePNGDecompressSettings* /*settings*/)
{
int status = Z_OK;
size_t outdataSize = insize;
size_t sizeMultiplier = 0;
unsigned char *outdata = nullptr;
while (true)
{
// Enough size to hold the decompressed data, hopefully.
outdataSize = insize << (++sizeMultiplier);
try
{
outdata = new unsigned char[outdataSize];
}
catch (std::bad_alloc &)
{
return 83; // "Memory allocation failed" error code for LodePNG.
}
// Use zlib to decompress the PNG data.
status = uncompress(outdata, &outdataSize, in, insize);
// If the out buffer was big enough, break out of the loop.
if (status != Z_BUF_ERROR)
break;
// Otherwise delete the out buffer and try again with a larger size...
delete[] outdata;
outdata = nullptr;
}
if (status != Z_OK)
{
delete[] outdata;
return 10000; // "Unknown error code" for LodePNG.
}
if (out != nullptr)
*out = outdata;
if (outsize != nullptr)
*outsize = outdataSize;
return 0; // Success.
}
// Custom PNG compression function for LodePNG, using zlib.
static unsigned zlibCompress(unsigned char **out, size_t *outsize, const unsigned char *in,
size_t insize, const LodePNGCompressSettings* /*settings*/)
{
// Get the maximum compressed size of the data.
uLongf outdataSize = compressBound(insize);
unsigned char *outdata = nullptr;
try
{
outdata = new unsigned char[outdataSize];
}
catch (std::bad_alloc &)
{
return 83; // "Memory allocation failed" error code for LodePNG.
}
// Use zlib to compress the PNG data.
int status = compress(outdata, &outdataSize, in, insize);
if (status != Z_OK)
{
delete[] outdata;
return 10000; // "Unknown error code" for LodePNG.
}
if (out != nullptr)
*out = outdata;
if (outsize != nullptr)
*outsize = (size_t) outdataSize;
return 0; // Success.
}
bool PNGHandler::canDecode(love::filesystem::FileData *data)
{
std::string ext = data->getExtension();
std::transform(ext.begin(), ext.end(), ext.begin(), tolower);
return ext.compare("png") == 0;
}
bool PNGHandler::canEncode(ImageData::Format format)
{
return format == ImageData::FORMAT_PNG;
}
PNGHandler::DecodedImage PNGHandler::decode(love::filesystem::FileData *fdata)
{
unsigned int width = 0, height = 0;
unsigned char *indata = (unsigned char *) fdata->getData();
size_t insize = fdata->getSize();
DecodedImage img;
LodePNGState state;
lodepng_state_init(&state);
state.info_raw.colortype = LCT_RGBA;
state.info_raw.bitdepth = 8;
state.decoder.zlibsettings.custom_zlib = zlibDecompress;
unsigned status = lodepng_decode(&img.data, &width, &height,
&state, indata, insize);
lodepng_state_cleanup(&state);
if (status != 0)
{
const char *err = lodepng_error_text(status);
throw love::Exception("Could not decode PNG image (%s)", err);
}
img.width = (int) width;
img.height = (int) height;
img.size = width * height * 4;
return img;
}
PNGHandler::EncodedImage PNGHandler::encode(const DecodedImage &img, ImageData::Format format)
{
if (format != ImageData::FORMAT_PNG)
throw love::Exception("PNG encoder cannot encode to non-PNG format.");
EncodedImage encimg;
LodePNGState state;
lodepng_state_init(&state);
state.info_raw.colortype = LCT_RGBA;
state.info_raw.bitdepth = 8;
// TODO: support plain RGB (24-bit) encoding in the future?
state.info_png.color.colortype = LCT_RGBA;
state.info_png.color.bitdepth = 8;
state.encoder.zlibsettings.custom_zlib = zlibCompress;
unsigned status = lodepng_encode(&encimg.data, &encimg.size,
img.data, img.width, img.height, &state);
lodepng_state_cleanup(&state);
if (status != 0)
{
const char *err = lodepng_error_text(status);
throw love::Exception("Could not encode PNG image (%s)", err);
}
return encimg;
}
void PNGHandler::free(unsigned char *mem)
{
// LodePNG uses malloc, realloc, and free.
if (mem)
::free(mem);
}
} // magpie
} // image
} // love
@@ -18,13 +18,12 @@
* 3. This notice may not be removed or altered from any source distribution.
**/
#ifndef LOVE_IMAGE_MAGPIE_DEVIL_HANDLER_H
#define LOVE_IMAGE_MAGPIE_DEVIL_HANDLER_H
#ifndef LOVE_IMAGE_MAGPIE_PNG_HANDLER_H
#define LOVE_IMAGE_MAGPIE_PNG_HANDLER_H
// LOVE
#include "filesystem/FileData.h"
#include "FormatHandler.h"
#include "thread/threads.h"
namespace love
{
@@ -34,31 +33,26 @@ namespace magpie
{
/**
* Interface between ImageData and DevIL.
* Interface between ImageData and LodePNG.
**/
class DevilHandler : public FormatHandler
class PNGHandler : public FormatHandler
{
public:
// Implements FormatHandler.
DevilHandler();
virtual ~DevilHandler();
virtual bool canDecode(love::filesystem::FileData *data);
virtual bool canEncode(ImageData::Format format);
virtual DecodedImage decode(love::filesystem::FileData *data);
virtual EncodedImage encode(const DecodedImage &img, ImageData::Format format);
private:
virtual void free(unsigned char *mem);
Mutex *mutex;
}; // DevilHandler
}; // PNGHandler
} // magpie
} // image
} // love
#endif // LOVE_IMAGE_MAGPIE_DEVIL_HANDLER_H
#endif // LOVE_IMAGE_MAGPIE_PNG_HANDLER_H