File: vtkDataEncoder.cxx

package info (click to toggle)
vtk9 9.5.2%2Bdfsg4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 206,616 kB
  • sloc: cpp: 2,340,827; ansic: 327,116; python: 114,881; yacc: 4,104; java: 3,977; sh: 3,032; xml: 2,771; perl: 2,189; lex: 1,787; javascript: 1,261; makefile: 189; objc: 153; tcl: 59
file content (334 lines) | stat: -rw-r--r-- 9,585 bytes parent folder | download | duplicates (2)
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
// SPDX-FileCopyrightText: Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
// SPDX-License-Identifier: BSD-3-Clause
#include "vtkDataEncoder.h"

#include "vtkBase64Utilities.h"
#include "vtkCommand.h"
#include "vtkImageData.h"
#include "vtkJPEGWriter.h"
#include "vtkLogger.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkPNGWriter.h"
#include "vtkSmartPointer.h"
#include "vtkUnsignedCharArray.h"

#include <cassert>
#include <cmath>
#include <condition_variable>
#include <map>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>

#include <vtksys/SystemTools.hxx>

#define MAX_NUMBER_OF_THREADS_IN_POOL 32

namespace detail
{
VTK_ABI_NAMESPACE_BEGIN

struct vtkWork
{
  vtkSmartPointer<vtkImageData> Image;
  int Quality = 0;
  int Encoding = 0;
  vtkTypeUInt64 TimeStamp = 0;
  vtkTypeUInt32 Key = 0;

  vtkWork() = default;
  vtkWork(vtkTypeUInt32 key, vtkImageData* image, int quality, int encoding)
    : Image(image)
    , Quality(quality)
    , Encoding(encoding)
    , TimeStamp(0)
    , Key(key)
  {
  }
  vtkWork(const vtkWork&) = default;
  vtkWork& operator=(const vtkWork&) = default;
};

class vtkWorkQueue
{
  mutable std::mutex ResultsMutex;
  std::map<vtkTypeUInt32, std::pair<vtkTypeUInt64, vtkSmartPointer<vtkUnsignedCharArray>>> Results;
  std::condition_variable ResultsCondition;

  std::map<vtkTypeUInt32, std::atomic<vtkTypeUInt32>> LastTimeStamp;

  std::mutex QueueMutex;
  std::queue<vtkWork> Queue;
  std::condition_variable QueueCondition;

  std::vector<std::thread> ThreadPool;
  std::atomic<bool> Terminate;

