158 lines
6.3 KiB
C++
158 lines
6.3 KiB
C++
#include "files_image_decode.h"
|
|
#include <windows.h>
|
|
#include <wincodec.h>
|
|
#include <webp/decode.h>
|
|
#include <webp/demux.h>
|
|
#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;}
|
|
};
|
|
|
|
ImageRaster decodeNativeImage(const fs::path &file,ImageFormat format,std::stop_token stop)
|
|
{
|
|
struct Apartment
|
|
{
|
|
const HRESULT initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
|
|
~Apartment() {if(SUCCEEDED(initialized)) CoUninitialize();}
|
|
};
|
|
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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|