File: vtkJPEGWriter.cxx

package info (click to toggle)
paraview 5.13.2%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 544,220 kB
  • sloc: cpp: 3,374,605; ansic: 1,332,409; python: 150,381; xml: 122,166; sql: 65,887; sh: 7,317; javascript: 5,262; yacc: 4,417; java: 3,977; perl: 2,363; lex: 1,929; f90: 1,397; makefile: 170; objc: 153; tcl: 59; pascal: 50; fortran: 29
file content (357 lines) | stat: -rw-r--r-- 10,290 bytes parent folder | download | duplicates (3)
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
// SPDX-FileCopyrightText: Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
// SPDX-License-Identifier: BSD-3-Clause
#include "vtkJPEGWriter.h"

#include "vtkErrorCode.h"
#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkUnsignedCharArray.h"
#include <vtksys/SystemTools.hxx>

extern "C"
{
#include "vtk_jpeg.h"
#include <csetjmp>
}
VTK_ABI_NAMESPACE_BEGIN

vtkStandardNewMacro(vtkJPEGWriter);

vtkCxxSetObjectMacro(vtkJPEGWriter, Result, vtkUnsignedCharArray);

vtkJPEGWriter::vtkJPEGWriter()
{
  this->FileLowerLeft = 1;
  this->FileDimensionality = 2;

  this->Quality = 95;
  this->Progressive = 1;
  this->Result = nullptr;
  this->TempFP = nullptr;
}

vtkJPEGWriter::~vtkJPEGWriter()
{
  if (this->Result)
  {
    this->Result->Delete();
    this->Result = nullptr;
  }
}

//------------------------------------------------------------------------------
// Writes all the data from the input.
void vtkJPEGWriter::Write()
{
  this->SetErrorCode(vtkErrorCode::NoError);

  // Error checking
  if (this->GetInput() == nullptr)
  {
    vtkErrorMacro(<< "Write:Please specify an input!");
    return;
  }
  if (!this->WriteToMemory && !this->FileName && !this->FilePattern)
  {
    vtkErrorMacro(<< "Write:Please specify either a FileName or a file prefix and pattern");
    this->SetErrorCode(vtkErrorCode::NoFileNameError);
    return;
  }

  // Make sure the file name is allocated
  this->InternalFileNameSize = (this->FileName ? strlen(this->FileName) : 1) +
    (this->FilePrefix ? strlen(this->FilePrefix) : 1) +
    (this->FilePattern ? strlen(this->FilePattern) : 1) + 10;
  this->InternalFileName = new char[InternalFileNameSize];

  // Fill in image information.
  vtkDemandDrivenPipeline::SafeDownCast(this->GetInputExecutive(0, 0))->UpdateInformation();
  int* wExtent;
  wExtent = this->GetInputInformation(0, 0)->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT());
  this->FileNumber = wExtent[4];
  this->MinimumFileNumber = this->MaximumFileNumber = this->FileNumber;
  this->FilesDeleted = 0;
  this->UpdateProgress(0.0);
  // loop over the z axis and write the slices
  for (this->FileNumber = wExtent[4]; this->FileNumber <= wExtent[5]; ++this->FileNumber)
  {
    this->MaximumFileNumber = this->FileNumber;
    int uExtent[6];
    memcpy(uExtent, wExtent, 4 * sizeof(int));
    uExtent[4] = this->FileNumber;
    uExtent[5] = this->FileNumber;
    // determine the name
    if (this->FileName)
    {
      snprintf(this->InternalFileName, this->InternalFileNameSize, "%s", this->FileName);
    }
    else
    {
      if (this->FilePrefix)
      {
        snprintf(this->InternalFileName, this->InternalFileNameSize, this->FilePattern,
          this->FilePrefix, this->FileNumber);
      }
      else
      {
        snprintf(
          this->InternalFileName, this->InternalFileNameSize, this->FilePattern, this->FileNumber);
      }
    }
    this->GetInputAlgorithm()->UpdateExtent(uExtent);
    this->WriteSlice(this->GetInput(), uExtent);
    if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)
    {
      vtkErrorMacro("Ran out of disk space; deleting file(s) already written");
      this->DeleteFiles();
      return;
    }
    this->UpdateProgress((this->FileNumber - wExtent[4]) / (wExtent[5] - wExtent[4] + 1.0));
  }
  delete[] this->InternalFileName;
  this->InternalFileName = nullptr;
}
VTK_ABI_NAMESPACE_END

