forked from Kitware/VTK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vtkDataEncoder.cxx
547 lines (475 loc) · 17 KB
/
vtkDataEncoder.cxx
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
/*=========================================================================
Program: Visualization Toolkit
Module: vtkDataEncoder.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkDataEncoder.h"
#include "vtkBase64Utilities.h"
#include "vtkCommand.h"
#include "vtkConditionVariable.h"
#include "vtkImageData.h"
#include "vtkJPEGWriter.h"
#include "vtkPNGWriter.h"
#include "vtkMultiThreader.h"
#include "vtkMutexLock.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkUnsignedCharArray.h"
#include <cassert>
#include <cmath>
#include <map>
#include <vector>
#include <vtksys/SystemTools.hxx>
#define MAX_NUMBER_OF_THREADS_IN_POOL 32
//****************************************************************************
namespace
{
class vtkSharedData
{
public:
struct OutputValueType
{
public:
vtkTypeUInt32 TimeStamp;
vtkSmartPointer<vtkUnsignedCharArray> Data;
OutputValueType() : TimeStamp(0), Data(nullptr)
{
}
};
enum
{
ENCODING_NONE = 0,
ENCODING_BASE64 = 1
};
struct InputValueType
{
public:
vtkTypeUInt32 OutputStamp;
vtkSmartPointer<vtkImageData> Image;
int Quality;
int Encoding;
InputValueType() : OutputStamp(0), Image(nullptr), Quality(100), Encoding(ENCODING_BASE64)
{
}
};
typedef std::map<vtkTypeUInt32, InputValueType > InputMapType;
typedef std::map<vtkTypeUInt32, OutputValueType> OutputMapType;
private:
bool Done;
vtkSimpleMutexLock DoneLock;
vtkSimpleMutexLock OutputsLock;
vtkSimpleConditionVariable OutputsAvailable;
vtkSimpleMutexLock ThreadDoneLock;
vtkSimpleConditionVariable ThreadDone;
int ActiveThreadCount;
//------------------------------------------------------------------------
// OutputsLock must be held before accessing any of the following members.
OutputMapType Outputs;
//------------------------------------------------------------------------
// Constructs used to synchronization.
vtkSimpleMutexLock InputsLock;
vtkSimpleConditionVariable InputsAvailable;
//------------------------------------------------------------------------
// InputsLock must be held before accessing any of the following members.
InputMapType Inputs;
public:
//------------------------------------------------------------------------
vtkSharedData() : Done(false), ActiveThreadCount(0)
{
}
//------------------------------------------------------------------------
// Each thread should call this method when it starts. It helps us clean up
// threads when they are done.
void BeginWorker()
{
this->ThreadDoneLock.Lock();
this->ActiveThreadCount++;
this->ThreadDoneLock.Unlock();
}
//------------------------------------------------------------------------
// Each thread should call this method when it ends.
void EndWorker()
{
this->ThreadDoneLock.Lock();
this->ActiveThreadCount--;
bool last_thread = (this->ActiveThreadCount == 0);
this->ThreadDoneLock.Unlock();
if (last_thread)
{
this->ThreadDone.Signal();
}
}
//------------------------------------------------------------------------
void RequestAndWaitForWorkersToEnd()
{
// Get the done lock so we other threads don't end up testing the Done
// flag and quitting before this thread starts to wait for them to quit.
this->DoneLock.Lock();
this->Done = true;
// Grab the ThreadDoneLock. so even if any thread ends up check this->Done
// as soon as we release the lock, it won't get a chance to terminate.
this->ThreadDoneLock.Lock();
// release the done lock. Let threads test for this->Done flag.
this->DoneLock.Unlock();
// Tell all workers that inputs are available, so they will try to check
// the input as well as the done flag.
this->InputsAvailable.Broadcast();
// Now wait for thread to terminate releasing this->ThreadDoneLock as soon
// as we start waiting. Thus, no threads have got a chance to call
// EndWorker() till the main thread starts waiting for them.
this->ThreadDone.Wait(this->ThreadDoneLock);
this->ThreadDoneLock.Unlock();
// reset Done flag since all threads have died.
this->Done = false;
}
//------------------------------------------------------------------------
bool IsDone()
{
this->DoneLock.Lock();
bool val = this->Done;
this->DoneLock.Unlock();
return val;
}
//------------------------------------------------------------------------
void PushAndTakeReference(vtkTypeUInt32 key, vtkImageData* &data,
vtkTypeUInt64 stamp, int quality, int encoding)
{
this->InputsLock.Lock();
{
vtkSharedData::InputValueType &value = this->Inputs[key];
value.Image.TakeReference(data);
value.OutputStamp = stamp;
value.Quality = quality;
value.Encoding = encoding;
data = nullptr;
}
this->InputsLock.Unlock();
this->InputsAvailable.Signal();
}
//------------------------------------------------------------------------
vtkTypeUInt64 GetExpectedOutputStamp(vtkTypeUInt32 key)
{
vtkTypeUInt64 stamp = 0;
this->InputsLock.Lock();
vtkSharedData::InputMapType::iterator iter = this->Inputs.find(key);
if (iter != this->Inputs.end())
{
stamp = iter->second.OutputStamp;
}
this->InputsLock.Unlock();
return stamp;
}
//------------------------------------------------------------------------
// NOTE: This method may suspend the calling thread until inputs become
// available.
vtkTypeUInt64 GetNextInputToProcess(vtkTypeUInt32& key,
vtkSmartPointer<vtkImageData>& image, int& quality, int& encoding)
{
vtkTypeUInt32 stamp = 0;
this->InputsLock.Lock();
do
{
// Check if we have an input available, if so, return it.
InputMapType::iterator iter;
for (iter = this->Inputs.begin(); iter != this->Inputs.end(); ++iter)
{
if (iter->second.Image != nullptr)
{
key = iter->first;
image = iter->second.Image;
iter->second.Image = nullptr;
stamp = iter->second.OutputStamp;
quality = iter->second.Quality;
encoding = iter->second.Encoding;
break;
}
}
if (image == nullptr && !this->IsDone())
{
// No data is available, let's wait till it becomes available.
this->InputsAvailable.Wait(this->InputsLock);
}
} while (image == nullptr && !this->IsDone());
this->InputsLock.Unlock();
return stamp;
}
//------------------------------------------------------------------------
void SetOutputReference(const vtkTypeUInt32 &key,
vtkTypeUInt64 timestamp, vtkUnsignedCharArray* &dataRef)
{
this->OutputsLock.Lock();
assert(dataRef->GetReferenceCount() == 1);
OutputMapType::iterator iter = this->Outputs.find(key);
if (iter == this->Outputs.end() ||
iter->second.Data == nullptr ||
iter->second.TimeStamp < timestamp)
{
//cout << "Done: " <<
// vtkMultiThreader::GetCurrentThreadID() << " "
// << key << ", " << timestamp << endl;
this->Outputs[key].TimeStamp = timestamp;
this->Outputs[key].Data.TakeReference(dataRef);
dataRef = nullptr;
}
else
{
dataRef->Delete();
dataRef = nullptr;
}
this->OutputsLock.Unlock();
this->OutputsAvailable.Broadcast();
}
//------------------------------------------------------------------------
bool CopyLatestOutputIfDifferent(
vtkTypeUInt32 key, vtkUnsignedCharArray* data)
{
vtkTypeUInt64 dataTimeStamp = 0;
this->OutputsLock.Lock();
{
const vtkSharedData::OutputValueType &output = this->Outputs[key];
if (output.Data != nullptr &&
(output.Data->GetMTime() > data->GetMTime() ||
output.Data->GetNumberOfTuples() != data->GetNumberOfTuples()))
{
data->DeepCopy(output.Data);
data->Modified();
}
dataTimeStamp = output.TimeStamp;
}
this->OutputsLock.Unlock();
vtkTypeUInt64 outputTS = 0;
this->InputsLock.Lock();
vtkSharedData::InputMapType::iterator iter = this->Inputs.find(key);
if (iter != this->Inputs.end())
{
outputTS = iter->second.OutputStamp;
}
this->InputsLock.Unlock();
return (dataTimeStamp >= outputTS);
}
//------------------------------------------------------------------------
void Flush(vtkTypeUInt32 key, vtkTypeUInt64 timestamp)
{
this->OutputsLock.Lock();
while (this->Outputs[key].TimeStamp < timestamp)
{
// output is not yet ready, we have to wait.
this->OutputsAvailable.Wait(this->OutputsLock);
}
this->OutputsLock.Unlock();
}
};
VTK_THREAD_RETURN_TYPE Worker(void *calldata)
{
//cout << "Start Thread: " << vtkMultiThreader::GetCurrentThreadID() << endl;
vtkMultiThreader::ThreadInfo* info =
reinterpret_cast<vtkMultiThreader::ThreadInfo*>(calldata);
vtkSharedData* sharedData = reinterpret_cast<vtkSharedData*>(info->UserData);
sharedData->BeginWorker();
while (true)
{
vtkTypeUInt32 key = 0;
vtkSmartPointer<vtkImageData> image;
vtkTypeUInt64 timestamp = 0;
// these are defaults, reset by GetNextInputToProcess
int quality = 100;
int encoding = 1;
timestamp = sharedData->GetNextInputToProcess(key, image, quality, encoding);
if (timestamp == 0 || image == nullptr)
{
// end thread.
break;
}
//cout << "Working Thread: " << vtkMultiThreader::GetCurrentThreadID() << endl;
// Do the encoding.
vtkNew<vtkJPEGWriter> writer;
writer->WriteToMemoryOn();
writer->SetInputData(image);
writer->SetQuality(quality);
writer->Write();
vtkUnsignedCharArray* data = writer->GetResult();
vtkUnsignedCharArray* result = vtkUnsignedCharArray::New();
if (encoding) {
result->SetNumberOfComponents(1);
result->SetNumberOfTuples(std::ceil(1.5 * data->GetNumberOfTuples()));
unsigned long size = vtkBase64Utilities::Encode(
data->GetPointer(0),
data->GetNumberOfTuples(),
result->GetPointer(0), /*mark_end=*/ 0);
result->SetNumberOfTuples(static_cast<vtkIdType>(size)+1);
result->SetValue(size, 0);
}
else
{
result->ShallowCopy(data);
}
// Pass over the "result" reference.
sharedData->SetOutputReference(key, timestamp, result);
assert(result == nullptr);
}
//cout << "Closing Thread: " << vtkMultiThreader::GetCurrentThreadID() << endl;
sharedData->EndWorker();
return VTK_THREAD_RETURN_VALUE;
}
}
//****************************************************************************
class vtkDataEncoder::vtkInternals
{
private:
std::map<vtkTypeUInt32, vtkSmartPointer<vtkUnsignedCharArray> > ClonedOutputs;
std::vector<int> RunningThreadIds;
public:
vtkNew<vtkMultiThreader> Threader;
vtkSharedData SharedData;
vtkTypeUInt64 Counter;
vtkSmartPointer<vtkUnsignedCharArray> lastBase64Image;
vtkInternals() : Counter(0)
{
lastBase64Image = vtkSmartPointer<vtkUnsignedCharArray>::New();
}
void TerminateAllWorkers()
{
// request and wait for all threads to close.
if (!this->RunningThreadIds.empty())
{
this->SharedData.RequestAndWaitForWorkersToEnd();
}
// Stop threads
while (!this->RunningThreadIds.empty())
{
this->Threader->TerminateThread(this->RunningThreadIds.back());
this->RunningThreadIds.pop_back();
}
}
void SpawnWorkers(vtkTypeUInt32 numberOfThreads)
{
for (vtkTypeUInt32 cc=0; cc < numberOfThreads; cc++)
{
this->RunningThreadIds.push_back(this->Threader->SpawnThread(&Worker, &this->SharedData));
}
}
// Since changes to vtkObjectBase::ReferenceCount are not thread safe, we have
// this level of indirection between the outputs stored in SharedData and
// passed back to the user/main thread.
bool GetLatestOutput(
vtkTypeUInt32 key, vtkSmartPointer<vtkUnsignedCharArray>& data)
{
vtkSmartPointer<vtkUnsignedCharArray>& output = this->ClonedOutputs[key];
if (!output)
{
output = vtkSmartPointer<vtkUnsignedCharArray>::New();
}
data = output;
return this->SharedData.CopyLatestOutputIfDifferent(key, data);
}
// Once an imagedata has been written to memory as a jpg or png, this
// convenience function can encode that image as a Base64 string.
const char* GetBase64EncodedImage(vtkUnsignedCharArray* encodedInputImage)
{
this->lastBase64Image->SetNumberOfComponents(1);
this->lastBase64Image->SetNumberOfTuples(std::ceil(1.5 * encodedInputImage->GetNumberOfTuples()));
unsigned long size = vtkBase64Utilities::Encode(
encodedInputImage->GetPointer(0),
encodedInputImage->GetNumberOfTuples(),
this->lastBase64Image->GetPointer(0), /*mark_end=*/ 0);
this->lastBase64Image->SetNumberOfTuples(static_cast<vtkIdType>(size)+1);
this->lastBase64Image->SetValue(size, 0);
return reinterpret_cast<char*>(this->lastBase64Image->GetPointer(0));
}
};
vtkStandardNewMacro(vtkDataEncoder);
//----------------------------------------------------------------------------
vtkDataEncoder::vtkDataEncoder() :
Internals(new vtkInternals())
{
this->MaxThreads = 3;
this->Initialize();
}
//----------------------------------------------------------------------------
vtkDataEncoder::~vtkDataEncoder()
{
this->Internals->TerminateAllWorkers();
delete this->Internals;
this->Internals = nullptr;
}
//----------------------------------------------------------------------------
void vtkDataEncoder::SetMaxThreads(vtkTypeUInt32 maxThreads)
{
if (maxThreads < MAX_NUMBER_OF_THREADS_IN_POOL && maxThreads > 0)
{
this->MaxThreads = maxThreads;
}
}
//----------------------------------------------------------------------------
void vtkDataEncoder::Initialize()
{
this->Internals->TerminateAllWorkers();
this->Internals->SpawnWorkers(this->MaxThreads);
}
//----------------------------------------------------------------------------
void vtkDataEncoder::PushAndTakeReference(vtkTypeUInt32 key, vtkImageData* &data, int quality, int encoding)
{
// if data->ReferenceCount != 1, it means the caller thread is keep an extra
// reference and that's bad.
assert(data->GetReferenceCount() == 1);
this->Internals->SharedData.PushAndTakeReference(
key, data, ++this->Internals->Counter, quality, encoding);
assert(data == nullptr);
}
//----------------------------------------------------------------------------
bool vtkDataEncoder::GetLatestOutput(
vtkTypeUInt32 key, vtkSmartPointer<vtkUnsignedCharArray>& data)
{
return this->Internals->GetLatestOutput(key, data);
}
//----------------------------------------------------------------------------
const char* vtkDataEncoder::EncodeAsBase64Png(vtkImageData* img, int compressionLevel)
{
// Perform in-memory write of image as png
vtkNew<vtkPNGWriter> writer;
writer->WriteToMemoryOn();
writer->SetInputData(img);
writer->SetCompressionLevel(compressionLevel);
writer->Write();
// Return Base64-encoded string
return this->Internals->GetBase64EncodedImage(writer->GetResult());
}
//----------------------------------------------------------------------------
const char* vtkDataEncoder::EncodeAsBase64Jpg(vtkImageData* img, int quality)
{
// Perform in-memory write of image as jpg
vtkNew<vtkJPEGWriter> writer;
writer->WriteToMemoryOn();
writer->SetInputData(img);
writer->SetQuality(quality);
writer->Write();
// Return Base64-encoded string
return this->Internals->GetBase64EncodedImage(writer->GetResult());
}
//----------------------------------------------------------------------------
void vtkDataEncoder::Flush(vtkTypeUInt32 key)
{
vtkTypeUInt64 outputTS =
this->Internals->SharedData.GetExpectedOutputStamp(key);
if (outputTS != 0)
{
// Now wait till we see the outputTS in the output for key.
//cout << "Wait till : " << outputTS << endl;
this->Internals->SharedData.Flush(key, outputTS);
}
}
//----------------------------------------------------------------------------
void vtkDataEncoder::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
//----------------------------------------------------------------------------
void vtkDataEncoder::Finalize()
{
this->Internals->TerminateAllWorkers();
}