  static void DoWork(int threadIndex, vtkWorkQueue* self)
  {
    vtkLogger::SetThreadName("Worker " + std::to_string(threadIndex));
    vtkLogF(TRACE, "starting worker thread");
    vtkNew<vtkJPEGWriter> writer;
    writer->WriteToMemoryOn();
    while (!self->Terminate)
    {
      vtkWork work;
      {
        std::unique_lock<std::mutex> lock(self->QueueMutex);
        bool break_loop = false;
        do
        {
          self->QueueCondition.wait_for(lock, std::chrono::seconds(1),
            [self]() { return !self->Queue.empty() || self->Terminate; });
          if (self->Terminate)
          {
            break_loop = true;
            break;
          }
        } while (self->Queue.empty());
        if (break_loop)
        {
          break;
        }
        work = self->Queue.front();
        self->Queue.pop();
      }

      writer->SetInputData(work.Image);
      writer->SetQuality(work.Quality);
      writer->Write();

      auto result = vtkSmartPointer<vtkUnsignedCharArray>::New();
      if (work.Encoding)
      {
        vtkUnsignedCharArray* data = writer->GetResult();
        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
      {
        // We must do a deep copy here as the writer reuse that array
        // and will change its values concurrently during its next job...
        result->DeepCopy(writer->GetResult());
      }
      writer->SetInputData(nullptr);

      {
        std::unique_lock<std::mutex> lock(self->ResultsMutex);
        auto& pair = self->Results[work.Key];
        if (pair.first < work.TimeStamp)
        {
          pair = std::make_pair(work.TimeStamp, result);
          lock.unlock();
          self->ResultsCondition.notify_all();
        }
      }
    }

    vtkLogF(TRACE, "exiting worker thread");
  }

public:
  vtkWorkQueue(int numThreads)
    : Terminate(false)
  {
    assert(numThreads >= 0);
    for (int cc = 0; cc < numThreads; ++cc)
    {
      this->ThreadPool.emplace_back(&vtkWorkQueue::DoWork, cc, this);
    }
  }
  ~vtkWorkQueue()
  {
    this->Terminate = true;
    this->QueueCondition.notify_all();
    for (auto& thread : this->ThreadPool)
    {
      thread.join();
    }
  }

  bool IsValid() const { return !this->ThreadPool.empty(); }

  void PushBack(vtkWork&& work)
  {
    if (!this->IsValid())
    {
      vtkLogF(ERROR, "Queue is invalid! Can't push work!");
      return;
    }

    auto key = work.Key;
    work.TimeStamp = ++this->LastTimeStamp[key];
    {
      std::unique_lock<std::mutex> lock(this->QueueMutex);
      this->Queue.emplace(std::move(work));
    }
    this->QueueCondition.notify_one();
  }

  bool GetResult(vtkTypeUInt32 key, vtkSmartPointer<vtkUnsignedCharArray>& data) const
  {
    std::unique_lock<std::mutex> lock(this->ResultsMutex);
    auto iter = this->Results.find(key);
    if (iter == this->Results.end())
    {
      return false;
    }

    const auto& resultsPair = iter->second;
    data = resultsPair.second;
    // return true if this is the latest result for this key.
    return (resultsPair.first == this->LastTimeStamp.at(key));
  }

  void Flush(vtkTypeUInt32 key)
  {
    auto tsIter = this->LastTimeStamp.find(key);
    if (tsIter == this->LastTimeStamp.end())
    {
      return;
    }
    const auto& ts = tsIter->second;
    std::unique_lock<std::mutex> lock(this->ResultsMutex);
    this->ResultsCondition.wait(lock,
      [this, &ts, &key]()
      {
        try
        {
          return ts == this->Results[key].first;
        }
        catch (std::out_of_range&)
        {
          // result not available yet; keep waiting;
          return false;
        }
      });
  }
};
VTK_ABI_NAMESPACE_END
} // namespace detail

VTK_ABI_NAMESPACE_BEGIN
//****************************************************************************
class vtkDataEncoder::vtkInternals
{
public:
  detail::vtkWorkQueue Queue;
  vtkNew<vtkUnsignedCharArray> LastBase64Image;

  vtkInternals(int numThreads)
    : Queue(numThreads)
  {
  }

  // 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()
  : MaxThreads(3)
  , Internals(new vtkInternals(this->MaxThreads))
{
}

//------------------------------------------------------------------------------
vtkDataEncoder::~vtkDataEncoder() = default;

//------------------------------------------------------------------------------
void vtkDataEncoder::SetMaxThreads(vtkTypeUInt32 maxThreads)
{
  if (maxThreads < MAX_NUMBER_OF_THREADS_IN_POOL && maxThreads > 0)
  {
    this->MaxThreads = maxThreads;
  }
}

//------------------------------------------------------------------------------
void vtkDataEncoder::Initialize()
{
  this->Internals.reset(new vtkDataEncoder::vtkInternals(this->MaxThreads));
}

//------------------------------------------------------------------------------
void vtkDataEncoder::Push(vtkTypeUInt32 key, vtkImageData* data, int quality, int encoding)
{
  auto& internals = (*this->Internals);
  internals.Queue.PushBack(detail::vtkWork(key, data, quality, encoding));
}

//------------------------------------------------------------------------------
bool vtkDataEncoder::GetLatestOutput(vtkTypeUInt32 key, vtkSmartPointer<vtkUnsignedCharArray>& data)
{
  auto& internals = (*this->Internals);
  return internals.Queue.GetResult(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)
{
  auto& internals = (*this->Internals);
  internals.Queue.Flush(key);
}

//------------------------------------------------------------------------------
void vtkDataEncoder::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}

//------------------------------------------------------------------------------
void vtkDataEncoder::Finalize()
{
  this->Internals.reset(new vtkDataEncoder::vtkInternals(0));
}
VTK_ABI_NAMESPACE_END