// these three routines are for writing into memory
extern "C"
{
  static void vtkJPEGWriteToMemoryInit(j_compress_ptr cinfo)
  {
    vtkJPEGWriter* self = vtkJPEGWriter::SafeDownCast(static_cast<vtkObject*>(cinfo->client_data));
    if (self)
    {
      vtkUnsignedCharArray* uc = self->GetResult();
      if (!uc || uc->GetReferenceCount() > 1)
      {
        uc = vtkUnsignedCharArray::New();
        self->SetResult(uc);
        uc->Delete();
        // start out with 10K as a guess for the image size
        uc->Allocate(10000);
      }
      cinfo->dest->next_output_byte = uc->GetPointer(0);
      cinfo->dest->free_in_buffer = uc->GetSize();
    }
  }
}

extern "C"
{
  static boolean vtkJPEGWriteToMemoryEmpty(j_compress_ptr cinfo)
  {
    // Even if (cinfo->dest->free_in_buffer != 0) we still need to write on the
    // new array and not at (arraySize - nbFree)
    vtkJPEGWriter* self = vtkJPEGWriter::SafeDownCast(static_cast<vtkObject*>(cinfo->client_data));
    if (self)
    {
      vtkUnsignedCharArray* uc = self->GetResult();
      // we must grow the array
      vtkIdType oldSize = uc->GetSize();
      uc->Resize(static_cast<vtkIdType>(oldSize + oldSize / 2));
      // Resize do grow the array but it is not the size we expect
      vtkIdType newSize = uc->GetSize();
      cinfo->dest->next_output_byte = uc->GetPointer(oldSize);
      cinfo->dest->free_in_buffer = static_cast<size_t>(newSize - oldSize);
    }
    return TRUE;
  }
}

extern "C"
{
  static void vtkJPEGWriteToMemoryTerm(j_compress_ptr cinfo)
  {
    vtkJPEGWriter* self = vtkJPEGWriter::SafeDownCast(static_cast<vtkObject*>(cinfo->client_data));
    if (self)
    {
      vtkUnsignedCharArray* uc = self->GetResult();
      // we must close the array
      vtkIdType realSize = uc->GetSize() - static_cast<vtkIdType>(cinfo->dest->free_in_buffer);
      uc->SetNumberOfTuples(realSize);
    }
  }
}

#if defined(_MSC_VER)
#if defined(_WIN64)
#pragma warning(disable : 4324) // structure was padded at end...
#endif
#endif

VTK_ABI_NAMESPACE_BEGIN

struct VTK_JPEG_ERROR_MANAGER
{
  struct jpeg_error_mgr pub;
  jmp_buf setjmp_buffer;
};

typedef struct VTK_JPEG_ERROR_MANAGER* VTK_JPEG_ERROR_PTR;
VTK_ABI_NAMESPACE_END

namespace
{
/* The JPEG library does not expect the error function to return.
   Therefore we must use this ugly longjmp call.  */
void VTK_JPEG_ERROR_EXIT(j_common_ptr cinfo)
{
  VTK_JPEG_ERROR_PTR jpegErr = reinterpret_cast<VTK_JPEG_ERROR_PTR>(cinfo->err);
  longjmp(jpegErr->setjmp_buffer, 1);
}
}

