Debian Codegraph @

src/lib/BMIParser.cpp

raw symbols SCIP
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /*
3 * This file is a part of the libzmf project.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
9
10 #include "BMIParser.h"
11
12 #include <algorithm>
13 #include <cassert>
14 #include <iterator>
15 #include <memory>
16 #include <string>
17 #include <utility>
18 #include <vector>
19
20 #include <boost/optional.hpp>
21
22 #include <png.h>
23
24 #include <zlib.h>
25
26 #include "ZMFCollector.h"
27
28 using librevenge::RVNGBinaryData;
29
30 namespace libzmf
31 {
32
33 namespace
34 {
35
36 double px2in(unsigned px, double dpi = 72)
37 {
38 return px / dpi;
39 }
40
41 bool uncompress(const uint8_t *compressedData, unsigned size, std::vector<uint8_t> &uncompressedData)
42 {
43 int ret;
44 z_stream strm;
45
46 /* allocate inflate state */
47 strm.zalloc = Z_NULL;
48 strm.zfree = Z_NULL;
49 strm.opaque = Z_NULL;
50 strm.avail_in = 0;
51 strm.next_in = Z_NULL;
52 ret = inflateInit2(&strm, MAX_WBITS);
53 if (ret != Z_OK)
54 return false;
55
56 const unsigned long blockSize = (std::max)(4096u, 2 * size);
57
58 std::vector<uint8_t> data(blockSize);
59
60 strm.avail_in = size;
61 strm.next_in = (Bytef *)compressedData;
62 strm.next_out = &data[0];
63
64 bool done = false;
65 while (!done)
66 {
67 const std::ptrdiff_t nextOutIndex = strm.next_out - &data[0];
68 assert(nextOutIndex >= 0);
69 data.resize(data.size() + blockSize);
70 assert(data.size() > std::size_t(nextOutIndex));
71 strm.avail_out = unsigned(data.size() - std::size_t(nextOutIndex));
72 strm.next_out = reinterpret_cast<Bytef *>(&data[nextOutIndex]);
73
74 ret = inflate(&strm, Z_SYNC_FLUSH);
75
76 switch (ret)
77 {
78 case Z_OK:
79 break;
80 default:
81 // abandon partially uncompressed data on error
82 strm.total_out = 0;
83 ZMF_FALLTHROUGH;
84 case Z_STREAM_END:
85 done = true;
86 break;
87 }
88 }
89
90 (void)inflateEnd(&strm);
91
92 if (strm.total_out == 0)
93 return false;
94
95 std::move(data.begin(), std::next(data.begin(), strm.total_out), std::back_inserter(uncompressedData));
96
97 return true;
98 }
99
100 }
101
102 namespace
103 {
104
105 extern "C" void pngWriteCallback(png_structp png, png_bytep data, png_size_t length) try
106 {
107 auto p = reinterpret_cast<RVNGBinaryData *>(png_get_io_ptr(png));
108
109 p->append(data, length);
110 }
111 catch (...)
112 {
113 png_error(png, "pngWriteCallback exception");
114 }
115
116 extern "C" void pngFlushCallback(png_structp)
117 { }
118
119 extern "C" void pngErrorCallback(png_structp png, png_const_charp msg);
120
121 class PNGWriter
122 {
123 public:
124 struct Error
125 {
126 explicit Error(const std::string &msg)
127 : m_msg(msg)
128 {
129 }
130
131 const std::string &message() const
132 {
133 return m_msg;
134 }
135
136 private:
137 const std::string m_msg;
138 };
139
140 public:
141 PNGWriter(RVNGBinaryData &output, const ColorBitmap &bitmap, const ColorBitmap &transparencyBitmap);
142
143 void writeInfo();
144 void writeData();
145 void writeEnd();
146
147 void setError(const std::string &error);
148
149 private:
150 struct PNGInfoDeleter
151 {
152 PNGInfoDeleter(const std::shared_ptr<png_struct> &png)
153 : m_png(png)
154 {
155 }
156
157 void operator()(png_infop info) const
158 {
159 png_destroy_info_struct(m_png.get(), &info);
160 }
161
162 private:
163 std::shared_ptr<png_struct> m_png;
164 };
165
166 typedef std::unique_ptr<png_info, PNGInfoDeleter> PNGInfoPtr;
167
168 private:
169 std::shared_ptr<png_struct> createStruct();
170 PNGInfoPtr createInfo(const std::shared_ptr<png_struct> &png) const;
171
172 void writeRow();
173
174 bool hasTransparency() const;
175
176 private:
177 const ColorBitmap &m_bitmap;
178 const ColorBitmap &m_transparencyBitmap;
179 std::unique_ptr<png_byte[]> m_row;
180 std::shared_ptr<png_struct> m_png;
181 PNGInfoPtr m_info;
182 std::string m_error;
183 };
184
185 PNGWriter::PNGWriter(RVNGBinaryData &output, const ColorBitmap &bitmap, const ColorBitmap &transparencyBitmap)
186 : m_bitmap(bitmap)
187 , m_transparencyBitmap(transparencyBitmap)
188 , m_row()
189 , m_png(createStruct())
190 , m_info(createInfo(m_png))
191 , m_error()
192 {
193 png_set_write_fn(m_png.get(), &output, pngWriteCallback, pngFlushCallback);
194 png_set_IHDR(m_png.get(), m_info.get(), bitmap.width, bitmap.height,
195 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
196 PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
197
198 m_row.reset(new png_byte[4 * m_bitmap.width]);
199 }
200
201 std::shared_ptr<png_struct> PNGWriter::createStruct()
202 {
203 const std::shared_ptr<png_struct> png(
204 png_create_write_struct(PNG_LIBPNG_VER_STRING, this, pngErrorCallback, nullptr),
205 [](png_structp p)
206 {
207 png_destroy_write_struct(&p, nullptr);
208 });
209 if (!png)
210 throw Error("Could not allocate png_struct");
211 return png;
212 }
213
214 PNGWriter::PNGInfoPtr PNGWriter::createInfo(const std::shared_ptr<png_struct> &png) const
215 {
216 PNGInfoPtr info(png_create_info_struct(png.get()), PNGInfoDeleter(png));
217 if (!info)
218 throw Error("Could not allocate png_info");
219 return info;
220 }
221
222 void PNGWriter::writeInfo()
223 {
224 if (setjmp(png_jmpbuf(m_png.get())))
225 throw Error(m_error);
226 png_write_info(m_png.get(), m_info.get());
227 }
228
229 void PNGWriter::writeData()
230 {
231 const png_bytep row = m_row.get();
232
233 for (unsigned r = 0; r < m_bitmap.height; r++)
234 {
235 size_t rowByteInd = 0;
236
237 for (unsigned c = 0; c < m_bitmap.width; c++)
238 {
239 size_t ind = r * m_bitmap.width + c;
240 const Color &color = m_bitmap.data[ind];
241
242 row[rowByteInd++] = color.red;
243 row[rowByteInd++] = color.green;
244 row[rowByteInd++] = color.blue;
245 row[rowByteInd++] = (hasTransparency() && m_transparencyBitmap.data[ind].red != 0) ? 0 : 255;
246 }
247
248 writeRow();
249 }
250 }
251
252 void PNGWriter::writeEnd()
253 {
254 if (setjmp(png_jmpbuf(m_png.get())))
255 throw Error(m_error);
256 png_write_end(m_png.get(), nullptr);
257 }
258
259 void PNGWriter::setError(const std::string &error)
260 {
261 m_error = error;
262 }
263
264 void PNGWriter::writeRow()
265 {
266 if (setjmp(png_jmpbuf(m_png.get())))
267 throw Error(m_error);
268 png_write_row(m_png.get(), m_row.get());
269 }
270
271 bool PNGWriter::hasTransparency() const
272 {
273 return !m_transparencyBitmap.data.empty();
274 }
275
276 extern "C" void pngErrorCallback(png_structp png, png_const_charp msg)
277 {
278 try
279 {
280 PNGWriter *const writer = reinterpret_cast<PNGWriter *>(png_get_error_ptr(png));
281 assert(writer);
282 writer->setError(msg);
283 }
284 catch (...)
285 {
286 // Ignore. What else to do anyway?
287 }
288 longjmp(png_jmpbuf(png), -1);
289 }
290
291 bool makePng(RVNGBinaryData &output, const ColorBitmap &bitmap, const ColorBitmap &transparencyBitmap) try
292 {
293 PNGWriter writer(output, bitmap, transparencyBitmap);
294 writer.writeInfo();
295 writer.writeData();
296 writer.writeEnd();
297 return true;
298 }
299 catch (const PNGWriter::Error &error)
300 {
301 ZMF_DEBUG_MSG(("%s\n", error.message().c_str()));
302 return false;
303 }
304
305 }
306
307 struct BMIParser::ColorBitmapHeader
308 {
309 ColorBitmapHeader();
310
311 void parse(const RVNGInputStreamPtr &input, const BMIHeader &header, const BMIOffset &offset);
312
313 unsigned m_width;
314 unsigned m_height;
315 unsigned m_colorDepth;
316 unsigned m_startOffset;
317 unsigned m_endOffset;
318 };
319
320 BMIParser::ColorBitmapHeader::ColorBitmapHeader()
321 : m_width(0)
322 , m_height(0)
323 , m_colorDepth(0)
324 , m_startOffset(0)
325 , m_endOffset(0)
326 {
327 }
328
329 void BMIParser::ColorBitmapHeader::parse(const RVNGInputStreamPtr &input, const BMIHeader &header, const BMIOffset &offset)
330 {
331 seek(input, header.startOffset() + offset.start);
332 m_endOffset = header.startOffset() + offset.end;
333
334 m_width = readU16(input);
335 m_height = readU16(input);
336
337 const unsigned colorDepth = readU16(input);
338 if (colorDepth <= 1)
339 m_colorDepth = 1;
340 else if (colorDepth <= 4)
341 m_colorDepth = 4;
342 else if (colorDepth <= 8)
343 m_colorDepth = 8;
344 else
345 m_colorDepth = 24;
346
347 m_startOffset = unsigned(static_cast<unsigned long>(input->tell()) + 10);
348 }
349
350 BMIParser::BMIParser(const RVNGInputStreamPtr &input, librevenge::RVNGDrawingInterface *const painter)
351 : m_input(input)
352 , m_painter(painter)
353 , m_header()
354 {
355 }
356
357 bool BMIParser::parse()
358 {
359 auto bitmap = readImage();
360
361 if (bitmap.data.empty())
362 return false;
363
364 ZMFCollector collector(m_painter);
365
366 collector.startDocument();
367 collector.startPage(ZMFPageSettings(8.5, 11, 0, 0));
368 collector.startLayer();
369
370 collector.collectImage(bitmap.data, Point(0, 0), px2in(m_header.width()), px2in(m_header.height()), 0, false, false);
371
372 collector.endLayer();
373 collector.endPage();
374 collector.endDocument();
375
376 return true;
377 }
378
379 Image BMIParser::readImage()
380 {
381 if (!m_header.load(m_input) || !m_header.isSupported())
382 return Image();
383
384 boost::optional<ColorBitmapHeader> bitmapHeader;
385 boost::optional<ColorBitmapHeader> transparencyBitmapHeader;
386
387 for (const auto &offset : m_header.offsets())
388 {
389 if (offset.type == BMIStreamType::BITMAP)
390 {
391 if (!bitmapHeader)
392 {
393 bitmapHeader = ColorBitmapHeader();
394 bitmapHeader->parse(m_input, m_header, offset);
395 }
396 else if (!transparencyBitmapHeader)
397 {
398 transparencyBitmapHeader = ColorBitmapHeader();
399 transparencyBitmapHeader->parse(m_input, m_header, offset);
400 }
401 }
402 }
403
404 if (!bitmapHeader)
405 return Image();
406
407 if (transparencyBitmapHeader)
408 {
409 if (!reconcileDimensions(get(bitmapHeader), get(transparencyBitmapHeader)))
410 return Image();
411 }
412
413 ColorBitmap bitmap = readColorBitmap(get(bitmapHeader));
414 ColorBitmap transparencyBitmap;
415 if (transparencyBitmapHeader)
416 transparencyBitmap = readColorBitmap(get(transparencyBitmapHeader));
417
418 if (bitmap.width == 0 || bitmap.height == 0)
419 return Image();
420
421 Image result;
422 result.width = bitmap.width;
423 result.height = bitmap.height;
424 if (makePng(result.data, bitmap, transparencyBitmap))
425 {
426 return result;
427 }
428
429 return Image();
430 }
431
432 const BMIHeader &BMIParser::header() const
433 {
434 return m_header;
435 }
436
437 ColorBitmap BMIParser::readColorBitmap(const BMIParser::ColorBitmapHeader &hdr)
438 {
439 ColorBitmap bitmap;
440
441 bitmap.width = hdr.m_width;
442 bitmap.height = hdr.m_height;
443
444 seek(m_input, hdr.m_startOffset);
445
446 std::vector<Color> colorPalette;
447 if (hdr.m_colorDepth < 24)
448 {
449 colorPalette = readColorPalette(hdr.m_colorDepth);
450 }
451
452 auto data = readData(hdr.m_endOffset);
453
454 unsigned lineBitCount = bitmap.width * hdr.m_colorDepth;
455
456 unsigned lineWidth = lineBitCount / 8;
457 if (lineBitCount % 8 != 0)
458 lineWidth++;
459
460 unsigned padding = 0;
461 while ((lineWidth + padding) % 4 != 0)
462 padding++;
463
464 lineWidth += padding;
465
466 unsigned shift = 8 - std::min<uint16_t>(hdr.m_colorDepth, 8);
467 unsigned mask = (0xff >> shift) << shift;
468
469 if (data.size() < bitmap.height * lineWidth)
470 return ColorBitmap();
471
472 bitmap.data.reserve(bitmap.width * bitmap.height);
473
474 unsigned i = 0;
475
476 for (unsigned row = 0; row < bitmap.height; row++)
477 {
478 unsigned col = 0;
479
480 while (col < bitmap.width)
481 {
482 if (hdr.m_colorDepth == 24)
483 {
484 Color color;
485 color.blue = data[i++];
486 color.green = data[i++];
487 color.red = data[i++];
488
489 bitmap.data.push_back(color);
490
491 col++;
492 }
493 else
494 {
495 uint8_t indexes = data[i++];
496 for (unsigned j = 0; j < 8 / hdr.m_colorDepth; j++)
497 {
498 uint8_t index = (indexes & mask) >> shift;
499
500 bitmap.data.push_back(colorPalette[index]);
501
502 indexes = indexes << hdr.m_colorDepth;
503
504 col++;
505 if (col == bitmap.width)
506 break;
507 }
508 }
509 }
510
511 i += padding;
512 }
513
514 return bitmap;
515 }
516
517 std::vector<uint8_t> BMIParser::readData(unsigned endOffset)
518 {
519 std::vector<uint8_t> data;
520
521 while (m_input->tell() < endOffset)
522 {
523 auto blockSize = readU16(m_input);
524
525 skip(m_input, 1);
526
527 auto compressedBlock = readNBytes(m_input, blockSize);
528
529 if (!uncompress(compressedBlock, blockSize, data))
530 {
531 data.clear();
532 break;
533 }
534 }
535
536 return data;
537 }
538
539 std::vector<Color> BMIParser::readColorPalette(unsigned colorDepth)
540 {
541 unsigned colorCount = 1 << colorDepth;
542
543 std::vector<Color> colors(colorCount);
544 for (auto &color : colors)
545 {
546 color.blue = readU8(m_input);
547 color.green = readU8(m_input);
548 color.red = readU8(m_input);
549 skip(m_input, 1);
550 }
551
552 return colors;
553 }
554
555 bool BMIParser::reconcileDimensions(BMIParser::ColorBitmapHeader &colorHeader, BMIParser::ColorBitmapHeader &transparencyHeader)
556 {
557 return m_header.reconcileWidth(colorHeader.m_width, transparencyHeader.m_width)
558 && m_header.reconcileHeight(colorHeader.m_height, transparencyHeader.m_height);
559 }
560
561 }
562
563 /* vim:set shiftwidth=2 softtabstop=2 expandtab: */