Debian Codegraph @

vcl/skia/salbmp.cxx

raw symbols SCIP
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice 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 * This file incorporates work covered by the following license notice:
10 *
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18 */
19
20 #include <skia/salbmp.hxx>
21
22 #include <o3tl/safeint.hxx>
23 #include <tools/helpers.hxx>
24 #include <boost/smart_ptr/make_shared.hpp>
25
26 #include <salgdi.hxx>
27 #include <salinst.hxx>
28 #include <scanlinewriter.hxx>
29 #include <svdata.hxx>
30 #include <bitmap/bmpfast.hxx>
31 #include <vcl/BitmapReadAccess.hxx>
32
33 #include <skia/utils.hxx>
34 #include <skia/zone.hxx>
35
36 #include <SkBitmap.h>
37 #include <SkCanvas.h>
38 #include <SkImage.h>
39 #include <SkPixelRef.h>
40 #include <SkShader.h>
41 #include <SkSurface.h>
42 #include <SkSwizzle.h>
43 #include <SkColorFilter.h>
44 #include <SkColorMatrix.h>
45 #include <skia_opts.hxx>
46
47 #ifdef DBG_UTIL
48 #include <fstream>
49 #define CANARY "skia-canary"
50 #endif
51
52 using namespace SkiaHelper;
53
54 // As constexpr here, evaluating it directly in code makes Clang warn about unreachable code.
55 constexpr bool kN32_SkColorTypeIsBGRA = (kN32_SkColorType == kBGRA_8888_SkColorType);
56
57 SkiaSalBitmap::SkiaSalBitmap() {}
58
59 SkiaSalBitmap::~SkiaSalBitmap() {}
60
61 SkiaSalBitmap::SkiaSalBitmap(const sk_sp<SkImage>& image, bool bWithoutAlpha)
62 {
63 ResetAllData();
64 mImage = image;
65 mPalette = BitmapPalette();
66 mBitCount = 32;
67 m_bWithoutAlpha = bWithoutAlpha;
68 mSize = mPixelsSize = Size(image->width(), image->height());
69 ComputeScanlineSize();
70 mReadAccessCount = 0;
71 #ifdef DBG_UTIL
72 mWriteAccessCount = 0;
73 #endif
74 SAL_INFO("vcl.skia.trace", "bitmapfromimage(" << this << ")");
75 }
76
77 bool SkiaSalBitmap::Create(const Size& rSize, vcl::PixelFormat ePixelFormat,
78 const BitmapPalette& rPal)
79 {
80 assert(mReadAccessCount == 0);
81 ResetAllData();
82 if (ePixelFormat == vcl::PixelFormat::INVALID)
83 return false;
84 mPalette = rPal;
85 mBitCount = vcl::pixelFormatBitCount(ePixelFormat);
86 mSize = rSize;
87 ResetPendingScaling();
88 if (!ComputeScanlineSize())
89 {
90 mBitCount = 0;
91 mSize = mPixelsSize = Size();
92 mScanlineSize = 0;
93 mPalette = BitmapPalette();
94 return false;
95 }
96 SAL_INFO("vcl.skia.trace", "create(" << this << ")");
97 return true;
98 }
99
100 bool SkiaSalBitmap::ComputeScanlineSize()
101 {
102 int bitScanlineWidth;
103 if (o3tl::checked_multiply<int>(mPixelsSize.Width(), mBitCount, bitScanlineWidth))
104 {
105 SAL_WARN("vcl.skia", "checked multiply failed");
106 return false;
107 }
108 mScanlineSize = AlignedWidth4Bytes(bitScanlineWidth);
109 return true;
110 }
111
112 void SkiaSalBitmap::CreateBitmapData()
113 {
114 assert(!mBuffer);
115 // Make sure code has not missed calling ComputeScanlineSize().
116 assert(mScanlineSize == int(AlignedWidth4Bytes(mPixelsSize.Width() * mBitCount)));
117 // The pixels could be stored in SkBitmap, but Skia only supports 8bit gray, 16bit and 32bit formats
118 // (e.g. 24bpp is actually stored as 32bpp). But some of our code accessing the bitmap assumes that
119 // when it asked for 24bpp, the format really will be 24bpp (e.g. the png loader), so we cannot use
120 // SkBitmap to store the data. And even 8bpp is problematic, since Skia does not support palettes
121 // and a VCL bitmap can change its grayscale status simply by changing the palette.
122 // Moreover creating SkImage from SkBitmap does a data copy unless the bitmap is immutable.
123 // So just always store pixels in our buffer and convert as necessary.
124 if (mScanlineSize == 0 || mPixelsSize.Height() == 0)
125 return;
126
127 size_t allocate = mScanlineSize * mPixelsSize.Height();
128 #ifdef DBG_UTIL
129 allocate += sizeof(CANARY);
130 #endif
131 mBuffer = boost::make_shared_noinit<sal_uInt8[]>(allocate);
132 #ifdef DBG_UTIL
133 // fill with random garbage
134 sal_uInt8* buffer = mBuffer.get();
135 for (size_t i = 0; i < allocate; i++)
136 buffer[i] = (i & 0xFF);
137 memcpy(buffer + allocate - sizeof(CANARY), CANARY, sizeof(CANARY));
138 #endif
139 }
140
141 bool SkiaSalBitmap::Create(const SalBitmap& rSalBmp)
142 {
143 assert(mReadAccessCount == 0);
144 assert(&rSalBmp != this);
145 ResetAllData();
146 const SkiaSalBitmap& src = static_cast<const SkiaSalBitmap&>(rSalBmp);
147 mImage = src.mImage;
148 mImageImmutable = src.mImageImmutable;
149 mAlphaImage = src.mAlphaImage;
150 mBuffer = src.mBuffer;
151 mPalette = src.mPalette;
152 mBitCount = src.mBitCount;
153 mSize = src.mSize;
154 mPixelsSize = src.mPixelsSize;
155 mScanlineSize = src.mScanlineSize;
156 mScaleQuality = src.mScaleQuality;
157 mEraseColorSet = src.mEraseColorSet;
158 mEraseColor = src.mEraseColor;
159 SAL_INFO("vcl.skia.trace", "create(" << this << "): (" << &src << ")");
160 return true;
161 }
162
163 bool SkiaSalBitmap::Create(const SalBitmap& rSalBmp, [[maybe_unused]] SalGraphics& rGraphics)
164 {
165 const SkiaSalBitmap& src = static_cast<const SkiaSalBitmap&>(rSalBmp);
166 assert(mReadAccessCount == 0);
167 assert(&rSalBmp != this);
168 assert(rGraphics.GetBitCount() == src.mBitCount);
169 ResetAllData();
170 mImage = src.mImage;
171 mImageImmutable = src.mImageImmutable;
172 mAlphaImage = src.mAlphaImage;
173 mBuffer = src.mBuffer;
174 mPalette = src.mPalette;
175 mBitCount = src.mBitCount;
176 mSize = src.mSize;
177 mPixelsSize = src.mPixelsSize;
178 mScanlineSize = src.mScanlineSize;
179 mScaleQuality = src.mScaleQuality;
180 mEraseColorSet = src.mEraseColorSet;
181 mEraseColor = src.mEraseColor;
182 SAL_INFO("vcl.skia.trace", "create(" << this << "): (" << &src << ")");
183 return true;
184 }
185
186 bool SkiaSalBitmap::Create(const css::uno::Reference<css::rendering::XBitmapCanvas>&, Size&)
187 {
188 return false;
189 }
190
191 void SkiaSalBitmap::Destroy()
192 {
193 SAL_INFO("vcl.skia.trace", "destroy(" << this << ")");
194 #ifdef DBG_UTIL
195 assert(mWriteAccessCount == 0);
196 #endif
197 assert(mReadAccessCount == 0);
198 ResetAllData();
199 }
200
201 Size SkiaSalBitmap::GetSize() const { return mSize; }
202
203 ScanlineFormat SkiaSalBitmap::GetScanlineFormat() const
204 {
205 switch (mBitCount)
206 {
207 case 8:
208 return ScanlineFormat::N8BitPal;
209 case 24:
210 // Make the RGB/BGR format match the default Skia 32bpp format, to allow
211 // easy conversion later.
212 return kN32_SkColorTypeIsBGRA ? ScanlineFormat::N24BitTcBgr
213 : ScanlineFormat::N24BitTcRgb;
214 case 32:
215 if (m_bWithoutAlpha)
216 {
217 return kN32_SkColorTypeIsBGRA ? ScanlineFormat::N32BitTcBgrx
218 : ScanlineFormat::N32BitTcRgbx;
219 }
220 else
221 {
222 return kN32_SkColorTypeIsBGRA ? ScanlineFormat::N32BitTcBgra
223 : ScanlineFormat::N32BitTcRgba;
224 }
225 default:
226 abort();
227 }
228 }
229
230 BitmapBuffer* SkiaSalBitmap::AcquireBuffer(BitmapAccessMode nMode)
231 {
232 switch (nMode)
233 {
234 case BitmapAccessMode::Write:
235 EnsureBitmapUniqueData();
236 if (!mBuffer)
237 return nullptr;
238 assert(mPixelsSize == mSize);
239 assert(!mEraseColorSet);
240 break;
241 case BitmapAccessMode::Read:
242 EnsureBitmapData();
243 if (!mBuffer)
244 return nullptr;
245 assert(mPixelsSize == mSize);
246 assert(!mEraseColorSet);
247 break;
248 case BitmapAccessMode::Info:
249 // Related tdf#156629 and tdf#156630 force snapshot of alpha mask
250 // On macOS, with Skia/Metal or Skia/Raster with a Retina display
251 // (i.e. 2.0 window scale), the alpha mask gets upscaled in certain
252 // cases.
253 // This bug appears to be caused by pending scaling of an existing
254 // SkImage in the bitmap parameter. So, force the SkiaSalBitmap to
255 // handle its pending scaling.
256 // Note: also handle pending scaling if SAL_FORCE_HIDPI_SCALING is
257 // set otherwise exporting the following animated .png image will
258 // fail:
259 // https://bugs.documentfoundation.org/attachment.cgi?id=188792
260 static const bool bForceHiDPIScaling = getenv("SAL_FORCE_HIDPI_SCALING") != nullptr;
261 if (mImage && !mImageImmutable && mBitCount == 8 && mPalette.IsGreyPalette8Bit()
262 && (mPixelsSize != mSize || bForceHiDPIScaling))
263 {
264 ResetToSkImage(GetSkImage());
265 ResetPendingScaling();
266 assert(mPixelsSize == mSize);
267
268 // When many of the images affected by tdf#156629 and
269 // tdf#156630 are exported to PDF the first time after the
270 // image has been opened and before it has been printed or run
271 // in a slideshow, the alpha mask will unexpectedly be
272 // inverted. Fix that by marking this alpha mask as immutable
273 // so that when Invert() is called on this alpha mask, it will
274 // be a noop. Invert() is a noop after EnsureBitmapData() is
275 // called but we don't want to call that due to performance
276 // so set a flag instead.
277 mImageImmutable = true;
278 }
279 break;
280 }
281 #ifdef DBG_UTIL
282 // BitmapWriteAccess stores also a copy of the palette and it can
283 // be modified, so concurrent reading of it might result in inconsistencies.
284 assert(mWriteAccessCount == 0 || nMode == BitmapAccessMode::Write);
285 #endif
286 BitmapBuffer* buffer = new BitmapBuffer;
287 buffer->mnWidth = mSize.Width();
288 buffer->mnHeight = mSize.Height();
289 buffer->mnBitCount = mBitCount;
290 buffer->maPalette = mPalette;
291 if (nMode != BitmapAccessMode::Info)
292 buffer->mpBits = mBuffer.get();
293 else
294 buffer->mpBits = nullptr;
295 if (mPixelsSize == mSize)
296 buffer->mnScanlineSize = mScanlineSize;
297 else
298 {
299 // The value of mScanlineSize is based on internal mPixelsSize, but the outside
300 // world cares about mSize, the size that the report as the size of the bitmap,
301 // regardless of any internal state. So report scanline size for that size.
302 Size savedPixelsSize = mPixelsSize;
303 mPixelsSize = mSize;
304 ComputeScanlineSize();
305 buffer->mnScanlineSize = mScanlineSize;
306 mPixelsSize = savedPixelsSize;
307 ComputeScanlineSize();
308 }
309 buffer->meFormat = GetScanlineFormat();
310 buffer->meDirection = ScanlineDirection::TopDown;
311 // Refcount all read/write accesses, to catch problems with existing accesses while
312 // a bitmap changes, and also to detect when we can free mBuffer if wanted.
313 // Write mode implies also reading. It would be probably a good idea to count even
314 // Info accesses, but VclCanvasBitmap keeps one around pointlessly, causing tdf#150817.
315 if (nMode == BitmapAccessMode::Read || nMode == BitmapAccessMode::Write)
316 ++mReadAccessCount;
317 #ifdef DBG_UTIL
318 if (nMode == BitmapAccessMode::Write)
319 ++mWriteAccessCount;
320 #endif
321 return buffer;
322 }
323
324 void SkiaSalBitmap::ReleaseBuffer(BitmapBuffer* pBuffer, BitmapAccessMode nMode)
325 {
326 if (nMode == BitmapAccessMode::Write)
327 {
328 #ifdef DBG_UTIL
329 assert(mWriteAccessCount > 0);
330 --mWriteAccessCount;
331 #endif
332 mPalette = pBuffer->maPalette;
333 ResetToBuffer();
334 DataChanged();
335 }
336 if (nMode == BitmapAccessMode::Read || nMode == BitmapAccessMode::Write)
337 {
338 assert(mReadAccessCount > 0);
339 --mReadAccessCount;
340 }
341 // Are there any more ground movements underneath us ?
342 assert(pBuffer->mnWidth == mSize.Width());
343 assert(pBuffer->mnHeight == mSize.Height());
344 assert(pBuffer->mnBitCount == mBitCount);
345 assert(pBuffer->mpBits == mBuffer.get() || nMode == BitmapAccessMode::Info);
346 verify();
347 delete pBuffer;
348 }
349
350 bool SkiaSalBitmap::GetSystemData(BitmapSystemData&)
351 {
352 #ifdef DBG_UTIL
353 assert(mWriteAccessCount == 0);
354 #endif
355 return false;
356 }
357
358 bool SkiaSalBitmap::ScalingSupported() const { return true; }
359
360 bool SkiaSalBitmap::Scale(const double& rScaleX, const double& rScaleY, BmpScaleFlag nScaleFlag)
361 {
362 SkiaZone zone;
363 #ifdef DBG_UTIL
364 assert(mWriteAccessCount == 0);
365 #endif
366 Size newSize(basegfx::fround<tools::Long>(mSize.Width() * rScaleX),
367 basegfx::fround<tools::Long>(mSize.Height() * rScaleY));
368 if (mSize == newSize)
369 return true;
370
371 SAL_INFO("vcl.skia.trace", "scale(" << this << "): " << mSize << "/" << mBitCount << "->"
372 << newSize << ":" << static_cast<int>(nScaleFlag));
373
374 if (mEraseColorSet)
375 { // Simple.
376 mSize = newSize;
377 ResetPendingScaling();
378 EraseInternal(mEraseColor);
379 return true;
380 }
381
382 if (mBitCount < 24 && !mPalette.IsGreyPalette8Bit())
383 {
384 // Scaling can introduce additional colors not present in the original
385 // bitmap (e.g. when smoothing). If the bitmap is indexed (has non-trivial palette),
386 // this would break the bitmap, because the actual scaling is done only somewhen later.
387 // Linear 8bit palette (grey) is ok, since there we use directly the values as colors.
388 SAL_INFO("vcl.skia.trace", "scale(" << this << "): indexed bitmap");
389 return false;
390 }
391 // The idea here is that the actual scaling will be delayed until the result
392 // is actually needed. Usually the scaled bitmap will be drawn somewhere,
393 // so delaying will mean the scaling can be done as a part of GetSkImage().
394 // That means it can be GPU-accelerated, while done here directly it would need
395 // to be either done by CPU, or with the CPU->GPU->CPU roundtrip required
396 // by GPU-accelerated scaling.
397 // Pending scaling is detected by 'mSize != mPixelsSize' for mBuffer,
398 // and 'imageSize(mImage) != mSize' for mImage. It is not intended to have 3 different
399 // sizes though, code below keeps only mBuffer or mImage. Note that imageSize(mImage)
400 // may or may not be equal to mPixelsSize, depending on whether mImage is set here
401 // (sizes will be equal) or whether it's set in GetSkImage() (will not be equal).
402 // Pending scaling is considered "done" by the time mBuffer is resized (or created).
403 // Resizing of mImage is somewhat independent of this, since mImage is primarily
404 // considered to be a cached object (although sometimes it's the only data available).
405
406 // If there is already one scale() pending, use the lowest quality of all requested.
407 switch (nScaleFlag)
408 {
409 case BmpScaleFlag::Fast:
410 mScaleQuality = nScaleFlag;
411 break;
412 case BmpScaleFlag::NearestNeighbor:
413 // We handle this the same way as Fast by mapping to Skia's nearest-neighbor,
414 // and it's needed for unittests (mScaling and testTdf132367()).
415 mScaleQuality = nScaleFlag;
416 break;
417 case BmpScaleFlag::Default:
418 if (mScaleQuality == BmpScaleFlag::BestQuality)
419 mScaleQuality = nScaleFlag;
420 break;
421 case BmpScaleFlag::BestQuality:
422 // Best is the maximum, set by default.
423 break;
424 default:
425 SAL_INFO("vcl.skia.trace", "scale(" << this << "): unsupported scale algorithm");
426 return false;
427 }
428 mSize = newSize;
429 // If we have both mBuffer and mImage, prefer mImage, since it likely will be drawn later.
430 // We could possibly try to keep the buffer as well, but that would complicate things
431 // with two different data structures to be scaled on-demand, and it's a question
432 // if that'd realistically help with anything.
433 if (mImage)
434 ResetToSkImage(mImage);
435 else
436 ResetToBuffer();
437 DataChanged();
438 // The rest will be handled when the scaled bitmap is actually needed,
439 // such as in EnsureBitmapData() or GetSkImage().
440 return true;
441 }
442
443 bool SkiaSalBitmap::ConvertToGreyscale()
444 {
445 #ifdef DBG_UTIL
446 assert(mWriteAccessCount == 0);
447 #endif
448 // Normally this would need to convert contents of mBuffer for all possible formats,
449 // so just let the VCL algorithm do it.
450 // Avoid the costly SkImage->buffer->SkImage conversion.
451 if (!mBuffer && mImage && !mEraseColorSet)
452 {
453 if (mBitCount == 8 && mPalette.IsGreyPalette8Bit())
454 return true;
455 sk_sp<SkSurface> surface
456 = createSkSurface(imageSize(mImage), mImage->imageInfo().alphaType());
457 SkPaint paint;
458 paint.setBlendMode(SkBlendMode::kSrc); // set as is, including alpha
459 // VCL uses different coefficients for conversion to gray than Skia, so use the VCL
460 // values from Bitmap::ImplMakeGreyscales(). Do not use kGray_8_SkColorType,
461 // Skia would use its gray conversion formula.
462 // NOTE: The matrix is 4x5 organized as columns (i.e. each line is a column, not a row).
463 static constexpr SkColorMatrix toGray(77 / 256.0, 151 / 256.0, 28 / 256.0, 0, 0, // R column
464 77 / 256.0, 151 / 256.0, 28 / 256.0, 0, 0, // G column
465 77 / 256.0, 151 / 256.0, 28 / 256.0, 0, 0, // B column
466 0, 0, 0, 1, 0); // don't modify alpha
467 paint.setColorFilter(SkColorFilters::Matrix(toGray));
468 surface->getCanvas()->drawImage(mImage, 0, 0, SkSamplingOptions(), &paint);
469 mBitCount = 8;
470 ComputeScanlineSize();
471 mPalette = Bitmap::GetGreyPalette(256);
472 ResetToSkImage(makeCheckedImageSnapshot(surface));
473 DataChanged();
474 SAL_INFO("vcl.skia.trace", "converttogreyscale(" << this << ")");
475 return true;
476 }
477 return false;
478 }
479
480 bool SkiaSalBitmap::InterpretAs8Bit()
481 {
482 #ifdef DBG_UTIL
483 assert(mWriteAccessCount == 0);
484 #endif
485 if (mBitCount == 8 && mPalette.IsGreyPalette8Bit())
486 return true;
487 if (mEraseColorSet)
488 {
489 mBitCount = 8;
490 ComputeScanlineSize();
491 mPalette = Bitmap::GetGreyPalette(256);
492 EraseInternal(mEraseColor);
493 SAL_INFO("vcl.skia.trace", "interpretas8bit(" << this << ") with erase color");
494 return true;
495 }
496 // This is usually used by AlphaMask, the point is just to treat
497 // the content as an alpha channel. This is often used
498 // by the horrible separate-alpha-outdev hack, where the bitmap comes
499 // from SkiaSalGraphicsImpl::GetBitmap(), so only mImage is set,
500 // and that is followed by a later call to GetAlphaSkImage().
501 // Avoid the costly SkImage->buffer->SkImage conversion and simply
502 // just treat the SkImage as being for 8bit bitmap. EnsureBitmapData()
503 // will do the conversion if needed, but the normal case will be
504 // GetAlphaSkImage() creating kAlpha_8_SkColorType SkImage from it.
505 if (mImage)
506 {
507 mBitCount = 8;
508 ComputeScanlineSize();
509 mPalette = Bitmap::GetGreyPalette(256);
510 ResetToSkImage(mImage); // keep mImage, it will be interpreted as 8bit if needed
511 DataChanged();
512 SAL_INFO("vcl.skia.trace", "interpretas8bit(" << this << ") with image");
513 return true;
514 }
515 SAL_INFO("vcl.skia.trace", "interpretas8bit(" << this << ") with pixel data, ignoring");
516 return false;
517 }
518
519 bool SkiaSalBitmap::Erase(const Color& color)
520 {
521 #ifdef DBG_UTIL
522 assert(mWriteAccessCount == 0);
523 #endif
524 // Optimized variant, just remember the color and apply it when needed,
525 // which may save having to do format conversions (e.g. GetSkImage()
526 // may directly erase the SkImage).
527 EraseInternal(color);
528 SAL_INFO("vcl.skia.trace", "erase(" << this << ")");
529 return true;
530 }
531
532 void SkiaSalBitmap::EraseInternal(const Color& color)
533 {
534 ResetAllData();
535 mEraseColorSet = true;
536 mEraseColor = color;
537 }
538
539 bool SkiaSalBitmap::AlphaBlendWith(const SalBitmap& rSalBmp)
540 {
541 #ifdef DBG_UTIL
542 assert(mWriteAccessCount == 0);
543 #endif
544 const SkiaSalBitmap* otherBitmap = dynamic_cast<const SkiaSalBitmap*>(&rSalBmp);
545 if (!otherBitmap)
546 return false;
547 if (mSize != otherBitmap->mSize)
548 return false;
549 // We're called from AlphaMask, which should ensure 8bit.
550 assert(GetBitCount() == 8 && mPalette.IsGreyPalette8Bit());
551 // If neither bitmap have Skia images, then AlphaMask::BlendWith() will be faster,
552 // as it will operate on mBuffer pixel buffers, while for Skia we'd need to convert it.
553 // If one has and one doesn't, do it using Skia, under the assumption that after this
554 // the resulting Skia image will be needed for drawing.
555 if (!(mImage || mEraseColorSet) && !(otherBitmap->mImage || otherBitmap->mEraseColorSet))
556 return false;
557 // This is for AlphaMask, which actually stores the alpha as the pixel values.
558 // I.e. take value of the color channel (one of them, if >8bit, they should be the same).
559 if (mEraseColorSet && otherBitmap->mEraseColorSet)
560 {
561 const sal_uInt16 nGrey1 = mEraseColor.GetRed();
562 const sal_uInt16 nGrey2 = otherBitmap->mEraseColor.GetRed();
563 // See comment in AlphaMask::BlendWith for how this calculation was derived
564 const sal_uInt8 nGrey = static_cast<sal_uInt8>(nGrey1 * nGrey2 / 255);
565 mEraseColor = Color(nGrey, nGrey, nGrey);
566 DataChanged();
567 SAL_INFO("vcl.skia.trace",
568 "alphablendwith(" << this << ") : with erase color " << otherBitmap);
569 return true;
570 }
571 std::unique_ptr<SkiaSalBitmap> otherBitmapAllocated;
572 if (otherBitmap->GetBitCount() != 8 || !otherBitmap->mPalette.IsGreyPalette8Bit())
573 { // Convert/interpret as 8bit if needed.
574 otherBitmapAllocated = std::make_unique<SkiaSalBitmap>();
575 if (!otherBitmapAllocated->Create(*otherBitmap) || !otherBitmapAllocated->InterpretAs8Bit())
576 return false;
577 otherBitmap = otherBitmapAllocated.get();
578 }
579 // This is 8-bit bitmap serving as mask, so the image itself needs no alpha.
580 sk_sp<SkSurface> surface = createSkSurface(mSize, kOpaque_SkAlphaType);
581 SkPaint paint;
582 paint.setBlendMode(SkBlendMode::kSrc); // set as is
583 surface->getCanvas()->drawImage(GetSkImage(), 0, 0, SkSamplingOptions(), &paint);
584 // in the 0..1 range that skia uses, the equation we want is:
585 // r = 1 - ((1 - src) + (1 - dest) - (1 - src) * (1 - dest))
586 // which simplifies to:
587 // r = src * dest
588 // which is SkBlendMode::kModulate
589 paint.setBlendMode(SkBlendMode::kModulate);
590 surface->getCanvas()->drawImage(otherBitmap->GetSkImage(), 0, 0, SkSamplingOptions(), &paint);
591 ResetToSkImage(makeCheckedImageSnapshot(surface));
592 DataChanged();
593 SAL_INFO("vcl.skia.trace", "alphablendwith(" << this << ") : with image " << otherBitmap);
594 return true;
595 }
596
597 bool SkiaSalBitmap::Invert()
598 {
599 #ifdef DBG_UTIL
600 assert(mWriteAccessCount == 0);
601 #endif
602 // Normally this would need to convert contents of mBuffer for all possible formats,
603 // so just let the VCL algorithm do it.
604 // Avoid the costly SkImage->buffer->SkImage conversion.
605 if (!mBuffer && mImage && !mImageImmutable && !mEraseColorSet)
606 {
607 // This is 8-bit bitmap serving as alpha/transparency/mask, so the image itself needs no alpha.
608 // tdf#156866 use mSize instead of mPixelSize for inverted surface
609 // Commit 5baac4e53128d3c0fc73b9918dc9a9c2777ace08 switched to setting
610 // the surface size to mPixelsSize in an attempt to avoid downscaling
611 // mImage but since it causes tdf#156866, revert back to setting the
612 // surface size to mSize.
613 sk_sp<SkSurface> surface = createSkSurface(mSize, kOpaque_SkAlphaType);
614 surface->getCanvas()->clear(SK_ColorWHITE);
615 SkPaint paint;
616 paint.setBlendMode(SkBlendMode::kDifference);
617 // Drawing the image does not work so create a shader from the image
618 paint.setShader(GetSkShader(SkSamplingOptions()));
619 surface->getCanvas()->drawRect(SkRect::MakeXYWH(0, 0, mSize.Width(), mSize.Height()),
620 paint);
621 ResetToSkImage(makeCheckedImageSnapshot(surface));
622 DataChanged();
623
624 #ifdef MACOSX
625 // tdf#158014 make image immutable after using Skia to invert
626 // I can't explain why inverting using Skia causes this bug on
627 // macOS but not other platforms. My guess is that Skia on macOS
628 // is sharing some data when different SkiaSalBitmap instances
629 // are created from the same OutputDevice. So, mark this
630 // SkiaSalBitmap instance's image as immutable so that successive
631 // inversions are done with buffered bitmap data instead of Skia.
632 mImageImmutable = true;
633 #endif
634
635 SAL_INFO("vcl.skia.trace", "invert(" << this << ")");
636 return true;
637 }
638 return false;
639 }
640
641 SkBitmap SkiaSalBitmap::GetAsSkBitmap() const
642 {
643 #ifdef DBG_UTIL
644 assert(mWriteAccessCount == 0);
645 #endif
646 EnsureBitmapData();
647 assert(mSize == mPixelsSize); // data has already been scaled if needed
648 SkiaZone zone;
649 SkBitmap bitmap;
650 if (mBuffer)
651 {
652 if (mBitCount == 32)
653 {
654 // Make a copy, the bitmap should be immutable (otherwise converting it
655 // to SkImage will make a copy anyway).
656 const size_t bytes = mPixelsSize.Height() * mScanlineSize;
657 std::unique_ptr<sal_uInt8[]> data(new sal_uInt8[bytes]);
658 memcpy(data.get(), mBuffer.get(), bytes);
659 if (!bitmap.installPixels(
660 SkImageInfo::MakeS32(mPixelsSize.Width(), mPixelsSize.Height(), alphaType()),
661 data.release(), mScanlineSize,
662 [](void* addr, void*) { delete[] static_cast<sal_uInt8*>(addr); }, nullptr))
663 abort();
664 }
665 else if (mBitCount == 24)
666 {
667 // Convert 24bpp RGB/BGR to 32bpp RGBA/BGRA.
668 std::unique_ptr<uint32_t[]> data(
669 new uint32_t[mPixelsSize.Height() * mPixelsSize.Width()]);
670 uint32_t* dest = data.get();
671 // SkConvertRGBToRGBA() also works as BGR to BGRA (the function extends 3 bytes to 4
672 // by adding 0xFF alpha, so position of B and R doesn't matter).
673 if (mPixelsSize.Width() * 3 == mScanlineSize)
674 SkConvertRGBToRGBA(dest, mBuffer.get(), mPixelsSize.Height() * mPixelsSize.Width());
675 else
676 {
677 for (tools::Long y = 0; y < mPixelsSize.Height(); ++y)
678 {
679 const sal_uInt8* src = mBuffer.get() + mScanlineSize * y;
680 SkConvertRGBToRGBA(dest, src, mPixelsSize.Width());
681 dest += mPixelsSize.Width();
682 }
683 }
684 if (!bitmap.installPixels(
685 SkImageInfo::MakeS32(mPixelsSize.Width(), mPixelsSize.Height(),
686 kOpaque_SkAlphaType),
687 data.release(), mPixelsSize.Width() * 4,
688 [](void* addr, void*) { delete[] static_cast<sal_uInt8*>(addr); }, nullptr))
689 abort();
690 }
691 else if (mBitCount == 8 && mPalette.IsGreyPalette8Bit())
692 {
693 // Convert 8bpp gray to 32bpp RGBA/BGRA.
694 // There's also kGray_8_SkColorType, but it's probably simpler to make
695 // GetAsSkBitmap() always return 32bpp SkBitmap and then assume mImage
696 // is always 32bpp too.
697 std::unique_ptr<uint32_t[]> data(
698 new uint32_t[mPixelsSize.Height() * mPixelsSize.Width()]);
699 uint32_t* dest = data.get();
700 if (mPixelsSize.Width() * 1 == mScanlineSize)
701 SkConvertGrayToRGBA(dest, mBuffer.get(),
702 mPixelsSize.Height() * mPixelsSize.Width());
703 else
704 {
705 for (tools::Long y = 0; y < mPixelsSize.Height(); ++y)
706 {
707 const sal_uInt8* src = mBuffer.get() + mScanlineSize * y;
708 SkConvertGrayToRGBA(dest, src, mPixelsSize.Width());
709 dest += mPixelsSize.Width();
710 }
711 }
712 if (!bitmap.installPixels(
713 SkImageInfo::MakeS32(mPixelsSize.Width(), mPixelsSize.Height(),
714 kOpaque_SkAlphaType),
715 data.release(), mPixelsSize.Width() * 4,
716 [](void* addr, void*) { delete[] static_cast<sal_uInt8*>(addr); }, nullptr))
717 abort();
718 }
719 else
720 {
721 std::unique_ptr<sal_uInt8[]> data = convertDataBitCount(
722 mBuffer.get(), mPixelsSize.Width(), mPixelsSize.Height(), mBitCount, mScanlineSize,
723 mPalette, kN32_SkColorTypeIsBGRA ? BitConvert::BGRA : BitConvert::RGBA);
724 if (!bitmap.installPixels(
725 SkImageInfo::MakeS32(mPixelsSize.Width(), mPixelsSize.Height(),
726 kOpaque_SkAlphaType),
727 data.release(), mPixelsSize.Width() * 4,
728 [](void* addr, void*) { delete[] static_cast<sal_uInt8*>(addr); }, nullptr))
729 abort();
730 }
731 }
732 bitmap.setImmutable();
733 return bitmap;
734 }
735
736 // If mEraseColor is set, this is the color to use when the bitmap is used as alpha bitmap.
737 // E.g. COL_BLACK actually means fully transparent and COL_WHITE means fully opaque.
738 // This is because the alpha value is set as the color itself, not the alpha of the color.
739 static SkColor fromEraseColorToAlphaImageColor(Color color)
740 {
741 return SkColorSetARGB(color.GetBlue(), 0, 0, 0);
742 }
743
744 // SkiaSalBitmap can store data in both the SkImage and our mBuffer, which with large
745 // images can waste quite a lot of memory. Ideally we should store the data in Skia's
746 // SkBitmap, but LO wants us to support data formats that Skia doesn't support.
747 // So try to conserve memory by keeping the data only once in that was the most
748 // recently wanted storage, and drop the other one. Usually the other one won't be needed
749 // for a long time, and especially with raster the conversion is usually fast.
750 // Do this only with raster, to avoid GPU->CPU transfer in GPU mode (exception is 32bit
751 // builds, where memory is more important). Also don't do this with paletted bitmaps,
752 // where EnsureBitmapData() would be expensive.
753 // Ideally SalBitmap should be able to say which bitmap formats it supports
754 // and VCL code should oblige, which would allow reusing the same data.
755 bool SkiaSalBitmap::ConserveMemory() const
756 {
757 static bool keepBitmapBuffer = getenv("SAL_SKIA_KEEP_BITMAP_BUFFER") != nullptr;
758 constexpr bool is32Bit = sizeof(void*) == 4;
759 // 16MiB bitmap data at least (set to 0 for easy testing).
760 constexpr tools::Long maxBufferSize = 2000 * 2000 * 4;
761 return !keepBitmapBuffer && (renderMethodToUse() == RenderRaster || is32Bit)
762 && mPixelsSize.Height() * mScanlineSize > maxBufferSize
763 && (mBitCount > 8 || (mBitCount == 8 && mPalette.IsGreyPalette8Bit()));
764 }
765
766 const sk_sp<SkImage>& SkiaSalBitmap::GetSkImage(DirectImage direct) const
767 {
768 #ifdef DBG_UTIL
769 assert(mWriteAccessCount == 0);
770 #endif
771 if (direct == DirectImage::Yes)
772 return mImage;
773 if (mEraseColorSet)
774 {
775 if (mImage)
776 {
777 assert(imageSize(mImage) == mSize);
778 return mImage;
779 }
780 SkiaZone zone;
781 sk_sp<SkSurface> surface = createSkSurface(
782 mSize, mEraseColor.IsTransparent() ? kPremul_SkAlphaType : kOpaque_SkAlphaType);
783 assert(surface);
784 surface->getCanvas()->clear(toSkColor(mEraseColor));
785 SkiaSalBitmap* thisPtr = const_cast<SkiaSalBitmap*>(this);
786 thisPtr->mImage = makeCheckedImageSnapshot(surface);
787 SAL_INFO("vcl.skia.trace", "getskimage(" << this << ") from erase color " << mEraseColor);
788 return mImage;
789 }
790 if (mPixelsSize != mSize && !mImage && renderMethodToUse() != RenderRaster)
791 {
792 // The bitmap has a pending scaling, but no image. This function would below call GetAsSkBitmap(),
793 // which would do CPU-based pixel scaling, and then it would get converted to an image.
794 // Be more efficient, first convert to an image and then the block below will scale on the GPU.
795 SAL_INFO("vcl.skia.trace", "getskimage(" << this << "): shortcut image scaling "
796 << mPixelsSize << "->" << mSize);
797 SkiaSalBitmap* thisPtr = const_cast<SkiaSalBitmap*>(this);
798 Size savedSize = mSize;
799 thisPtr->mSize = mPixelsSize; // block scaling
800 SkiaZone zone;
801 sk_sp<SkImage> image = createSkImage(GetAsSkBitmap());
802 assert(image);
803 thisPtr->mSize = savedSize;
804 thisPtr->ResetToSkImage(image);
805 }
806 if (mImage)
807 {
808 if (imageSize(mImage) != mSize)
809 {
810 assert(!mBuffer); // This code should be only called if only mImage holds data.
811 SkiaZone zone;
812 sk_sp<SkSurface> surface = createSkSurface(mSize, mImage->imageInfo().alphaType());
813 assert(surface);
814 SkPaint paint;
815 paint.setBlendMode(SkBlendMode::kSrc); // set as is, including alpha
816 surface->getCanvas()->drawImageRect(
817 mImage, SkRect::MakeWH(mSize.Width(), mSize.Height()),
818 makeSamplingOptions(mScaleQuality, imageSize(mImage), mSize, 1), &paint);
819 SAL_INFO("vcl.skia.trace", "getskimage(" << this << "): image scaled "
820 << Size(mImage->width(), mImage->height())
821 << "->" << mSize << ":"
822 << static_cast<int>(mScaleQuality));
823 SkiaSalBitmap* thisPtr = const_cast<SkiaSalBitmap*>(this);
824 thisPtr->mImage = makeCheckedImageSnapshot(surface);
825 }
826 return mImage;
827 }
828 SkiaZone zone;
829 sk_sp<SkImage> image = createSkImage(GetAsSkBitmap());
830 assert(image);
831 SkiaSalBitmap* thisPtr = const_cast<SkiaSalBitmap*>(this);
832 thisPtr->mImage = image;
833 // The data is now stored both in the SkImage and in our mBuffer, so drop the buffer
834 // if conserving memory. It'll be converted back by EnsureBitmapData() if needed.
835 if (ConserveMemory() && mReadAccessCount == 0)
836 {
837 SAL_INFO("vcl.skia.trace", "getskimage(" << this << "): dropping buffer");
838 thisPtr->ResetToSkImage(mImage);
839 }
840 SAL_INFO("vcl.skia.trace", "getskimage(" << this << ")");
841 return mImage;
842 }
843
844 const sk_sp<SkImage>& SkiaSalBitmap::GetAlphaSkImage(DirectImage direct) const
845 {
846 #ifdef DBG_UTIL
847 assert(mWriteAccessCount == 0);
848 #endif
849 if (direct == DirectImage::Yes)
850 return mAlphaImage;
851 if (mEraseColorSet)
852 {
853 if (mAlphaImage)
854 {
855 assert(imageSize(mAlphaImage) == mSize);
856 return mAlphaImage;
857 }
858 SkiaZone zone;
859 sk_sp<SkSurface> surface = createSkSurface(mSize, kAlpha_8_SkColorType);
860 assert(surface);
861 surface->getCanvas()->clear(fromEraseColorToAlphaImageColor(mEraseColor));
862 SkiaSalBitmap* thisPtr = const_cast<SkiaSalBitmap*>(this);
863 thisPtr->mAlphaImage = makeCheckedImageSnapshot(surface);
864 SAL_INFO("vcl.skia.trace",
865 "getalphaskimage(" << this << ") from erase color " << mEraseColor);
866 return mAlphaImage;
867 }
868 if (mAlphaImage)
869 {
870 if (imageSize(mAlphaImage) == mSize)
871 return mAlphaImage;
872 }
873 if (mImage)
874 {
875 SkiaZone zone;
876 const bool scaling = imageSize(mImage) != mSize;
877 SkPixmap pixmap;
878 if (mImage->peekPixels(&pixmap))
879 {
880 assert(pixmap.colorType() == kN32_SkColorType);
881 // In non-GPU mode, convert 32bit data to 8bit alpha, this is faster than
882 // the SkColorFilter below. Since this is the VCL alpha-vdev alpha, where
883 // all R,G,B are the same and in fact mean alpha, this means we simply take one
884 // 8bit channel from the input, and that's the output.
885 SkBitmap bitmap;
886 if (!bitmap.installPixels(pixmap))
887 abort();
888 SkBitmap alphaBitmap;
889 if (!alphaBitmap.tryAllocPixels(SkImageInfo::MakeA8(bitmap.width(), bitmap.height())))
890 abort();
891 if (int(bitmap.rowBytes()) == bitmap.width() * 4)
892 {
893 SkConvertRGBAToR(alphaBitmap.getAddr8(0, 0), bitmap.getAddr32(0, 0),
894 bitmap.width() * bitmap.height());
895 }
896 else
897 {
898 for (tools::Long y = 0; y < bitmap.height(); ++y)
899 SkConvertRGBAToR(alphaBitmap.getAddr8(0, y), bitmap.getAddr32(0, y),
900 bitmap.width());
901 }
902 alphaBitmap.setImmutable();
903 sk_sp<SkImage> alphaImage = createSkImage(alphaBitmap);
904 assert(alphaImage);
905 SAL_INFO("vcl.skia.trace", "getalphaskimage(" << this << ") from raster image");
906 // Don't bother here with ConserveMemory(), mImage -> mAlphaImage conversions should
907 // generally only happen with the separate-alpha-outdev hack, and those bitmaps should
908 // be temporary.
909 SkiaSalBitmap* thisPtr = const_cast<SkiaSalBitmap*>(this);
910 thisPtr->mAlphaImage = alphaImage;
911 // Fix testDelayedScaleAlphaImage unit test
912 // Do not return the alpha mask if it is awaiting pending scaling.
913 // Pending scaling has not yet been done at this point since the
914 // scaling is done in the code following this block.
915 if (!scaling)
916 return mAlphaImage;
917 }
918 // Move the R channel value to the alpha channel. This seems to be the only
919 // way to reinterpret data in SkImage as an alpha SkImage without accessing the pixels.
920 // NOTE: The matrix is 4x5 organized as columns (i.e. each line is a column, not a row).
921 static constexpr SkColorMatrix redToAlpha(0, 0, 0, 0, 0, // R column
922 0, 0, 0, 0, 0, // G column
923 0, 0, 0, 0, 0, // B column
924 1, 0, 0, 0, 0); // A column
925 SkPaint paint;
926 paint.setColorFilter(SkColorFilters::Matrix(redToAlpha));
927 if (scaling)
928 assert(!mBuffer); // This code should be only called if only mImage holds data.
929 sk_sp<SkSurface> surface = createSkSurface(mSize, kAlpha_8_SkColorType);
930 assert(surface);
931 paint.setBlendMode(SkBlendMode::kSrc); // set as is, including alpha
932 surface->getCanvas()->drawImageRect(
933 mImage, SkRect::MakeWH(mSize.Width(), mSize.Height()),
934 scaling ? makeSamplingOptions(mScaleQuality, imageSize(mImage), mSize, 1)
935 : SkSamplingOptions(),
936 &paint);
937 if (scaling)
938 SAL_INFO("vcl.skia.trace", "getalphaskimage(" << this << "): image scaled "
939 << Size(mImage->width(), mImage->height())
940 << "->" << mSize << ":"
941 << static_cast<int>(mScaleQuality));
942 else
943 SAL_INFO("vcl.skia.trace", "getalphaskimage(" << this << ") from image");
944 // Don't bother here with ConserveMemory(), mImage -> mAlphaImage conversions should
945 // generally only happen with the separate-alpha-outdev hack, and those bitmaps should
946 // be temporary.
947 SkiaSalBitmap* thisPtr = const_cast<SkiaSalBitmap*>(this);
948 thisPtr->mAlphaImage = makeCheckedImageSnapshot(surface);
949 return mAlphaImage;
950 }
951 SkiaZone zone;
952 EnsureBitmapData();
953 assert(mSize == mPixelsSize); // data has already been scaled if needed
954 SkBitmap alphaBitmap;
955 if (mBuffer && mBitCount <= 8)
956 {
957 assert(mBuffer.get());
958 verify();
959 std::unique_ptr<sal_uInt8[]> data
960 = convertDataBitCount(mBuffer.get(), mSize.Width(), mSize.Height(), mBitCount,
961 mScanlineSize, mPalette, BitConvert::A8);
962 if (!alphaBitmap.installPixels(
963 SkImageInfo::MakeA8(mSize.Width(), mSize.Height()), data.release(), mSize.Width(),
964 [](void* addr, void*) { delete[] static_cast<sal_uInt8*>(addr); }, nullptr))
965 abort();
966 alphaBitmap.setImmutable();
967 sk_sp<SkImage> image = createSkImage(alphaBitmap);
968 assert(image);
969 const_cast<sk_sp<SkImage>&>(mAlphaImage) = image;
970 }
971 else
972 {
973 sk_sp<SkSurface> surface = createSkSurface(mSize, kAlpha_8_SkColorType);
974 assert(surface);
975 SkPaint paint;
976 paint.setBlendMode(SkBlendMode::kSrc); // set as is, including alpha
977 // Move the R channel value to the alpha channel. This seems to be the only
978 // way to reinterpret data in SkImage as an alpha SkImage without accessing the pixels.
979 // NOTE: The matrix is 4x5 organized as columns (i.e. each line is a column, not a row).
980 static constexpr SkColorMatrix redToAlpha(0, 0, 0, 0, 0, // R column
981 0, 0, 0, 0, 0, // G column
982 0, 0, 0, 0, 0, // B column
983 1, 0, 0, 0, 0); // A column
984 paint.setColorFilter(SkColorFilters::Matrix(redToAlpha));
985 surface->getCanvas()->drawImage(GetAsSkBitmap().asImage(), 0, 0, SkSamplingOptions(),
986 &paint);
987 SkiaSalBitmap* thisPtr = const_cast<SkiaSalBitmap*>(this);
988 thisPtr->mAlphaImage = makeCheckedImageSnapshot(surface);
989 }
990 // The data is now stored both in the SkImage and in our mBuffer, so drop the buffer
991 // if conserving memory and the conversion back would be simple (it'll be converted back
992 // by EnsureBitmapData() if needed).
993 if (ConserveMemory() && mBitCount == 8 && mPalette.IsGreyPalette8Bit() && mReadAccessCount == 0)
994 {
995 SAL_INFO("vcl.skia.trace", "getalphaskimage(" << this << "): dropping buffer");
996 SkiaSalBitmap* thisPtr = const_cast<SkiaSalBitmap*>(this);
997 thisPtr->mBuffer.reset();
998 }
999 SAL_INFO("vcl.skia.trace", "getalphaskimage(" << this << ")");
1000 return mAlphaImage;
1001 }
1002
1003 // If the bitmap is to be erased, SkShader with the color set is more efficient
1004 // than creating an image filled with the color.
1005 bool SkiaSalBitmap::PreferSkShader() const { return mEraseColorSet; }
1006
1007 sk_sp<SkShader> SkiaSalBitmap::GetSkShader(const SkSamplingOptions& samplingOptions,
1008 DirectImage direct) const
1009 {
1010 if (mEraseColorSet)
1011 return SkShaders::Color(toSkColor(mEraseColor));
1012 return GetSkImage(direct)->makeShader(samplingOptions);
1013 }
1014
1015 sk_sp<SkShader> SkiaSalBitmap::GetAlphaSkShader(const SkSamplingOptions& samplingOptions,
1016 DirectImage direct) const
1017 {
1018 if (mEraseColorSet)
1019 return SkShaders::Color(fromEraseColorToAlphaImageColor(mEraseColor));
1020 return GetAlphaSkImage(direct)->makeShader(samplingOptions);
1021 }
1022
1023 SkAlphaType SkiaSalBitmap::alphaType() const
1024 {
1025 if (mEraseColorSet)
1026 return mEraseColor.IsTransparent() ? kPremul_SkAlphaType : kOpaque_SkAlphaType;
1027 if (mBitCount == 32)
1028 return kPremul_SkAlphaType;
1029 return kOpaque_SkAlphaType;
1030 }
1031
1032 void SkiaSalBitmap::PerformErase()
1033 {
1034 if (mPixelsSize.IsEmpty())
1035 return;
1036 BitmapBuffer* bitmapBuffer = AcquireBuffer(BitmapAccessMode::Write);
1037 if (bitmapBuffer == nullptr)
1038 abort();
1039 Color fastColor = mEraseColor;
1040 if (!!mPalette)
1041 fastColor = Color(ColorAlpha, mPalette.GetBestIndex(fastColor));
1042 if (!ImplFastEraseBitmap(*bitmapBuffer, fastColor))
1043 {
1044 FncSetPixel setPixel = BitmapReadAccess::SetPixelFunction(bitmapBuffer->meFormat);
1045 assert(bitmapBuffer->meDirection == ScanlineDirection::TopDown);
1046 // Set first scanline, copy to others.
1047 Scanline scanline = bitmapBuffer->mpBits;
1048 for (tools::Long x = 0; x < bitmapBuffer->mnWidth; ++x)
1049 setPixel(scanline, x, mEraseColor);
1050 for (tools::Long y = 1; y < bitmapBuffer->mnHeight; ++y)
1051 memcpy(scanline + y * bitmapBuffer->mnScanlineSize, scanline,
1052 bitmapBuffer->mnScanlineSize);
1053 }
1054 ReleaseBuffer(bitmapBuffer, BitmapAccessMode::Write);
1055 }
1056
1057 void SkiaSalBitmap::EnsureBitmapData()
1058 {
1059 if (mEraseColorSet)
1060 {
1061 SkiaZone zone;
1062 assert(mPixelsSize == mSize);
1063 assert(!mBuffer);
1064 CreateBitmapData();
1065 // Unset now, so that repeated call will return mBuffer.
1066 mEraseColorSet = false;
1067 PerformErase();
1068 verify();
1069 SAL_INFO("vcl.skia.trace",
1070 "ensurebitmapdata(" << this << ") from erase color " << mEraseColor);
1071 return;
1072 }
1073
1074 if (mBuffer)
1075 {
1076 if (mSize == mPixelsSize)
1077 return;
1078 // Pending scaling. Create raster SkImage from the bitmap data
1079 // at the pixel size and then the code below will scale at the correct
1080 // bpp from the image.
1081 SAL_INFO("vcl.skia.trace", "ensurebitmapdata(" << this << "): pixels to be scaled "
1082 << mPixelsSize << "->" << mSize << ":"
1083 << static_cast<int>(mScaleQuality));
1084 Size savedSize = mSize;
1085 mSize = mPixelsSize;
1086 ResetToSkImage(SkImages::RasterFromBitmap(GetAsSkBitmap()));
1087 mSize = savedSize;
1088 }
1089
1090 // Convert from alpha image, if the conversion is simple.
1091 if (mAlphaImage && imageSize(mAlphaImage) == mSize && mBitCount == 8
1092 && mPalette.IsGreyPalette8Bit())
1093 {
1094 assert(mAlphaImage->colorType() == kAlpha_8_SkColorType);
1095 SkiaZone zone;
1096 SkBitmap bitmap;
1097 SkPixmap pixmap;
1098 if (mAlphaImage->peekPixels(&pixmap))
1099 bitmap.installPixels(pixmap);
1100 else
1101 {
1102 if (!bitmap.tryAllocPixels(SkImageInfo::MakeA8(mSize.Width(), mSize.Height())))
1103 abort();
1104 SkCanvas canvas(bitmap);
1105 SkPaint paint;
1106 paint.setBlendMode(SkBlendMode::kSrc); // set as is, including alpha
1107 canvas.drawImage(mAlphaImage, 0, 0, SkSamplingOptions(), &paint);
1108 if (auto dContext = GrAsDirectContext(canvas.recordingContext()))
1109 dContext->flushAndSubmit();
1110 }
1111 bitmap.setImmutable();
1112 ResetPendingScaling();
1113 CreateBitmapData();
1114 assert(mBuffer != nullptr);
1115 assert(mPixelsSize == mSize);
1116 if (int(bitmap.rowBytes()) == mScanlineSize)
1117 memcpy(mBuffer.get(), bitmap.getPixels(), mSize.Height() * mScanlineSize);
1118 else
1119 {
1120 for (tools::Long y = 0; y < mSize.Height(); ++y)
1121 {
1122 const uint8_t* src = static_cast<uint8_t*>(bitmap.getAddr(0, y));
1123 sal_uInt8* dest = mBuffer.get() + mScanlineSize * y;
1124 memcpy(dest, src, mScanlineSize);
1125 }
1126 }
1127 verify();
1128 // We've created the bitmap data from mAlphaImage, drop the image if conserving memory,
1129 // it'll be converted back if needed.
1130 if (ConserveMemory())
1131 {
1132 SAL_INFO("vcl.skia.trace", "ensurebitmapdata(" << this << "): dropping images");
1133 ResetToBuffer();
1134 }
1135 SAL_INFO("vcl.skia.trace", "ensurebitmapdata(" << this << "): from alpha image");
1136 return;
1137 }
1138
1139 if (!mImage)
1140 {
1141 // No data at all, create uninitialized data.
1142 CreateBitmapData();
1143 SAL_INFO("vcl.skia.trace", "ensurebitmapdata(" << this << "): uninitialized");
1144 return;
1145 }
1146 // Try to fill mBuffer from mImage.
1147 assert(mImage->colorType() == kN32_SkColorType);
1148 SkiaZone zone;
1149 // If the source image has no alpha, then use no alpha (faster to convert).
1150 SkAlphaType alphaType = kUnpremul_SkAlphaType;
1151 if (mImage->imageInfo().alphaType() == kOpaque_SkAlphaType)
1152 alphaType = kOpaque_SkAlphaType;
1153 if (mBitCount == 32)
1154 alphaType = kPremul_SkAlphaType;
1155 SkBitmap bitmap;
1156 SkPixmap pixmap;
1157 if (imageSize(mImage) == mSize && mImage->imageInfo().alphaType() == alphaType
1158 && mImage->peekPixels(&pixmap))
1159 {
1160 bitmap.installPixels(pixmap);
1161 }
1162 else
1163 {
1164 if (!bitmap.tryAllocPixels(SkImageInfo::MakeS32(mSize.Width(), mSize.Height(), alphaType)))
1165 abort();
1166 SkCanvas canvas(bitmap);
1167 SkPaint paint;
1168 paint.setBlendMode(SkBlendMode::kSrc); // set as is, including alpha
1169 if (imageSize(mImage) != mSize) // pending scaling?
1170 {
1171 canvas.drawImageRect(mImage, SkRect::MakeWH(mSize.getWidth(), mSize.getHeight()),
1172 makeSamplingOptions(mScaleQuality, imageSize(mImage), mSize, 1),
1173 &paint);
1174 SAL_INFO("vcl.skia.trace",
1175 "ensurebitmapdata(" << this << "): image scaled " << imageSize(mImage) << "->"
1176 << mSize << ":" << static_cast<int>(mScaleQuality));
1177 }
1178 else
1179 canvas.drawImage(mImage, 0, 0, SkSamplingOptions(), &paint);
1180 if (auto dContext = GrAsDirectContext(canvas.recordingContext()))
1181 dContext->flushAndSubmit();
1182 }
1183 bitmap.setImmutable();
1184 ResetPendingScaling();
1185 CreateBitmapData();
1186 assert(mBuffer != nullptr);
1187 assert(mPixelsSize == mSize);
1188 if (mBitCount == 32)
1189 {
1190 if (int(bitmap.rowBytes()) == mScanlineSize)
1191 memcpy(mBuffer.get(), bitmap.getPixels(), mSize.Height() * mScanlineSize);
1192 else
1193 {
1194 for (tools::Long y = 0; y < mSize.Height(); ++y)
1195 {
1196 const uint8_t* src = static_cast<uint8_t*>(bitmap.getAddr(0, y));
1197 sal_uInt8* dest = mBuffer.get() + mScanlineSize * y;
1198 memcpy(dest, src, mScanlineSize);
1199 }
1200 }
1201 }
1202 else if (mBitCount == 24) // non-paletted
1203 {
1204 if (int(bitmap.rowBytes()) == mSize.Width() * 4 && mSize.Width() * 3 == mScanlineSize)
1205 {
1206 SkConvertRGBAToRGB(mBuffer.get(), bitmap.getAddr32(0, 0),
1207 mSize.Height() * mSize.Width());
1208 }
1209 else
1210 {
1211 for (tools::Long y = 0; y < mSize.Height(); ++y)
1212 {
1213 const uint32_t* src = bitmap.getAddr32(0, y);
1214 sal_uInt8* dest = mBuffer.get() + mScanlineSize * y;
1215 SkConvertRGBAToRGB(dest, src, mSize.Width());
1216 }
1217 }
1218 }
1219 else if (mBitCount == 8 && mPalette.IsGreyPalette8Bit())
1220 { // no actual data conversion, use one color channel as the gray value
1221 if (int(bitmap.rowBytes()) == mSize.Width() * 4 && mSize.Width() * 1 == mScanlineSize)
1222 {
1223 SkConvertRGBAToR(mBuffer.get(), bitmap.getAddr32(0, 0), mSize.Height() * mSize.Width());
1224 }
1225 else
1226 {
1227 for (tools::Long y = 0; y < mSize.Height(); ++y)
1228 {
1229 const uint32_t* src = bitmap.getAddr32(0, y);
1230 sal_uInt8* dest = mBuffer.get() + mScanlineSize * y;
1231 SkConvertRGBAToR(dest, src, mSize.Width());
1232 }
1233 }
1234 }
1235 else
1236 {
1237 std::unique_ptr<vcl::ScanlineWriter> pWriter
1238 = vcl::ScanlineWriter::Create(mBitCount, mPalette);
1239 for (tools::Long y = 0; y < mSize.Height(); ++y)
1240 {
1241 const uint8_t* src = static_cast<uint8_t*>(bitmap.getAddr(0, y));
1242 sal_uInt8* dest = mBuffer.get() + mScanlineSize * y;
1243 pWriter->nextLine(dest);
1244 for (tools::Long x = 0; x < mSize.Width(); ++x)
1245 {
1246 sal_uInt8 r = *src++;
1247 sal_uInt8 g = *src++;
1248 sal_uInt8 b = *src++;
1249 ++src; // skip alpha
1250 pWriter->writeRGB(r, g, b);
1251 }
1252 }
1253 }
1254 verify();
1255 // We've created the bitmap data from mImage, drop the image if conserving memory,
1256 // it'll be converted back if needed.
1257 if (ConserveMemory())
1258 {
1259 SAL_INFO("vcl.skia.trace", "ensurebitmapdata(" << this << "): dropping images");
1260 ResetToBuffer();
1261 }
1262 SAL_INFO("vcl.skia.trace", "ensurebitmapdata(" << this << ")");
1263 }
1264
1265 void SkiaSalBitmap::EnsureBitmapUniqueData()
1266 {
1267 #ifdef DBG_UTIL
1268 assert(mWriteAccessCount == 0);
1269 #endif
1270 EnsureBitmapData();
1271 assert(mPixelsSize == mSize);
1272 if (mBuffer.use_count() > 1)
1273 {
1274 sal_uInt32 allocate = mScanlineSize * mSize.Height();
1275 #ifdef DBG_UTIL
1276 assert(memcmp(mBuffer.get() + allocate, CANARY, sizeof(CANARY)) == 0);
1277 allocate += sizeof(CANARY);
1278 #endif
1279 boost::shared_ptr<sal_uInt8[]> newBuffer = boost::make_shared_noinit<sal_uInt8[]>(allocate);
1280 memcpy(newBuffer.get(), mBuffer.get(), allocate);
1281 mBuffer = newBuffer;
1282 }
1283 }
1284
1285 void SkiaSalBitmap::ResetToBuffer()
1286 {
1287 SkiaZone zone;
1288 // This should never be called to drop mImage if that's the only data we have.
1289 assert(mBuffer || !mImage);
1290 mImage.reset();
1291 mImageImmutable = false;
1292 mAlphaImage.reset();
1293 mEraseColorSet = false;
1294 }
1295
1296 void SkiaSalBitmap::ResetToSkImage(sk_sp<SkImage> image)
1297 {
1298 assert(mReadAccessCount == 0); // can't reset mBuffer if there's a read access pointing to it
1299 SkiaZone zone;
1300 mBuffer.reset();
1301 // Just to be safe, assume mutability of the image does not change
1302 mImage = image;
1303 mAlphaImage.reset();
1304 mEraseColorSet = false;
1305 }
1306
1307 void SkiaSalBitmap::ResetAllData()
1308 {
1309 assert(mReadAccessCount == 0);
1310 SkiaZone zone;
1311 mBuffer.reset();
1312 mImage.reset();
1313 mImageImmutable = false;
1314 mAlphaImage.reset();
1315 mEraseColorSet = false;
1316 mPixelsSize = mSize;
1317 ComputeScanlineSize();
1318 DataChanged();
1319 }
1320
1321 void SkiaSalBitmap::DataChanged() { InvalidateChecksum(); }
1322
1323 void SkiaSalBitmap::ResetPendingScaling()
1324 {
1325 if (mPixelsSize == mSize)
1326 return;
1327 SkiaZone zone;
1328 mScaleQuality = BmpScaleFlag::BestQuality;
1329 mPixelsSize = mSize;
1330 ComputeScanlineSize();
1331 // Information about the pending scaling has been discarded, so make sure we do not
1332 // keep around any cached images that would still need scaling.
1333 if (mImage && imageSize(mImage) != mSize)
1334 {
1335 mImage.reset();
1336 mImageImmutable = false;
1337 }
1338 if (mAlphaImage && imageSize(mAlphaImage) != mSize)
1339 mAlphaImage.reset();
1340 }
1341
1342 OString SkiaSalBitmap::GetImageKey(DirectImage direct) const
1343 {
1344 if (mEraseColorSet)
1345 {
1346 std::stringstream ss;
1347 ss << std::hex << std::setfill('0') << std::setw(6)
1348 << static_cast<sal_uInt32>(mEraseColor.GetRGBColor()) << std::setw(2)
1349 << static_cast<int>(mEraseColor.GetAlpha());
1350 return OString::Concat("E") + ss.str().c_str();
1351 }
1352 assert(direct == DirectImage::No || mImage);
1353 sk_sp<SkImage> image = GetSkImage(direct);
1354 // In some cases drawing code may try to draw the same content but using
1355 // different bitmaps (even underlying bitmaps), for example canvas apparently
1356 // copies the same things around in tdf#146095. For pixel-based images
1357 // it should be still cheaper to compute a checksum and avoid re-caching.
1358 if (!image->isTextureBacked())
1359 return OString::Concat("C") + OString::number(getSkImageChecksum(image));
1360 return OString::Concat("I") + OString::number(image->uniqueID());
1361 }
1362
1363 void SkiaSalBitmap::dump(const char* file) const
1364 {
1365 // Use a copy, so that debugging doesn't affect this instance.
1366 SkiaSalBitmap copy;
1367 copy.Create(*this);
1368 SkiaHelper::dump(copy.GetSkImage(), file);
1369 }
1370
1371 #ifdef DBG_UTIL
1372 void SkiaSalBitmap::verify() const
1373 {
1374 if (!mBuffer)
1375 return;
1376 // Use mPixelsSize, that describes the size of the actual data.
1377 assert(memcmp(mBuffer.get() + mScanlineSize * mPixelsSize.Height(), CANARY, sizeof(CANARY))
1378 == 0);
1379 }
1380 #endif
1381
1382 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */