232 lines
9.6 KiB
C++
232 lines
9.6 KiB
C++
#include "files_image_decode.h"
|
|
#include <windows.h>
|
|
#include <wincodec.h>
|
|
#include <webp/decode.h>
|
|
#include <webp/demux.h>
|
|
#include <algorithm>
|
|
#include <cstring>
|
|
#include <fstream>
|
|
#include <memory>
|
|
#include <stdexcept>
|
|
|
|
namespace ks::files
|
|
{
|
|
namespace
|
|
{
|
|
namespace fs=std::filesystem;
|
|
constexpr char invalidImage[]="Could not decode the image. The file may be damaged.";
|
|
constexpr char largeImage[]="This image is too large to preview.";
|
|
|
|
enum class ImageFormat { unknown, png, jpeg, gif, webp, bmp };
|
|
|
|
ImageFormat imageFormat(const fs::path &path)
|
|
{
|
|
const auto extension=path.extension();
|
|
const auto matches=[&](const wchar_t *suffix)
|
|
{
|
|
return CompareStringOrdinal(extension.c_str(),-1,suffix,-1,TRUE)==CSTR_EQUAL;
|
|
};
|
|
if(matches(L".png")) return ImageFormat::png;
|
|
if(matches(L".jpg") || matches(L".jpeg") || matches(L".jpe")) return ImageFormat::jpeg;
|
|
if(matches(L".gif")) return ImageFormat::gif;
|
|
if(matches(L".webp")) return ImageFormat::webp;
|
|
if(matches(L".bmp")) return ImageFormat::bmp;
|
|
return ImageFormat::unknown;
|
|
}
|
|
|
|
void checkImage(HRESULT result)
|
|
{
|
|
if(FAILED(result)) throw std::runtime_error(invalidImage);
|
|
}
|
|
|
|
void checkImageDimensions(unsigned width,unsigned height)
|
|
{
|
|
if(!width || !height) throw std::runtime_error(invalidImage);
|
|
if(width>16384 || height>16384 || uint64_t(width)*height>32ULL*1024*1024)
|
|
throw std::runtime_error(largeImage);
|
|
}
|
|
|
|
void checkImageStop(std::stop_token stop)
|
|
{
|
|
if(stop.stop_requested()) throw std::system_error(ERROR_CANCELLED,std::system_category());
|
|
}
|
|
|
|
template<class T>
|
|
struct ImagingObject
|
|
{
|
|
T *value{};
|
|
~ImagingObject() {if(value) value->Release();}
|
|
T *operator->() const {return value;}
|
|
};
|
|
|
|
struct Apartment
|
|
{
|
|
const HRESULT initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
|
|
~Apartment() {if(SUCCEEDED(initialized)) CoUninitialize();}
|
|
};
|
|
|
|
ImageRaster decodeNativeImage(const fs::path &file,ImageFormat format,std::stop_token stop)
|
|
{
|
|
const Apartment apartment;
|
|
if(apartment.initialized!=RPC_E_CHANGED_MODE) checkImage(apartment.initialized);
|
|
ImagingObject<IWICImagingFactory> factory;
|
|
checkImage(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory.value)));
|
|
ImagingObject<IWICStream> stream;
|
|
checkImage(factory->CreateStream(&stream.value));
|
|
checkImage(stream->InitializeFromFilename(file.c_str(),GENERIC_READ));
|
|
const auto &container=format==ImageFormat::png?GUID_ContainerFormatPng:
|
|
format==ImageFormat::jpeg?GUID_ContainerFormatJpeg:format==ImageFormat::gif?GUID_ContainerFormatGif:
|
|
GUID_ContainerFormatBmp;
|
|
ImagingObject<IWICBitmapDecoder> decoder;
|
|
checkImage(factory->CreateDecoder(container,nullptr,&decoder.value));
|
|
checkImage(decoder->Initialize(stream.value,WICDecodeMetadataCacheOnDemand));
|
|
ImagingObject<IWICBitmapFrameDecode> frame;
|
|
checkImage(decoder->GetFrame(0,&frame.value));
|
|
ImageRaster raster;
|
|
checkImage(frame->GetSize(&raster.width,&raster.height));
|
|
checkImageDimensions(raster.width,raster.height);
|
|
checkImageStop(stop);
|
|
ImagingObject<IWICFormatConverter> formatConverter;
|
|
checkImage(factory->CreateFormatConverter(&formatConverter.value));
|
|
checkImage(formatConverter->Initialize(frame.value,GUID_WICPixelFormat32bppPBGRA,WICBitmapDitherTypeNone,
|
|
nullptr,0,WICBitmapPaletteTypeCustom));
|
|
raster.pixels.resize(size_t(raster.width)*raster.height);
|
|
checkImage(formatConverter->CopyPixels(nullptr,raster.width*sizeof(uint32_t),
|
|
static_cast<UINT>(raster.pixels.size()*sizeof(uint32_t)),reinterpret_cast<BYTE *>(raster.pixels.data())));
|
|
return raster;
|
|
}
|
|
|
|
ImageRaster decodeWebp(const fs::path &file,size_t size,std::stop_token stop)
|
|
{
|
|
std::vector<uint8_t> bytes(size);
|
|
std::ifstream stream(file,std::ios::binary);
|
|
if(!stream.read(reinterpret_cast<char *>(bytes.data()),size)) throw std::runtime_error(invalidImage);
|
|
WebPBitstreamFeatures info{};
|
|
if(WebPGetFeatures(bytes.data(),bytes.size(),&info)!=VP8_STATUS_OK) throw std::runtime_error(invalidImage);
|
|
ImageRaster raster{static_cast<unsigned>(info.width),static_cast<unsigned>(info.height)};
|
|
checkImageDimensions(raster.width,raster.height);
|
|
checkImageStop(stop);
|
|
raster.pixels.resize(size_t(raster.width)*raster.height);
|
|
auto *output=reinterpret_cast<uint8_t *>(raster.pixels.data());
|
|
const auto outputSize=raster.pixels.size()*sizeof(uint32_t);
|
|
if(info.has_animation)
|
|
{
|
|
WebPAnimDecoderOptions options{};
|
|
if(!WebPAnimDecoderOptionsInit(&options)) throw std::runtime_error(invalidImage);
|
|
options.color_mode=MODE_bgrA;
|
|
const WebPData data{bytes.data(),bytes.size()};
|
|
const std::unique_ptr<WebPAnimDecoder,decltype(&WebPAnimDecoderDelete)> decoder(
|
|
WebPAnimDecoderNew(&data,&options),WebPAnimDecoderDelete);
|
|
uint8_t *frame=nullptr;
|
|
int timestamp{};
|
|
if(!decoder || !WebPAnimDecoderGetNext(decoder.get(),&frame,×tamp))
|
|
throw std::runtime_error(invalidImage);
|
|
std::memcpy(output,frame,outputSize);
|
|
}
|
|
else
|
|
{
|
|
WebPDecoderConfig config{};
|
|
if(!WebPInitDecoderConfig(&config)) throw std::runtime_error(invalidImage);
|
|
config.output.colorspace=MODE_bgrA;
|
|
config.output.is_external_memory=1;
|
|
config.output.u.RGBA={output,static_cast<int>(raster.width*sizeof(uint32_t)),outputSize};
|
|
const auto status=WebPDecode(bytes.data(),bytes.size(),&config);
|
|
WebPFreeDecBuffer(&config.output);
|
|
if(status!=VP8_STATUS_OK) throw std::runtime_error(invalidImage);
|
|
}
|
|
return raster;
|
|
}
|
|
}
|
|
|
|
bool isImagePath(const std::filesystem::path &path)
|
|
{
|
|
return imageFormat(path)!=ImageFormat::unknown;
|
|
}
|
|
|
|
bool isEditableImagePath(const std::filesystem::path &path)
|
|
{
|
|
const auto format=imageFormat(path);
|
|
return format==ImageFormat::png || format==ImageFormat::jpeg;
|
|
}
|
|
|
|
void encodeImage(const ImageRaster &raster,const fs::path &contents,const fs::path &name)
|
|
{
|
|
const auto format=imageFormat(name);
|
|
if(format!=ImageFormat::png && format!=ImageFormat::jpeg)
|
|
throw std::runtime_error("Choose a PNG or JPEG file.");
|
|
checkImageDimensions(raster.width,raster.height);
|
|
if(raster.pixels.size()!=size_t(raster.width)*raster.height) throw std::runtime_error(invalidImage);
|
|
const auto check=[](HRESULT result) {
|
|
if(FAILED(result)) throw std::system_error(static_cast<int>(result),std::system_category(),"Encode image");
|
|
};
|
|
const Apartment apartment;
|
|
if(apartment.initialized!=RPC_E_CHANGED_MODE) check(apartment.initialized);
|
|
ImagingObject<IWICImagingFactory> factory;
|
|
check(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory.value)));
|
|
const bool png=format==ImageFormat::png;
|
|
ImagingObject<IWICStream> stream;
|
|
check(factory->CreateStream(&stream.value));
|
|
check(stream->InitializeFromFilename(contents.c_str(),GENERIC_WRITE));
|
|
ImagingObject<IWICBitmapEncoder> encoder;
|
|
check(factory->CreateEncoder(png?GUID_ContainerFormatPng:GUID_ContainerFormatJpeg,nullptr,&encoder.value));
|
|
check(encoder->Initialize(stream.value,WICBitmapEncoderNoCache));
|
|
ImagingObject<IWICBitmapFrameEncode> frame;
|
|
ImagingObject<IPropertyBag2> options;
|
|
check(encoder->CreateNewFrame(&frame.value,&options.value));
|
|
if(!png)
|
|
{
|
|
wchar_t qualityName[]=L"ImageQuality";
|
|
PROPBAG2 property{};
|
|
property.pstrName=qualityName;
|
|
VARIANT quality{};
|
|
quality.vt=VT_R4;
|
|
quality.fltVal=0.95f;
|
|
check(options->Write(1,&property,&quality));
|
|
}
|
|
check(frame->Initialize(options.value));
|
|
check(frame->SetSize(raster.width,raster.height));
|
|
auto pixelFormat=png?GUID_WICPixelFormat32bppBGRA:GUID_WICPixelFormat24bppBGR;
|
|
check(frame->SetPixelFormat(&pixelFormat));
|
|
|
|
auto *pixels=raster.pixels.data();
|
|
std::vector<uint32_t> opaque;
|
|
if(!png && std::any_of(raster.pixels.begin(),raster.pixels.end(),[](uint32_t pixel){return (pixel>>24)!=255;}))
|
|
{
|
|
opaque=raster.pixels;
|
|
for(auto &pixel:opaque)
|
|
{
|
|
const auto white=255-(pixel>>24);
|
|
const auto gray=white|(white<<8)|(white<<16);
|
|
pixel=0xff000000|((pixel&0x00ffffff)+gray);
|
|
}
|
|
pixels=opaque.data();
|
|
}
|
|
const auto stride=static_cast<UINT>(raster.width*sizeof(uint32_t));
|
|
ImagingObject<IWICBitmap> source;
|
|
check(factory->CreateBitmapFromMemory(raster.width,raster.height,GUID_WICPixelFormat32bppPBGRA,stride,
|
|
static_cast<UINT>(raster.pixels.size()*sizeof(uint32_t)),
|
|
reinterpret_cast<BYTE *>(const_cast<uint32_t *>(pixels)),&source.value));
|
|
ImagingObject<IWICFormatConverter> converter;
|
|
check(factory->CreateFormatConverter(&converter.value));
|
|
check(converter->Initialize(source.value,pixelFormat,WICBitmapDitherTypeNone,nullptr,0,WICBitmapPaletteTypeCustom));
|
|
check(frame->WriteSource(converter.value,nullptr));
|
|
check(frame->Commit());
|
|
check(encoder->Commit());
|
|
check(stream->Commit(STGC_DEFAULT));
|
|
}
|
|
|
|
ImageRaster decodeImage(const std::filesystem::path &contents,const std::filesystem::path &name,std::stop_token stop)
|
|
{
|
|
const auto format=imageFormat(name);
|
|
if(format==ImageFormat::unknown) throw std::runtime_error("This image format is not supported.");
|
|
checkImageStop(stop);
|
|
const auto size=std::filesystem::file_size(contents);
|
|
if(size==0) throw std::runtime_error(invalidImage);
|
|
if(size>imageSourceLimit) throw std::runtime_error(largeImage);
|
|
auto image=format==ImageFormat::webp?decodeWebp(contents,static_cast<size_t>(size),stop):
|
|
decodeNativeImage(contents,format,stop);
|
|
checkImageStop(stop);
|
|
return image;
|
|
}
|
|
}
|