Rise
The Vieneo Province
Loading...
Searching...
No Matches
GifAnimation.cpp
Go to the documentation of this file.
1// Adapted from Makeship/GifAnimation.cpp: same WIC decoder and disposal rules.
2#include "GifAnimation.h"
3
4#include <algorithm>
5#include <cmath>
6#include <cstring>
7#include <new>
8#include <utility>
9#include <wincodec.h>
10#include <wrl/client.h>
11
12#pragma comment(lib, "windowscodecs.lib")
13#pragma comment(lib, "ole32.lib")
14
15namespace
16{
17 using Microsoft::WRL::ComPtr;
18 const std::uint64_t MemoryBudget = 128ull * 1024 * 1024;
19
20 class ComApartment
21 {
22 public:
23 ComApartment() : result(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED)) {}
24 ~ComApartment() { if (SUCCEEDED(result)) CoUninitialize(); }
25 HRESULT result;
26 };
27
28 unsigned int MetadataNumber(
29 IWICMetadataQueryReader& reader, const wchar_t* name,
30 unsigned int fallback = 0)
31 {
32 PROPVARIANT value = {};
33 unsigned int result = fallback;
34 if (SUCCEEDED(reader.GetMetadataByName(name, &value)))
35 {
36 if (value.vt == VT_UI1) result = value.bVal;
37 else if (value.vt == VT_UI2) result = value.uiVal;
38 else if (value.vt == VT_BOOL) result = value.boolVal != VARIANT_FALSE;
39 }
40 PropVariantClear(&value);
41 return result;
42 }
43
44 unsigned int ReadPlayCount(IWICMetadataQueryReader& reader)
45 {
46 PROPVARIANT value = {};
47 unsigned int count = 1;
48 bool hasLoopExtension = false;
49 if (SUCCEEDED(reader.GetMetadataByName(L"/appext/application", &value)) &&
50 value.vt == (VT_VECTOR | VT_UI1) && value.caub.cElems == 11)
51 {
52 hasLoopExtension = !std::memcmp(value.caub.pElems, "NETSCAPE2.0", 11) ||
53 !std::memcmp(value.caub.pElems, "ANIMEXTS1.0", 11);
54 }
55 PropVariantClear(&value);
56 if (hasLoopExtension &&
57 SUCCEEDED(reader.GetMetadataByName(L"/appext/data", &value)) &&
58 value.vt == (VT_VECTOR | VT_UI1) && value.caub.cElems >= 4 &&
59 value.caub.pElems[0] >= 3 && value.caub.pElems[1] == 1)
60 {
61 const unsigned int repeats = value.caub.pElems[2] |
62 (static_cast<unsigned int>(value.caub.pElems[3]) << 8);
63 count = repeats == 0 ? 0 : repeats + 1;
64 }
65 PropVariantClear(&value);
66 return count;
67 }
68
69 // Keep the compressed file in memory so image editors can replace it during playback.
70 HRESULT ReadFileBytes(const wchar_t* path, std::vector<BYTE>& bytes)
71 {
72 const HANDLE file = CreateFileW(path, GENERIC_READ,
73 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
74 nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
75 if (file == INVALID_HANDLE_VALUE) return HRESULT_FROM_WIN32(GetLastError());
76 LARGE_INTEGER size;
77 HRESULT hr = S_OK;
78 if (!GetFileSizeEx(file, &size)) hr = HRESULT_FROM_WIN32(GetLastError());
79 else if (size.QuadPart <= 0) hr = WINCODEC_ERR_BADIMAGE;
80 else if (size.QuadPart > MemoryBudget) hr = HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE);
81 if (SUCCEEDED(hr))
82 {
83 try
84 {
85 bytes.resize(static_cast<std::size_t>(size.QuadPart));
86 DWORD read = 0;
87 if (!ReadFile(file, bytes.data(), static_cast<DWORD>(bytes.size()), &read, nullptr))
88 hr = HRESULT_FROM_WIN32(GetLastError());
89 else if (read != bytes.size()) hr = WINCODEC_ERR_BADIMAGE;
90 }
91 catch (const std::bad_alloc&) { hr = E_OUTOFMEMORY; }
92 }
93 CloseHandle(file);
94 return hr;
95 }
96}
97
99{
100public:
101 struct Frame
102 {
104 std::uint32_t clearColor;
105 };
106
107 // Declared first so COM is uninitialized only after all WIC objects are released.
108 ComApartment apartment;
109 std::vector<BYTE> fileBytes;
110 ComPtr<IWICImagingFactory> factory;
111 ComPtr<IWICStream> stream;
112 ComPtr<IWICBitmapDecoder> decoder;
114 std::vector<Frame> frames;
115 std::vector<std::uint32_t> canvas;
116 std::vector<std::uint32_t> previous;
117 std::vector<std::uint32_t> scratch;
118 std::size_t nextFrame = 0;
119
121 {
122 if (FAILED(apartment.result) && apartment.result != RPC_E_CHANGED_MODE)
123 return apartment.result;
124 HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory, nullptr,
125 CLSCTX_INPROC_SERVER, IID_PPV_ARGS(factory.GetAddressOf()));
126 if (FAILED(hr)) return hr;
127 hr = factory->CreateStream(stream.GetAddressOf());
128 if (FAILED(hr)) return hr;
129 hr = stream->InitializeFromMemory(fileBytes.data(), static_cast<DWORD>(fileBytes.size()));
130 if (FAILED(hr)) return hr;
131 hr = factory->CreateDecoderFromStream(stream.Get(), nullptr,
132 WICDecodeMetadataCacheOnLoad, decoder.GetAddressOf());
133 if (FAILED(hr)) return hr;
134 GUID format;
135 hr = decoder->GetContainerFormat(&format);
136 if (FAILED(hr)) return hr;
137 if (format != GUID_ContainerFormatGif) return WINCODEC_ERR_UNKNOWNIMAGEFORMAT;
138 ComPtr<IWICMetadataQueryReader> metadata;
139 hr = decoder->GetMetadataQueryReader(metadata.GetAddressOf());
140 if (FAILED(hr)) return hr;
141 animation.width = MetadataNumber(*metadata.Get(), L"/logscrdesc/Width");
142 animation.height = MetadataNumber(*metadata.Get(), L"/logscrdesc/Height");
143 animation.playCount = ReadPlayCount(*metadata.Get());
144 UINT count = 0;
145 hr = decoder->GetFrameCount(&count);
146 if (FAILED(hr)) return hr;
147 if (!animation.width || !animation.height || !count) return WINCODEC_ERR_BADIMAGE;
148 const std::uint64_t pixelCount =
149 static_cast<std::uint64_t>(animation.width) * animation.height;
150 // Memory scales with the canvas, not the number of animation frames.
151 if (animation.width > 8192 || animation.height > 8192 || count > 4096 ||
152 pixelCount * 4 * 3 > MemoryBudget)
153 return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE);
154
155 std::uint32_t background = 0;
156 ComPtr<IWICPalette> palette;
157 if (MetadataNumber(*metadata.Get(), L"/logscrdesc/GlobalColorTableFlag") &&
158 SUCCEEDED(factory->CreatePalette(palette.GetAddressOf())) &&
159 SUCCEEDED(decoder->CopyPalette(palette.Get())))
160 {
161 WICColor colors[256];
162 UINT colorCount = 0;
163 const UINT index = MetadataNumber(*metadata.Get(), L"/logscrdesc/BackgroundColorIndex");
164 if (SUCCEEDED(palette->GetColors(256, colors, &colorCount)) && index < colorCount)
165 background = colors[index] | 0xff000000;
166 }
167 std::uint64_t endTime = 0;
168 animation.frames.reserve(count);
169 frames.reserve(count);
170 for (UINT index = 0; index < count; ++index)
171 {
172 ComPtr<IWICBitmapFrameDecode> frame;
173 hr = decoder->GetFrame(index, frame.GetAddressOf());
174 if (FAILED(hr)) return hr;
175 ComPtr<IWICMetadataQueryReader> frameMetadata;
176 hr = frame->GetMetadataQueryReader(frameMetadata.GetAddressOf());
177 if (FAILED(hr)) return hr;
178 Frame info = {};
179 hr = frame->GetSize(&info.width, &info.height);
180 if (FAILED(hr)) return hr;
181 info.left = MetadataNumber(*frameMetadata.Get(), L"/imgdesc/Left");
182 info.top = MetadataNumber(*frameMetadata.Get(), L"/imgdesc/Top");
183 if (!info.width || !info.height || info.left >= animation.width || info.top >= animation.height ||
184 info.width > animation.width - info.left || info.height > animation.height - info.top)
185 return WINCODEC_ERR_BADIMAGE;
186 info.disposal = MetadataNumber(*frameMetadata.Get(), L"/grctlext/Disposal");
187 info.clearColor = MetadataNumber(*frameMetadata.Get(), L"/grctlext/TransparencyFlag")
188 ? 0 : background;
189 const UINT delay = MetadataNumber(*frameMetadata.Get(), L"/grctlext/Delay");
190 // Preserve GIF hundredth-second delays, including intermediate zero
191 // delay frames. A wholly zero-duration GIF holds the final composite.
192 endTime += delay * 10;
193 animation.frames.push_back({{}, endTime});
194 frames.push_back(info);
195 }
196 canvas.resize(static_cast<std::size_t>(pixelCount));
197 previous.reserve(static_cast<std::size_t>(pixelCount));
198 scratch.resize(static_cast<std::size_t>(pixelCount));
199 return S_OK;
200 }
201
202 HRESULT Compose(std::size_t target)
203 {
204 if (nextFrame && target == nextFrame - 1) return S_OK;
205 if (target < nextFrame) nextFrame = 0;
206 while (nextFrame <= target)
207 {
208 if (nextFrame == 0)
209 std::fill(canvas.begin(), canvas.end(), frames[0].clearColor);
210 else
211 {
212 const Frame& disposed = frames[nextFrame - 1];
213 if (disposed.disposal == 2)
214 for (UINT y = 0; y < disposed.height; ++y)
215 std::fill_n(canvas.begin() + (disposed.top + y) * animation.width + disposed.left,
216 disposed.width, disposed.clearColor);
217 else if (disposed.disposal == 3)
218 canvas.swap(previous);
219 }
220 const Frame& info = frames[nextFrame];
221 if (info.disposal == 3) previous = canvas;
222 ComPtr<IWICBitmapFrameDecode> frame;
223 HRESULT hr = decoder->GetFrame(static_cast<UINT>(nextFrame), frame.GetAddressOf());
224 if (FAILED(hr)) return hr;
225 ComPtr<IWICFormatConverter> converter;
226 hr = factory->CreateFormatConverter(converter.GetAddressOf());
227 if (FAILED(hr)) return hr;
228 hr = converter->Initialize(frame.Get(), GUID_WICPixelFormat32bppBGRA,
229 WICBitmapDitherTypeNone, nullptr, 0, WICBitmapPaletteTypeCustom);
230 if (FAILED(hr)) return hr;
231 hr = converter->CopyPixels(nullptr, info.width * 4,
232 static_cast<UINT>(scratch.size() * 4), reinterpret_cast<BYTE*>(scratch.data()));
233 if (FAILED(hr)) return hr;
234 for (UINT y = 0; y < info.height; ++y)
235 for (UINT x = 0; x < info.width; ++x)
236 {
237 const auto pixel = scratch[y * info.width + x];
238 if (pixel & 0xff000000)
239 canvas[(info.top + y) * animation.width + info.left + x] = pixel;
240 }
241 ++nextFrame;
242 }
243 return S_OK;
244 }
245};
246
247std::size_t GifAnimation::FrameAt(double elapsedSeconds) const
248{
249 if (frames.size() < 2 || !std::isfinite(elapsedSeconds) || elapsedSeconds < 0)
250 return 0;
251 const auto duration = frames.back().endMilliseconds;
252 if (!duration) return frames.size() - 1;
253 const double elapsed = elapsedSeconds * 1000.0;
254 if (playCount && elapsed >= static_cast<double>(duration) * playCount)
255 return frames.size() - 1;
256 const double position = std::isfinite(elapsed)
257 ? std::fmod(elapsed, static_cast<double>(duration))
258 : std::fmod(elapsedSeconds, static_cast<double>(duration) / 1000.0) * 1000.0;
259 const auto frame = std::upper_bound(frames.begin(), frames.end(), position,
260 [](double time, const GifAnimationFrame& value) { return time < value.endMilliseconds; });
261 return frame == frames.end() ? 0 : static_cast<std::size_t>(frame - frames.begin());
262}
263
266
268{
269 impl_.reset();
270 if (!path) return E_INVALIDARG;
271 try
272 {
273 std::unique_ptr<Impl> decoded(new Impl);
274 HRESULT hr = ReadFileBytes(path, decoded->fileBytes);
275 if (SUCCEEDED(hr)) hr = decoded->Open();
276 if (SUCCEEDED(hr)) impl_ = std::move(decoded);
277 return hr;
278 }
279 catch (const std::bad_alloc&) { return E_OUTOFMEMORY; }
280}
281
282HRESULT GifAnimationDecoder::Open(const void* bytes, std::size_t size)
283{
284 impl_.reset();
285 if (!bytes || size < 6 || size > MemoryBudget) return E_INVALIDARG;
286 try
287 {
288 std::unique_ptr<Impl> decoded(new Impl);
289 const auto* first = static_cast<const BYTE*>(bytes);
290 decoded->fileBytes.assign(first, first + size);
291 const HRESULT hr = decoded->Open();
292 if (SUCCEEDED(hr)) impl_ = std::move(decoded);
293 return hr;
294 }
295 catch (const std::bad_alloc&) { return E_OUTOFMEMORY; }
296}
297
299{
300 static const GifAnimation empty;
301 return impl_ ? impl_->animation : empty;
302}
303
304HRESULT GifAnimationDecoder::RenderFrame(std::size_t index, const std::vector<std::uint32_t>*& pixels)
305{
306 pixels = nullptr;
307 if (!impl_ || index >= impl_->frames.size()) return E_INVALIDARG;
308 HRESULT hr;
309 try { hr = impl_->Compose(index); }
310 catch (const std::bad_alloc&) { hr = E_OUTOFMEMORY; }
311 if (SUCCEEDED(hr)) pixels = &impl_->canvas;
312 else impl_->nextFrame = 0;
313 return hr;
314}
315
316HRESULT GifAnimationDecoder::Load(const wchar_t* path, GifAnimation& animation)
317{
318 animation = GifAnimation{};
319 try
320 {
321 GifAnimationDecoder decoder;
322 HRESULT hr = decoder.Open(path);
323 if (FAILED(hr)) return hr;
324 GifAnimation decoded = decoder.Animation();
325 if (static_cast<std::uint64_t>(decoded.width) * decoded.height * 4 *
326 (decoded.frames.size() + 3) > MemoryBudget) return E_OUTOFMEMORY;
327 for (std::size_t index = 0; index < decoded.frames.size(); ++index)
328 {
329 const std::vector<std::uint32_t>* pixels = nullptr;
330 hr = decoder.RenderFrame(index, pixels);
331 if (FAILED(hr)) return hr;
332 decoded.frames[index].pixels = *pixels;
333 }
334 animation = std::move(decoded);
335 return S_OK;
336 }
337 catch (const std::bad_alloc&) { return E_OUTOFMEMORY; }
338}
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
SCRIPT_CONTROL SCRIPT_STATE const void DWORD
HRESULT Compose(std::size_t target)
std::vector< std::uint32_t > previous
ComPtr< IWICBitmapDecoder > decoder
ComPtr< IWICStream > stream
ComPtr< IWICImagingFactory > factory
std::vector< BYTE > fileBytes
std::vector< std::uint32_t > canvas
std::vector< Frame > frames
std::vector< std::uint32_t > scratch
HRESULT Open(const wchar_t *path)
HRESULT RenderFrame(std::size_t index, const std::vector< std::uint32_t > *&pixels)
const GifAnimation & Animation() const
std::unique_ptr< Impl > impl_
static HRESULT Load(const wchar_t *path, GifAnimation &animation)
unsigned int width
std::vector< GifAnimationFrame > frames
unsigned int height
std::size_t FrameAt(double elapsedSeconds) const
unsigned int playCount