Rise
The Vieneo Province
Loading...
Searching...
No Matches
GifAnimationWorker.h
Go to the documentation of this file.
1#pragma once
2#include "GifAnimation.h"
3#include <atomic>
4#include <condition_variable>
5#include <mutex>
6#include <thread>
7#include <utility>
8
9// One worker for the city cache. WIC objects are created, used and destroyed on
10// that thread. Only immutable, fully composed BGRA frames cross to the renderer.
12{
13 struct Budget { std::atomic<uint64_t> bytes{0}; };
14public:
15 struct Metadata
16 {
18 uint64_t hash = 0;
19 };
20 struct Result
21 {
22 std::shared_ptr<const Metadata> metadata;
23 std::vector<uint32_t> pixels;
24 size_t frame = 0;
25 double decodeMs = 0;
26 };
27 struct State
28 {
29 std::atomic<bool> cancelled{false}, requested{false};
30 std::atomic<size_t> target{0};
31 std::atomic<HRESULT> error{S_OK};
32 std::mutex resultMutex;
33 std::shared_ptr<const Result> result;
34 std::vector<uint8_t> input;
35 std::shared_ptr<Budget> budget;
36 uint64_t charged = 0;
37
38 bool Charge(uint64_t total)
39 {
40 const auto extra = total - charged;
41 auto used = budget->bytes.load();
42 do { if (used + extra > 256ull * 1024 * 1024) return false; }
43 while (!budget->bytes.compare_exchange_weak(used, used + extra));
44 charged = total;
45 return true;
46 }
47 ~State() { budget->bytes.fetch_sub(charged); }
48 std::shared_ptr<const Result> Take()
49 {
50 // Never wait for the worker, even while it publishes a result.
51 std::unique_lock<std::mutex> lock(resultMutex, std::try_to_lock);
52 return lock.owns_lock() ? std::exchange(result, {}) : nullptr;
53 }
54 };
55
56 GifAnimationWorker() = default;
58 {
59 { std::lock_guard<std::mutex> lock(gate); stopping = true; }
60 changed.notify_one();
61 if (thread.joinable()) thread.join();
62 }
65
66 std::shared_ptr<State> Open(const void* bytes, size_t size)
67 {
68 auto state = std::make_shared<State>();
69 state->budget = budget;
70 if (!state->Charge(size)) return {};
71 const auto* data = static_cast<const uint8_t*>(bytes);
72 state->input.assign(data, data + size);
73 std::lock_guard<std::mutex> lock(gate);
74 if (!thread.joinable()) thread = std::thread([this] { Run(); });
75 incoming.push_back(state);
76 wake = true;
77 changed.notify_one();
78 return state;
79 }
80 void Request(const std::shared_ptr<State>& state, size_t frame)
81 {
82 state->target.store(frame);
83 state->requested.store(true);
84 Wake();
85 }
86 void Cancel(const std::shared_ptr<State>& state)
87 {
88 if (state) { state->cancelled.store(true); Wake(); }
89 }
90
91private:
92 struct Session
93 {
94 std::shared_ptr<State> state;
95 std::unique_ptr<GifAnimationDecoder> decoder;
96 std::shared_ptr<Metadata> metadata;
97 size_t last = size_t(-1);
98 };
99 std::shared_ptr<Budget> budget = std::make_shared<Budget>();
100 std::mutex gate;
101 std::condition_variable changed;
102 bool wake = false, stopping = false;
103 std::vector<std::shared_ptr<State>> incoming;
104 std::thread thread;
105
106 void Wake()
107 {
108 { std::lock_guard<std::mutex> lock(gate); wake = true; }
109 changed.notify_one();
110 }
111 static void Decode(Session& session, size_t frame)
112 {
113 auto& state = *session.state;
114 if (state.cancelled.load() || FAILED(state.error.load()) || session.last == frame) return;
115 LARGE_INTEGER start{}, end{}, frequency{};
116 QueryPerformanceCounter(&start);
117 const std::vector<uint32_t>* pixels = nullptr;
118 const HRESULT hr = session.decoder->RenderFrame(frame, pixels);
119 if (FAILED(hr)) { state.error.store(hr); return; }
120 if (state.cancelled.load()) return;
121 auto result = std::make_shared<Result>();
122 result->metadata = session.metadata;
123 result->frame = frame;
124 result->pixels = *pixels;
125 QueryPerformanceCounter(&end); QueryPerformanceFrequency(&frequency);
126 result->decodeMs = 1000.0 * double(end.QuadPart - start.QuadPart) / double(frequency.QuadPart);
127 session.last = frame;
128 std::shared_ptr<const Result> previous;
129 {
130 std::lock_guard<std::mutex> lock(state.resultMutex);
131 previous = std::exchange(state.result, std::move(result));
132 } // Release old pixels outside the publication lock.
133 }
134 static HRESULT Initialize(Session& session)
135 {
136 auto& state = *session.state;
137 session.decoder = std::make_unique<GifAnimationDecoder>();
138 HRESULT hr = session.decoder->Open(state.input.data(), state.input.size());
139 if (FAILED(hr)) return hr;
140 const auto& animation = session.decoder->Animation();
141 // Three decoder canvases, up to four completed/building CPU frames,
142 // one GPU texture, compressed input, timing and lazy ad metadata.
143 const uint64_t bytes = state.input.size() + uint64_t(animation.width) * animation.height * 32 +
144 animation.frames.size() * 256ull;
145 if (!state.Charge(bytes)) return E_OUTOFMEMORY;
146 session.metadata = std::make_shared<Metadata>();
147 session.metadata->animation = animation;
148 session.metadata->hash = 14695981039346656037ull;
149 for (auto byte : state.input) { session.metadata->hash ^= byte; session.metadata->hash *= 1099511628211ull; }
150 std::vector<uint8_t>().swap(state.input);
151 Decode(session, animation.FrameAt(0));
152 return state.error.load();
153 }
154 void Run()
155 {
156 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
157 // This container (including every decoder's COM apartment) is local to
158 // the worker. Cancellation/reassignment never joins it in FrameMove.
159 std::vector<Session> sessions;
160 for (;;)
161 {
162 std::vector<std::shared_ptr<State>> added;
163 {
164 std::unique_lock<std::mutex> lock(gate);
165 changed.wait(lock, [this] { return wake || stopping; });
166 if (stopping) return;
167 wake = false;
168 added.swap(incoming);
169 }
170 for (auto it = sessions.begin(); it != sessions.end();)
171 if (it->state->cancelled.load()) it = sessions.erase(it); else ++it;
172 for (auto& state : added)
173 {
174 if (state->cancelled.load()) continue;
175 try
176 {
177 Session session; session.state = state;
178 const HRESULT hr = Initialize(session);
179 if (FAILED(hr)) state->error.store(hr);
180 else sessions.push_back(std::move(session));
181 }
182 catch (const std::bad_alloc&) { state->error.store(E_OUTOFMEMORY); }
183 }
184 for (auto& session : sessions)
185 {
186 auto& state = *session.state;
187 if (!state.requested.exchange(false)) continue;
188 try { Decode(session, state.target.load()); }
189 catch (const std::bad_alloc&) { state.error.store(E_OUTOFMEMORY); }
190 }
191 }
192 }
193};
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
HRESULT Open(const wchar_t *path)
HRESULT RenderFrame(std::size_t index, const std::vector< std::uint32_t > *&pixels)
const GifAnimation & Animation() const
std::shared_ptr< Budget > budget
static void Decode(Session &session, size_t frame)
std::vector< std::shared_ptr< State > > incoming
GifAnimationWorker(const GifAnimationWorker &)=delete
std::condition_variable changed
std::shared_ptr< State > Open(const void *bytes, size_t size)
GifAnimationWorker()=default
void Cancel(const std::shared_ptr< State > &state)
GifAnimationWorker & operator=(const GifAnimationWorker &)=delete
static HRESULT Initialize(Session &session)
void Request(const std::shared_ptr< State > &state, size_t frame)
unsigned int height
std::atomic< uint64_t > bytes
std::shared_ptr< const Metadata > metadata
std::vector< uint32_t > pixels
std::shared_ptr< State > state
std::shared_ptr< Metadata > metadata
std::unique_ptr< GifAnimationDecoder > decoder
std::atomic< bool > cancelled
std::shared_ptr< const Result > result
bool Charge(uint64_t total)
std::atomic< HRESULT > error
std::shared_ptr< const Result > Take()
std::shared_ptr< Budget > budget
std::atomic< bool > requested
std::vector< uint8_t > input
std::atomic< size_t > target