VTK_ABI_NAMESPACE_BEGIN
// we disable this warning because even though this is a C++ file, between
// the setjmp and resulting longjmp there should not be any C++ constructors
// or destructors.
#if defined(_MSC_VER) && !defined(VTK_DISPLAY_WIN32_WARNINGS)
#pragma warning(disable : 4611)
#endif
void vtkJPEGWriter::WriteSlice(vtkImageData* data, int* uExtent)
{
  // Call the correct templated function for the output
  unsigned int ui;

  // Call the correct templated function for the input
  if (data->GetScalarType() != VTK_UNSIGNED_CHAR)
  {
    vtkWarningMacro("JPEGWriter only supports unsigned char input");
    return;
  }

  if (data->GetNumberOfScalarComponents() > MAX_COMPONENTS)
  {
    vtkErrorMacro("Exceed JPEG limits for number of components ("
      << data->GetNumberOfScalarComponents() << " > " << MAX_COMPONENTS << ")");
    return;
  }

  // overriding jpeg_error_mgr so we don't exit when an error happens

  // Create the jpeg compression object and error handler
  struct jpeg_compress_struct cinfo;
  struct VTK_JPEG_ERROR_MANAGER jerr;
  this->TempFP = nullptr;
  if (!this->WriteToMemory)
  {
    this->TempFP = vtksys::SystemTools::Fopen(this->InternalFileName, "wb");
    if (!this->TempFP)
    {
      vtkErrorMacro("Unable to open file " << this->InternalFileName);
      this->SetErrorCode(vtkErrorCode::CannotOpenFileError);
      return;
    }
  }

  cinfo.err = jpeg_std_error(&jerr.pub);
  jerr.pub.error_exit = VTK_JPEG_ERROR_EXIT;
  if (setjmp(jerr.setjmp_buffer))
  {
    jpeg_destroy_compress(&cinfo);
    if (!this->WriteToMemory)
    {
      fclose(this->TempFP);
    }
    this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);
    return;
  }

  jpeg_create_compress(&cinfo);

  // set the destination file
  struct jpeg_destination_mgr compressionDestination;
  if (this->WriteToMemory)
  {
    // setup the compress structure to write to memory
    compressionDestination.init_destination = vtkJPEGWriteToMemoryInit;
    compressionDestination.empty_output_buffer = vtkJPEGWriteToMemoryEmpty;
    compressionDestination.term_destination = vtkJPEGWriteToMemoryTerm;
    cinfo.dest = &compressionDestination;
    cinfo.client_data = static_cast<void*>(this);
  }
  else
  {
    jpeg_stdio_dest(&cinfo, this->TempFP);
  }

  // set the information about image
  unsigned int width, height;
  width = uExtent[1] - uExtent[0] + 1;
  height = uExtent[3] - uExtent[2] + 1;

  cinfo.image_width = width; /* image width and height, in pixels */
  cinfo.image_height = height;

  cinfo.input_components = data->GetNumberOfScalarComponents();
  switch (cinfo.input_components)
  {
    case 1:
      cinfo.in_color_space = JCS_GRAYSCALE;
      break;
    case 3:
      cinfo.in_color_space = JCS_RGB;
      break;
    default:
      cinfo.in_color_space = JCS_UNKNOWN;
      break;
  }

  // set the compression parameters
  jpeg_set_defaults(&cinfo); // start with reasonable defaults
  jpeg_set_quality(&cinfo, this->Quality, TRUE);
  if (this->Progressive)
  {
    jpeg_simple_progression(&cinfo);
  }

  // start compression
  jpeg_start_compress(&cinfo, TRUE);

  // write the data. in jpeg, the first row is the top row of the image
  void* outPtr;
  outPtr = data->GetScalarPointer(uExtent[0], uExtent[2], uExtent[4]);
  JSAMPROW* row_pointers = new JSAMPROW[height];
  vtkIdType* outInc = data->GetIncrements();
  vtkIdType rowInc = outInc[1];
  for (ui = 0; ui < height; ui++)
  {
    row_pointers[height - ui - 1] = (JSAMPROW)outPtr;
    outPtr = (unsigned char*)outPtr + rowInc;
  }
  jpeg_write_scanlines(&cinfo, row_pointers, height);

  if (!this->WriteToMemory)
  {
    if (fflush(this->TempFP) == EOF)
    {
      this->ErrorCode = vtkErrorCode::OutOfDiskSpaceError;
      fclose(this->TempFP);
      return;
    }
  }

  // finish the compression
  jpeg_finish_compress(&cinfo);

  // clean up and close the file
  delete[] row_pointers;
  jpeg_destroy_compress(&cinfo);

  if (!this->WriteToMemory)
  {
    fclose(this->TempFP);
  }
}

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

  os << indent << "Quality: " << this->Quality << "\n";
  os << indent << "Progressive: " << (this->Progressive ? "On" : "Off") << "\n";
  os << indent << "Result: " << this->Result << "\n";
}
VTK_ABI_NAMESPACE_END