-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathEnergyCalculatorPerPixel.cpp
569 lines (486 loc) · 17.2 KB
/
EnergyCalculatorPerPixel.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//
// Copyright 2010, Darren Lafreniere
// <http://www.lafarren.com/image-completer/>
//
// This file is part of lafarren.com's Image Completer.
//
// Image Completer is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Image Completer is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Image Completer, named License.txt. If not, see
// <http://www.gnu.org/licenses/>.
//
#include "Pch.h"
#include "EnergyCalculatorPerPixel.h"
#include "tech/Atomic.h"
#include "tech/Core.h"
#include "tech/MathUtils.h"
#include "EnergyCalculatorUtils.h"
#include "ImageConst.h"
#include "LfnIcSettings.h"
#include "MaskLod.h"
#include "tech/DbgMem.h"
namespace LfnIc
{
// If the batch has maxCalculations has >= this value and there are worker
// threads, queued calculations will be processed over all available hardware
// threads. Attempting asynchronous batches with fewer calculations than this
// might actually be slower due to synchronization overhead.
//
// NOTE: value is arbitrary. Do some tests to find the sweet spot.
const int MIN_CALCULATIONS_FOR_ASYNC_BATCH = 30;
//
// PolicyNoMask - handles straight pixel SSD calculations without any masking.
// This policy, along with the non-specialized CalculateEnergy function, provide
// an extremely efficient implementation for pixels with exactly 3 unsigned char channels.
//
class PolicyNoMask_24BitRgb
{
public:
static const bool HAS_MASK = false;
typedef uint32 ResultType;
inline void OnPreLoop(const Mask* mask) {}
inline void OnARow(int aSrcIndex) {}
inline void OnBRow(int bSrcIndex) {}
inline int GetMaxPixelsPerBunch() const
{
// MaxPixelsForUint32Energy is how many pixels a uint32 energy variable
// can safely capture without overflowing, assuming the worst case of
// a pure black patch vs pure white patch, where each channel difference is
// 255. This is a 32-bit application, but the Energy typedef is 64-bit because
// of how large the patches can be. Performing the energy calculations in
// 64-bit has a big performance penalty, so calculate in 32-bit bunches,
// dumping the bunch result into the 64-bit energy result before reaching
// overflow.
static const int MAX_CHANNEL_VALUE = std::numeric_limits<Image::Pixel::ChannelType>::max();
static const int MAX_ENERGY_PER_PIXEL = (MAX_CHANNEL_VALUE * MAX_CHANNEL_VALUE) * Image::Pixel::NUM_CHANNELS;
static const int MAX_PIXELS_PER_RESULT = std::numeric_limits<ResultType>::max() / MAX_ENERGY_PER_PIXEL;
return MAX_PIXELS_PER_RESULT;
}
FORCE_INLINE ResultType CalculateSquaredDifference(const Image::Pixel* aSrcRow, const Image::Pixel* bSrcRow, int x)
{
const Image::Pixel& a = aSrcRow[x];
const Image::Pixel& b = bSrcRow[x];
// d[x] = channel delta
// e = dr^2 + dg^2 + db^2
const ResultType dr = a.channel[0] - b.channel[0];
const ResultType dg = a.channel[1] - b.channel[1];
const ResultType db = a.channel[2] - b.channel[2];
return (dr * dr) + (dg * dg) + (db * db);
}
};
class PolicyNoMask_General
{
public:
static const bool HAS_MASK = false;
typedef float ResultType;
inline void OnPreLoop(const Mask* mask) {}
inline void OnARow(int aSrcIndex) {}
inline void OnBRow(int bSrcIndex) {}
inline int GetMaxPixelsPerBunch() const
{
// It's difficult to get a hard limit for how much a floating
// point result type can hold without overflowing, since the
// input pixel range is unknown. This 32x32 bunch limit is
// arbitrary.
// TODO: base this on std::numeric_limits<ResultType>::digits.
return 32 * 32;
}
FORCE_INLINE ResultType CalculateSquaredDifference(const Image::Pixel* aSrcRow, const Image::Pixel* bSrcRow, int x)
{
const Image::Pixel& a = aSrcRow[x];
const Image::Pixel& b = bSrcRow[x];
ResultType squaredDifference = ResultType(0);
for (int i = 0; i < Image::Pixel::NUM_CHANNELS; ++i)
{
squaredDifference += (a.channel[i] - b.channel[i]) * (a.channel[i] - b.channel[i]);
}
return squaredDifference;
}
};
//
// PolicyMask - base class for testing one of the regions against the mask
//
template<typename POLICY_NO_MASK>
class PolicyMask : public POLICY_NO_MASK
{
public:
static const bool HAS_MASK = true;
typedef POLICY_NO_MASK Super;
typedef typename Super::ResultType ResultType;
inline void OnPreLoop(const MaskLod* mask)
{
m_lodBuffer = mask ? mask->GetLodBuffer(mask->GetHighestLod()) : NULL;
}
inline ResultType CalculateSquaredDifference(const Image::Pixel* aSrcRow, const Image::Pixel* bSrcRow, int x)
{
return (!m_lodRow || m_lodRow[x] == Mask::KNOWN)
? Super::CalculateSquaredDifference(aSrcRow, bSrcRow, x)
: ResultType(0);
}
protected:
const Mask::Value* m_lodBuffer;
const Mask::Value* m_lodRow;
};
//
// PolicyMaskA - tests region A against the mask
//
template<typename POLICY_NO_MASK>
class PolicyMaskA : public PolicyMask<POLICY_NO_MASK>
{
public:
typedef PolicyMask<POLICY_NO_MASK> Super;
inline void OnARow(int aSrcIndex)
{
Super::m_lodRow = Super::m_lodBuffer ? (Super::m_lodBuffer + aSrcIndex) : NULL;
}
};
typedef PolicyMaskA<PolicyNoMask_24BitRgb> PolicyMaskA_24BitRgb;
typedef PolicyMaskA<PolicyNoMask_General> PolicyMaskA_General;
//
// General purpose energy calculation template. Performs masking via a policy
// template parameter. Because the policy is resolved at compile time, the
// mask testing is compiled out when it's not needed.
//
template<typename POLICY>
static inline Energy CalculateEnergy(
const ImageConst& inputImage, const MaskLod* mask,
int width, int height,
int aLeft, int aTop,
int bLeft, int bTop)
{
Energy energy64Bit = Energy(0);
const int imageWidth = inputImage.GetWidth();
const int imageHeight = inputImage.GetHeight();
EnergyCalculatorUtils::ClampToMinBoundary(aLeft, bLeft, width, 0);
EnergyCalculatorUtils::ClampToMinBoundary(aTop, bTop, height, 0);
EnergyCalculatorUtils::ClampToMaxBoundary(aLeft, bLeft, width, imageWidth);
EnergyCalculatorUtils::ClampToMaxBoundary(aTop, bTop, height, imageHeight);
if (width > 0 && height > 0)
{
POLICY policy;
policy.OnPreLoop(mask);
typename POLICY::ResultType energyBunch = 0;
int numPixelsInBunch = 0;
const bool canFitInSingleBunch = (width * height) <= policy.GetMaxPixelsPerBunch();
const Image::Pixel* inputImageRgb = inputImage.GetData();
int aRowIndex = LfnTech::GetRowMajorIndex(imageWidth, aLeft, aTop);
int bRowIndex = LfnTech::GetRowMajorIndex(imageWidth, bLeft, bTop);
for (int y = 0; y < height; ++y, aRowIndex += imageWidth, bRowIndex += imageWidth)
{
const Image::Pixel* aRow = inputImageRgb + aRowIndex;
const Image::Pixel* bRow = inputImageRgb + bRowIndex;
policy.OnARow(aRowIndex);
policy.OnBRow(bRowIndex);
if (canFitInSingleBunch)
{
for (int x = 0; x < width; ++x)
{
energyBunch += policy.CalculateSquaredDifference(aRow, bRow, x++);
}
}
else
{
int x = 0;
do
{
const int remainingPixelsInRow = width - x;
const bool shouldDumpBunchAfterStrip = (remainingPixelsInRow > policy.GetMaxPixelsPerBunch());
const int stripWidth = shouldDumpBunchAfterStrip ? policy.GetMaxPixelsPerBunch() : remainingPixelsInRow;
while (x < stripWidth)
{
energyBunch += policy.CalculateSquaredDifference(aRow, bRow, x++);
}
if (shouldDumpBunchAfterStrip)
{
energy64Bit += energyBunch;
energyBunch = 0;
numPixelsInBunch = 0;
}
else
{
numPixelsInBunch += stripWidth;
}
}
while (x < width);
}
}
// Add what's left in the bunch.
energy64Bit += energyBunch;
}
wxASSERT(energy64Bit >= ENERGY_MIN && energy64Bit <= ENERGY_MAX);
return energy64Bit;
}
}
//
// EnergyCalculatorPerPixel implementation
//
LfnIc::EnergyCalculatorPerPixel::EnergyCalculatorPerPixel(const ImageConst& inputImage, const MaskLod& mask) :
m_inputImage(inputImage),
m_mask(mask),
m_batchState(BatchStateClosed),
m_isAsyncBatch(false),
m_queuedCalculationAndResultIndexBuffer(*this),
m_targetThreadIndex(0)
{
#ifdef USE_THREADS
const int cpuCount = wxThread::GetCPUCount();
if (cpuCount > 1)
{
const int numWorkerThreads = cpuCount - 1;
for (int i = 0; i < numWorkerThreads; ++i)
{
WorkerThread* workerThread = new WorkerThread(*this);
m_workerThreads.push_back(workerThread);
wxASSERT(workerThread->IsPaused());
}
}
#endif
}
LfnIc::EnergyCalculatorPerPixel::~EnergyCalculatorPerPixel()
{
for (int i = 0, n = m_workerThreads.size(); i < n; ++i)
{
WorkerThread* workerThread = m_workerThreads[i];
workerThread->ResumeAndQuit();
delete workerThread;
}
}
void LfnIc::EnergyCalculatorPerPixel::BatchOpenImmediate(const BatchParams& params)
{
wxASSERT(m_batchState == BatchStateClosed);
m_batchState = BatchStateOpenImmediate;
m_batchParams = params;
}
void LfnIc::EnergyCalculatorPerPixel::BatchOpenQueued(const BatchParams& params)
{
wxASSERT(m_batchState == BatchStateClosed);
m_batchState = BatchStateOpenQueued;
m_batchParams = params;
// Set the capacity and clear any previous data.
{
m_queuedCalculationsAndResults.clear();
m_queuedCalculationsAndResults.reserve(m_batchParams.maxCalculations);
}
{
m_isAsyncBatch = (m_workerThreads.size() > 0 && m_batchParams.maxCalculations >= MIN_CALCULATIONS_FOR_ASYNC_BATCH);
}
}
void LfnIc::EnergyCalculatorPerPixel::BatchClose()
{
wxASSERT(m_batchState != BatchStateClosed);
m_batchState = BatchStateClosed;
m_isAsyncBatch = false;
}
LfnIc::Energy LfnIc::EnergyCalculatorPerPixel::Calculate(int bLeft, int bTop) const
{
wxASSERT(m_batchState != BatchStateClosed);
if (LfnIc::Image::PixelInfo::IS_24_BIT_RGB)
{
if (m_batchParams.aMasked)
{
return CalculateMaskA<PolicyMaskA_24BitRgb>(bLeft, bTop);
}
else
{
return CalculateNoMask<PolicyNoMask_24BitRgb>(bLeft, bTop);
}
}
else
{
if (m_batchParams.aMasked)
{
return CalculateMaskA<PolicyMaskA_General>(bLeft, bTop);
}
else
{
return CalculateNoMask<PolicyNoMask_General>(bLeft, bTop);
}
}
} // end Calculate
LfnIc::EnergyCalculator::BatchQueued::Handle LfnIc::EnergyCalculatorPerPixel::QueueCalculation(int bLeft, int bTop)
{
wxASSERT(m_batchState != BatchStateClosed);
wxASSERT(m_queuedCalculationsAndResults.size() + 1 <= m_queuedCalculationsAndResults.capacity());
const uint queuedCalculationAndResultIndex = m_queuedCalculationsAndResults.size();
// Add QueuedCalculationAndResult.
{
QueuedCalculationAndResult queuedCalculationAndResult;
queuedCalculationAndResult.bLeft = bLeft;
queuedCalculationAndResult.bTop = bTop;
m_queuedCalculationsAndResults.push_back(queuedCalculationAndResult);
}
// Give index of new QueuedCalculationAndResult to the next target thread.
{
// See comments above m_targetThreadIndex member.
QueuedCalculationAndResultIndexBuffer& queuedCalculationAndResultIndexBuffer = (!m_isAsyncBatch || static_cast<unsigned int>(m_targetThreadIndex) == m_workerThreads.size())
? m_queuedCalculationAndResultIndexBuffer // main thread
: m_workerThreads[m_targetThreadIndex]->GetQueuedCalculationAndResultIndexBuffer(); // worker thread
queuedCalculationAndResultIndexBuffer.push_back(queuedCalculationAndResultIndex);
// Cycle to the next thread index.
m_targetThreadIndex = (m_targetThreadIndex + 1) % (m_workerThreads.size() + 1);
}
return BatchQueued::Handle(queuedCalculationAndResultIndex);
}
void LfnIc::EnergyCalculatorPerPixel::ProcessCalculations()
{
// Resume the worker threads and have them process their calculations.
if (m_isAsyncBatch)
{
for (int i = 0, n = m_workerThreads.size(); i < n; ++i)
{
wxASSERT(m_workerThreads[i]->IsPaused());
m_workerThreads[i]->ResumeAndStartProcessingCalculations();
wxASSERT(!m_workerThreads[i]->IsPaused());
}
}
// Process the main thread's calculations.
m_queuedCalculationAndResultIndexBuffer.ProcessCalculationsAndClear();
// Wait for all worker threads to finish.
if (m_isAsyncBatch)
{
for (int i = 0, n = m_workerThreads.size(); i < n; ++i)
{
wxASSERT(!m_workerThreads[i]->IsPaused());
m_workerThreads[i]->FinishProcessingCalculationsAndPause();
wxASSERT(m_workerThreads[i]->IsPaused());
}
}
m_batchState = BatchStateOpenQueuedAndProcessed;
}
LfnIc::Energy LfnIc::EnergyCalculatorPerPixel::GetResult(BatchQueued::Handle handle) const
{
wxASSERT(m_batchState == BatchStateOpenQueuedAndProcessed);
return m_queuedCalculationsAndResults[handle].result;
}
template <typename POLICY>
LfnIc::Energy LfnIc::EnergyCalculatorPerPixel::CalculateNoMask(int bLeft, int bTop) const
{
wxCOMPILE_TIME_ASSERT(!POLICY::HAS_MASK, CalculateNoMask_IsCalledWithAMaskPolicy);
return CalculateEnergy<POLICY>(
m_inputImage, NULL,
m_batchParams.width, m_batchParams.height,
m_batchParams.aLeft, m_batchParams.aTop,
bLeft, bTop);
}
template<typename POLICY>
LfnIc::Energy LfnIc::EnergyCalculatorPerPixel::CalculateMaskA(int bLeft, int bTop) const
{
wxCOMPILE_TIME_ASSERT(POLICY::HAS_MASK, CalculateMaskA_IsCalledWithANoMaskPolicy);
return CalculateEnergy<POLICY>(
m_inputImage, &m_mask,
m_batchParams.width, m_batchParams.height,
m_batchParams.aLeft, m_batchParams.aTop,
bLeft, bTop);
}
LfnIc::EnergyCalculatorPerPixel::QueuedCalculationAndResultIndexBuffer::QueuedCalculationAndResultIndexBuffer(EnergyCalculatorPerPixel& energyCalculatorPerPixel) :
m_energyCalculatorPerPixel(energyCalculatorPerPixel)
{
}
void LfnIc::EnergyCalculatorPerPixel::QueuedCalculationAndResultIndexBuffer::ProcessCalculationsAndClear()
{
for (int i = 0, n = size(); i < n; ++i)
{
QueuedCalculationAndResult& queuedCalculationAndResult = m_energyCalculatorPerPixel.m_queuedCalculationsAndResults[at(i)];
queuedCalculationAndResult.result = m_energyCalculatorPerPixel.Calculate(queuedCalculationAndResult.bLeft, queuedCalculationAndResult.bTop);
}
clear();
}
LfnIc::EnergyCalculatorPerPixel::WorkerThread::WorkerThread(EnergyCalculatorPerPixel& energyCalculatorPerPixel) :
wxThread(wxTHREAD_JOINABLE),
m_energyCalculatorPerPixel(energyCalculatorPerPixel),
m_queuedCalculationAndResultIndexBuffer(energyCalculatorPerPixel),
m_state(Active)
{
Create();
Run();
FinishProcessingCalculationsAndPause();
}
wxThread::ExitCode LfnIc::EnergyCalculatorPerPixel::WorkerThread::Entry()
{
State state = Active;
while (state != Quitting)
{
m_queuedCalculationAndResultIndexBuffer.ProcessCalculationsAndClear();
// Just query the state; it's never expected to be invalid, the
// exchange and comparand are dummies.
state = AtomicGetState();
// If the main thread wants us to pause, safely loop in here till it
// wants to resume.
if (state == Pausing)
{
// Set the paused state, and verify that the main thread's sync
// loop did its job by waiting.
{
const State previousState = State(LfnTech::Atomic<>::CompareExchange(&m_state, Paused, Pausing));
wxASSERT(previousState == Pausing);
}
// Loop until the resuming state is set.
while ((state = AtomicGetState()) == Paused)
{
wxThread::Yield();
}
// If we're resuming, set the active state, and verify that the
// main thread's sync loop did its job by waiting.
if (state == Resuming)
{
const State previousState = State(LfnTech::Atomic<>::CompareExchange(&m_state, Active, Resuming));
wxASSERT(previousState == Resuming);
}
}
}
return 0;
}
bool LfnIc::EnergyCalculatorPerPixel::WorkerThread::IsPaused() const
{
return wxThread::IsPaused();
}
void LfnIc::EnergyCalculatorPerPixel::WorkerThread::ResumeAndStartProcessingCalculations()
{
wxASSERT(IsPaused());
const State previousState = State(LfnTech::Atomic<>::CompareExchange(&m_state, Resuming, Paused));
wxASSERT(previousState == Paused);
wxThread::Resume();
// No need to wait until thread sets state to active;
// FinishProcessingCalculationsAndPause() handles all synchronization.
}
void LfnIc::EnergyCalculatorPerPixel::WorkerThread::FinishProcessingCalculationsAndPause()
{
wxASSERT(!IsPaused());
// Sync: loop until state is Active, which is required to set the Pausing
// state. This is done in case ResumeAndStartProcessingCalculations()
// was just called and the thread hasn't had a chance to wake up.
while (LfnTech::Atomic<>::CompareExchange(&m_state, Pausing, Active) != Active)
{
wxThread::Yield();
}
// Sync: loop until state is Paused, which won't happen until the thread
// has finished processing.
while (AtomicGetState() != Paused)
{
wxThread::Yield();
}
wxThread::Pause();
}
void LfnIc::EnergyCalculatorPerPixel::WorkerThread::ResumeAndQuit()
{
wxASSERT(IsPaused());
const State previousState = State(LfnTech::Atomic<>::CompareExchange(&m_state, Quitting, Paused));
wxASSERT(previousState == Paused);
wxThread::Resume();
// Joinable thread, wait for it to join.
Wait();
}
LfnIc::EnergyCalculatorPerPixel::WorkerThread::State LfnIc::EnergyCalculatorPerPixel::WorkerThread::AtomicGetState() const
{
// The exchange and comparand are dummies.
return State(LfnTech::Atomic<>::CompareExchange(&m_state, Invalid, Invalid));
}